diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b33c305e5345..184da5b8f136 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,3 +9,10 @@ updates: - "status/2-code-review" cooldown: default-days: 7 + groups: + codeql-actions: + patterns: + - "github/codeql-action/*" + docker-actions: + patterns: + - "docker/*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 212c548d4ce1..8b4aa5234f54 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,7 +35,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - @@ -65,10 +65,10 @@ jobs: steps: - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 - name: Build - uses: docker/bake-action@6614cfa25eff9a0b2b2697efb0b6159e7680d584 # v7.2.0 + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0 with: targets: ${{ matrix.target }} set: | @@ -98,46 +98,32 @@ jobs: if-no-files-found: error bin-image: - runs-on: ubuntu-24.04 if: ${{ github.event_name != 'pull_request' && github.repository == 'docker/cli' }} - steps: - - - name: Login to DockerHub - if: github.event_name != 'pull_request' - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 - with: - username: ${{ secrets.DOCKERHUB_CLIBIN_USERNAME }} - password: ${{ secrets.DOCKERHUB_CLIBIN_TOKEN }} - - - name: Set up QEMU - uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v4.1.0 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - - - name: Docker meta - id: meta - uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 - with: - images: dockereng/cli-bin - tags: | - type=semver,pattern={{version}} - type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{major}} - type=semver,pattern={{major}}.{{minor}} - - - name: Build and push image - uses: docker/bake-action@6614cfa25eff9a0b2b2697efb0b6159e7680d584 # v7.2.0 - with: - files: | - ./docker-bake.hcl - cwd://${{ steps.meta.outputs.bake-file }} - targets: bin-image-cross - push: ${{ github.event_name != 'pull_request' }} - set: | - *.cache-from=type=gha,scope=bin-image - *.cache-to=type=gha,scope=bin-image,mode=max + uses: docker/github-builder/.github/workflows/bake.yml@27ade872c1e2296e62ef15ab3b10d37665e57cf7 # v1.15.0 + permissions: + contents: read # same as global permission + id-token: write # for signing attestation(s) and authenticating to Docker Hub with GitHub OIDC Token + with: + setup-qemu: true + target: bin-image-cross + cache: true + cache-scope: bin-image + output: image + push: true + vars: | + VERSION=${{ github.ref }} + meta-images: | + dockereng/cli-bin + meta-tags: | + type=semver,pattern={{version}} + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{major}} + type=semver,pattern={{major}}.{{minor}} + registry-identities: | + - type: dockerhub + username: dockereng + connection_id: ${{ vars.DOCKERHUB_OIDC_CONNECTIONID }} prepare-plugins: runs-on: ubuntu-24.04 @@ -146,7 +132,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - @@ -170,10 +156,10 @@ jobs: steps: - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 - name: Build - uses: docker/bake-action@6614cfa25eff9a0b2b2697efb0b6159e7680d584 # v7.2.0 + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0 with: targets: plugins-cross set: | diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index eb03bd5ca1a3..abfe6f91438c 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 2 persist-credentials: false @@ -62,20 +62,20 @@ jobs: ln -s vendor.sum go.sum - name: Update Go - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.26.4" + go-version: "1.26.5" cache: false - name: Initialize CodeQL - uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2 + uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3 with: languages: go - name: Autobuild - uses: github/codeql-action/autobuild@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2 + uses: github/codeql-action/autobuild@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2 + uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3 with: category: "/language:go" diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 9de7fb2b120e..cd8b629ed2ae 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -44,7 +44,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - @@ -65,7 +65,7 @@ jobs: docker info - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 - name: Run ${{ matrix.target }} run: | diff --git a/.github/workflows/pr-review-trigger.yml b/.github/workflows/pr-review-trigger.yml index c176020256e5..1ecc03b098dc 100644 --- a/.github/workflows/pr-review-trigger.yml +++ b/.github/workflows/pr-review-trigger.yml @@ -7,8 +7,17 @@ on: permissions: {} +# Deduplicate simultaneous pull_request events for the same fork PR. +# When reviewers are requested at the same time, GitHub fires multiple +# review_requested events. Without this group each event triggers a +# separate review via workflow_run, producing duplicate reviews. +concurrency: + group: pr-review-trigger-${{ github.event.pull_request.number }} + cancel-in-progress: true + jobs: save-context: + if: github.event.pull_request.head.repo.fork runs-on: ubuntu-latest steps: - name: Save event context diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index d2e6a3585541..1f459fc27335 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -11,7 +11,7 @@ permissions: jobs: review: - uses: docker/docker-agent-action/.github/workflows/review-pr.yml@e96a4bb40cac114f64358621e1d08346c8eadc8c # v2.0.1 + uses: docker/docker-agent-action/.github/workflows/review-pr.yml@774b6e0e60d6c648b0f2dc43bd5221377a0a7420 # v2.0.2 permissions: contents: read # Read repository files and PR diffs pull-requests: write # Post review comments diff --git a/.github/workflows/sync-release-branch.yml b/.github/workflows/sync-release-branch.yml new file mode 100644 index 000000000000..d87249286b12 --- /dev/null +++ b/.github/workflows/sync-release-branch.yml @@ -0,0 +1,157 @@ +name: Sync Docker release branch + +concurrency: + group: ${{ github.workflow }}-${{ inputs.release_branch }} + cancel-in-progress: false + +permissions: + contents: read + +on: + workflow_dispatch: + inputs: + release_branch: + description: Release branch to sync, for example 29.x + required: true + type: string + tag: + description: Tag to sync from, for example v29.6.0 + required: true + type: string + dry_run: + description: Merge but don't push + required: true + default: false + type: boolean + +jobs: + sync-release-branch: + runs-on: ubuntu-24.04 + permissions: + contents: write + actions: write + outputs: + base_sha: ${{ steps.sync.outputs.base_sha }} + has_changes: ${{ steps.sync.outputs.has_changes }} + temporary_branch: ${{ steps.sync.outputs.temporary_branch }} + temporary_sha: ${{ steps.sync.outputs.temporary_sha }} + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Validate + env: + BRANCH: ${{ github.ref_name }} + RELEASE_BRANCH: ${{ inputs.release_branch }} + run: | + if [ "$BRANCH" != "master" ]; then + echo "::error::This workflow is expected to be run on master, not $BRANCH" + exit 1 + fi + if [ "$RELEASE_BRANCH" = "master" ]; then + echo "::error::The release branch must not be master" + exit 1 + fi + if ! [[ "$RELEASE_BRANCH" =~ ^[0-9]+\.[x0-9]+$ ]]; then + echo "::error::Invalid release branch name: '$RELEASE_BRANCH'. Expected format: 29.x" + exit 1 + fi + + - name: Configure git author + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Sync release branch to tag range + id: sync + env: + DRY_RUN: ${{ inputs.dry_run }} + RELEASE_BRANCH: ${{ inputs.release_branch }} + RUN_ATTEMPT: ${{ github.run_attempt }} + RUN_ID: ${{ github.run_id }} + TAG: ${{ inputs.tag }} + run: | + set -o pipefail + base_sha=$(git rev-parse "origin/$RELEASE_BRANCH") + temporary_branch="process/sync-release-branch/$RUN_ID-$RUN_ATTEMPT" + echo "base_sha=$base_sha" >> "$GITHUB_OUTPUT" + echo "temporary_branch=$temporary_branch" >> "$GITHUB_OUTPUT" + + # Keep the master checkout unchanged so scripts run from the dispatched revision. + release_worktree="$RUNNER_TEMP/release-branch" + git worktree add --detach "$release_worktree" "$base_sha" + cd "$release_worktree" + + tags_file=$(mktemp) + "$GITHUB_WORKSPACE/scripts/unmerged-tags" \ + "origin/$RELEASE_BRANCH" \ + "$TAG" \ + > "$tags_file" + + echo >> "$GITHUB_STEP_SUMMARY" + echo "## Tags to sync" >> "$GITHUB_STEP_SUMMARY" + echo >> "$GITHUB_STEP_SUMMARY" + sed 's/^/- /' "$tags_file" >> "$GITHUB_STEP_SUMMARY" + + xargs -r "$GITHUB_WORKSPACE/scripts/sync-branch" < "$tags_file" | tee -a "$GITHUB_STEP_SUMMARY" + + if [[ "$DRY_RUN" == "true" ]]; then + echo "has_changes=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + if [[ $(git rev-parse HEAD) == $(git rev-parse "origin/$RELEASE_BRANCH") ]]; then + echo "has_changes=false" >> "$GITHUB_OUTPUT" + echo "No changes to push" + exit 0 + fi + + echo "has_changes=true" >> "$GITHUB_OUTPUT" + git push origin "HEAD:refs/heads/$temporary_branch" + echo "temporary_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + push-release-branch: + needs: sync-release-branch + if: ${{ !inputs.dry_run && needs.sync-release-branch.outputs.has_changes == 'true' }} + runs-on: ubuntu-24.04 + environment: docker-releases + permissions: + contents: write + actions: write + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Push release branch + env: + BASE_SHA: ${{ needs.sync-release-branch.outputs.base_sha }} + RELEASE_BRANCH: ${{ inputs.release_branch }} + TEMPORARY_BRANCH: ${{ needs.sync-release-branch.outputs.temporary_branch }} + TEMPORARY_SHA: ${{ needs.sync-release-branch.outputs.temporary_sha }} + run: | + git fetch origin "$RELEASE_BRANCH" + current_sha=$(git rev-parse "origin/$RELEASE_BRANCH") + if [[ "$current_sha" != "$BASE_SHA" ]]; then + echo "$RELEASE_BRANCH changed from $BASE_SHA to $current_sha" + exit 1 + fi + + git fetch origin "$TEMPORARY_BRANCH" + current_temporary_sha=$(git rev-parse FETCH_HEAD) + if [[ "$current_temporary_sha" != "$TEMPORARY_SHA" ]]; then + echo "$TEMPORARY_BRANCH changed from $TEMPORARY_SHA to $current_temporary_sha" + exit 1 + fi + + git push origin "FETCH_HEAD:$RELEASE_BRANCH" + + - name: Delete temporary branch + env: + TEMPORARY_BRANCH: ${{ needs.sync-release-branch.outputs.temporary_branch }} + run: git push origin --delete "$TEMPORARY_BRANCH" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 85959f2bb0f0..aca0e26b0967 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,10 +30,10 @@ jobs: steps: - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 - name: Test - uses: docker/bake-action@6614cfa25eff9a0b2b2697efb0b6159e7680d584 # v7.2.0 + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0 with: targets: test-coverage - @@ -60,15 +60,15 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ env.GOPATH }}/src/github.com/docker/cli persist-credentials: false - name: Set up Go - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.26.4" + go-version: "1.26.5" cache: false - name: Test diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index e1d8b4ab3406..681c3f5bb8de 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -38,7 +38,7 @@ jobs: steps: - name: Run - uses: docker/bake-action@6614cfa25eff9a0b2b2697efb0b6159e7680d584 # v7.2.0 + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0 with: targets: ${{ matrix.target }} @@ -48,7 +48,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - @@ -76,7 +76,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - @@ -93,15 +93,15 @@ jobs: steps: - name: Checkout - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: src/github.com/docker/cli persist-credentials: false - name: Set up Go - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.26.4" + go-version: "1.26.5" cache: false - name: Run gocompat check diff --git a/.golangci.yml b/.golangci.yml index dfb592403cc0..6aec71dbb74e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -5,7 +5,7 @@ run: # which causes it to fallback to go1.17 semantics. # # TODO(thaJeztah): update "usetesting" settings to enable go1.24 features once our minimum version is go1.24 - go: "1.26.4" + go: "1.26.5" timeout: 5m diff --git a/Dockerfile b/Dockerfile index ccde94ee6df7..2a71bf8889e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ ARG BASE_VARIANT=alpine ARG ALPINE_VERSION=3.23 ARG BASE_DEBIAN_DISTRO=bookworm -ARG GO_VERSION=1.26.4 +ARG GO_VERSION=1.26.5 # XX_VERSION specifies the version of the xx utility to use. # It must be a valid tag in the docker.io/tonistiigi/xx image repository. diff --git a/README.md b/README.md index 1183834102b4..512eb9ab0f50 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ [![PkgGoDev](https://pkg.go.dev/badge/github.com/docker/cli)](https://pkg.go.dev/github.com/docker/cli) [![Build Status](https://img.shields.io/github/actions/workflow/status/docker/cli/build.yml?branch=master&label=build&logo=github)](https://github.com/docker/cli/actions?query=workflow%3Abuild) [![Test Status](https://img.shields.io/github/actions/workflow/status/docker/cli/test.yml?branch=master&label=test&logo=github)](https://github.com/docker/cli/actions?query=workflow%3Atest) -[![Go Report Card](https://goreportcard.com/badge/github.com/docker/cli)](https://goreportcard.com/report/github.com/docker/cli) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/docker/cli/badge)](https://scorecard.dev/viewer/?uri=github.com/docker/cli) [![Codecov](https://img.shields.io/codecov/c/github/docker/cli?logo=codecov)](https://codecov.io/gh/docker/cli) diff --git a/VERSION b/VERSION index d73ed40a839d..bfa22ee30d79 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -29.6.1 +29.7.0 diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index 944cdfd2a100..be5bcabfbbdb 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -208,52 +208,70 @@ func TestInitializeFromClient(t *testing.T) { // Makes sure we don't hang forever on the initial connection. // https://github.com/docker/cli/issues/3652 func TestInitializeFromClientHangs(t *testing.T) { + const ( + // Sized against measured scheduler stalls: + // under CPU pressure this test sees 40-90ms stalls; + // this should give about 5x headroom. + // See https://github.com/docker/cli/issues/6003. + clientInitTimeout = 500 * time.Millisecond + + // This is only a backstop against a genuine hang. + // It should never be reached on a healthy run. + // So, it should be fine to have a lenient timeout here. + waitTimeout = 10 * time.Second + ) + tmpDir := t.TempDir() socket := filepath.Join(tmpDir, "my.sock") l, err := net.Listen("unix", socket) assert.NilError(t, err) - receiveReqCh := make(chan bool) - timeoutCtx, cancel := context.WithTimeout(context.TODO(), time.Second) - defer cancel() + // Buffered, so the handler can record + // that it was reached without a reader + // having to be ready at that instant. + receivedReqCh := make(chan struct{}, 1) + releaseHandlerCh := make(chan struct{}) // Simulate a server that hangs on connections. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { select { - case <-timeoutCtx.Done(): - case receiveReqCh <- true: // Blocks until someone receives on the channel. + case receivedReqCh <- struct{}{}: + default: } - _, _ = w.Write([]byte("OK")) + <-releaseHandlerCh })) ts.Listener = l ts.Start() - defer ts.Close() + t.Cleanup(func() { + close(releaseHandlerCh) + ts.Close() + }) opts := &flags.ClientOptions{Hosts: []string{"unix://" + socket}} configFile := &configfile.ConfigFile{} apiClient, err := NewAPIClientFromFlags(opts, configFile) assert.NilError(t, err) - initializedCh := make(chan bool) + initErrCh := make(chan error, 1) go func() { - cli := &DockerCli{client: apiClient, initTimeout: time.Millisecond} + cli := &DockerCli{client: apiClient, initTimeout: clientInitTimeout} err := cli.Initialize(flags.NewClientOptions()) - assert.Check(t, err) cli.CurrentVersion() - close(initializedCh) + initErrCh <- err }() select { - case <-timeoutCtx.Done(): + case err := <-initErrCh: + assert.Check(t, err) + case <-time.After(waitTimeout): t.Fatal("timeout waiting for initialization to complete") - case <-initializedCh: } select { - case <-timeoutCtx.Done(): + case <-receivedReqCh: + case <-time.After(waitTimeout): t.Fatal("server never received an init request") - case <-receiveReqCh: } } diff --git a/cli/command/completion/functions.go b/cli/command/completion/functions.go index 1fa4ff621182..7e040f60cc71 100644 --- a/cli/command/completion/functions.go +++ b/cli/command/completion/functions.go @@ -172,6 +172,28 @@ func FromList(options ...string) cobra.CompletionFunc { return Unique(cobra.FixedCompletions(options, cobra.ShellCompDirectiveNoFileComp)) } +// WithPrefix prefixes every element in the slice with the given prefix. +// It is a helper for building "--filter" completions, where each candidate +// value is offered as "key=value". +func WithPrefix(prefix string, values []string) []string { + result := make([]string, len(values)) + for i, v := range values { + result[i] = prefix + v + } + return result +} + +// WithSuffix appends the given suffix to every element in the slice. It is a +// helper for building "--filter" completions, where filter keys are offered +// with a trailing "=" (combined with [cobra.ShellCompDirectiveNoSpace]). +func WithSuffix(suffix string, values []string) []string { + result := make([]string, len(values)) + for i, v := range values { + result[i] = v + suffix + } + return result +} + // FileNames is a convenience function to use [cobra.ShellCompDirectiveDefault], // which indicates to let the shell perform its default behavior after // completions have been provided. diff --git a/cli/command/completion/functions_test.go b/cli/command/completion/functions_test.go index 58fee8de06fd..bb2fa1b62ddb 100644 --- a/cli/command/completion/functions_test.go +++ b/cli/command/completion/functions_test.go @@ -196,6 +196,18 @@ func TestCompleteFromList(t *testing.T) { assert.Check(t, is.DeepEqual(values, expected)) } +func TestWithPrefix(t *testing.T) { + assert.Check(t, is.DeepEqual(WithPrefix("node=", []string{"n1", "n2"}), []string{"node=n1", "node=n2"})) + assert.Check(t, is.DeepEqual(WithPrefix("node=", []string{}), []string{})) + assert.Check(t, is.DeepEqual(WithPrefix("", []string{"n1"}), []string{"n1"})) +} + +func TestWithSuffix(t *testing.T) { + assert.Check(t, is.DeepEqual(WithSuffix("=", []string{"id", "name"}), []string{"id=", "name="})) + assert.Check(t, is.DeepEqual(WithSuffix("=", []string{}), []string{})) + assert.Check(t, is.DeepEqual(WithSuffix("", []string{"id"}), []string{"id"})) +} + func TestCompleteImageNames(t *testing.T) { tests := []struct { doc string diff --git a/cli/command/container/create.go b/cli/command/container/create.go index 2598323d7e6e..122d15e2e149 100644 --- a/cli/command/container/create.go +++ b/cli/command/container/create.go @@ -71,7 +71,7 @@ func newCreateCommand(dockerCLI command.Cli) *cobra.Command { flags.SetInterspersed(false) flags.StringVar(&options.name, "name", "", "Assign a name to the container") - flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "|`+PullImageMissing+`", "`+PullImageNever+`")`) + flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "`+PullImageMissing+`", "`+PullImageNever+`")`) flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output") flags.BoolVarP(&options.useAPISocket, "use-api-socket", "", false, "Bind mount Docker API socket and required auth") _ = flags.SetAnnotation("use-api-socket", "experimentalCLI", nil) // Mark flag as experimental for now. diff --git a/cli/command/container/rm.go b/cli/command/container/rm.go index c38256a468b4..eaa23dec04bc 100644 --- a/cli/command/container/rm.go +++ b/cli/command/container/rm.go @@ -88,7 +88,6 @@ func runRm(ctx context.Context, dockerCLI command.Cli, opts *rmOptions) error { for _, name := range opts.containers { if err := <-errChan; err != nil { if opts.force && errdefs.IsNotFound(err) { - _, _ = fmt.Fprintln(dockerCLI.Err(), err) continue } errs = append(errs, err) diff --git a/cli/command/container/rm_test.go b/cli/command/container/rm_test.go index 86f6c4e0a2e9..4ab14407bb35 100644 --- a/cli/command/container/rm_test.go +++ b/cli/command/container/rm_test.go @@ -52,6 +52,7 @@ func TestRemoveForce(t *testing.T) { } else { assert.NilError(t, err) } + assert.Equal(t, cli.ErrBuffer().String(), "") sort.Strings(removed) assert.DeepEqual(t, removed, []string{"mycontainer", "nosuchcontainer"}) }) diff --git a/cli/command/node/completion.go b/cli/command/node/completion.go index f3ccf757279e..7fb7bdfb9834 100644 --- a/cli/command/node/completion.go +++ b/cli/command/node/completion.go @@ -2,12 +2,26 @@ package node import ( "os" + "strings" "github.com/docker/cli/cli/command/completion" + "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" "github.com/spf13/cobra" ) +var ( + // nodePsFilters are the filters that can be used with "docker node ps --filter". + nodePsFilters = []string{"desired-state", "id", "label", "name"} + + // taskDesiredStates are the valid values for the "desired-state" task filter. + taskDesiredStates = []string{ + string(swarm.TaskStateRunning), + string(swarm.TaskStateShutdown), + string(swarm.TaskStateAccepted), + } +) + // completeNodeNames offers completion for swarm node (host)names and optional IDs. // By default, only names are returned. // Set DOCKER_COMPLETION_SHOW_NODE_IDS=yes to also complete IDs. @@ -35,3 +49,23 @@ func completeNodeNames(dockerCLI completion.APIClientProvider) cobra.CompletionF return names, cobra.ShellCompDirectiveNoFileComp } } + +// completeNodePsFilters provides completion for the filters that can be used +// with "docker node ps --filter". +func completeNodePsFilters(_ completion.APIClientProvider) cobra.CompletionFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + key, _, ok := strings.Cut(toComplete, "=") + if !ok { + return completion.WithSuffix("=", nodePsFilters), cobra.ShellCompDirectiveNoSpace + } + switch key { + case "desired-state": + return completion.WithPrefix("desired-state=", taskDesiredStates), cobra.ShellCompDirectiveNoFileComp + case "id", "name", "label": + // Task IDs, names, and labels are not easily discoverable; only offer the key. + return nil, cobra.ShellCompDirectiveNoFileComp + default: + return completion.WithSuffix("=", nodePsFilters), cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp + } + } +} diff --git a/cli/command/node/completion_test.go b/cli/command/node/completion_test.go new file mode 100644 index 000000000000..13068319de26 --- /dev/null +++ b/cli/command/node/completion_test.go @@ -0,0 +1,52 @@ +package node + +import ( + "testing" + + "github.com/docker/cli/internal/test" + "github.com/spf13/cobra" + "gotest.tools/v3/assert" +) + +func TestCompleteNodePsFilters(t *testing.T) { + tests := []struct { + doc string + toComplete string + expected []string + directive cobra.ShellCompDirective + }{ + { + doc: "no input offers the filter keys", + toComplete: "", + expected: []string{"desired-state=", "id=", "label=", "name="}, + directive: cobra.ShellCompDirectiveNoSpace, + }, + { + doc: "desired-state values", + toComplete: "desired-state=", + expected: []string{"desired-state=running", "desired-state=shutdown", "desired-state=accepted"}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "label offers no values", + toComplete: "label=", + expected: nil, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "unknown key falls back to the filter keys", + toComplete: "bogus=", + expected: []string{"desired-state=", "id=", "label=", "name="}, + directive: cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp, + }, + } + + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + cli := test.NewFakeCli(&fakeClient{}) + completions, directive := completeNodePsFilters(cli)(newPsCommand(cli), nil, tc.toComplete) + assert.DeepEqual(t, completions, tc.expected) + assert.Equal(t, directive, tc.directive) + }) + } +} diff --git a/cli/command/node/ps.go b/cli/command/node/ps.go index 4ad64530b187..1cd397883b74 100644 --- a/cli/command/node/ps.go +++ b/cli/command/node/ps.go @@ -48,6 +48,8 @@ func newPsCommand(dockerCLI command.Cli) *cobra.Command { flags.StringVar(&options.format, "format", "", "Pretty-print tasks using a Go template") flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display task IDs") + _ = cmd.RegisterFlagCompletionFunc("filter", completeNodePsFilters(dockerCLI)) + return cmd } diff --git a/cli/command/registry.go b/cli/command/registry.go index e39635283afa..2e767d5b72f3 100644 --- a/cli/command/registry.go +++ b/cli/command/registry.go @@ -97,17 +97,22 @@ func GetDefaultAuthConfig(cfg *configfile.ConfigFile, checkCredStore bool, serve // If defaultUsername is not empty, the username prompt includes that username // and the user can hit enter without inputting a username to use that default // username. -func PromptUserForCredentials(ctx context.Context, cli Cli, argUser, argPassword, defaultUsername, serverAddress string) (registrytypes.AuthConfig, error) { +func PromptUserForCredentials(ctx context.Context, cli Streams, argUser, argPassword, defaultUsername, serverAddress string) (registrytypes.AuthConfig, error) { // On Windows, force the use of the regular OS stdin stream. // + // StdStreams() may wrap stdin with windowsconsole.NewAnsiReader to + // emulate VT input on consoles that do not support it natively, but + // that wrapper has historically caused interactive prompts to hang + // or behave incorrectly. + // // See: // - https://github.com/moby/moby/issues/14336 // - https://github.com/moby/moby/issues/14210 // - https://github.com/moby/moby/pull/17738 - // - // TODO(thaJeztah): we need to confirm if this special handling is still needed, as we may not be doing this in other places. + stdIn := cli.In() if runtime.GOOS == "windows" { - cli.SetIn(streams.NewIn(os.Stdin)) + // TODO(thaJeztah); change to io.Reader and skip wrapping once prompt.DisableInputEcho no longer requires a streams.In + stdIn = streams.NewIn(os.Stdin) } argUser = strings.TrimSpace(argUser) @@ -132,7 +137,7 @@ func PromptUserForCredentials(ctx context.Context, cli Cli, argUser, argPassword } var err error - argUser, err = prompt.ReadInput(ctx, cli.In(), cli.Out(), msg) + argUser, err = prompt.ReadInput(ctx, stdIn, cli.Out(), msg) if err != nil { return registrytypes.AuthConfig{}, err } @@ -146,7 +151,7 @@ func PromptUserForCredentials(ctx context.Context, cli Cli, argUser, argPassword isEmpty := strings.TrimSpace(argPassword) == "" if isEmpty { - restoreInput, err := prompt.DisableInputEcho(cli.In()) + restoreInput, err := prompt.DisableInputEcho(stdIn) if err != nil { return registrytypes.AuthConfig{}, err } @@ -166,7 +171,7 @@ func PromptUserForCredentials(ctx context.Context, cli Cli, argUser, argPassword "To create a PAT, visit " + aec.Underline.Apply("https://app.docker.com/settings") + "\n\n") } - argPassword, err = prompt.ReadInput(ctx, cli.In(), cli.Out(), "Password: ") + argPassword, err = prompt.ReadInput(ctx, stdIn, cli.Out(), "Password: ") if err != nil { return registrytypes.AuthConfig{}, err } diff --git a/cli/command/service/completion.go b/cli/command/service/completion.go index 9e244ac41019..6d5438c2cd83 100644 --- a/cli/command/service/completion.go +++ b/cli/command/service/completion.go @@ -2,12 +2,32 @@ package service import ( "os" + "strings" "github.com/docker/cli/cli/command/completion" + "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" "github.com/spf13/cobra" ) +var ( + // serviceListFilters are the filters that can be used with "docker service ls --filter". + serviceListFilters = []string{"id", "label", "mode", "name"} + + // serviceModes are the valid values for the "mode" filter of "docker service ls". + serviceModes = []string{"replicated", "global", "replicated-job", "global-job"} + + // servicePsFilters are the filters that can be used with "docker service ps --filter". + servicePsFilters = []string{"desired-state", "id", "name", "node"} + + // taskDesiredStates are the valid values for the "desired-state" task filter. + taskDesiredStates = []string{ + string(swarm.TaskStateRunning), + string(swarm.TaskStateShutdown), + string(swarm.TaskStateAccepted), + } +) + // completeServiceNames offers completion for swarm service names and optional IDs. // By default, only names are returned. // Set DOCKER_COMPLETION_SHOW_SERVICE_IDS=yes to also complete IDs. @@ -31,3 +51,74 @@ func completeServiceNames(dockerCLI completion.APIClientProvider) cobra.Completi return names, cobra.ShellCompDirectiveNoFileComp } } + +// completeServiceListFilters provides completion for the filters that can be +// used with "docker service ls --filter". +func completeServiceListFilters(dockerCLI completion.APIClientProvider) cobra.CompletionFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + key, _, ok := strings.Cut(toComplete, "=") + if !ok { + return completion.WithSuffix("=", serviceListFilters), cobra.ShellCompDirectiveNoSpace + } + switch key { + case "id", "name": + return completion.WithPrefix(key+"=", serviceNames(dockerCLI, cmd)), cobra.ShellCompDirectiveNoFileComp + case "mode": + return completion.WithPrefix("mode=", serviceModes), cobra.ShellCompDirectiveNoFileComp + case "label": + return nil, cobra.ShellCompDirectiveNoFileComp + default: + return completion.WithSuffix("=", serviceListFilters), cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp + } + } +} + +// completeServicePsFilters provides completion for the filters that can be +// used with "docker service ps --filter". +func completeServicePsFilters(dockerCLI completion.APIClientProvider) cobra.CompletionFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + key, _, ok := strings.Cut(toComplete, "=") + if !ok { + return completion.WithSuffix("=", servicePsFilters), cobra.ShellCompDirectiveNoSpace + } + switch key { + case "desired-state": + return completion.WithPrefix("desired-state=", taskDesiredStates), cobra.ShellCompDirectiveNoFileComp + case "node": + return completion.WithPrefix("node=", nodeNames(dockerCLI, cmd)), cobra.ShellCompDirectiveNoFileComp + case "id", "name": + // Task IDs and names are not easily discoverable; only offer the key. + return nil, cobra.ShellCompDirectiveNoFileComp + default: + return completion.WithSuffix("=", servicePsFilters), cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp + } + } +} + +// serviceNames contacts the API to get a list of service names. +// In case of an error, an empty list is returned. +func serviceNames(dockerCLI completion.APIClientProvider, cmd *cobra.Command) []string { + res, err := dockerCLI.Client().ServiceList(cmd.Context(), client.ServiceListOptions{}) + if err != nil { + return []string{} + } + names := make([]string, 0, len(res.Items)) + for _, service := range res.Items { + names = append(names, service.Spec.Name) + } + return names +} + +// nodeNames contacts the API to get a list of node (host)names. +// In case of an error, an empty list is returned. +func nodeNames(dockerCLI completion.APIClientProvider, cmd *cobra.Command) []string { + res, err := dockerCLI.Client().NodeList(cmd.Context(), client.NodeListOptions{}) + if err != nil { + return []string{} + } + names := make([]string, 0, len(res.Items)) + for _, node := range res.Items { + names = append(names, node.Description.Hostname) + } + return names +} diff --git a/cli/command/service/completion_test.go b/cli/command/service/completion_test.go new file mode 100644 index 000000000000..9df2580f8a41 --- /dev/null +++ b/cli/command/service/completion_test.go @@ -0,0 +1,156 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/docker/cli/internal/test" + "github.com/docker/cli/internal/test/builders" + "github.com/moby/moby/api/types/swarm" + "github.com/moby/moby/client" + "github.com/spf13/cobra" + "gotest.tools/v3/assert" +) + +func TestCompleteServicePsFilters(t *testing.T) { + tests := []struct { + doc string + client *fakeClient + toComplete string + expected []string + directive cobra.ShellCompDirective + }{ + { + doc: "no input offers the filter keys", + toComplete: "", + expected: []string{"desired-state=", "id=", "name=", "node="}, + directive: cobra.ShellCompDirectiveNoSpace, + }, + { + doc: "desired-state values", + toComplete: "desired-state=", + expected: []string{"desired-state=running", "desired-state=shutdown", "desired-state=accepted"}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "node values", + client: &fakeClient{ + nodeListFunc: func(_ context.Context, _ client.NodeListOptions) (client.NodeListResult, error) { + return client.NodeListResult{ + Items: []swarm.Node{ + *builders.Node(builders.Hostname("n1")), + *builders.Node(builders.Hostname("n2")), + }, + }, nil + }, + }, + toComplete: "node=", + expected: []string{"node=n1", "node=n2"}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "node values on API error", + client: &fakeClient{ + nodeListFunc: func(_ context.Context, _ client.NodeListOptions) (client.NodeListResult, error) { + return client.NodeListResult{}, errors.New("API error") + }, + }, + toComplete: "node=", + expected: []string{}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "id offers no values", + toComplete: "id=", + expected: nil, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "unknown key falls back to the filter keys", + toComplete: "bogus=", + expected: []string{"desired-state=", "id=", "name=", "node="}, + directive: cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp, + }, + } + + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + cli := test.NewFakeCli(tc.client) + completions, directive := completeServicePsFilters(cli)(newPsCommand(cli), nil, tc.toComplete) + assert.DeepEqual(t, completions, tc.expected) + assert.Equal(t, directive, tc.directive) + }) + } +} + +func TestCompleteServiceListFilters(t *testing.T) { + tests := []struct { + doc string + client *fakeClient + toComplete string + expected []string + directive cobra.ShellCompDirective + }{ + { + doc: "no input offers the filter keys", + toComplete: "", + expected: []string{"id=", "label=", "mode=", "name="}, + directive: cobra.ShellCompDirectiveNoSpace, + }, + { + doc: "mode values", + toComplete: "mode=", + expected: []string{"mode=replicated", "mode=global", "mode=replicated-job", "mode=global-job"}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "name values", + client: &fakeClient{ + serviceListFunc: func(_ context.Context, _ client.ServiceListOptions) (client.ServiceListResult, error) { + return client.ServiceListResult{ + Items: []swarm.Service{ + *builders.Service(builders.ServiceName("s1")), + *builders.Service(builders.ServiceName("s2")), + }, + }, nil + }, + }, + toComplete: "name=", + expected: []string{"name=s1", "name=s2"}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "name values on API error", + client: &fakeClient{ + serviceListFunc: func(_ context.Context, _ client.ServiceListOptions) (client.ServiceListResult, error) { + return client.ServiceListResult{}, errors.New("API error") + }, + }, + toComplete: "name=", + expected: []string{}, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "label offers no values", + toComplete: "label=", + expected: nil, + directive: cobra.ShellCompDirectiveNoFileComp, + }, + { + doc: "unknown key falls back to the filter keys", + toComplete: "bogus=", + expected: []string{"id=", "label=", "mode=", "name="}, + directive: cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp, + }, + } + + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + cli := test.NewFakeCli(tc.client) + completions, directive := completeServiceListFilters(cli)(newListCommand(cli), nil, tc.toComplete) + assert.DeepEqual(t, completions, tc.expected) + assert.Equal(t, directive, tc.directive) + }) + } +} diff --git a/cli/command/service/list.go b/cli/command/service/list.go index d2e2fe6a1003..346eb6651f59 100644 --- a/cli/command/service/list.go +++ b/cli/command/service/list.go @@ -38,6 +38,8 @@ func newListCommand(dockerCLI command.Cli) *cobra.Command { flags.StringVar(&options.format, "format", "", flagsHelper.FormatHelp) flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") + _ = cmd.RegisterFlagCompletionFunc("filter", completeServiceListFilters(dockerCLI)) + return cmd } diff --git a/cli/command/service/ps.go b/cli/command/service/ps.go index 4591f1cf0a5e..791949184cd4 100644 --- a/cli/command/service/ps.go +++ b/cli/command/service/ps.go @@ -45,6 +45,8 @@ func newPsCommand(dockerCLI command.Cli) *cobra.Command { flags.StringVar(&options.format, "format", "", "Pretty-print tasks using a Go template") flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") + _ = cmd.RegisterFlagCompletionFunc("filter", completeServicePsFilters(dockerCLI)) + return cmd } diff --git a/cli/config/credentials/file_store.go b/cli/config/credentials/file_store.go index e3ef8e25edf9..d4037b7a488c 100644 --- a/cli/config/credentials/file_store.go +++ b/cli/config/credentials/file_store.go @@ -104,7 +104,7 @@ func (c *fileStore) Store(authConfig types.AuthConfig) error { // stored as hostname or as hostname including scheme (in legacy configuration // files). // -// It's the equivalent to [registry.ConvertToHostname] in the daemon. +// It's based on [registry.ConvertToHostname] from Moby daemon. // // [registry.ConvertToHostname]: https://pkg.go.dev/github.com/moby/moby/v2@v2.0.0-beta.7/daemon/pkg/registry#ConvertToHostname func ConvertToHostname(maybeURL string) string { @@ -117,7 +117,48 @@ func ConvertToHostname(maybeURL string) string { } return net.JoinHostPort(u.Hostname(), u.Port()) } + + if hostName := hostFromURLFallback(stripped); hostName != "" { + return hostName + } } hostName, _, _ := strings.Cut(stripped, "/") return hostName } + +// hostFromURLFallback extracts a host from scheme URLs that net/url rejects. +// Go rejects unbracketed IPv6 literals in URL hosts since +// https://github.com/golang/go/commit/0c28789bd7dfc55099cac86a3212dda0d6c091f6 +func hostFromURLFallback(maybeURL string) string { + _, rest, ok := strings.Cut(maybeURL, "://") + if !ok { + return "" + } + + hostName, _, _ := strings.Cut(rest, "/") + if hostName == "" { + return "" + } + + if strings.Count(hostName, ":") > 1 && !strings.HasPrefix(hostName, "[") { + portStart := strings.LastIndex(hostName, ":") + addr, port := hostName[:portStart], hostName[portStart+1:] + if addr != "" && isPort(port) { + return net.JoinHostPort(addr, port) + } + } + + return hostName +} + +func isPort(port string) bool { + if port == "" { + return false + } + for _, r := range port { + if r < '0' || r > '9' { + return false + } + } + return true +} diff --git a/cmd/docker-trust/go.mod b/cmd/docker-trust/go.mod index 9ea8a225a193..e29e424805e8 100644 --- a/cmd/docker-trust/go.mod +++ b/cmd/docker-trust/go.mod @@ -65,11 +65,11 @@ require ( go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect go.opentelemetry.io/otel/trace v1.43.0 // indirect go.opentelemetry.io/proto/otlp v1.10.0 // indirect - golang.org/x/crypto v0.50.0 // indirect - golang.org/x/net v0.53.0 // indirect - golang.org/x/sys v0.43.0 // indirect - golang.org/x/term v0.42.0 // indirect - golang.org/x/text v0.36.0 // indirect + golang.org/x/crypto v0.52.0 // indirect + golang.org/x/net v0.54.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/term v0.43.0 // indirect + golang.org/x/text v0.37.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect google.golang.org/grpc v1.80.0 // indirect diff --git a/cmd/docker-trust/go.sum b/cmd/docker-trust/go.sum index 8630a983c978..cbf1eca9b8f8 100644 --- a/cmd/docker-trust/go.sum +++ b/cmd/docker-trust/go.sum @@ -265,14 +265,14 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= -golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= -golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= +golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= +golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -285,14 +285,14 @@ golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= -golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= -golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= +golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= +golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= -golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= diff --git a/docker.Makefile b/docker.Makefile index ce0cbd533d6c..75a7dca34e79 100644 --- a/docker.Makefile +++ b/docker.Makefile @@ -8,6 +8,7 @@ DOCKER_CLI_MOUNTS ?= -v "$(CURDIR)":/go/src/github.com/docker/cli DOCKER_CLI_CONTAINER_NAME ?= DOCKER_CLI_GO_BUILD_CACHE ?= y +DOCKER_SOCK ?= $(or $(patsubst unix://%,%,$(filter unix://%,$(shell docker context inspect --format '{{.Endpoints.docker.Host}}'))),/var/run/docker.sock) # Sets the name of the company that produced the windows binary. PACKAGER_NAME ?= @@ -62,7 +63,7 @@ dynbinary: ## build dynamically linked binary .PHONY: dev dev: build_docker_image ## start a build container in interactive mode for in-container development $(DOCKER_RUN) -it \ - --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \ + --mount 'type=bind,src=$(DOCKER_SOCK),dst=/var/run/docker.sock' \ $(DEV_DOCKER_IMAGE_NAME) shell: dev ## alias for dev @@ -134,14 +135,14 @@ test-e2e: test-e2e-local test-e2e-connhelper-ssh ## run all e2e tests test-e2e-local: build-e2e-image # run experimental e2e tests docker run --rm $(ENVVARS) \ --mount type=bind,src=$(CURDIR)/build/coverage,dst=/tmp/coverage \ - --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \ + --mount 'type=bind,src=$(DOCKER_SOCK),dst=/var/run/docker.sock' \ $(E2E_IMAGE_NAME) .PHONY: test-e2e-connhelper-ssh test-e2e-connhelper-ssh: build-e2e-image # run experimental SSH-connection helper e2e tests docker run --rm $(ENVVARS) -e TEST_CONNHELPER=ssh \ --mount type=bind,src=$(CURDIR)/build/coverage,dst=/tmp/coverage \ - --mount type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock \ + --mount 'type=bind,src=$(DOCKER_SOCK),dst=/var/run/docker.sock' \ $(E2E_IMAGE_NAME) .PHONY: help diff --git a/dockerfiles/Dockerfile.dev b/dockerfiles/Dockerfile.dev index c4a9a39b1ba5..b40cbb287c11 100644 --- a/dockerfiles/Dockerfile.dev +++ b/dockerfiles/Dockerfile.dev @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1 -ARG GO_VERSION=1.26.4 +ARG GO_VERSION=1.26.5 # ALPINE_VERSION sets the version of the alpine base image to use, including for the golang image. # It must be a supported tag in the docker.io/library/alpine image repository diff --git a/dockerfiles/Dockerfile.lint b/dockerfiles/Dockerfile.lint index 10cc37266258..4f8e1b46b380 100644 --- a/dockerfiles/Dockerfile.lint +++ b/dockerfiles/Dockerfile.lint @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1 -ARG GO_VERSION=1.26.4 +ARG GO_VERSION=1.26.5 # ALPINE_VERSION sets the version of the alpine base image to use, including for the golang image. # It must be a supported tag in the docker.io/library/alpine image repository diff --git a/dockerfiles/Dockerfile.vendor b/dockerfiles/Dockerfile.vendor index 9c2f91a323b1..df06caaaf3ed 100644 --- a/dockerfiles/Dockerfile.vendor +++ b/dockerfiles/Dockerfile.vendor @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1 -ARG GO_VERSION=1.26.4 +ARG GO_VERSION=1.26.5 # ALPINE_VERSION sets the version of the alpine base image to use, including for the golang image. # It must be a supported tag in the docker.io/library/alpine image repository diff --git a/docs/extend/plugins_authorization.md b/docs/extend/plugins_authorization.md index 8c84d6e384d1..605fac16fa04 100644 --- a/docs/extend/plugins_authorization.md +++ b/docs/extend/plugins_authorization.md @@ -95,6 +95,18 @@ The Engine's authorization middleware fails closed: when a plugin returns an err the request is denied and the error is surfaced to the client. Plugins should also fail closed: if the plugin cannot confidently evaluate a request, it should return an error or `Allow: false`. +> [!WARNING] +> Because the plugin receives the [**raw** request body](#authzpluginauthzreq) from the daemon, it must +> apply the same decoding semantics as the daemon to be sure it evaluates the request the daemon will +> act on. The daemon decodes JSON with Go's [`encoding/json.Unmarshal`](https://pkg.go.dev/encoding/json#Unmarshal). +> +> The same requirement applies to the response body. Plugins that depend on `ResponseBody` +> inspection for redaction or content-filtering should restrict their policies to endpoints +> whose response is produced as a single write (typical of REST-style API responses). For +> commands whose responses are streamed or are likely to exceed the [buffer](#response-body-size-and-partial-buffering) through multiple +> writes, do not rely on `ResponseBody` for security-relevant decisions; perform the filtering +> in a separate layer in front of the daemon. + ### Response body size and partial buffering The internal buffer that holds the response body between the daemon's HTTP @@ -111,15 +123,6 @@ is the practical effect of this 64 KiB threshold combined with the is immediately drained to the client and is therefore no longer available for plugin inspection by the time the handler returns. -> [!NOTE] -> Plugins that depend on `ResponseBody` inspection for redaction or -> content-filtering should restrict their policies to endpoints whose -> response is produced as a single write (typical of REST-style API -> responses). For commands whose responses are streamed or are likely to -> exceed the buffer through multiple writes, do not rely on `ResponseBody` -> for security-relevant decisions; perform the filtering in a separate -> layer in front of the daemon. - During request/response processing, some authorization flows might need to do additional queries to the Docker daemon. To complete such flows, plugins can call the daemon API similar to a regular user. To enable these diff --git a/docs/reference/commandline/container_create.md b/docs/reference/commandline/container_create.md index 5bb5e18442db..d69b163389cb 100644 --- a/docs/reference/commandline/container_create.md +++ b/docs/reference/commandline/container_create.md @@ -87,7 +87,7 @@ Create a new container | `--privileged` | `bool` | | Give extended privileges to this container | | `-p`, `--publish` | `list` | | Publish a container's port(s) to the host | | `-P`, `--publish-all` | `bool` | | Publish all exposed ports to random ports | -| `--pull` | `string` | `missing` | Pull image before creating (`always`, `\|missing`, `never`) | +| `--pull` | `string` | `missing` | Pull image before creating (`always`, `missing`, `never`) | | `-q`, `--quiet` | `bool` | | Suppress the pull output | | `--read-only` | `bool` | | Mount the container's root filesystem as read only | | `--restart` | `string` | `no` | Restart policy to apply when a container exits | diff --git a/docs/reference/commandline/create.md b/docs/reference/commandline/create.md index 5a7390b7f26c..2a46bec81ab2 100644 --- a/docs/reference/commandline/create.md +++ b/docs/reference/commandline/create.md @@ -87,7 +87,7 @@ Create a new container | `--privileged` | `bool` | | Give extended privileges to this container | | `-p`, `--publish` | `list` | | Publish a container's port(s) to the host | | `-P`, `--publish-all` | `bool` | | Publish all exposed ports to random ports | -| `--pull` | `string` | `missing` | Pull image before creating (`always`, `\|missing`, `never`) | +| `--pull` | `string` | `missing` | Pull image before creating (`always`, `missing`, `never`) | | `-q`, `--quiet` | `bool` | | Suppress the pull output | | `--read-only` | `bool` | | Mount the container's root filesystem as read only | | `--restart` | `string` | `no` | Restart policy to apply when a container exits | diff --git a/docs/reference/commandline/docker.md b/docs/reference/commandline/docker.md index b926315defde..73ef948beae2 100644 --- a/docs/reference/commandline/docker.md +++ b/docs/reference/commandline/docker.md @@ -431,7 +431,7 @@ a `docker` command. You can use the following protocols: | Scheme | Description | Example | |----------------------------------------|---------------------------|----------------------------------| -| `unix://[]` | Unix socket (Linux only) | `unix:///var/run/docker.sock` | +| `unix://[]` | Unix socket | `unix:///var/run/docker.sock` | | `tcp://[[:port]]` | TCP connection | `tcp://174.17.0.1:2376` | | `ssh://[username@][:port]` | SSH connection | `ssh://user@192.168.64.5` | | `npipe://[]` | Named pipe (Windows only) | `npipe:////./pipe/docker_engine` | diff --git a/e2e/.gitignore b/e2e/.gitignore new file mode 100644 index 000000000000..262c637b7361 --- /dev/null +++ b/e2e/.gitignore @@ -0,0 +1,5 @@ +# Generated by gen-certs.sh at setup time +testdata/registry/certs/ca.crt +testdata/registry/certs/ca.key +testdata/registry/certs/tlsregistry.crt +testdata/registry/certs/tlsregistry.key diff --git a/e2e/compose-env.yaml b/e2e/compose-env.yaml index 651d5d145aee..c4f3774319ff 100644 --- a/e2e/compose-env.yaml +++ b/e2e/compose-env.yaml @@ -3,9 +3,35 @@ services: registry: image: 'registry:3' + privateregistry: + build: + context: ./testdata/registry + environment: + - REGISTRY_HTTP_ADDR=0.0.0.0:5001 + - REGISTRY_HTTP_DEBUG_ADDR=0.0.0.0:5002 + - REGISTRY_AUTH=htpasswd + - REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm + - REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd + + tlsregistry: + build: + context: ./testdata/registry + environment: + - REGISTRY_HTTP_ADDR=0.0.0.0:5003 + - REGISTRY_HTTP_DEBUG_ADDR=0.0.0.0:5004 + - REGISTRY_AUTH=htpasswd + - REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm + - REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd + - REGISTRY_HTTP_TLS_CERTIFICATE=/certs/tlsregistry.crt + - REGISTRY_HTTP_TLS_KEY=/certs/tlsregistry.key + engine: - image: 'docker:${ENGINE_VERSION:-29}-dind' + build: + context: ./testdata + dockerfile: engine/Dockerfile + args: + ENGINE_VERSION: ${ENGINE_VERSION:-29} privileged: true - command: ['--insecure-registry=registry:5000', '--experimental'] + command: ['--insecure-registry=registry:5000', '--insecure-registry=privateregistry:5001', '--experimental'] environment: - DOCKER_TLS_CERTDIR= diff --git a/e2e/container/run_test.go b/e2e/container/run_test.go index 6b35127b47a3..574a203603b9 100644 --- a/e2e/container/run_test.go +++ b/e2e/container/run_test.go @@ -209,7 +209,11 @@ func TestProcessTermination(t *testing.T) { assert.NilError(t, result.Cmd.Process.Signal(syscall.SIGTERM)) - icmd.WaitOnCmd(time.Second*10, result).Assert(t, icmd.Expected{ + // Use a generous timeout (20s) because when run through SSH connhelper, + // the Docker engine may take longer to close the attach stream after + // the container exits. This is a known timing difference across engine + // versions (e.g. engine 25 over SSH connhelper). + icmd.WaitOnCmd(time.Second*20, result).Assert(t, icmd.Expected{ ExitCode: 0, }) } diff --git a/e2e/image/private_test.go b/e2e/image/private_test.go new file mode 100644 index 000000000000..351a1983cf6f --- /dev/null +++ b/e2e/image/private_test.go @@ -0,0 +1,126 @@ +package image + +import ( + "strings" + "testing" + "time" + + "github.com/docker/cli/e2e/internal/fixtures" + "gotest.tools/v3/assert" + "gotest.tools/v3/icmd" +) + +// Regression test for https://github.com/docker/cli/issues/5963 +func TestPullPushPrivateRepository(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + registryPrefix string + tagSuffix string + }{ + {name: "insecure", registryPrefix: "privateregistry:5001", tagSuffix: "private"}, + {name: "tls", registryPrefix: "tlsregistry:5003", tagSuffix: "tls"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + dir := fixtures.SetupConfigFile(t) + t.Cleanup(dir.Remove) + emptyConfigDir := t.TempDir() + + sourceImage := fixtures.AlpineImage + privateImage := tc.registryPrefix + "/private/alpine:test-" + tc.tagSuffix + "-pull-push" + + runWithPrivateRegistryRetry(t, + icmd.Command("docker", "pull", sourceImage), + ).Assert(t, icmd.Success) + t.Cleanup(func() { + icmd.RunCommand("docker", "image", "rm", "-f", privateImage).Assert(t, icmd.Success) + }) + + icmd.RunCommand("docker", "tag", sourceImage, privateImage).Assert(t, icmd.Success) + + pushNoAuth := runWithPrivateRegistryRetry(t, + icmd.Command("docker", "push", privateImage), + fixtures.WithConfig(emptyConfigDir), + ) + pushNoAuth.Assert(t, icmd.Expected{ExitCode: 1}) + assertAuthDenied(t, pushNoAuth) + + pushWithAuth := runWithPrivateRegistryRetry(t, + icmd.Command("docker", "push", privateImage), + fixtures.WithConfig(dir.Path()), + ) + pushWithAuth.Assert(t, icmd.Success) + // Docker omits the tag in the "push refers to repository" line; strip it before asserting. + privateRepo := privateImage[:strings.LastIndex(privateImage, ":")] + assert.Check(t, strings.Contains(pushWithAuth.Combined(), "The push refers to repository ["+privateRepo+"]"), pushWithAuth.Combined()) + + icmd.RunCommand("docker", "image", "rm", "-f", privateImage).Assert(t, icmd.Success) + + pullNoAuth := runWithPrivateRegistryRetry(t, + icmd.Command("docker", "pull", privateImage), + fixtures.WithConfig(emptyConfigDir), + ) + pullNoAuth.Assert(t, icmd.Expected{ExitCode: 1}) + assertAuthDenied(t, pullNoAuth) + + pullWithAuth := runWithPrivateRegistryRetry(t, + icmd.Command("docker", "pull", privateImage), + fixtures.WithConfig(dir.Path()), + ) + pullWithAuth.Assert(t, icmd.Success) + assert.Check(t, strings.Contains(pullWithAuth.Combined(), privateImage), pullWithAuth.Combined()) + }) + } +} + +func assertAuthDenied(t *testing.T, result *icmd.Result) { + t.Helper() + output := result.Combined() + if isPrivateRegistryTransient(output) { + t.Fatalf("private registry unavailable while expecting auth failure: %s", output) + } + + assert.Assert(t, + strings.Contains(output, "requested access to the resource is denied") || + strings.Contains(output, "no basic auth credentials") || + strings.Contains(output, "unauthorized") || + strings.Contains(output, "authentication required"), + output, + ) +} + +func runWithPrivateRegistryRetry(t *testing.T, cmd icmd.Cmd, opts ...icmd.CmdOp) *icmd.Result { + t.Helper() + + deadline := time.Now().Add(90 * time.Second) + for { + result := icmd.RunCmd(cmd, opts...) + output := result.Combined() + if isPrivateRegistryTransient(output) { + if time.Now().Before(deadline) { + t.Logf("waiting for private registry availability: %s", output) + time.Sleep(500 * time.Millisecond) + continue + } + } + return result + } +} + +func isPrivateRegistryTransient(output string) bool { + return strings.Contains(output, "lookup privateregistry") || + strings.Contains(output, "lookup tlsregistry") || + strings.Contains(output, "lookup registry") || + strings.Contains(output, "no such host") || + strings.Contains(output, "server misbehaving") || + strings.Contains(output, "Temporary failure in name resolution") || + strings.Contains(output, "connection refused") || + strings.Contains(output, "i/o timeout") || + strings.Contains(output, "TLS handshake timeout") || + strings.Contains(output, "context deadline exceeded") || + strings.Contains(output, "connection reset by peer") || + strings.Contains(output, "unexpected EOF") +} diff --git a/e2e/internal/fixtures/fixtures.go b/e2e/internal/fixtures/fixtures.go index 256e14f17612..26bec1d49ce9 100644 --- a/e2e/internal/fixtures/fixtures.go +++ b/e2e/internal/fixtures/fixtures.go @@ -23,6 +23,12 @@ func SetupConfigFile(t *testing.T) fs.Dir { "auths": { "registry:5000": { "auth": "ZWlhaXM6cGFzc3dvcmQK" + }, + "privateregistry:5001": { + "auth": "ZTJlOnBhc3N3b3Jk" + }, + "tlsregistry:5003": { + "auth": "ZTJlOnBhc3N3b3Jk" } }}`), fs.WithDir("trust", fs.WithDir("private"))) return *dir diff --git a/e2e/testdata/Dockerfile.connhelper-ssh b/e2e/testdata/Dockerfile.connhelper-ssh index 61c24b6cf458..6f65ea793410 100644 --- a/e2e/testdata/Dockerfile.connhelper-ssh +++ b/e2e/testdata/Dockerfile.connhelper-ssh @@ -12,6 +12,9 @@ RUN apk --no-cache add openssl openssh-client openssh-server shadow && \ useradd --create-home --shell /bin/sh --password $(head -c32 /dev/urandom | base64) penguin && \ usermod -aG docker penguin && \ ssh-keygen -A +# Trust the tlsregistry CA so dockerd connects without --insecure-registry. +COPY registry/certs/ca.crt /usr/local/share/ca-certificates/tlsregistry-ca.crt +RUN update-ca-certificates # workaround: ssh session excludes /usr/local/bin from $PATH RUN ln -s /usr/local/bin/docker /usr/bin/docker COPY ./connhelper-ssh/entrypoint.sh / diff --git a/e2e/testdata/engine/Dockerfile b/e2e/testdata/engine/Dockerfile new file mode 100644 index 000000000000..d688a2060694 --- /dev/null +++ b/e2e/testdata/engine/Dockerfile @@ -0,0 +1,6 @@ +ARG ENGINE_VERSION +FROM docker:${ENGINE_VERSION}-dind + +# Trust the tlsregistry CA so dockerd connects without --insecure-registry. +COPY registry/certs/ca.crt /usr/local/share/ca-certificates/tlsregistry-ca.crt +RUN update-ca-certificates diff --git a/e2e/testdata/registry/Dockerfile b/e2e/testdata/registry/Dockerfile new file mode 100644 index 000000000000..26a4f63656b5 --- /dev/null +++ b/e2e/testdata/registry/Dockerfile @@ -0,0 +1,3 @@ +FROM registry:3 +COPY auth /auth +COPY certs /certs diff --git a/e2e/testdata/registry/auth/htpasswd b/e2e/testdata/registry/auth/htpasswd new file mode 100644 index 000000000000..708391c2c1cf --- /dev/null +++ b/e2e/testdata/registry/auth/htpasswd @@ -0,0 +1 @@ +e2e:$2y$05$DxRBsGSy61vZsBgNVxwUh.UtZmlg3wZHMxYcHYAlupY7r1xbIiuoq diff --git a/e2e/testdata/registry/certs/gen-certs.sh b/e2e/testdata/registry/certs/gen-certs.sh new file mode 100755 index 000000000000..4d754e631ce9 --- /dev/null +++ b/e2e/testdata/registry/certs/gen-certs.sh @@ -0,0 +1,33 @@ +#!/bin/sh +set -eu + +# Regenerate test certificates for the TLS-enabled private registry. +# Run this from the repository root or from e2e/testdata/registry/certs/. + +cd "$(dirname "$0")" + +# --- CA --- +openssl genrsa -out ca.key 2048 +openssl req -new -x509 -days 3650 \ + -key ca.key \ + -subj '/CN=Test CA (TLS Registry)' \ + -out ca.crt + +# --- Server cert for tlsregistry (signed by CA) --- +cat > openssl-tlsregistry.cnf <<-EOF + [v3_req] + subjectAltName=DNS:tlsregistry +EOF +openssl genrsa -out tlsregistry.key 2048 +openssl req -new \ + -key tlsregistry.key \ + -subj '/CN=tlsregistry' \ + -out tlsregistry.csr +openssl x509 -req -days 3650 \ + -in tlsregistry.csr \ + -CA ca.crt -CAkey ca.key \ + -CAcreateserial \ + -out tlsregistry.crt \ + -extfile openssl-tlsregistry.cnf \ + -extensions v3_req +rm -f tlsregistry.csr ca.srl openssl-tlsregistry.cnf diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index 4d47a10e6b7a..58b6bbc17587 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -88,8 +88,18 @@ func Confirm(ctx context.Context, in io.Reader, out io.Writer, message string) ( _, _ = out.Write([]byte(message)) // On Windows, force the use of the regular OS stdin stream. + // + // StdStreams() may wrap stdin with windowsconsole.NewAnsiReader to + // emulate VT input on consoles that do not support it natively, but + // that wrapper has historically caused interactive prompts to hang + // or behave incorrectly. + // + // See: + // - https://github.com/moby/moby/issues/14336 + // - https://github.com/moby/moby/issues/14210 + // - https://github.com/moby/moby/pull/17738 if runtime.GOOS == "windows" { - in = streams.NewIn(os.Stdin) + in = os.Stdin } result := make(chan bool) diff --git a/opts/throttledevice_test.go b/opts/throttledevice_test.go new file mode 100644 index 000000000000..f9f84c3eedbb --- /dev/null +++ b/opts/throttledevice_test.go @@ -0,0 +1,84 @@ +package opts + +import ( + "testing" + + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +func TestValidateThrottleBpsDevice(t *testing.T) { + tests := []struct { + doc string + input string + expectedErr string + expectedPath string + expectedRate uint64 + }{ + {doc: "plain integer", input: "/dev/sda:1000", expectedPath: "/dev/sda", expectedRate: 1000}, + {doc: "with unit", input: "/dev/sda:1mb", expectedPath: "/dev/sda", expectedRate: 1048576}, + {doc: "zero", input: "/dev/sda:0", expectedPath: "/dev/sda", expectedRate: 0}, + {doc: "missing colon", input: "/dev/sda", expectedErr: "bad format: /dev/sda"}, + {doc: "empty device", input: ":1mb", expectedErr: "bad format: :1mb"}, + {doc: "missing /dev/ prefix", input: "sda:1mb", expectedErr: "bad format for device path: sda:1mb"}, + {doc: "non-numeric rate", input: "/dev/sda:foo", expectedErr: "invalid rate for device"}, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + v, err := ValidateThrottleBpsDevice(tc.input) + if tc.expectedErr != "" { + assert.Check(t, is.ErrorContains(err, tc.expectedErr)) + assert.Check(t, is.Nil(v)) + return + } + assert.NilError(t, err) + assert.Check(t, is.Equal(v.Path, tc.expectedPath)) + assert.Check(t, is.Equal(v.Rate, tc.expectedRate)) + }) + } +} + +func TestValidateThrottleIOpsDevice(t *testing.T) { + tests := []struct { + doc string + input string + expectedErr string + expectedPath string + expectedRate uint64 + }{ + {doc: "valid integer", input: "/dev/sda:100", expectedPath: "/dev/sda", expectedRate: 100}, + {doc: "fractional rejected", input: "/dev/sda:1.5", expectedErr: "invalid rate for device"}, + {doc: "negative rejected", input: "/dev/sda:-5", expectedErr: "invalid rate for device"}, + {doc: "unit suffix rejected (iops are integers)", input: "/dev/sda:1mb", expectedErr: "invalid rate for device"}, + {doc: "missing /dev/ prefix", input: "sda:100", expectedErr: "bad format for device path: sda:100"}, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + v, err := ValidateThrottleIOpsDevice(tc.input) + if tc.expectedErr != "" { + assert.Check(t, is.ErrorContains(err, tc.expectedErr)) + assert.Check(t, is.Nil(v)) + return + } + assert.NilError(t, err) + assert.Check(t, is.Equal(v.Path, tc.expectedPath)) + assert.Check(t, is.Equal(v.Rate, tc.expectedRate)) + }) + } +} + +func TestThrottledeviceOptSetGetList(t *testing.T) { + opt := NewThrottledeviceOpt(ValidateThrottleBpsDevice) + assert.NilError(t, opt.Set("/dev/sda:1mb")) + assert.NilError(t, opt.Set("/dev/sdb:2mb")) + + list := opt.GetList() + assert.Assert(t, is.Len(list, 2)) + assert.Check(t, is.Equal(list[0].Path, "/dev/sda")) + assert.Check(t, is.Equal(list[0].Rate, uint64(1048576))) + assert.Check(t, is.Equal(list[1].Path, "/dev/sdb")) + assert.Check(t, is.Equal(list[1].Rate, uint64(2097152))) + + assert.Check(t, is.ErrorContains(opt.Set("/dev/sdc:bad"), "invalid rate for device")) + assert.Check(t, is.Equal(opt.Type(), "list")) +} diff --git a/opts/weightdevice_test.go b/opts/weightdevice_test.go new file mode 100644 index 000000000000..9c562d1b6e2d --- /dev/null +++ b/opts/weightdevice_test.go @@ -0,0 +1,57 @@ +package opts + +import ( + "testing" + + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +func TestValidateWeightDevice(t *testing.T) { + tests := []struct { + doc string + input string + expectedErr string + expectedPath string + expectedWeight uint16 + }{ + {doc: "valid minimum", input: "/dev/sda:10", expectedPath: "/dev/sda", expectedWeight: 10}, + {doc: "valid maximum", input: "/dev/sda:1000", expectedPath: "/dev/sda", expectedWeight: 1000}, + {doc: "zero is accepted (unset)", input: "/dev/sda:0", expectedPath: "/dev/sda", expectedWeight: 0}, + {doc: "below minimum", input: "/dev/sda:9", expectedErr: "invalid weight for device: /dev/sda:9"}, + {doc: "above maximum", input: "/dev/sda:1001", expectedErr: "invalid weight for device: /dev/sda:1001"}, + {doc: "overflows uint16", input: "/dev/sda:70000", expectedErr: "invalid weight for device: /dev/sda:70000"}, + {doc: "missing colon", input: "/dev/sda", expectedErr: "bad format: /dev/sda"}, + {doc: "empty device", input: ":100", expectedErr: "bad format: :100"}, + {doc: "missing /dev/ prefix", input: "sda:100", expectedErr: "bad format for device path: sda:100"}, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + v, err := ValidateWeightDevice(tc.input) + if tc.expectedErr != "" { + assert.Check(t, is.Error(err, tc.expectedErr)) + assert.Check(t, is.Nil(v)) + return + } + assert.NilError(t, err) + assert.Check(t, is.Equal(v.Path, tc.expectedPath)) + assert.Check(t, is.Equal(v.Weight, tc.expectedWeight)) + }) + } +} + +func TestWeightdeviceOptSetGetList(t *testing.T) { + opt := NewWeightdeviceOpt(ValidateWeightDevice) + assert.NilError(t, opt.Set("/dev/sda:100")) + assert.NilError(t, opt.Set("/dev/sdb:200")) + + list := opt.GetList() + assert.Assert(t, is.Len(list, 2)) + assert.Check(t, is.Equal(list[0].Path, "/dev/sda")) + assert.Check(t, is.Equal(list[0].Weight, uint16(100))) + assert.Check(t, is.Equal(list[1].Path, "/dev/sdb")) + assert.Check(t, is.Equal(list[1].Weight, uint16(200))) + + assert.Check(t, is.Error(opt.Set("/dev/sdc:1"), "invalid weight for device: /dev/sdc:1")) + assert.Check(t, is.Equal(opt.Type(), "list")) +} diff --git a/scripts/sync-branch b/scripts/sync-branch new file mode 100755 index 000000000000..ed24e507ffcc --- /dev/null +++ b/scripts/sync-branch @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Merge the given release tags. +set -Eeuo pipefail + +if [[ $# -lt 1 ]]; then + echo "usage: $0 TAG..." >&2 + exit 1 +fi + +tags_to_sync=("$@") + +for tag_to_sync in "${tags_to_sync[@]}"; do + if git merge --no-edit --no-ff "$tag_to_sync"; then + continue + fi + + if ! git rev-parse --verify --quiet MERGE_HEAD > /dev/null || git diff --quiet --diff-filter=U; then + exit 1 + fi + + git checkout "$tag_to_sync" -- '.' + git add --all + + # Can't use --no-edit with --continue + EDITOR=true git merge --continue +done + +# Check that every tag is in the branch. +# This catches cases where a merge did not actually incorporate one of the +# requested release tags. +for tag_to_sync in "${tags_to_sync[@]}"; do + if ! git merge-base --is-ancestor "$tag_to_sync" HEAD; then + echo "tag $tag_to_sync is not contained in $(git rev-parse --abbrev-ref HEAD)" >&2 + exit 1 + fi +done diff --git a/scripts/test/e2e/run b/scripts/test/e2e/run index a13359660fc6..ad6caaaa1362 100755 --- a/scripts/test/e2e/run +++ b/scripts/test/e2e/run @@ -26,8 +26,55 @@ setup() { export TEST_CONNHELPER_SSH_ID_RSA_PUB file="${file}:./e2e/compose-env.connhelper-ssh.yaml" fi + # Generate TLS certificates for the TLS-enabled private registry. + # The certs are baked into the tlsregistry and engine container images, + # so they must exist on disk before docker compose up --build. + # gen-certs.sh handles its own directory navigation. + certdir=e2e/testdata/registry/certs + missing=0 + for f in ca.crt ca.key tlsregistry.crt tlsregistry.key; do + if [ ! -f "${certdir}/${f}" ]; then + missing=1 + break + fi + done + if [ "$missing" -eq 1 ]; then + sh e2e/testdata/registry/certs/gen-certs.sh + fi + COMPOSE_PROJECT_NAME=$project COMPOSE_FILE=$file docker compose up --build -d >&2 + # Ensure supporting services exist before running tests. If one fails to start, + # fail fast and surface logs instead of waiting on downstream DNS timeouts. + local deadline=$((SECONDS + 120)) + while [ $SECONDS -lt $deadline ]; do + local ok=1 + for svc in registry privateregistry tlsregistry engine; do + cid="$(COMPOSE_PROJECT_NAME=$project COMPOSE_FILE=$file docker compose ps -q "$svc" 2>/dev/null || true)" + if [ -z "$cid" ]; then + ok=0 + break + fi + if ! docker inspect -f '{{.State.Running}}' "$cid" 2>/dev/null | grep -q true; then + ok=0 + break + fi + done + if [ "$ok" -eq 1 ]; then + break + fi + sleep 1 + done + if [ $SECONDS -ge $deadline ]; then + echo "Timed out waiting for e2e services to start" >&2 + COMPOSE_PROJECT_NAME=$project COMPOSE_FILE=$file docker compose ps >&2 || true + for svc in registry privateregistry tlsregistry engine; do + echo "--- logs: $svc ---" >&2 + COMPOSE_PROJECT_NAME=$project COMPOSE_FILE=$file docker compose logs --no-color --tail=200 "$svc" >&2 || true + done + exit 1 + fi + local network="${project}_default" # TODO: only run if inside a container docker network connect "$network" "$(hostname)" diff --git a/scripts/unmerged-tags b/scripts/unmerged-tags new file mode 100755 index 000000000000..57b90666af3c --- /dev/null +++ b/scripts/unmerged-tags @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +if [[ $# -ne 2 ]]; then + echo "usage: $0 " >&2 + exit 1 +fi + +release_branch="$1" +tag="$2" + +if [[ "$tag" == *"-rc."* ]]; then + echo "error: RC tags cannot be used as sync targets" >&2 + exit 1 +fi + +if [[ "$tag" != v* ]]; then + echo "error: Tag must start with 'v' (e.g. v29.6.0)" >&2 + exit 1 +fi + +if ! git rev-parse --verify --quiet "refs/tags/$tag" > /dev/null; then + echo "error: Tag $tag does not exist" >&2 + exit 1 +fi + +# Return early the requested tag is already merged into release branch. +if git merge-base --is-ancestor "$tag" "$release_branch"; then + exit 0 +fi + +if git rev-parse --verify --quiet upstream/master > /dev/null 2>&1; then + master="upstream/master" +else + master="origin/master" +fi + +if ! git merge-base --is-ancestor "$tag" "$master"; then + echo "error: Tag $tag is not in $master" >&2 + exit 1 +fi + +# Get all docker release tags merged into master but not into release branch +git tag --merged "$master" --no-merged "$release_branch" \ + | grep '^v' \ + | grep -v -- "-rc." \ + | sort -V \ + | awk -v tag="$tag" '{print} $0==tag{exit}' diff --git a/vendor.mod b/vendor.mod index 832b84b4a5f7..db9e9ac843c3 100644 --- a/vendor.mod +++ b/vendor.mod @@ -21,7 +21,7 @@ require ( github.com/docker/cli-docs-tool v0.11.0 github.com/docker/distribution v2.8.3+incompatible github.com/docker/docker-credential-helpers v0.9.8 - github.com/docker/go-connections v0.7.0 + github.com/docker/go-connections v0.8.0 github.com/docker/go-units v0.5.0 github.com/fvbommel/sortorder v1.1.0 github.com/go-jose/go-jose/v4 v4.1.4 @@ -31,9 +31,9 @@ require ( github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/google/uuid v1.6.0 github.com/mattn/go-runewidth v0.0.24 - github.com/moby/go-archive v0.2.0 + github.com/moby/go-archive v0.3.0 github.com/moby/moby/api v1.55.0 - github.com/moby/moby/client v0.5.0 + github.com/moby/moby/client v0.5.1 github.com/moby/patternmatcher v0.6.1 github.com/moby/swarmkit/v2 v2.1.2 github.com/moby/sys/atomicwriter v0.1.0 @@ -59,11 +59,11 @@ require ( go.opentelemetry.io/otel/sdk v1.44.0 go.opentelemetry.io/otel/sdk/metric v1.44.0 go.opentelemetry.io/otel/trace v1.44.0 - go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/sync v0.21.0 - golang.org/x/sys v0.46.0 - golang.org/x/term v0.44.0 - golang.org/x/text v0.38.0 + go.yaml.in/yaml/v3 v3.0.5 + golang.org/x/sync v0.22.0 + golang.org/x/sys v0.47.0 + golang.org/x/term v0.45.0 + golang.org/x/text v0.40.0 gotest.tools/v3 v3.5.2 tags.cncf.io/container-device-interface v1.1.0 ) @@ -87,7 +87,7 @@ require ( github.com/gorilla/mux v1.8.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.18.6 // indirect + github.com/klauspost/compress v1.18.7 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/sys/user v0.4.1 // indirect github.com/moby/sys/userns v0.1.0 // indirect @@ -103,11 +103,11 @@ require ( go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect go.opentelemetry.io/proto/otlp v1.10.0 // indirect - golang.org/x/mod v0.37.0 // indirect - golang.org/x/net v0.56.0 // indirect + golang.org/x/mod v0.38.0 // indirect + golang.org/x/net v0.57.0 // indirect golang.org/x/time v0.15.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect - google.golang.org/grpc v1.81.1 // indirect + google.golang.org/grpc v1.82.1 // indirect google.golang.org/protobuf v1.36.11 // indirect ) diff --git a/vendor.sum b/vendor.sum index 6e0a010bd05e..86c70a452ba0 100644 --- a/vendor.sum +++ b/vendor.sum @@ -42,8 +42,8 @@ github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBi github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/docker-credential-helpers v0.9.8 h1:bIREROb7So6PRlq6KTtdS9MPEjC29OQRkFNlvK2OX8Q= github.com/docker/docker-credential-helpers v0.9.8/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c= -github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= -github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-connections v0.8.0 h1:T9UlP76qPLA/HaLrcC+s4Doqqv5XsWMMUGPF5Aih/k0= +github.com/docker/go-connections v0.8.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-events v0.0.0-20260608200158-dbf6103125a4 h1:Bj+mzWc7MJqqD0UzTaPmwszW3ttOVjSFi84ZU5l+2I0= github.com/docker/go-events v0.0.0-20260608200158-dbf6103125a4/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= @@ -96,14 +96,10 @@ github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= -github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= +github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU= @@ -111,12 +107,12 @@ github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhg github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= -github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= +github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c= +github.com/moby/go-archive v0.3.0/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE= github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= -github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc= -github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s= +github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= +github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= github.com/moby/swarmkit/v2 v2.1.2 h1:1WDZAI6HVYNKdCG4zlXnTAPyLsLwuhRGWlHoOUf5Z6I= @@ -173,8 +169,6 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= @@ -230,31 +224,32 @@ go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpu go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= -golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= -golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -263,14 +258,14 @@ golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= -golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= -golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= -golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -287,14 +282,12 @@ google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1: google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= -google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= +google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go index 06fcf747ac4b..d35b105f37c6 100644 --- a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go +++ b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go @@ -1,21 +1,19 @@ package sockets import ( + "context" "net" "sync" ) -// dummyAddr is used to satisfy net.Addr for the in-mem socket -// it is just stored as a string and returns the string for all calls -type dummyAddr string +// inmemAddr is used to satisfy net.Addr for the in-memory socket. +type inmemAddr string // Network returns the addr string, satisfies net.Addr -func (a dummyAddr) Network() string { - return string(a) -} +func (a inmemAddr) Network() string { return "inmem" } // String returns the string form -func (a dummyAddr) String() string { +func (a inmemAddr) String() string { return string(a) } @@ -23,7 +21,7 @@ func (a dummyAddr) String() string { type InmemSocket struct { chConn chan net.Conn chClose chan struct{} - addr dummyAddr + addr inmemAddr mu sync.Mutex } @@ -34,7 +32,7 @@ func NewInmemSocket(addr string, bufSize int) *InmemSocket { return &InmemSocket{ chConn: make(chan net.Conn, bufSize), chClose: make(chan struct{}), - addr: dummyAddr(addr), + addr: inmemAddr(addr), } } @@ -67,15 +65,41 @@ func (s *InmemSocket) Close() error { return nil } -// Dial is used to establish a connection with the in-mem server. -// It returns a [net.ErrClosed] if the connection is already closed. +// Dial establishes a connection with the in-memory listener. +// +// The network and addr parameters are accepted for compatibility with +// conventional dialer APIs but are currently ignored. +// +// It is equivalent to calling DialContext with context.Background(). +// It returns [net.ErrClosed] if the listener has already been closed. func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { + return s.DialContext(context.Background(), network, addr) +} + +// DialContext establishes a connection with the in-memory listener. +// +// The network and addr parameters are accepted for compatibility with +// conventional dialer APIs but are currently ignored. +// +// If ctx is canceled before the connection is established, DialContext +// returns the context error. It returns [net.ErrClosed] if the listener +// has already been closed. +func (s *InmemSocket) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + srvConn, clientConn := net.Pipe() select { case s.chConn <- srvConn: + return clientConn, nil + case <-ctx.Done(): + _ = srvConn.Close() + _ = clientConn.Close() + return nil, ctx.Err() case <-s.chClose: + _ = srvConn.Close() + _ = clientConn.Close() return nil, net.ErrClosed } - - return clientConn, nil } diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go index e736f71d38b1..1f7b7cd95eed 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket.go @@ -47,38 +47,69 @@ For example: package sockets import ( + "errors" + "fmt" "net" "os" + "runtime" "syscall" ) +const supportsAbstractSockets = runtime.GOOS == "linux" + // SockOption sets up socket file's creating option type SockOption func(string) error -// NewUnixSocketWithOpts creates a unix socket with the specified options. -// By default, socket permissions are 0000 (i.e.: no access for anyone); pass -// WithChmod() and WithChown() to set the desired ownership and permissions. +// NewUnixSocketWithOpts creates a Unix socket with the specified options. +// +// On Unix platforms, socket permissions are 0000 by default, i.e. no access +// for anyone. Pass WithChmod() and WithChown() to set the desired permissions +// and ownership. +// +// On Windows, the socket uses Windows ACLs. Pass WithBasePermissions() to allow +// Administrators and LocalSystem full access, or WithAdditionalUsersAndGroups() +// to also grant generic read and write access to additional users or groups. // -// This function temporarily changes the system's "umask" to 0777 to work around -// a race condition between creating the socket and setting its permissions. While -// this should only be for a short duration, it may affect other processes that -// create files/directories during that period. +// Abstract Unix sockets (Go's Linux-specific "@" shorthand and the native +// leading-NUL representation) are supported only on Linux. On other platforms, +// attempts to use abstract socket addresses return an error. Because abstract +// sockets have no filesystem representation, filesystem-specific socket +// options are not supported. +// +// On platforms without abstract Unix socket support, attempts to use abstract +// socket addresses return an error wrapping [errors.ErrUnsupported]. func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err + if isAbstractSocket(path) { + if !supportsAbstractSockets { + return nil, fmt.Errorf("abstract Unix socket %q is not supported on %s: %w", path, runtime.GOOS, errors.ErrUnsupported) + } + for _, opt := range opts { + if err := opt(path); err != nil { + return nil, err + } + } + return net.Listen("unix", path) } - - l, err := listenUnix(path) - if err != nil { + if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } - for _, op := range opts { - if err := op(path); err != nil { - _ = l.Close() - return nil, err - } - } + return listenUnix(path, opts...) +} - return l, nil +// isAbstractSocket reports whether path is an abstract Unix socket address. +// +// Go recognizes two representations of abstract socket addresses: +// +// - On Linux, a path beginning with '@' is translated by the standard library +// to the kernel's native leading-NUL representation. +// See https://pkg.go.dev/net@go1.27rc2#UnixAddr. +// +// - A path beginning with a NUL byte uses the kernel's native representation +// directly. See https://github.com/golang/go/issues/78615. +// +// The interpretation of these addresses is platform-dependent; this helper only +// recognizes the syntax. +func isAbstractSocket(path string) bool { + return len(path) > 0 && (path[0] == '@' || path[0] == 0) } diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go new file mode 100644 index 000000000000..59860610c3a1 --- /dev/null +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_linux.go @@ -0,0 +1,25 @@ +package sockets + +import ( + "os" + "strconv" + "strings" + "syscall" +) + +// maxListenerBacklog returns the maximum length of the queue of pending +// connections for a listening socket. +// +// It is similar to in stdlib, but without the fallbacks for Kernel < 4.1.0; +// https://github.com/golang/go/blob/go1.26.3/src/net/sock_linux.go#L33-L53 +func maxListenerBacklog() int { + b, err := os.ReadFile("/proc/sys/net/core/somaxconn") + if err != nil { + return syscall.SOMAXCONN + } + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || n <= 0 { + return syscall.SOMAXCONN + } + return n +} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_nolinux.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_nolinux.go new file mode 100644 index 000000000000..e269c7d75b45 --- /dev/null +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_nolinux.go @@ -0,0 +1,39 @@ +//go:build !linux && !windows + +package sockets + +import ( + "runtime" + "syscall" +) + +// maxListenerBacklog is similar to the equivalent in stdlib; +// https://github.com/golang/go/blob/go1.26.3/src/net/sock_bsd.go#L14-L39 +func maxListenerBacklog() int { + var ( + n uint32 + err error + ) + switch runtime.GOOS { + case "darwin", "ios": + n, err = syscall.SysctlUint32("kern.ipc.somaxconn") + case "freebsd": + n, err = syscall.SysctlUint32("kern.ipc.soacceptqueue") + case "netbsd": + // NOTE: NetBSD has no somaxconn-like kernel state so far + case "openbsd": + n, err = syscall.SysctlUint32("kern.somaxconn") + default: + return syscall.SOMAXCONN + } + if n == 0 || err != nil { + return syscall.SOMAXCONN + } + // FreeBSD stores the backlog in a uint16, as does Linux. + // Assume the other BSDs do too. Truncate number to avoid wrapping. + // See issue 5030. + if n > 1<<16-1 { + n = 1<<16 - 1 + } + return int(n) +} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go index a41a71654742..2bc1c1b44bf3 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_unix.go @@ -3,14 +3,35 @@ package sockets import ( + "errors" + "fmt" "net" "os" + "sync" "syscall" ) -// WithChown modifies the socket file's uid and gid +// defaultSocketPerms is the default permission mode applied to newly created +// Unix sockets. Sockets are created inaccessible by default; callers can +// override this by passing [WithChmod]. +// +// TODO(thaJeztah): Consider changing the default to 0o600, making the socket usable by its owner by default. +const defaultSocketPerms os.FileMode = 0o000 + +// WithChown modifies the socket file's uid and gid. +// +// Abstract Unix sockets have no filesystem representation, so this option +// returns an error wrapping [errors.ErrUnsupported] when used with an abstract +// socket. func WithChown(uid, gid int) SockOption { return func(path string) error { + if isAbstractSocket(path) { + return &os.PathError{ + Op: "chown", + Path: path, + Err: fmt.Errorf("abstract Unix sockets do not support filesystem permissions: %w", errors.ErrUnsupported), + } + } if err := os.Chown(path, uid, gid); err != nil { return err } @@ -19,8 +40,19 @@ func WithChown(uid, gid int) SockOption { } // WithChmod modifies socket file's access mode. +// +// Abstract Unix sockets have no filesystem representation, so this option +// returns an error wrapping [errors.ErrUnsupported] when used with an abstract +// socket. func WithChmod(mask os.FileMode) SockOption { return func(path string) error { + if isAbstractSocket(path) { + return &os.PathError{ + Op: "chmod", + Path: path, + Err: fmt.Errorf("abstract Unix sockets do not support filesystem permissions: %w", errors.ErrUnsupported), + } + } if err := os.Chmod(path, mask); err != nil { return err } @@ -28,27 +60,90 @@ func WithChmod(mask os.FileMode) SockOption { } } -// NewUnixSocket creates a unix socket with the specified path and group. +// NewUnixSocket creates a Unix socket with the specified path and group. +// +// On Unix platforms, the socket is owned by root:gid and has permissions 0660. +// +// Abstract Unix sockets are not supported by this helper. Use [NewUnixSocketWithOpts] +// without filesystem permission options instead. func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0o660)) } -func listenUnix(path string) (net.Listener, error) { - // net.Listen does not allow for permissions to be set. As a result, when - // specifying custom permissions ("WithChmod()"), there is a short time - // between creating the socket and applying the permissions, during which - // the socket permissions are Less restrictive than desired. +func listenUnix(path string, opts ...SockOption) (_ net.Listener, retErr error) { + // net.Listen does not allow permissions or ownership to be set between + // bind(2), which creates the socket path, and listen(2), which makes it + // possible for clients to connect. // - // To work around this limitation of net.Listen(), we temporarily set the - // umask to 0777, which forces the socket to be created with 000 permissions - // (i.e.: no access for anyone). After that, WithChmod() must be used to set - // the desired permissions. + // Creating the socket manually lets us apply options after bind(2), but + // before listen(2). This avoids temporarily relaxing the process umask while + // still preventing a socket from becoming connectable before the requested + // permissions are applied. // - // We don't use "defer" here, to reset the umask to its original value as soon - // as possible. Ideally we'd be able to detect if WithChmod() was passed as - // an option, and skip changing umask if default permissions are used. - origUmask := syscall.Umask(0o777) - l, err := net.Listen("unix", path) - syscall.Umask(origUmask) - return l, err + // See https://github.com/golang/go/issues/11822 + + // Similar to sysSocket in stdlib, but without the fast path for Linux. + // https://github.com/golang/go/blob/go1.26.3/src/net/sys_cloexec.go#L18-L36 + syscall.ForkLock.RLock() + fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + if err == nil { + syscall.CloseOnExec(fd) // No syscall.SOCK_CLOEXEC on macOS. + } + syscall.ForkLock.RUnlock() + if err != nil { + return nil, os.NewSyscallError("socket", err) + } + + defer func() { + if fd >= 0 { + _ = syscall.Close(fd) + } + }() + + if err := syscall.Bind(fd, &syscall.SockaddrUnix{Name: path}); err != nil { + return nil, os.NewSyscallError("bind", err) + } + + defer func() { + if retErr != nil { + _ = syscall.Unlink(path) + } + }() + + // Secure by default: the socket is not accessible at all + // unless permission options are set through WithChmod. + if err := os.Chmod(path, defaultSocketPerms); err != nil { + return nil, err + } + + for _, op := range opts { + if err := op(path); err != nil { + return nil, err + } + } + + if err := syscall.Listen(fd, listenerBacklog()); err != nil { + return nil, os.NewSyscallError("listen", err) + } + + f := os.NewFile(uintptr(fd), "unix:"+path) + fd = -1 // f now owns the original fd; prevent the defer from closing it. + + // FileListener duplicates f, sets the duplicate close-on-exec and nonblocking, + // and returns a net.Listener backed by that duplicate. The temporary *os.File + // is no longer needed after this point. + l, err := net.FileListener(f) + _ = f.Close() + if err != nil { + return nil, err + } + + if ul, ok := l.(*net.UnixListener); ok { + ul.SetUnlinkOnClose(true) + } + + return l, nil } + +// listenerBacklog is a caching wrapper around maxListenerBacklog. +var listenerBacklog = sync.OnceValue(maxListenerBacklog) diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go b/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go index 01aee5f11a5b..a9a9e80d5012 100644 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go +++ b/vendor/github.com/docker/go-connections/sockets/unix_socket_windows.go @@ -48,7 +48,7 @@ func WithAdditionalUsersAndGroups(additionalUsersAndGroups []string) SockOption } sd, err := getSecurityDescriptor(additionalUsersAndGroups...) if err != nil { - return fmt.Errorf("looking up SID: %w", err) + return err } return withSDDL(sd)(path) } @@ -85,12 +85,15 @@ func withSDDL(sddl string) SockOption { } } -// NewUnixSocket creates a new unix socket. +// NewUnixSocket creates a new Unix socket. // // It sets [BasePermissions] on the socket path and grants the given additional // users and groups to generic read (GR) and write (GW) access. It returns // an error when failing to resolve any of the additional users and groups, // or when failing to apply the ACL. +// +// Abstract Unix sockets are not supported by this helper. Attempts to use +// abstract socket addresses return an error wrapping [errors.ErrUnsupported]. func NewUnixSocket(path string, additionalUsersAndGroups []string) (net.Listener, error) { var opts []SockOption if len(additionalUsersAndGroups) > 0 { @@ -103,27 +106,38 @@ func NewUnixSocket(path string, additionalUsersAndGroups []string) (net.Listener // getSecurityDescriptor returns the DACL for the Unix socket. // -// By default, it grants [BasePermissions], but allows for additional -// users and groups to get generic read (GR) and write (GW) access. It -// returns an error when failing to resolve any of the additional users -// and groups. +// By default, it grants [BasePermissions]. Additional users and groups +// are granted generic read (GR) and write (GW) access. It returns an +// error if any name cannot be resolved to a SID. func getSecurityDescriptor(additionalUsersAndGroups ...string) (string, error) { sddl := BasePermissions // Grant generic read (GR) and write (GW) access to whatever // additional users or groups were specified. // - // TODO(thaJeztah): should we fail on, or remove duplicates? + // We keep duplicates; two identical allow ACEs are redundant, + // but they do not create conflicting permissions, so should not error. + // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/20233ed8-a6c6-4097-aafa-dd545ed24428 for _, g := range additionalUsersAndGroups { sid, err := winio.LookupSidByName(strings.TrimSpace(g)) if err != nil { return "", fmt.Errorf("looking up SID: %w", err) } - sddl += fmt.Sprintf("(A;;GRGW;;;%s)", sid) + sddl += "(A;;GRGW;;;" + sid + ")" } return sddl, nil } -func listenUnix(path string) (net.Listener, error) { - return net.Listen("unix", path) +func listenUnix(path string, opts ...SockOption) (net.Listener, error) { + l, err := net.Listen("unix", path) + if err != nil { + return nil, err + } + for _, op := range opts { + if err := op(path); err != nil { + _ = l.Close() + return nil, err + } + } + return l, nil } diff --git a/vendor/github.com/moby/go-archive/.golangci.yml b/vendor/github.com/moby/go-archive/.golangci.yml index 21439e5c6951..761e36d9d944 100644 --- a/vendor/github.com/moby/go-archive/.golangci.yml +++ b/vendor/github.com/moby/go-archive/.golangci.yml @@ -9,6 +9,7 @@ issues: linters: enable: - errorlint + - gosec - unconvert - unparam exclusions: @@ -16,7 +17,18 @@ linters: presets: - comments - std-error-handling + rules: + # Ignore "G204: Subprocess launched with a potential tainted input or cmd arguments" + - path: '(.+)_test\.go' + linters: + - gosec + text: 'G204: Subprocess launched' settings: + gosec: + excludes: + - G301 # Expect directory permissions to be 0750 or less + - G304 # Potential file inclusion via variable + - G306 # Expect WriteFile permissions to be 0600 or less staticcheck: # Enable all options, with some exceptions. # For defaults, see https://golangci-lint.run/usage/linters/#staticcheck diff --git a/vendor/github.com/moby/go-archive/archive.go b/vendor/github.com/moby/go-archive/archive.go index 8dce2e6e2afa..4d9e87d20490 100644 --- a/vendor/github.com/moby/go-archive/archive.go +++ b/vendor/github.com/moby/go-archive/archive.go @@ -8,9 +8,11 @@ import ( "fmt" "io" "os" + "path" "path/filepath" "runtime" "strings" + "sync" "syscall" "time" @@ -46,9 +48,18 @@ type ( // TarOptions wraps the tar options. TarOptions struct { - IncludeFiles []string - ExcludePatterns []string - Compression compression.Compression + // IncludeFiles lists archive-relative paths to include. + // Paths use POSIX ('/') separators. + IncludeFiles []string + + // ExcludePatterns lists archive-relative exclude patterns. + // Patterns use POSIX ('/') separators, matching patternmatcher semantics. + ExcludePatterns []string + Compression compression.Compression + // NoLchown disables applying ownership from the archive to extracted files + // and directories. Despite its historical name, it applies to all ownership + // changes, leaving extracted filesystem objects owned by the user performing + // the extraction. NoLchown bool IDMap user.IdentityMapping ChownOpts *ChownOpts @@ -86,10 +97,33 @@ func NewDefaultArchiver() *Archiver { return &Archiver{Untar: Untar} } -// breakoutError is used to differentiate errors related to breaking out -// When testing archive breakout in the unit tests, this error is expected -// in order for the test to pass. -type breakoutError error +// isPathEscapes reports whether err is os.Root's path-containment error. +// +// os.Root currently returns an unexported errPathEscapes sentinel, so callers +// cannot detect it with errors.Is. Keep the string comparison isolated here +// until Go exports the error; see https://go.dev/issue/74640. +func isPathEscapes(err error) bool { + // https://github.com/golang/go/blob/go1.26.5/src/os/file.go#L421 + const errPathEscapes = "path escapes from parent" + for err != nil { + if errors.Unwrap(err) == nil { + return err.Error() == errPathEscapes + } + err = errors.Unwrap(err) + } + return false +} + +// breakoutErr marks errors caused by archive breakout attempts. +// Unit tests use it to distinguish expected breakout failures from other +// errors. +type breakoutErr struct{ error } + +func breakoutError(err error) error { + return &breakoutErr{error: err} +} + +func (e *breakoutErr) Unwrap() error { return e.error } const ( AUFSWhiteoutFormat WhiteoutFormat = 0 // AUFSWhiteoutFormat is the default format for whiteouts @@ -98,17 +132,17 @@ const ( // IsArchivePath checks if the (possibly compressed) file at the given path // starts with a tar file header. -func IsArchivePath(path string) bool { - file, err := os.Open(path) +func IsArchivePath(filePath string) bool { + file, err := os.Open(filePath) if err != nil { return false } - defer file.Close() + defer func() { _ = file.Close() }() rdr, err := compression.DecompressStream(file) if err != nil { return false } - defer rdr.Close() + defer func() { _ = rdr.Close() }() r := tar.NewReader(rdr) _, err = r.Next() return err == nil @@ -129,8 +163,10 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi go func() { tarReader := tar.NewReader(inputTarStream) tarWriter := tar.NewWriter(pipeWriter) - defer inputTarStream.Close() - defer tarWriter.Close() + defer func() { + _ = tarWriter.Close() + _ = inputTarStream.Close() + }() modify := func(name string, original *tar.Header, modifier TarModifierFunc, tarReader io.Reader) error { header, data, err := modifier(name, original, tarReader) @@ -164,7 +200,7 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi break } if err != nil { - pipeWriter.CloseWithError(err) + _ = pipeWriter.CloseWithError(err) return } @@ -172,11 +208,11 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi if !ok { // No modifiers for this file, copy the header and data if err := tarWriter.WriteHeader(originalHeader); err != nil { - pipeWriter.CloseWithError(err) + _ = pipeWriter.CloseWithError(err) return } if err := copyWithBuffer(tarWriter, tarReader); err != nil { - pipeWriter.CloseWithError(err) + _ = pipeWriter.CloseWithError(err) return } continue @@ -184,7 +220,7 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi delete(mods, originalHeader.Name) if err := modify(originalHeader.Name, originalHeader, modifier, tarReader); err != nil { - pipeWriter.CloseWithError(err) + _ = pipeWriter.CloseWithError(err) return } } @@ -192,12 +228,12 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi // Apply the modifiers that haven't matched any files in the archive for name, modifier := range mods { if err := modify(name, nil, modifier, nil); err != nil { - pipeWriter.CloseWithError(err) + _ = pipeWriter.CloseWithError(err) return } } - pipeWriter.Close() + _ = pipeWriter.Close() }() return pipeReader } @@ -218,7 +254,7 @@ func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, erro hdr.ModTime = hdr.ModTime.Truncate(time.Second) hdr.AccessTime = time.Time{} hdr.ChangeTime = time.Time{} - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) + hdr.Mode = chmodTarEntry(hdr.Mode) hdr.Name = canonicalTarName(name, fi.IsDir()) return hdr, nil } @@ -227,7 +263,7 @@ const paxSchilyXattr = "SCHILY.xattr." // ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem // to a tar header -func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { +func ReadSecurityXattrToTarHeader(filePath string, hdr *tar.Header) error { const ( // Values based on linux/include/uapi/linux/capability.h xattrCapsSz2 = 20 @@ -235,7 +271,7 @@ func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { vfsCapRevision2 = 2 vfsCapRevision3 = 3 ) - capability, _ := lgetxattr(path, "security.capability") + capability, _ := lgetxattr(filePath, "security.capability") if capability != nil { if capability[versionOffset] == vfsCapRevision3 { // Convert VFS_CAP_REVISION_3 to VFS_CAP_REVISION_2 as root UID makes no @@ -253,7 +289,7 @@ func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { type tarWhiteoutConverter interface { ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error) - ConvertRead(*tar.Header, string) (bool, error) + ConvertRead(*os.Root, *tar.Header, string) (bool, error) } type tarAppender struct { @@ -292,9 +328,10 @@ func canonicalTarName(name string, isDir bool) string { return name } -// addTarFile adds to the tar archive a file from `path` as `name` -func (ta *tarAppender) addTarFile(path, name string) error { - fi, err := os.Lstat(path) +// addTarFile adds to the tar archive a file from `srcPath` as `name` +func (ta *tarAppender) addTarFile(srcPath, archivePath string) error { + archivePath = filepath.ToSlash(archivePath) + fi, err := os.Lstat(srcPath) if err != nil { return err } @@ -302,17 +339,17 @@ func (ta *tarAppender) addTarFile(path, name string) error { var link string if fi.Mode()&os.ModeSymlink != 0 { var err error - link, err = os.Readlink(path) + link, err = os.Readlink(srcPath) if err != nil { return err } } - hdr, err := FileInfoHeader(name, fi, link) + hdr, err := FileInfoHeader(archivePath, fi, link) if err != nil { return err } - if err := ReadSecurityXattrToTarHeader(path, hdr); err != nil { + if err := ReadSecurityXattrToTarHeader(srcPath, hdr); err != nil { return err } @@ -321,7 +358,7 @@ func (ta *tarAppender) addTarFile(path, name string) error { if !fi.IsDir() && hasHardlinks(fi) { inode, err := getInodeFromStat(fi.Sys()) if err != nil { - return err + return fmt.Errorf("unexpected file info for %q: %w", srcPath, err) } // a link should have a name that it links too // and that linked name should be first in the tar archive @@ -330,7 +367,7 @@ func (ta *tarAppender) addTarFile(path, name string) error { hdr.Linkname = oldpath hdr.Size = 0 // This Must be here for the writer math to add up! } else { - ta.SeenFiles[inode] = name + ta.SeenFiles[inode] = hdr.Name } } @@ -341,7 +378,7 @@ func (ta *tarAppender) addTarFile(path, name string) error { // handle re-mapping container ID mappings back to host ID mappings before // writing tar headers/files. We skip whiteout files because they were written // by the kernel and already have proper ownership relative to the host - if !isOverlayWhiteout && !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() { + if !isOverlayWhiteout && !strings.HasPrefix(path.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() { uid, gid, err := getFileUIDGID(fi.Sys()) if err != nil { return err @@ -359,7 +396,7 @@ func (ta *tarAppender) addTarFile(path, name string) error { } if ta.WhiteoutConverter != nil { - wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi) + wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, srcPath, fi) if err != nil { return err } @@ -370,12 +407,12 @@ func (ta *tarAppender) addTarFile(path, name string) error { // hdr may have been updated to be a whiteout with returning // a whiteout header if wo != nil { + if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { + return fmt.Errorf("tar: cannot use whiteout for non-empty file %q", hdr.Name) + } if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } - if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { - return fmt.Errorf("tar: cannot use whiteout for non-empty file") - } hdr = wo } } @@ -387,13 +424,13 @@ func (ta *tarAppender) addTarFile(path, name string) error { if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { // We use sequential file access to avoid depleting the standby list on // Windows. On Linux, this equates to a regular os.Open. - file, err := sequential.Open(path) + file, err := sequential.Open(srcPath) if err != nil { return err } err = copyWithBuffer(ta.TarWriter, file) - file.Close() + _ = file.Close() if err != nil { return err } @@ -402,7 +439,10 @@ func (ta *tarAppender) addTarFile(path, name string) error { return nil } -func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, opts *TarOptions) error { +// createTarFile extracts a single tar entry into the given root. dstPath is the +// root-relative path of the entry being extracted, in native (host-separator) +// form so it can be passed directly to os.Root methods and fsRootPath. +func createTarFile(root *os.Root, dstPath string, hdr *tar.Header, reader io.Reader, opts *TarOptions) error { var ( Lchown = true inUserns, bestEffortXattrs bool @@ -424,18 +464,24 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o switch hdr.Typeflag { case tar.TypeDir: - // Create directory unless it exists as a directory already. - // In that case we just want to merge the two - if fi, err := os.Lstat(path); err != nil || !fi.IsDir() { - if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { + // Create directory unless it already exists as one; merge in that case. + // os.Root.Mkdir only accepts the nine least-significant permission + // bits; special bits (setuid, setgid, sticky) are applied afterward + // by handleLChmod via root.Chmod. + if fi, err := root.Lstat(dstPath); err != nil || !fi.IsDir() { + if err := root.Mkdir(dstPath, hdrInfo.Mode()&0o777); err != nil { return err } } case tar.TypeReg: - // Source is regular file. We use sequential file access to avoid depleting - // the standby list on Windows. On Linux, this equates to a regular os.OpenFile. - file, err := sequential.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) + // Source is a regular file. Use os.Root.OpenFile so that all + // path resolution is bounded within root using openat(2) semantics. + // os.Root.OpenFile only accepts the nine least-significant permission + // bits; special bits are applied afterward by handleLChmod. + // We use sequential file access to avoid depleting the standby list + // on Windows (go1.26). On Linux, this equates to a regular os.OpenFile. + file, err := root.OpenFile(dstPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC|windows_O_FILE_FLAG_SEQUENTIAL_SCAN, hdrInfo.Mode()&0o777) if err != nil { return err } @@ -447,47 +493,47 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o case tar.TypeBlock, tar.TypeChar: if inUserns { // cannot create devices in a userns - log.G(context.TODO()).WithFields(log.Fields{"path": path, "type": hdr.Typeflag}).Debug("skipping device nodes in a userns") + log.G(context.TODO()).WithFields(log.Fields{"path": dstPath, "type": hdr.Typeflag}).Debug("skipping device nodes in a userns") return nil } - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { + if err := handleTarTypeBlockCharFifo(root, hdr, dstPath); err != nil { return err } case tar.TypeFifo: - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { + if err := handleTarTypeBlockCharFifo(root, hdr, dstPath); err != nil { if inUserns && errors.Is(err, syscall.EPERM) { // In most cases, cannot create a fifo if running in user namespace - log.G(context.TODO()).WithFields(log.Fields{"error": err, "path": path, "type": hdr.Typeflag}).Debug("creating fifo node in a userns") + log.G(context.TODO()).WithFields(log.Fields{"error": err, "path": dstPath, "type": hdr.Typeflag}).Debug("creating fifo node in a userns") return nil } return err } case tar.TypeLink: - // #nosec G305 -- The target path is checked for path traversal. - targetPath := filepath.Join(extractDir, hdr.Linkname) - // check for hardlink breakout - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) + // Defence in depth: root.Link's containment is limited when + // dest is a volume root. + linkname := path.Clean(hdr.Linkname) + if linkname == "." || !filepath.IsLocal(linkname) { + return breakoutError(fmt.Errorf("invalid hardlink target %q", hdr.Linkname)) } - if err := os.Link(targetPath, path); err != nil { + if err := root.Link(filepath.FromSlash(linkname), dstPath); err != nil { return err } case tar.TypeSymlink: - // path -> hdr.Linkname = targetPath - // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file - targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // #nosec G305 -- The target path is checked for path traversal. - - // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because - // that symlink would first have to be created, which would be caught earlier, at this very check: - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) - } - if err := os.Symlink(hdr.Linkname, path); err != nil { + // Symlink targets are archive data, not filesystem paths. Preserve the + // target verbatim rather than cleaning or converting it (filepath.FromSlash). + linkTarget := hdr.Linkname + + // os.Root.Symlink contains the symlink's location (newname) within + // root but stores the target (oldname) verbatim, so absolute targets + // such as /usr/lib -- common and legitimate in container images -- are + // preserved rather than rejected. The symlink node is therefore always + // created within root via openat(2) semantics, without resolving to an + // absolute path; containment applies when the symlink is followed, not + // at creation. + if err := root.Symlink(linkTarget, dstPath); err != nil { return err } @@ -504,22 +550,31 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o if chownOpts == nil { chownOpts = &ChownOpts{UID: hdr.Uid, GID: hdr.Gid} } - if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { + if err := root.Lchown(dstPath, chownOpts.UID, chownOpts.GID); err != nil { var msg string if inUserns && errors.Is(err, syscall.EINVAL) { msg = " (try increasing the number of subordinate IDs in /etc/subuid and /etc/subgid)" } - return fmt.Errorf("failed to Lchown %q for UID %d, GID %d%s: %w", path, hdr.Uid, hdr.Gid, msg, err) + return fmt.Errorf("failed to Lchown %q for UID %d, GID %d%s: %w", dstPath, hdr.Uid, hdr.Gid, msg, err) } } var xattrErrs []string + absPath := sync.OnceValues(func() (string, error) { + return fsRootPath(root.Name(), dstPath) + }) for key, value := range hdr.PAXRecords { xattr, ok := strings.CutPrefix(key, paxSchilyXattr) if !ok { continue } - if err := lsetxattr(path, xattr, []byte(value), 0); err != nil { + // os.Root has no xattr support; use the absolute path derived from + // the root so the path remains bounded. + ap, err := absPath() + if err != nil { + return err + } + if err := lsetxattr(ap, xattr, []byte(value), 0); err != nil { if bestEffortXattrs && errors.Is(err, syscall.ENOTSUP) || errors.Is(err, syscall.EPERM) { // EPERM occurs if modifying xattrs is not allowed. This can // happen when running in userns with restrictions (ChromeOS). @@ -538,39 +593,43 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode - if err := handleLChmod(hdr, path, hdrInfo); err != nil { + if err := handleLChmod(root, dstPath, hdr, hdrInfo); err != nil { return err } aTime := boundTime(latestTime(hdr.AccessTime, hdr.ModTime)) mTime := boundTime(hdr.ModTime) - // chtimes doesn't support a NOFOLLOW flag atm - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := chtimes(path, aTime, mTime); err != nil { + switch hdr.Typeflag { + case tar.TypeSymlink: + // Apply timestamps to the symlink itself (AT_SYMLINK_NOFOLLOW). + if err := lchtimes(root, dstPath, aTime, mTime); err != nil { + return err + } + case tar.TypeLink: + // Follow the hardlink only when its target is not itself a symlink. + fi, err := root.Lstat(filepath.FromSlash(path.Clean(hdr.Linkname))) + if err == nil && fi.Mode()&os.ModeSymlink == 0 { + if err := chtimes(root, dstPath, aTime, mTime); err != nil { return err } } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := chtimes(path, aTime, mTime); err != nil { - return err - } - } else { - if err := lchtimes(path, aTime, mTime); err != nil { + default: + // All other file types follow symlinks. + if err := chtimes(root, dstPath, aTime, mTime); err != nil { return err } } return nil } -// Tar creates an archive from the directory at `path`, and returns it as a +// Tar creates an archive from the directory at `srcPath`, and returns it as a // stream of bytes. -func Tar(path string, comp compression.Compression) (io.ReadCloser, error) { - return TarWithOptions(path, &TarOptions{Compression: comp}) +func Tar(srcPath string, comp compression.Compression) (io.ReadCloser, error) { + return TarWithOptions(srcPath, &TarOptions{Compression: comp}) } -// TarWithOptions creates an archive from the directory at `path`, only including files whose relative +// TarWithOptions creates an archive from the directory at `srcPath`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { tb, err := NewTarballer(srcPath, options) @@ -803,11 +862,28 @@ func (t *Tarballer) Do() { } } +// unpackedDir records a directory whose mtime must be restored after all +// entries are extracted, along with the root-relative entry name used during +// extraction. +type unpackedDir struct { + hdr *tar.Header + name string // root-relative entry name +} + // Unpack unpacks the decompressedArchive to dest with options. func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { + if options == nil { + options = &TarOptions{} + } + root, err := os.OpenRoot(dest) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tr := tar.NewReader(decompressedArchive) - var dirs []*tar.Header + var dirs []unpackedDir whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat) // Iterate through the files in the archive. @@ -828,48 +904,50 @@ loop: continue } - // Normalize name, for safety and for a simple is-root check - // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: - // This keeps "..\" as-is, but normalizes "\..\" to "\". - hdr.Name = filepath.Clean(hdr.Name) - + // Strip a leading "/" so absolute entries stay root-relative, and + // normalize the POSIX tar path. Skip entries referring to the extraction + // root and reject paths that escape it. + name := path.Clean(strings.TrimLeft(hdr.Name, "/")) + if name == "." { + continue + } + if !filepath.IsLocal(name) { + return breakoutError(fmt.Errorf("invalid entry name %q", hdr.Name)) + } for _, exclude := range options.ExcludePatterns { - if strings.HasPrefix(hdr.Name, exclude) { + if strings.HasPrefix(name, exclude) { continue loop } } - // Ensure that the parent directory exists. - err = createImpliedDirectories(dest, hdr, options) - if err != nil { - return err - } + hdr.Name = name - // #nosec G305 -- The joined path is checked for path traversal. - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return err - } - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) + // Skip entries whose name (or hardlink target) Windows cannot represent. + if err := unrepresentableOnWindows(hdr); err != nil { + log.G(context.TODO()).Warnf("Windows: ignoring entry: %v", err) + continue loop } - // If path exits we almost always just want to remove and replace it + // dstPath is the native (host-separator) form of the entry name, + // used at all filesystem boundaries (os.Root methods, fsRootPath). + // hdr.Name stays POSIX (forward-slash) for logical string checks. + dstPath := filepath.FromSlash(hdr.Name) + + // If dstPath exists we almost always just want to remove and replace it. // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { + if fi, err := root.Lstat(dstPath); err == nil { if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing directory with a non-directory from the archive. - return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) + return fmt.Errorf("cannot overwrite directory %q with non-directory %q", hdr.Name, dest) } if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing non-directory with a directory from the archive. - return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) + return fmt.Errorf("cannot overwrite non-directory %q with directory %q", hdr.Name, dest) } if fi.IsDir() && hdr.Name == "." { @@ -877,7 +955,7 @@ loop: } if !fi.IsDir() || hdr.Typeflag != tar.TypeDir { - if err := os.RemoveAll(path); err != nil { + if err := root.RemoveAll(dstPath); err != nil { return err } } @@ -887,8 +965,16 @@ loop: return err } + // Ensure that the parent directory exists. + // + // This must be done before whiteoutConverter.ConvertRead, which + // may set xattrs on the directory or create whiteout files. + if err := createImpliedDirectories(root, hdr, options); err != nil { + return err + } + if whiteoutConverter != nil { - writeFile, err := whiteoutConverter.ConvertRead(hdr, path) + writeFile, err := whiteoutConverter.ConvertRead(root, hdr, dstPath) if err != nil { return err } @@ -897,51 +983,122 @@ loop: } } - if err := createTarFile(path, dest, hdr, tr, options); err != nil { + if err := createTarFile(root, dstPath, hdr, tr, options); err != nil { return err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) + dirs = append(dirs, unpackedDir{hdr: hdr, name: dstPath}) } } - for _, hdr := range dirs { - // #nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. - path := filepath.Join(dest, hdr.Name) - - if err := chtimes(path, boundTime(latestTime(hdr.AccessTime, hdr.ModTime)), boundTime(hdr.ModTime)); err != nil { + for _, d := range dirs { + aTime := boundTime(latestTime(d.hdr.AccessTime, d.hdr.ModTime)) + if err := chtimes(root, d.name, aTime, boundTime(d.hdr.ModTime)); err != nil { return err } } return nil } +// unrepresentableOnWindows returns an error describing why a tar entry cannot +// be faithfully created on Windows, or nil if it can (always on non-Windows). +// On Windows ":" is illegal in a filename and "\" is a path separator, so a tar +// name or hardlink target containing them (they use POSIX semantics) would be +// misinterpreted by os.Root (e.g. "a\b" resolved as two components). Symlink +// targets are stored verbatim (not resolved at creation), so they are exempt. +func unrepresentableOnWindows(hdr *tar.Header) error { + if runtime.GOOS != "windows" { + return nil + } + if strings.ContainsAny(hdr.Name, `:\`) { + return fmt.Errorf("entry name %q contains a character Windows cannot represent in a path", hdr.Name) + } + // A hardlink target is resolved within the root by os.Root.Link; a symlink + // target is stored verbatim, so only hardlinks need the target checked. + if hdr.Typeflag == tar.TypeLink && strings.ContainsAny(hdr.Linkname, `:\`) { + return fmt.Errorf("hardlink target %q contains a character Windows cannot represent in a path", hdr.Linkname) + } + return nil +} + // createImpliedDirectories will create all parent directories of the current path with default permissions, if they do // not already exist. This is possible as the tar format supports 'implicit' directories, where their existence is // defined by the paths of files in the tar, but there are no header entries for the directories themselves, and thus // we most both create them and choose metadata like permissions. // -// The caller should have performed filepath.Clean(hdr.Name), so hdr.Name will now be in the filepath format for the OS -// on which the daemon is running. This precondition is required because this function assumes a OS-specific path -// separator when checking that a path is not the root. -func createImpliedDirectories(dest string, hdr *tar.Header, options *TarOptions) error { - // Not the root directory, ensure that the parent directory exists - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - // RootPair() is confined inside this loop as most cases will not require a call, so we can spend some - // unneeded function calls in the uncommon case to encapsulate logic -- implied directories are a niche - // usage that reduces the portability of an image. - uid, gid := options.IDMap.RootPair() - - err = user.MkdirAllAndChown(parentPath, ImpliedDirectoryMode, uid, gid, user.WithOnlyNew) +// The caller must have normalized hdr.Name (no leading ".." components). +// All directory creation is performed via root so it is bounded within the +// destination at the OS level (openat(2) semantics), preventing escape via +// symlinks in the destination tree. +func createImpliedDirectories(root *os.Root, hdr *tar.Header, options *TarOptions) error { + // For non-directory entries, ensure that the parent directory exists. + if hdr.Typeflag != tar.TypeDir { + parent := filepath.FromSlash(path.Dir(strings.TrimSuffix(hdr.Name, "/"))) + // Skip when the parent is the root itself; nothing to create. + if parent == "." || parent == "" { + return nil + } + if _, err := root.Lstat(parent); err == nil { + return nil + } else if !os.IsNotExist(err) { + return err + } + // RootPair() is confined inside this loop as most cases will not require a call, so we can spend some + // unneeded function calls in the uncommon case to encapsulate logic -- implied directories are a niche + // usage that reduces the portability of an image. + uid, gid := options.IDMap.RootPair() + + // Similar to [user.MkdirAllAndChown] + // + // [user.MkdirAllAndChown]: https://pkg.go.dev/github.com/moby/sys/user#MkdirAllAndChown + var cur string + for c := range strings.SplitSeq(parent, string(os.PathSeparator)) { + if c == "" { + continue + } + cur = filepath.Join(cur, c) + if err := root.Mkdir(cur, ImpliedDirectoryMode); err != nil { + if !errors.Is(err, os.ErrExist) { + return err + } + + fi, err := root.Stat(cur) + if err != nil { + return err + } + if fi.IsDir() { + continue + } + return &os.PathError{Op: "mkdir", Path: cur, Err: syscall.ENOTDIR} + } + if options.NoLchown { + continue + } + // Only the successful Mkdir case is newly-created. + dir, err := root.Open(cur) if err != nil { return err } + if uid != 0 || gid != 0 { + if err := dir.Chown(uid, gid); err != nil { + _ = dir.Close() + return err + } + } + // root.Mkdir applies the mode subject to the process umask, so + // re-apply it with Chmod to guarantee ImpliedDirectoryMode + // independent of umask, matching the previous MkdirAllAndChown + // behavior. + if err := dir.Chmod(ImpliedDirectoryMode); err != nil { + _ = dir.Close() + return err + } + if err := dir.Close(); err != nil { + return err + } } } @@ -974,9 +1131,6 @@ func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decomp if options == nil { options = &TarOptions{} } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } r := tarArchive if decompress { @@ -984,7 +1138,7 @@ func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decomp if err != nil { return err } - defer decompressedArchive.Close() + defer func() { _ = decompressedArchive.Close() }() r = decompressedArchive } @@ -998,7 +1152,7 @@ func (archiver *Archiver) TarUntar(src, dst string) error { if err != nil { return err } - defer archive.Close() + defer func() { _ = archive.Close() }() return archiver.Untar(archive, dst, &TarOptions{ IDMap: archiver.IDMapping, }) @@ -1010,7 +1164,7 @@ func (archiver *Archiver) UntarPath(src, dst string) error { if err != nil { return err } - defer archive.Close() + defer func() { _ = archive.Close() }() return archiver.Untar(archive, dst, &TarOptions{ IDMap: archiver.IDMapping, }) @@ -1070,13 +1224,13 @@ func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { defer close(errC) errC <- func() error { - defer w.Close() + defer func() { _ = w.Close() }() srcF, err := os.Open(src) if err != nil { return err } - defer srcF.Close() + defer func() { _ = srcF.Close() }() hdr, err := tarheader.FileInfoHeaderNoLookups(srcSt, "") if err != nil { @@ -1087,14 +1241,14 @@ func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { hdr.AccessTime = time.Time{} hdr.ChangeTime = time.Time{} hdr.Name = filepath.Base(dst) - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) + hdr.Mode = chmodTarEntry(hdr.Mode) if err := remapIDs(archiver.IDMapping, hdr); err != nil { return err } tw := tar.NewWriter(w) - defer tw.Close() + defer func() { _ = tw.Close() }() if err := tw.WriteHeader(hdr); err != nil { return err } @@ -1112,7 +1266,7 @@ func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { err = archiver.Untar(r, filepath.Dir(dst), nil) if err != nil { - r.CloseWithError(err) + _ = r.CloseWithError(err) } return err } diff --git a/vendor/github.com/moby/go-archive/archive_linux.go b/vendor/github.com/moby/go-archive/archive_linux.go index 7b6c3e02b643..9341bc59978a 100644 --- a/vendor/github.com/moby/go-archive/archive_linux.go +++ b/vendor/github.com/moby/go-archive/archive_linux.go @@ -4,6 +4,7 @@ import ( "archive/tar" "fmt" "os" + "path" "path/filepath" "strings" @@ -13,36 +14,43 @@ import ( func getWhiteoutConverter(format WhiteoutFormat) tarWhiteoutConverter { if format == OverlayWhiteoutFormat { - return overlayWhiteoutConverter{} + return newOverlayWhiteoutConverter() } return nil } -type overlayWhiteoutConverter struct{} +type overlayWhiteoutConverter struct { + opaqueXattr string +} + +func newOverlayWhiteoutConverter() overlayWhiteoutConverter { + opaqueXattr := "trusted.overlay.opaque" + if userns.RunningInUserNS() { + opaqueXattr = "user.overlay.opaque" + } + return overlayWhiteoutConverter{ + opaqueXattr: opaqueXattr, + } +} -func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (wo *tar.Header, _ error) { +func (c overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, filePath string, fi os.FileInfo) (wo *tar.Header, _ error) { // convert whiteouts to AUFS format if fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 { // we just rename the file and make it normal - dir, filename := filepath.Split(hdr.Name) - hdr.Name = filepath.Join(dir, WhiteoutPrefix+filename) + dir, filename := path.Split(hdr.Name) + hdr.Name = path.Join(dir, WhiteoutPrefix+filename) hdr.Mode = 0o600 hdr.Typeflag = tar.TypeReg hdr.Size = 0 } - if fi.Mode()&os.ModeDir == 0 { + if !fi.IsDir() { // FIXME(thaJeztah): return a sentinel error instead of nil, nil return nil, nil } - opaqueXattrName := "trusted.overlay.opaque" - if userns.RunningInUserNS() { - opaqueXattrName = "user.overlay.opaque" - } - // convert opaque dirs to AUFS format by writing an empty file with the prefix - opaque, err := lgetxattr(path, opaqueXattrName) + opaque, err := lgetxattr(filePath, c.opaqueXattr) if err != nil { return nil, err } @@ -50,14 +58,14 @@ func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os // FIXME(thaJeztah): return a sentinel error instead of nil, nil return nil, nil } - delete(hdr.PAXRecords, paxSchilyXattr+opaqueXattrName) + delete(hdr.PAXRecords, paxSchilyXattr+c.opaqueXattr) // create a header for the whiteout file // it should inherit some properties from the parent, but be a regular file return &tar.Header{ Typeflag: tar.TypeReg, Mode: hdr.Mode & int64(os.ModePerm), - Name: filepath.Join(hdr.Name, WhiteoutOpaqueDir), // #nosec G305 -- An archive is being created, not extracted. + Name: path.Join(hdr.Name, WhiteoutOpaqueDir), // #nosec G305 -- An archive is being created, not extracted. Size: 0, Uid: hdr.Uid, Uname: hdr.Uname, @@ -68,40 +76,67 @@ func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os }, nil } -func (c overlayWhiteoutConverter) ConvertRead(hdr *tar.Header, path string) (bool, error) { - base := filepath.Base(path) - dir := filepath.Dir(path) +func (c overlayWhiteoutConverter) ConvertRead(root *os.Root, hdr *tar.Header, filePath string) (bool, error) { + base := filepath.Base(filePath) + dir := filepath.Dir(filePath) - // if a directory is marked as opaque by the AUFS special file, we need to translate that to overlay - if base == WhiteoutOpaqueDir { - opaqueXattrName := "trusted.overlay.opaque" - if userns.RunningInUserNS() { - opaqueXattrName = "user.overlay.opaque" + switch base { + case WhiteoutPrefix, WhiteoutPrefix + ".", WhiteoutPrefix + "..": + return false, fmt.Errorf("invalid whiteout entry %q", hdr.Name) + + case WhiteoutOpaqueDir: + parent, err := root.Open(dir) + if err != nil { + return false, err } + defer parent.Close() - err := unix.Setxattr(dir, opaqueXattrName, []byte{'y'}, 0) + // If a directory is marked as opaque by the AUFS special file, we need to translate that to overlay. + if err := unix.Fsetxattr(int(parent.Fd()), c.opaqueXattr, []byte{'y'}, 0); err != nil { + return false, fmt.Errorf("fsetxattr('%s', %s=y): %w", dir, c.opaqueXattr, err) + } + // Don't write the whiteout file itself. + return false, nil + + default: + originalBase, ok := strings.CutPrefix(base, WhiteoutPrefix) + if !ok { + // Regular file. + return true, nil + } + + parent, err := root.Open(dir) if err != nil { - return false, fmt.Errorf("setxattr('%s', %s=y): %w", dir, opaqueXattrName, err) + return false, err } - // don't write the file itself - return false, err - } + defer parent.Close() - // if a file was deleted and we are using overlay, we need to create a character device - if strings.HasPrefix(base, WhiteoutPrefix) { - originalBase := base[len(WhiteoutPrefix):] + // If a file was deleted, and we are using overlay, we need to create a character device. originalPath := filepath.Join(dir, originalBase) - - if err := unix.Mknod(originalPath, unix.S_IFCHR, 0); err != nil { + if err := unix.Mknodat(int(parent.Fd()), originalBase, unix.S_IFCHR, 0); err != nil { return false, fmt.Errorf("failed to mknod('%s', S_IFCHR, 0): %w", originalPath, err) } - if err := os.Chown(originalPath, hdr.Uid, hdr.Gid); err != nil { - return false, err + + // Header IDs have already been remapped. Optimize the common non-remapped + // root-owned (0:0) case by assuming the created whiteout has the expected + // ownership, rather than comparing against the effective UID/GID or stat'ing + // the created node to verify it. + if hdr.Uid != 0 || hdr.Gid != 0 { + // TODO(thaJeztah): Revisit whether whiteout ownership needs to be preserved. + // + // This was added in the original overlay whiteout implementation: + // https://github.com/moby/moby/pull/18560 / https://github.com/moby/moby/pull/22126 + // + // OverlayFS documents whiteouts in terms of a character device with device + // number 0:0, not ownership: https://docs.kernel.org/filesystems/overlayfs.html#whiteouts-and-opaque-directories + // + // If ownership is not required, this Fchownat can be removed to avoid the remaining TOCTOU window. + if err := unix.Fchownat(int(parent.Fd()), originalBase, hdr.Uid, hdr.Gid, unix.AT_SYMLINK_NOFOLLOW); err != nil { + return false, &os.PathError{Op: "lchown", Path: originalPath, Err: err} + } } - // don't write the file itself + // Don't write the whiteout file itself. return false, nil } - - return true, nil } diff --git a/vendor/github.com/moby/go-archive/archive_unix.go b/vendor/github.com/moby/go-archive/archive_unix.go index 3a9f5b0b5863..e2dcc4290fa4 100644 --- a/vendor/github.com/moby/go-archive/archive_unix.go +++ b/vendor/github.com/moby/go-archive/archive_unix.go @@ -5,7 +5,10 @@ package archive import ( "archive/tar" "errors" + "fmt" + "math" "os" + "path" "path/filepath" "strings" "syscall" @@ -13,6 +16,8 @@ import ( "golang.org/x/sys/unix" ) +var errInvalidArchive = errors.New("invalid archive") + // addLongPathPrefix adds the Windows long path prefix to the path provided if // it does not already have it. It is a no-op on platforms other than Windows. func addLongPathPrefix(srcPath string) string { @@ -29,20 +34,19 @@ func getWalkRoot(srcPath string, include string) string { // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { - return perm // noop for unix as golang APIs provide perm bits correctly +func chmodTarEntry(mode int64) int64 { + return mode // noop for unix as golang APIs provide perm bits correctly } -func getInodeFromStat(stat interface{}) (uint64, error) { +func getInodeFromStat(stat any) (uint64, error) { s, ok := stat.(*syscall.Stat_t) if !ok { - // FIXME(thaJeztah): this should likely return an error; see https://github.com/moby/moby/pull/49493#discussion_r1979152897 - return 0, nil + return 0, fmt.Errorf("unexpected stat type %T", stat) } return s.Ino, nil } -func getFileUIDGID(stat interface{}) (int, int, error) { +func getFileUIDGID(stat any) (int, int, error) { s, ok := stat.(*syscall.Stat_t) if !ok { @@ -56,7 +60,7 @@ func getFileUIDGID(stat interface{}) (int, int, error) { // // Creating device nodes is not supported when running in a user namespace, // produces a [syscall.EPERM] in most cases. -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { +func handleTarTypeBlockCharFifo(root *os.Root, hdr *tar.Header, dstPath string) error { mode := uint32(hdr.Mode & 0o7777) switch hdr.Typeflag { case tar.TypeBlock: @@ -67,20 +71,90 @@ func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { mode |= unix.S_IFIFO } - return mknod(path, mode, unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor))) + // Devmajor and Devminor come straight from the (untrusted) tar header as + // int64, but Mkdev only takes uint32. Casting a value that does not fit + // silently truncates it, so the node created on disk would carry a + // different major/minor than the header declares. Reject those instead of + // creating a mismatched device. + if hdr.Devmajor < 0 || hdr.Devmajor > math.MaxUint32 || + hdr.Devminor < 0 || hdr.Devminor > math.MaxUint32 { + return fmt.Errorf("device number %d:%d for %q out of range: %w", hdr.Devmajor, hdr.Devminor, hdr.Name, errInvalidArchive) + } + + // Prefer mknodat; fall back to a bounded path where unavailable. + return mknodInRoot(root, dstPath, mode, unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor))) } -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err +// handleLChmod applies the mode from hdrInfo to dstPath within root, skipping +// symlinks (there is no lchmod). For hardlinks, the mode is applied only when +// the link target is itself not a symlink. +func handleLChmod(root *os.Root, dstPath string, hdr *tar.Header, hdrInfo os.FileInfo) error { + switch hdr.Typeflag { + case tar.TypeSymlink: + return nil + + case tar.TypeLink: + // If the target is a symlink, there is no way to chmod the hardlink + // without following it. + fi, err := root.Lstat(filepath.FromSlash(path.Clean(hdr.Linkname))) + if err != nil || fi.Mode()&os.ModeSymlink != 0 { + return nil } + return chmodNoSymlink(root, dstPath, hdrInfo.Mode()) + + default: + return chmodNoSymlink(root, dstPath, hdrInfo.Mode()) + } +} + +// chmodNoSymlink applies mode to a non-symlink entry. +// +// Callers must have already excluded symlink entries. +func chmodNoSymlink(root *os.Root, name string, mode os.FileMode) error { + parent, err := root.OpenFile(filepath.Dir(name), os.O_RDONLY, 0) + if err != nil { + return err + } + defer parent.Close() + + base := filepath.Base(name) + perm := fileModeToPerm(mode) + // #nosec G115 -- ignore integer overflow conversion for parent.Fd + if err := unix.Fchmodat(int(parent.Fd()), base, perm, unix.AT_SYMLINK_NOFOLLOW); err == nil { + return nil + } else if !errors.Is(err, syscall.EOPNOTSUPP) { + return &os.PathError{Op: "fchmodat2", Path: name, Err: err} + } + + // Fallback for systems that cannot perform fchmodat with AT_SYMLINK_NOFOLLOW. + // Open the entry without following symlinks and apply the mode through the + // resulting file descriptor. + // #nosec G115 -- ignore integer overflow conversion for parent.Fd + fd, err := unix.Openat(int(parent.Fd()), base, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return &os.PathError{Op: "openat", Path: name, Err: err} + } + defer unix.Close(fd) + + if err := unix.Fchmod(fd, perm); err != nil { + return &os.PathError{Op: "fchmod", Path: name, Err: err} } return nil } + +// fileModeToPerm returns the subset of an os.FileMode that can be applied +// by chmod. +func fileModeToPerm(mode os.FileMode) uint32 { + perm := uint32(mode.Perm()) + + if mode&os.ModeSetuid != 0 { + perm |= unix.S_ISUID + } + if mode&os.ModeSetgid != 0 { + perm |= unix.S_ISGID + } + if mode&os.ModeSticky != 0 { + perm |= unix.S_ISVTX + } + return perm +} diff --git a/vendor/github.com/moby/go-archive/archive_windows.go b/vendor/github.com/moby/go-archive/archive_windows.go index 0e3e316afc2f..ffe00a44d0a5 100644 --- a/vendor/github.com/moby/go-archive/archive_windows.go +++ b/vendor/github.com/moby/go-archive/archive_windows.go @@ -33,30 +33,31 @@ func getWalkRoot(srcPath string, include string) string { // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { +func chmodTarEntry(mode int64) int64 { // Remove group- and world-writable bits. - perm &= 0o755 + mode &= 0o755 // Add the x bit: make everything +x on Windows - return perm | 0o111 + return mode | 0o111 } -func getInodeFromStat(stat interface{}) (uint64, error) { +func getInodeFromStat(stat any) (uint64, error) { // do nothing. no notion of Inode in stat on Windows return 0, nil } // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { +func handleTarTypeBlockCharFifo(root *os.Root, hdr *tar.Header, path string) error { return nil } -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { +// handleLChmod is a no-op on Windows because chmod is not supported. +func handleLChmod(root *os.Root, path string, hdr *tar.Header, hdrInfo os.FileInfo) error { return nil } -func getFileUIDGID(stat interface{}) (int, int, error) { +func getFileUIDGID(stat any) (int, int, error) { // no notion of file ownership mapping yet on Windows return 0, 0, nil } diff --git a/vendor/github.com/moby/go-archive/changes.go b/vendor/github.com/moby/go-archive/changes.go index 02a0372c6f99..c5d647c030d2 100644 --- a/vendor/github.com/moby/go-archive/changes.go +++ b/vendor/github.com/moby/go-archive/changes.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "io/fs" + "maps" "os" "path/filepath" "sort" @@ -217,8 +218,8 @@ func (info *FileInfo) LookUp(path string) *FileInfo { return info } - pathElements := strings.Split(path, string(os.PathSeparator)) - for _, elem := range pathElements { + pathElements := strings.SplitSeq(path, string(os.PathSeparator)) + for elem := range pathElements { if elem != "" { child := parent.children[elem] if child == nil { @@ -256,9 +257,7 @@ func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { // otherwise any previous delete/change is considered recursive oldChildren := make(map[string]*FileInfo) if oldInfo != nil && info.isDir() { - for k, v := range oldInfo.children { - oldChildren[k] = v - } + maps.Copy(oldChildren, oldInfo.children) } for name, newChild := range info.children { @@ -401,7 +400,7 @@ func ExportChanges(dir string, changes []Change, idMap user.IdentityMapping) (io whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) timestamp := time.Now() hdr := &tar.Header{ - Name: whiteOut[1:], + Name: strings.TrimPrefix(filepath.ToSlash(whiteOut), "/"), Size: 0, ModTime: timestamp, AccessTime: timestamp, @@ -411,9 +410,10 @@ func ExportChanges(dir string, changes []Change, idMap user.IdentityMapping) (io log.G(context.TODO()).Debugf("Can't write whiteout header: %s", err) } } else { - path := filepath.Join(dir, change.Path) - if err := ta.addTarFile(path, change.Path[1:]); err != nil { - log.G(context.TODO()).Debugf("Can't add file %s to tar: %s", path, err) + srcPath := filepath.Join(dir, change.Path) + archivePath := strings.TrimPrefix(filepath.ToSlash(change.Path), "/") + if err := ta.addTarFile(srcPath, archivePath); err != nil { + log.G(context.TODO()).Debugf("Can't add file %s to tar: %s", srcPath, err) } } } diff --git a/vendor/github.com/moby/go-archive/changes_linux.go b/vendor/github.com/moby/go-archive/changes_linux.go index 8289fe17d906..39ec7475f4ea 100644 --- a/vendor/github.com/moby/go-archive/changes_linux.go +++ b/vendor/github.com/moby/go-archive/changes_linux.go @@ -265,7 +265,7 @@ func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) } func clen(n []byte) int { - for i := 0; i < len(n); i++ { + for i := range n { if n[i] == 0 { return i } diff --git a/vendor/github.com/moby/go-archive/changes_other.go b/vendor/github.com/moby/go-archive/changes_other.go index a8a3a5a6faa8..7eb195d500ec 100644 --- a/vendor/github.com/moby/go-archive/changes_other.go +++ b/vendor/github.com/moby/go-archive/changes_other.go @@ -26,7 +26,7 @@ func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, err }() // block until both routines have returned - for i := 0; i < 2; i++ { + for range 2 { if err := <-errs; err != nil { return nil, nil, err } diff --git a/vendor/github.com/moby/go-archive/compression/compression.go b/vendor/github.com/moby/go-archive/compression/compression.go index e298cefb3249..824267924d8c 100644 --- a/vendor/github.com/moby/go-archive/compression/compression.go +++ b/vendor/github.com/moby/go-archive/compression/compression.go @@ -66,7 +66,7 @@ type nopWriteCloser struct { func (nopWriteCloser) Close() error { return nil } var bufioReader32KPool = &sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, 32*1024) }, + New: func() any { return bufio.NewReaderSize(nil, 32*1024) }, } type bufferedReader struct { @@ -217,7 +217,7 @@ func gzipDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) { log.G(ctx).Debugf("Using %s to decompress", unpigzPath) - return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) + return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) // #nosec G204 -- Subprocess launched with variable } // cmdStream executes a command, and returns its stdout as a stream. diff --git a/vendor/github.com/moby/go-archive/copy.go b/vendor/github.com/moby/go-archive/copy.go index 77d038c42310..7447e8bd106b 100644 --- a/vendor/github.com/moby/go-archive/copy.go +++ b/vendor/github.com/moby/go-archive/copy.go @@ -22,7 +22,7 @@ var ( ) var copyPool = sync.Pool{ - New: func() interface{} { s := make([]byte, 32*1024); return &s }, + New: func() any { s := make([]byte, 32*1024); return &s }, } func copyWithBuffer(dst io.Writer, src io.Reader) error { @@ -316,16 +316,40 @@ func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir } } +// newNameRebaser returns a function that replaces oldBase with newBase at the +// beginning of POSIX-style archive entry names. It converts oldBase and newBase +// to forward-slash form and trims trailing slashes. +// +// When rebasing from the archive root, the returned function removes all +// leading slashes from names. It otherwise preserves the remainder verbatim +// and does not clean or canonicalize paths. +func newNameRebaser(oldBase, newBase string) func(string) string { + oldBase = strings.TrimRight(filepath.ToSlash(oldBase), "/") + newBase = strings.TrimRight(filepath.ToSlash(newBase), "/") + + if oldBase == "" { + return func(name string) string { + name = strings.TrimLeft(name, "/") + if newBase == "" { + return name + } + return newBase + "/" + name + } + } + + return func(name string) string { + suffix, ok := strings.CutPrefix(name, oldBase) + if !ok || suffix != "" && !strings.HasPrefix(suffix, "/") { + return name + } + return newBase + suffix + } +} + // RebaseArchiveEntries rewrites the given srcContent archive replacing // an occurrence of oldBase with newBase at the beginning of entry names. func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.ReadCloser { - if oldBase == string(os.PathSeparator) { - // If oldBase specifies the root directory, use an empty string as - // oldBase instead so that newBase doesn't replace the path separator - // that all paths will start with. - oldBase = "" - } - + rebase := newNameRebaser(oldBase, newBase) rebased, w := io.Pipe() go func() { @@ -336,12 +360,12 @@ func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.Read hdr, err := srcTar.Next() if errors.Is(err, io.EOF) { // Signals end of archive. - rebasedTar.Close() - w.Close() + _ = rebasedTar.Close() + _ = w.Close() return } if err != nil { - w.CloseWithError(err) + _ = w.CloseWithError(err) return } @@ -353,13 +377,13 @@ func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.Read // // To fix, set the format to PAX here. See docker/for-linux issue #484. hdr.Format = tar.FormatPAX - hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) + hdr.Name = rebase(hdr.Name) if hdr.Typeflag == tar.TypeLink { - hdr.Linkname = strings.Replace(hdr.Linkname, oldBase, newBase, 1) + hdr.Linkname = rebase(hdr.Linkname) } if err = rebasedTar.WriteHeader(hdr); err != nil { - w.CloseWithError(err) + _ = w.CloseWithError(err) return } @@ -374,7 +398,7 @@ func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.Read // not be vulnerable to this code consuming memory. //nolint:gosec // G110: Potential DoS vulnerability via decompression bomb (gosec) if _, err = io.Copy(rebasedTar, srcTar); err != nil { - w.CloseWithError(err) + _ = w.CloseWithError(err) return } } @@ -408,7 +432,7 @@ func CopyResource(srcPath, dstPath string, followLink bool) error { if err != nil { return err } - defer content.Close() + defer func() { _ = content.Close() }() return CopyTo(content, srcInfo, dstPath) } @@ -427,14 +451,12 @@ func CopyTo(content io.Reader, srcInfo CopyInfo, dstPath string) error { if err != nil { return err } - defer copyArchive.Close() + defer func() { _ = copyArchive.Close() }() - options := &TarOptions{ + return Untar(copyArchive, dstDir, &TarOptions{ NoLchown: true, NoOverwriteDirNonDir: true, - } - - return Untar(copyArchive, dstDir, options) + }) } // ResolveHostSourcePath decides real path need to be copied with parameters such as diff --git a/vendor/github.com/moby/go-archive/dev_darwin.go b/vendor/github.com/moby/go-archive/dev_darwin.go new file mode 100644 index 000000000000..fcfe730ce0a8 --- /dev/null +++ b/vendor/github.com/moby/go-archive/dev_darwin.go @@ -0,0 +1,21 @@ +//go:build darwin + +package archive + +import ( + "os" + + "golang.org/x/sys/unix" +) + +func mknod(path string, mode uint32, dev uint64) error { + return unix.Mknod(path, mode, int(dev)) // #nosec G115 -- Required conversion for the platform-specific Mknod API. +} + +func mknodInRoot(root *os.Root, path string, mode uint32, dev uint64) error { + abs, err := fsRootPath(root.Name(), path) + if err != nil { + return err + } + return unix.Mknod(abs, mode, int(dev)) // #nosec G115 -- Required conversion for the platform-specific Mknod API. +} diff --git a/vendor/github.com/moby/go-archive/dev_freebsd.go b/vendor/github.com/moby/go-archive/dev_freebsd.go index b3068fce9110..d18e829b0507 100644 --- a/vendor/github.com/moby/go-archive/dev_freebsd.go +++ b/vendor/github.com/moby/go-archive/dev_freebsd.go @@ -2,8 +2,23 @@ package archive -import "golang.org/x/sys/unix" +import ( + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) func mknod(path string, mode uint32, dev uint64) error { return unix.Mknod(path, mode, dev) } + +func mknodInRoot(root *os.Root, path string, mode uint32, dev uint64) error { + parent, err := root.OpenFile(filepath.Dir(path), os.O_RDONLY|unix.O_DIRECTORY, 0) + if err != nil { + return err + } + defer parent.Close() + + return unix.Mknodat(int(parent.Fd()), filepath.Base(path), mode, dev) +} diff --git a/vendor/github.com/moby/go-archive/dev_unix.go b/vendor/github.com/moby/go-archive/dev_unix.go index dffc596f93f7..0eb8b6da5cea 100644 --- a/vendor/github.com/moby/go-archive/dev_unix.go +++ b/vendor/github.com/moby/go-archive/dev_unix.go @@ -1,9 +1,24 @@ -//go:build !windows && !freebsd +//go:build !darwin && !freebsd && !windows package archive -import "golang.org/x/sys/unix" +import ( + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) func mknod(path string, mode uint32, dev uint64) error { - return unix.Mknod(path, mode, int(dev)) + return unix.Mknod(path, mode, int(dev)) // #nosec G115 -- Required conversion for the platform-specific Mknod API. +} + +func mknodInRoot(root *os.Root, path string, mode uint32, dev uint64) error { + parent, err := root.OpenFile(filepath.Dir(path), os.O_RDONLY|unix.O_DIRECTORY, 0) + if err != nil { + return err + } + defer parent.Close() + + return unix.Mknodat(int(parent.Fd()), filepath.Base(path), mode, int(dev)) // #nosec G115 -- Required conversion for the platform-specific Mknod API. } diff --git a/vendor/github.com/moby/go-archive/diff.go b/vendor/github.com/moby/go-archive/diff.go index 96db972d1383..055f3c11ee6b 100644 --- a/vendor/github.com/moby/go-archive/diff.go +++ b/vendor/github.com/moby/go-archive/diff.go @@ -7,8 +7,8 @@ import ( "fmt" "io" "os" + "path" "path/filepath" - "runtime" "strings" "github.com/containerd/log" @@ -20,17 +20,22 @@ import ( // compressed or uncompressed. // Returns the size in bytes of the contents of the layer. func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) { + root, err := os.OpenRoot(dest) + if err != nil { + return 0, err + } + defer root.Close() + tr := tar.NewReader(layer) - var dirs []*tar.Header + var dirs []unpackedDir + // unpackedPaths tracks root-relative paths already written in this layer + // so that the AUFS opaque-whiteout walk knows which paths to preserve. unpackedPaths := make(map[string]struct{}) if options == nil { options = &TarOptions{} } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } aufsTempdir := "" aufsHardlinks := make(map[string]*tar.Header) @@ -48,32 +53,26 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, size += hdr.Size - // Normalize name, for safety and for a simple is-root check - hdr.Name = filepath.Clean(hdr.Name) - - // Windows does not support filenames with colons in them. Ignore - // these files. This is not a problem though (although it might - // appear that it is). Let's suppose a client is running docker pull. - // The daemon it points to is Windows. Would it make sense for the - // client to be doing a docker pull Ubuntu for example (which has files - // with colons in the name under /usr/share/man/man3)? No, absolutely - // not as it would really only make sense that they were pulling a - // Windows image. However, for development, it is necessary to be able - // to pull Linux images which are in the repository. - // - // TODO Windows. Once the registry is aware of what images are Windows- - // specific or Linux-specific, this warning should be changed to an error - // to cater for the situation where someone does manage to upload a Linux - // image but have it tagged as Windows inadvertently. - if runtime.GOOS == "windows" { - if strings.Contains(hdr.Name, ":") { - log.G(context.TODO()).Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) - continue - } + // Strip a leading "/" so absolute entries stay root-relative, and + // normalize the POSIX tar path. Skip entries referring to the extraction + // root and reject paths that escape it. + name := path.Clean(strings.TrimLeft(hdr.Name, "/")) + if name == "." { + continue + } + if !filepath.IsLocal(name) { + return 0, breakoutError(fmt.Errorf("invalid entry name %q", hdr.Name)) + } + hdr.Name = name + + // Skip entries whose name (or hardlink target) Windows cannot represent. + if err := unrepresentableOnWindows(hdr); err != nil { + log.G(context.TODO()).Warnf("Windows: ignoring entry: %v", err) + continue } // Ensure that the parent directory exists. - err = createImpliedDirectories(dest, hdr, options) + err = createImpliedDirectories(root, hdr, options) if err != nil { return 0, err } @@ -84,7 +83,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, // We don't want this directory, but we need the files in them so that // such hardlinks can be resolved. if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { - basename := filepath.Base(hdr.Name) + basename := path.Base(hdr.Name) aufsHardlinks[basename] = hdr if aufsTempdir == "" { if aufsTempdir, err = os.MkdirTemp(dest, "dockerplnk"); err != nil { @@ -92,47 +91,63 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, } defer os.RemoveAll(aufsTempdir) } - if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, options); err != nil { + aufsRoot, err := os.OpenRoot(aufsTempdir) + if err != nil { return 0, err } + cerr := createTarFile(aufsRoot, basename, hdr, tr, options) + _ = aufsRoot.Close() + if cerr != nil { + return 0, cerr + } } if hdr.Name != WhiteoutOpaqueDir { continue } } - // #nosec G305 -- The joined path is guarded against path traversal. - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return 0, err - } - - // Note as these operations are platform specific, so must the slash be. - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - base := filepath.Base(path) + // dstPath is the native (host-separator) form of the entry name, + // used at all filesystem boundaries (os.Root methods, fsRootPath). + // The tar-header name (hdr.Name) is POSIX, so convert it here. + dstPath := filepath.FromSlash(hdr.Name) + base := filepath.Base(dstPath) if strings.HasPrefix(base, WhiteoutPrefix) { - dir := filepath.Dir(path) + dir := filepath.Dir(dstPath) if base == WhiteoutOpaqueDir { - _, err := os.Lstat(dir) + _, err := root.Lstat(dir) if err != nil { return 0, err } - err = filepath.WalkDir(dir, func(path string, info os.DirEntry, err error) error { + // Walk the absolute directory so we can call os.RemoveAll on + // paths outside the walk callback's reach, then convert each + // walked path back to a root-relative name for the + // unpackedPaths check. + // fsRootPath walks each path component and bounds any symlinks + // within the root to prevent TOCTOU symlink attacks. + absDir, err := fsRootPath(root.Name(), dir) + if err != nil { + return 0, err + } + err = filepath.WalkDir(absDir, func(p string, info os.DirEntry, err error) error { if err != nil { if os.IsNotExist(err) { - err = nil // parent was deleted + return nil // parent was deleted } return err } - if path == dir { + if p == absDir { return nil } - if _, exists := unpackedPaths[path]; !exists { - return os.RemoveAll(path) + rel, err := filepath.Rel(root.Name(), p) + if err != nil { + return err + } + + // unpackedPaths is keyed by root-relative slash paths; convert + // filepath.WalkDir's native path before looking it up. + if _, exists := unpackedPaths[filepath.ToSlash(rel)]; !exists { + return root.RemoveAll(rel) } return nil }) @@ -142,18 +157,18 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, } else { originalBase := base[len(WhiteoutPrefix):] originalPath := filepath.Join(dir, originalBase) - if err := os.RemoveAll(originalPath); err != nil { + if err := root.RemoveAll(originalPath); err != nil { return 0, err } } } else { - // If path exits we almost always just want to remove and replace it. + // If dstPath exists we almost always just want to remove and replace it. // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { + if fi, err := root.Lstat(dstPath); err == nil { if !fi.IsDir() || hdr.Typeflag != tar.TypeDir { - if err := os.RemoveAll(path); err != nil { + if err := root.RemoveAll(dstPath); err != nil { return 0, err } } @@ -164,8 +179,8 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so // we manually retarget these into the temporary files we extracted them into - if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { - linkBasename := filepath.Base(hdr.Linkname) + if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(path.Clean(hdr.Linkname), WhiteoutLinkDir) { + linkBasename := path.Base(hdr.Linkname) srcHdr = aufsHardlinks[linkBasename] if srcHdr == nil { return 0, errors.New("invalid aufs hardlink") @@ -182,23 +197,23 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, return 0, err } - if err := createTarFile(path, dest, srcHdr, srcData, options); err != nil { + if err := createTarFile(root, dstPath, srcHdr, srcData, options); err != nil { return 0, err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) + dirs = append(dirs, unpackedDir{hdr: hdr, name: dstPath}) } - unpackedPaths[path] = struct{}{} + // unpackedPaths is keyed by the POSIX (forward-slash) name so it + // matches the ToSlash'd lookup in the opaque-whiteout walk above. + unpackedPaths[hdr.Name] = struct{}{} } } - for _, hdr := range dirs { - // #nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. - path := filepath.Join(dest, hdr.Name) - if err := chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { + for _, d := range dirs { + if err := chtimes(root, d.name, boundTime(latestTime(d.hdr.AccessTime, d.hdr.ModTime)), boundTime(d.hdr.ModTime)); err != nil { return 0, err } } diff --git a/vendor/github.com/moby/go-archive/rootpath.go b/vendor/github.com/moby/go-archive/rootpath.go new file mode 100644 index 000000000000..3834af2c4d4f --- /dev/null +++ b/vendor/github.com/moby/go-archive/rootpath.go @@ -0,0 +1,112 @@ +/* + Copyright The containerd Authors. + + 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 archive + +import ( + "errors" + "os" + "path/filepath" +) + +var errTooManyLinks = errors.New("too many links") + +// fsRootPath joins a path with a root, evaluating and bounding any +// symlink to the root directory. +func fsRootPath(root, path string) (string, error) { + if path == "" { + return root, nil + } + var linksWalked int // to protect against cycles + for { + i := linksWalked + newpath, err := walkLinks(root, path, &linksWalked) + if err != nil { + return "", err + } + path = newpath + if i == linksWalked { + newpath = filepath.Join(string(os.PathSeparator), newpath) + if path == newpath { + return filepath.Join(root, newpath), nil + } + path = newpath + } + } +} + +func walkLink(root, path string, linksWalked *int) (newpath string, islink bool, err error) { + if *linksWalked > 255 { + return "", false, errTooManyLinks + } + + path = filepath.Join(string(os.PathSeparator), path) + if path == string(os.PathSeparator) { + return path, false, nil + } + realPath := filepath.Join(root, path) + + fi, err := os.Lstat(realPath) + if err != nil { + // If path does not yet exist, treat as non-symlink + if os.IsNotExist(err) { + return path, false, nil + } + return "", false, err + } + if fi.Mode()&os.ModeSymlink == 0 { + return path, false, nil + } + newpath, err = os.Readlink(realPath) + if err != nil { + return "", false, err + } + *linksWalked++ + return newpath, true, nil +} + +func walkLinks(root, path string, linksWalked *int) (string, error) { + switch dir, file := filepath.Split(path); { + case dir == "": + newpath, _, err := walkLink(root, file, linksWalked) + return newpath, err + case file == "": + if os.IsPathSeparator(dir[len(dir)-1]) { + if dir == string(os.PathSeparator) { + return dir, nil + } + return walkLinks(root, dir[:len(dir)-1], linksWalked) + } + newpath, _, err := walkLink(root, dir, linksWalked) + return newpath, err + default: + newdir, err := walkLinks(root, dir, linksWalked) + if err != nil { + return "", err + } + newpath, islink, err := walkLink(root, filepath.Join(newdir, file), linksWalked) + if err != nil { + return "", err + } + if !islink { + return newpath, nil + } + if filepath.IsAbs(newpath) { + return newpath, nil + } + return filepath.Join(newdir, newpath), nil + } +} diff --git a/vendor/github.com/moby/go-archive/sequential_other.go b/vendor/github.com/moby/go-archive/sequential_other.go new file mode 100644 index 000000000000..90edb13933d2 --- /dev/null +++ b/vendor/github.com/moby/go-archive/sequential_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package archive + +// windows_O_FILE_FLAG_SEQUENTIAL_SCAN is not supported on go < 1.26. +const windows_O_FILE_FLAG_SEQUENTIAL_SCAN = 0 diff --git a/vendor/github.com/moby/go-archive/sequential_windows_go126.go b/vendor/github.com/moby/go-archive/sequential_windows_go126.go new file mode 100644 index 000000000000..1e80d11b73ea --- /dev/null +++ b/vendor/github.com/moby/go-archive/sequential_windows_go126.go @@ -0,0 +1,9 @@ +//go:build windows && go1.26 + +package archive + +// windows_O_FILE_FLAG_SEQUENTIAL_SCAN matches [golang.org/x/sys/windows.O_FILE_FLAG_SEQUENTIAL_SCAN]. +// Starting in Go 1.26, os.OpenFile supports passing this flag through. +// +// TODO(thaJeztah): use windows.O_FILE_FLAG_SEQUENTIAL_SCAN once we drop Go <1.26. +const windows_O_FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000 diff --git a/vendor/github.com/moby/go-archive/sequential_windows_pre126.go b/vendor/github.com/moby/go-archive/sequential_windows_pre126.go new file mode 100644 index 000000000000..2b281741ae12 --- /dev/null +++ b/vendor/github.com/moby/go-archive/sequential_windows_pre126.go @@ -0,0 +1,6 @@ +//go:build windows && !go1.26 + +package archive + +// windows_O_FILE_FLAG_SEQUENTIAL_SCAN is not supported on go < 1.26. +const windows_O_FILE_FLAG_SEQUENTIAL_SCAN = 0 diff --git a/vendor/github.com/moby/go-archive/tarheader/tarheader.go b/vendor/github.com/moby/go-archive/tarheader/tarheader.go index 03732a4f844b..78ab55cd410f 100644 --- a/vendor/github.com/moby/go-archive/tarheader/tarheader.go +++ b/vendor/github.com/moby/go-archive/tarheader/tarheader.go @@ -32,7 +32,7 @@ func (fi nosysFileInfo) Gname() (string, error) { return "", nil } -func (fi nosysFileInfo) Sys() interface{} { +func (fi nosysFileInfo) Sys() any { // A Sys value of type *tar.Header is safe as it is system-independent. // The tar.FileInfoHeader function copies the fields into the returned // header without performing any OS lookups. diff --git a/vendor/github.com/moby/go-archive/tarheader/tarheader_unix.go b/vendor/github.com/moby/go-archive/tarheader/tarheader_unix.go index 9c3311c63abc..bd12d46a8a67 100644 --- a/vendor/github.com/moby/go-archive/tarheader/tarheader_unix.go +++ b/vendor/github.com/moby/go-archive/tarheader/tarheader_unix.go @@ -36,10 +36,11 @@ func sysStat(fi os.FileInfo, hdr *tar.Header) error { hdr.Uid = int(s.Uid) hdr.Gid = int(s.Gid) - if s.Mode&unix.S_IFBLK != 0 || - s.Mode&unix.S_IFCHR != 0 { - hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) //nolint: unconvert - hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) //nolint: unconvert + if s.Mode&unix.S_IFBLK != 0 || s.Mode&unix.S_IFCHR != 0 { + // #nosec G115 -- Rdev type varies by platform. + rdev := uint64(s.Rdev) //nolint:unconvert // Rdev type varies by platform. + hdr.Devmajor = int64(unix.Major(rdev)) + hdr.Devminor = int64(unix.Minor(rdev)) } return nil diff --git a/vendor/github.com/moby/go-archive/time.go b/vendor/github.com/moby/go-archive/time.go index 4e9ae9508432..fb8c0299b9d3 100644 --- a/vendor/github.com/moby/go-archive/time.go +++ b/vendor/github.com/moby/go-archive/time.go @@ -22,6 +22,10 @@ func init() { } } +// boundTime returns t if it falls within the range supported by os.Chtimes. +// Times before the Unix epoch (minTime) or after the end of Unix time +// (maxTime) are replaced with minTime, as os.Chtimes has undefined behavior +// outside that range. func boundTime(t time.Time) time.Time { if t.Before(minTime) || t.After(maxTime) { return minTime diff --git a/vendor/github.com/moby/go-archive/time_nonwindows.go b/vendor/github.com/moby/go-archive/time_nonwindows.go index 5bfdfa2f17e8..418bc887a9b8 100644 --- a/vendor/github.com/moby/go-archive/time_nonwindows.go +++ b/vendor/github.com/moby/go-archive/time_nonwindows.go @@ -3,18 +3,55 @@ package archive import ( + "errors" "os" + "path" + "path/filepath" + "strings" + "syscall" "time" "golang.org/x/sys/unix" ) -// chtimes changes the access time and modified time of a file at the given path. -// If the modified time is prior to the Unix Epoch (unixMinTime), or after the -// end of Unix Time (unixEpochTime), os.Chtimes has undefined behavior. In this -// case, Chtimes defaults to Unix Epoch, just in case. -func chtimes(name string, atime time.Time, mtime time.Time) error { - return os.Chtimes(name, atime, mtime) +// chtimes changes the access and modification time of a file at the given +// path relative to root. +// +// Callers must use boundTime to ensure timestamps are within the range +// supported by os.Chtimes. +func chtimes(root *os.Root, name string, atime, mtime time.Time) error { + return root.Chtimes(name, atime, mtime) +} + +func lchtimes(root *os.Root, name string, atime, mtime time.Time) error { + dir, base := path.Split(filepath.ToSlash(name)) + if base == "" { + return &os.PathError{Op: "lchtimes", Path: name, Err: syscall.EINVAL} + } + + dir = strings.TrimSuffix(dir, "/") + if dir == "" { + dir = "." + } + + parent, err := root.Open(dir) + if err != nil { + return err + } + defer parent.Close() + + utimes := [2]unix.Timespec{ + timeToTimespec(atime), + timeToTimespec(mtime), + } + // #nosec G115 -- ignore integer overflow conversion for parent.Fd + if err := unix.UtimesNanoAt(int(parent.Fd()), base, utimes[:], unix.AT_SYMLINK_NOFOLLOW); err != nil { + if errors.Is(err, unix.ENOSYS) { + return nil + } + return &os.PathError{Op: "lchtimes", Path: name, Err: err} + } + return nil } func timeToTimespec(time time.Time) unix.Timespec { @@ -27,15 +64,3 @@ func timeToTimespec(time time.Time) unix.Timespec { } return unix.NsecToTimespec(time.UnixNano()) } - -func lchtimes(name string, atime time.Time, mtime time.Time) error { - utimes := [2]unix.Timespec{ - timeToTimespec(atime), - timeToTimespec(mtime), - } - err := unix.UtimesNanoAt(unix.AT_FDCWD, name, utimes[0:], unix.AT_SYMLINK_NOFOLLOW) - if err != nil && err != unix.ENOSYS { - return err - } - return err -} diff --git a/vendor/github.com/moby/go-archive/time_windows.go b/vendor/github.com/moby/go-archive/time_windows.go index af1f7c8f3a07..66173c58bbe2 100644 --- a/vendor/github.com/moby/go-archive/time_windows.go +++ b/vendor/github.com/moby/go-archive/time_windows.go @@ -1,32 +1,111 @@ package archive import ( + "errors" "os" + "path/filepath" "time" + "unsafe" "golang.org/x/sys/windows" ) -func chtimes(name string, atime time.Time, mtime time.Time) error { - if err := os.Chtimes(name, atime, mtime); err != nil { +// chtimes changes the access and modification time of a file at the given +// path relative to root. +// +// Symlink entries are handled separately through lchtimes. The final path +// component is expected not to be a reparse point; if one is encountered, +// chtimes returns an error. +// +// Callers must use boundTime to ensure timestamps are within the range +// supported by os.Chtimes. +func chtimes(root *os.Root, name string, atime, mtime time.Time) error { + parent, err := root.OpenFile(filepath.Dir(name), os.O_RDONLY, 0) + if err != nil { return err } + defer parent.Close() + + // Symlink entries are handled by lchtimes. The destination for all + // chtimes callers is therefore expected not to be a reparse point. + // + // Do not follow the final component: if it was concurrently replaced + // with a reparse point, fail instead of updating its target. + return chtimesAt(parent, filepath.Base(name), atime, mtime, true) +} - pathp, err := windows.UTF16PtrFromString(name) +func lchtimes(root *os.Root, name string, atime time.Time, mtime time.Time) error { + return nil +} + +func chtimesAt(parent *os.File, name string, atime, mtime time.Time, noFollow bool) error { + h, err := openForWriteAttributesAt(windows.Handle(parent.Fd()), name, noFollow) if err != nil { + if noFollow && errors.Is(err, windows.STATUS_REPARSE_POINT_ENCOUNTERED) { + // Encountering a reparse point when noFollow is requested is unexpected. + // Treat it as a potential breakout to fail extraction safely. + return breakoutError(err) + } return err } - h, err := windows.CreateFile(pathp, - windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, - windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) + defer func() { _ = windows.Close(h) }() + + var ( + creationTime = windows.NsecToFiletime(mtime.UnixNano()) + accessTime = windows.NsecToFiletime(atime.UnixNano()) + modificationTime = windows.NsecToFiletime(mtime.UnixNano()) + ) + return windows.SetFileTime(h, &creationTime, &accessTime, &modificationTime) +} + +// openForWriteAttributesAt opens name relative to parent with permission to +// modify its file attributes. If noFollow is true, it does not follow reparse +// points. +// +// This implementation is based on Go's internal Windows Openat support: +// +// https://github.com/golang/go/blob/go1.26.0/src/internal/syscall/windows/at_windows.go +// +// It is used by os.Root's Windows implementation for root-relative filesystem +// operations: +// +// https://github.com/golang/go/blob/go1.26.0/src/os/root_windows.go +// +// Keep this implementation aligned with the upstream code until an equivalent +// operation is available from golang.org/x/sys/windows. +func openForWriteAttributesAt(parent windows.Handle, name string, noFollow bool) (windows.Handle, error) { + name16, err := windows.UTF16FromString(name) if err != nil { - return err + return windows.InvalidHandle, err } - defer windows.Close(h) - c := windows.NsecToFiletime(mtime.UnixNano()) - return windows.SetFileTime(h, &c, nil, nil) -} -func lchtimes(name string, atime time.Time, mtime time.Time) error { - return nil + attrs := uint32(windows.OBJ_CASE_INSENSITIVE) + if noFollow { + attrs |= windows.OBJ_DONT_REPARSE + } + + var handle windows.Handle + err = windows.NtCreateFile( + &handle, + windows.SYNCHRONIZE|windows.FILE_WRITE_ATTRIBUTES, + &windows.OBJECT_ATTRIBUTES{ + Length: uint32(unsafe.Sizeof(windows.OBJECT_ATTRIBUTES{})), + RootDirectory: parent, + ObjectName: &windows.NTUnicodeString{ + Length: uint16((len(name16) - 1) * 2), // #nosec G115 -- Length is USHORT by definition. A Windows path component cannot exceed uint16 bytes. + MaximumLength: uint16(len(name16) * 2), // #nosec G115 -- MaximumLength is USHORT by definition. A Windows path component cannot exceed uint16 bytes. + Buffer: &name16[0], + }, + Attributes: attrs, + }, + &windows.IO_STATUS_BLOCK{}, + nil, + windows.FILE_ATTRIBUTE_NORMAL, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + windows.FILE_OPEN, + windows.FILE_OPEN_FOR_BACKUP_INTENT|windows.FILE_SYNCHRONOUS_IO_NONALERT, + 0, // EA buffer + 0, // EA length + ) + return handle, err } diff --git a/vendor/github.com/moby/go-archive/xattr_supported.go b/vendor/github.com/moby/go-archive/xattr_supported.go index 652a1f0f349d..8478fe1446da 100644 --- a/vendor/github.com/moby/go-archive/xattr_supported.go +++ b/vendor/github.com/moby/go-archive/xattr_supported.go @@ -13,26 +13,26 @@ import ( // lgetxattr retrieves the value of the extended attribute identified by attr // and associated with the given path in the file system. // It returns a nil slice and nil error if the xattr is not set. -func lgetxattr(path string, attr string) ([]byte, error) { +func lgetxattr(filePath string, attr string) ([]byte, error) { // Start with a 128 length byte array dest := make([]byte, 128) - sz, err := unix.Lgetxattr(path, attr, dest) + sz, err := unix.Lgetxattr(filePath, attr, dest) for errors.Is(err, unix.ERANGE) { // Buffer too small, use zero-sized buffer to get the actual size - sz, err = unix.Lgetxattr(path, attr, []byte{}) + sz, err = unix.Lgetxattr(filePath, attr, []byte{}) if err != nil { - return nil, wrapPathError("lgetxattr", path, attr, err) + return nil, wrapPathError("lgetxattr", filePath, attr, err) } dest = make([]byte, sz) - sz, err = unix.Lgetxattr(path, attr, dest) + sz, err = unix.Lgetxattr(filePath, attr, dest) } if err != nil { if errors.Is(err, noattr) { return nil, nil } - return nil, wrapPathError("lgetxattr", path, attr, err) + return nil, wrapPathError("lgetxattr", filePath, attr, err) } return dest[:sz], nil @@ -40,13 +40,13 @@ func lgetxattr(path string, attr string) ([]byte, error) { // lsetxattr sets the value of the extended attribute identified by attr // and associated with the given path in the file system. -func lsetxattr(path string, attr string, data []byte, flags int) error { - return wrapPathError("lsetxattr", path, attr, unix.Lsetxattr(path, attr, data, flags)) +func lsetxattr(filePath string, attr string, data []byte, flags int) error { + return wrapPathError("lsetxattr", filePath, attr, unix.Lsetxattr(filePath, attr, data, flags)) } -func wrapPathError(op, path, attr string, err error) error { +func wrapPathError(op, filePath, attr string, err error) error { if err == nil { return nil } - return &fs.PathError{Op: op, Path: path, Err: fmt.Errorf("xattr %q: %w", attr, err)} + return &fs.PathError{Op: op, Path: filePath, Err: fmt.Errorf("xattr %q: %w", attr, err)} } diff --git a/vendor/github.com/moby/moby/client/README.md b/vendor/github.com/moby/moby/client/README.md index aed3e641d9a4..ebe29495c91b 100644 --- a/vendor/github.com/moby/moby/client/README.md +++ b/vendor/github.com/moby/moby/client/README.md @@ -2,7 +2,6 @@ [![PkgGoDev](https://pkg.go.dev/badge/github.com/moby/moby/client)](https://pkg.go.dev/github.com/moby/moby/client) ![GitHub License](https://img.shields.io/github/license/moby/moby) -[![Go Report Card](https://goreportcard.com/badge/github.com/moby/moby/client)](https://goreportcard.com/report/github.com/moby/moby/client) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/moby/moby/badge)](https://scorecard.dev/viewer/?uri=github.com/moby/moby) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/10989/badge)](https://www.bestpractices.dev/projects/10989) diff --git a/vendor/github.com/moby/moby/client/container_commit.go b/vendor/github.com/moby/moby/client/container_commit.go index 79da44a54f80..f73cd22f51d6 100644 --- a/vendor/github.com/moby/moby/client/container_commit.go +++ b/vendor/github.com/moby/moby/client/container_commit.go @@ -31,8 +31,9 @@ func (cli *Client) ContainerCommit(ctx context.Context, containerID string, opti if err != nil { return ContainerCommitResult{}, err } + query := url.Values{} + query.Set("container", containerID) - var repository, tag string if options.Reference != "" { ref, err := reference.ParseNormalizedNamed(options.Reference) if err != nil { @@ -44,18 +45,18 @@ func (cli *Client) ContainerCommit(ctx context.Context, containerID string, opti } ref = reference.TagNameOnly(ref) + query.Set("repo", ref.Name()) if tagged, ok := ref.(reference.Tagged); ok { - tag = tagged.Tag() + query.Set("tag", tagged.Tag()) } - repository = ref.Name() } - query := url.Values{} - query.Set("container", containerID) - query.Set("repo", repository) - query.Set("tag", tag) - query.Set("comment", options.Comment) - query.Set("author", options.Author) + if options.Comment != "" { + query.Set("comment", options.Comment) + } + if options.Author != "" { + query.Set("author", options.Author) + } for _, change := range options.Changes { query.Add("changes", change) } diff --git a/vendor/github.com/moby/moby/client/container_restart.go b/vendor/github.com/moby/moby/client/container_restart.go index e883f75891bd..df7ca4c7ed6d 100644 --- a/vendor/github.com/moby/moby/client/container_restart.go +++ b/vendor/github.com/moby/moby/client/container_restart.go @@ -16,7 +16,8 @@ type ContainerRestartOptions struct { // Timeout (optional) is the timeout (in seconds) to wait for the container // to stop gracefully before forcibly terminating it with SIGKILL. // - // - Use nil to use the default timeout (10 seconds). + // - Use nil to use the container's configured timeout, or the engine default + // if the container has no configured timeout. // - Use '-1' to wait indefinitely. // - Use '0' to not wait for the container to exit gracefully, and // immediately proceeds to forcibly terminating the container. diff --git a/vendor/github.com/moby/moby/client/container_stop.go b/vendor/github.com/moby/moby/client/container_stop.go index d4d47d8fd407..d72358c5eec6 100644 --- a/vendor/github.com/moby/moby/client/container_stop.go +++ b/vendor/github.com/moby/moby/client/container_stop.go @@ -16,7 +16,8 @@ type ContainerStopOptions struct { // Timeout (optional) is the timeout (in seconds) to wait for the container // to stop gracefully before forcibly terminating it with SIGKILL. // - // - Use nil to use the default timeout (10 seconds). + // - Use nil to use the container's configured timeout, or the engine default + // if the container has no configured timeout. // - Use '-1' to wait indefinitely. // - Use '0' to not wait for the container to exit gracefully, and // immediately proceeds to forcibly terminating the container. diff --git a/vendor/github.com/moby/moby/client/internal/mod/mod.go b/vendor/github.com/moby/moby/client/internal/mod/mod.go index 355eb9532698..c9a11b3e5689 100644 --- a/vendor/github.com/moby/moby/client/internal/mod/mod.go +++ b/vendor/github.com/moby/moby/client/internal/mod/mod.go @@ -87,7 +87,7 @@ func getVersion(name string, dep *debug.Module) (string, bool) { func normalize(v string) string { base, metas, dirty := splitMetadata(v) - out := base + var out strings.Builder if base2, rev, undoPatch, ok := splitPseudo(base); ok { if undoPatch { // Downgrade the patch version that was raised by pseudo-versions: @@ -102,18 +102,22 @@ func normalize(v string) string { if len(rev) > 12 { rev = rev[:12] } - out = base2 + "+" + rev + out.WriteString(base2) + out.WriteByte('+') + out.WriteString(rev) + } else { + out.WriteString(base) } // Preserve other metadata (except for "+incompatible"). for _, m := range metas { - out += m + out.WriteString(m) } if dirty { // +dirty goes last - out += "+dirty" + out.WriteString("+dirty") } - return out + return out.String() } func splitMetadata(v string) (base string, metas []string, dirty bool) { diff --git a/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go index e3ac43afd44e..a955363d8a52 100644 --- a/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go +++ b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go @@ -128,7 +128,7 @@ func cursorDown(out io.Writer, l uint) { // Display prints the JSONMessage to out. If isTerminal is true, it erases // the entire current line when displaying the progressbar. It returns an -// error if the [JSONMessage.Error] field is non-nil. +// error if [jsonstream.Message.Error] is non-nil. func Display(jm jsonstream.Message, out io.Writer, isTerminal bool, width uint16) error { if jm.Error != nil { return jm.Error diff --git a/vendor/github.com/moby/moby/client/service_create.go b/vendor/github.com/moby/moby/client/service_create.go index 319bca6f4c87..8d5926bb9bf3 100644 --- a/vendor/github.com/moby/moby/client/service_create.go +++ b/vendor/github.com/moby/moby/client/service_create.go @@ -137,21 +137,37 @@ func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, ima if len(distributionInspect.Platforms) > 0 { platforms = make([]swarm.Platform, 0, len(distributionInspect.Platforms)) + seen := make(map[swarm.Platform]struct{}, len(distributionInspect.Platforms)) for _, p := range distributionInspect.Platforms { + // skip attestations and other data included in the manifest index. + if p.OS == "unknown" || p.Architecture == "unknown" { + continue + } // clear architecture field for arm. This is a temporary patch to address - // https://github.com/docker/swarmkit/issues/2294. The issue is that while + // https://github.com/moby/swarmkit/issues/2294. The issue is that while // image manifests report "arm" as the architecture, the node reports // something like "armv7l" (includes the variant), which causes arm images // to stop working with swarm mode. This patch removes the architecture // constraint for arm images to ensure tasks get scheduled. arch := p.Architecture - if strings.ToLower(arch) == "arm" { + if strings.EqualFold(arch, "arm") { arch = "" } - platforms = append(platforms, swarm.Platform{ + platform := swarm.Platform{ Architecture: arch, OS: p.OS, - }) + } + + // Skip duplicates. Swarm currently only uses os/arch, and doesn't + // support other fields (Variant, OSVersion, OSFeatures), which + // usually results in duplicate "os/arch" combinations coming from + // the image. + if _, ok := seen[platform]; ok { + continue + } + seen[platform] = struct{}{} + + platforms = append(platforms, platform) } } return imageWithDigest, platforms, err diff --git a/vendor/github.com/moby/moby/client/service_inspect.go b/vendor/github.com/moby/moby/client/service_inspect.go index 9bda43f86164..7b7d09894195 100644 --- a/vendor/github.com/moby/moby/client/service_inspect.go +++ b/vendor/github.com/moby/moby/client/service_inspect.go @@ -3,7 +3,6 @@ package client import ( "context" "encoding/json" - "fmt" "net/url" "github.com/moby/moby/api/types/swarm" @@ -28,7 +27,9 @@ func (cli *Client) ServiceInspect(ctx context.Context, serviceID string, options } query := url.Values{} - query.Set("insertDefaults", fmt.Sprintf("%v", options.InsertDefaults)) + if options.InsertDefaults { + query.Set("insertDefaults", "1") + } resp, err := cli.get(ctx, "/services/"+serviceID, query, nil) if err != nil { return ServiceInspectResult{}, err diff --git a/vendor/go.yaml.in/yaml/v3/parserc.go b/vendor/go.yaml.in/yaml/v3/parserc.go index 25fe823637ab..f35829db4daa 100644 --- a/vendor/go.yaml.in/yaml/v3/parserc.go +++ b/vendor/go.yaml.in/yaml/v3/parserc.go @@ -226,9 +226,9 @@ func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool } // Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END // -// ************ +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -249,13 +249,11 @@ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) } // Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// -// * // -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -// ************************* +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { token := peek_token(parser) @@ -359,9 +357,9 @@ func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t } // Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // -// *********** +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -382,11 +380,10 @@ func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event } // Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// -// ************* // -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -432,42 +429,32 @@ func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) } // Parse the productions: -// block_node_or_indentless_sequence ::= -// -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// -// block_node ::= ALIAS -// -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// -// flow_node ::= ALIAS -// -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// -// ************************* -// -// block_content ::= block_collection | flow_collection | SCALAR -// -// ****** // -// flow_content ::= flow_collection | SCALAR -// -// ****** +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() @@ -697,9 +684,9 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i } // Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END // -// ******************** *********** * ********* +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -755,9 +742,9 @@ func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_e } // Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ // -// *********** * +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -821,15 +808,15 @@ func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { } // Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START // -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* // -// BLOCK-END -// ********* +// BLOCK-END +// ********* func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -896,13 +883,14 @@ func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_even } // Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START // -// ((KEY block_node_or_indentless_sequence?)? +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? // -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -929,19 +917,17 @@ func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_ev } // Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** // -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// -// * +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -1005,9 +991,9 @@ func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_ev } // Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // -// *** * +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1026,9 +1012,9 @@ func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, ev } // Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // -// ***** * +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1050,9 +1036,9 @@ func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, } // Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // -// * +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1068,18 +1054,17 @@ func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, ev } // Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** // -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - *** * +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -1144,8 +1129,9 @@ func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event } // Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - ***** * +// +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { token := peek_token(parser) if token == nil { diff --git a/vendor/go.yaml.in/yaml/v3/yamlh.go b/vendor/go.yaml.in/yaml/v3/yamlh.go index f59aa40f6401..07c442361cea 100644 --- a/vendor/go.yaml.in/yaml/v3/yamlh.go +++ b/vendor/go.yaml.in/yaml/v3/yamlh.go @@ -433,21 +433,19 @@ type yaml_document_t struct { // The prototype of a read handler. // -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. // -// [in,out] data A pointer to an application data specified by +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. // -// yaml_parser_set_input(). -// -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) // This structure holds information about a potential simple key. @@ -655,19 +653,17 @@ type yaml_comment_t struct { // The prototype of a write handler. // -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// -// yaml_emitter_set_output(). +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. // -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. // -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int diff --git a/vendor/golang.org/x/mod/modfile/read.go b/vendor/golang.org/x/mod/modfile/read.go index 5b528c718e2f..9e35e1ac51f3 100644 --- a/vendor/golang.org/x/mod/modfile/read.go +++ b/vendor/golang.org/x/mod/modfile/read.go @@ -924,7 +924,7 @@ var ( moduleStr = []byte("module") ) -// ModulePath returns the module path from the gomod file text. +// ModulePath returns the module path from the go.mod file text. // If it cannot find a module path, it returns an empty string. // It is tolerant of unrelated problems in the go.mod file. func ModulePath(mod []byte) string { diff --git a/vendor/golang.org/x/mod/modfile/rule.go b/vendor/golang.org/x/mod/modfile/rule.go index 9ab203b56229..20ba825d2940 100644 --- a/vendor/golang.org/x/mod/modfile/rule.go +++ b/vendor/golang.org/x/mod/modfile/rule.go @@ -1477,7 +1477,7 @@ func (f *File) setRequireSeparateIndirect(req []*Require, simplify bool) { // Delete requirements we don't want anymore. // Update versions and indirect comments on requirements we want to keep. // If a requirement is in last{Direct,Indirect}Block with the wrong - // indirect marking after this, or if the requirement is in an single + // indirect marking after this, or if the requirement is in a single // uncommented mixed block (oneFlatUncommentedBlock), move it to the // correct block. // @@ -1537,7 +1537,7 @@ func (f *File) DropRequire(path string) error { return nil } -// AddExclude adds a exclude statement to the mod file. Errors if the provided +// AddExclude adds an exclude statement to the mod file. Errors if the provided // version is not a canonical version string func (f *File) AddExclude(path, vers string) error { if err := checkCanonicalVersion(path, vers); err != nil { @@ -1708,7 +1708,7 @@ func (f *File) AddIgnore(path string) error { return nil } -// DropIgnore removes a ignore directive with the given path. +// DropIgnore removes an ignore directive with the given path. // It does nothing if no such ignore directive exists. func (f *File) DropIgnore(path string) error { for _, t := range f.Ignore { diff --git a/vendor/golang.org/x/net/http2/transport_wrap.go b/vendor/golang.org/x/net/http2/transport_wrap.go index eab2e6b07312..534e77ab9635 100644 --- a/vendor/golang.org/x/net/http2/transport_wrap.go +++ b/vendor/golang.org/x/net/http2/transport_wrap.go @@ -55,7 +55,7 @@ type transportConfig struct { // Registered is called by net/http.Transport.RegisterProtocol, // to let us know that it understands the registration mechanism we're using. func (t transportConfig) Registered(t1 *http.Transport) { - t.t.t1 = t1 + t.t.lazyt1 = t1 } func (t transportConfig) DisableCompression() bool { @@ -145,29 +145,30 @@ func (t transportConfig) DialFromContext(ctx context.Context, network, address s type transportInternal struct { initOnce sync.Once - t1 *http.Transport + lazyt1 *http.Transport } -func (t *Transport) init() { +func (t *Transport) init() *http.Transport { t.initOnce.Do(func() { - if t.t1 != nil { + if t.lazyt1 != nil { return } t1 := &http.Transport{} t.configure(t1) }) + return t.lazyt1 } func (t *Transport) configure(t1 *http.Transport) { t1.RegisterProtocol("http/2", transportConfig{t}) - // tr2.t1 is set by transportConfig.Registered. - if t.t1 != t1 { + // tr2.lazyt1 is set by transportConfig.Registered. + if t.lazyt1 != t1 { panic("http2: net/http does not support this version of x/net/http2") } } func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { - t.init() + t1 := t.init() if req.URL.Scheme == "http" && !t.AllowHTTP { return nil, errors.New("http2: unencrypted HTTP/2 not enabled") @@ -188,22 +189,23 @@ func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res ctx := context.WithValue(req.Context(), http2TransportContextKey{}, t) req = req.WithContext(ctx) - return t.t1.RoundTrip(req) + return t1.RoundTrip(req) } func (t *Transport) closeIdleConnections() { - t.init() - t.t1.CloseIdleConnections() + t1 := t.init() + t1.CloseIdleConnections() } func (t *Transport) newUserClientConn(c net.Conn) (*ClientConn, error) { + t1 := t.init() // http.Transport's NewClientConn doesn't provide a supported way to create // a connection from a net.Conn. (This might be useful to add in the future?) // We're going to craftily sneak one in via the context key, with the // scheme of "http/2" telling NewClientConn to look for it. ctx := context.WithValue(context.Background(), netConnContextKey{}, c) - nhcc, err := t.t1.NewClientConn(ctx, "http/2", "") + nhcc, err := t1.NewClientConn(ctx, "http/2", "") if err != nil { return nil, err } diff --git a/vendor/golang.org/x/net/idna/idna.go b/vendor/golang.org/x/net/idna/idna.go index 22767125bf3e..e2f28fed489d 100644 --- a/vendor/golang.org/x/net/idna/idna.go +++ b/vendor/golang.org/x/net/idna/idna.go @@ -400,7 +400,11 @@ func (p *Profile) process(s string, toASCII bool) (string, error) { // Spec says keep the old label. continue } - if unicode16 && err == nil && len(u) > 0 && isASCII(u) { + if err == nil && len(u) > 0 && isASCII(u) { + // UTS 43 pre-revision 33 doesn't classify a xn-- label + // which contains only ASCII characters as an error, + // but that's a specification bug and a security issue. + // Always return an error in this case. err = punyError(enc) } isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index ce4d7ab1ed8a..21e2bfa398b9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1874,6 +1874,7 @@ func Dup2(oldfd, newfd int) error { //sys Dup3(oldfd int, newfd int, flags int) (err error) //sysnb EpollCreate1(flag int) (fd int, err error) //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) +//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2 //sys Exit(code int) = SYS_EXIT_GROUP //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go index 506dafa7b4c6..210d545c9377 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -20,7 +20,6 @@ func setTimeval(sec, usec int64) Timeval { // 64-bit file system and 32-bit uid calls // (386 default is 32-bit file system and 16-bit uid). -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index d557cf8de3f2..a9a52f231996 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index ecf92bfa2a39..54474c20feef 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -44,7 +44,6 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { // 64-bit file system and 32-bit uid calls // (16-bit uid calls are not always supported in newer kernels) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index 173738077b6d..e9f30db97d4e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index a3fd1d0b802f..6f09ca200ad9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index 70963a95abf3..ca3b56597d79 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index c218ebd28016..54ba667b1b2c 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -13,7 +13,6 @@ import ( func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go index e6c48500ca94..ce4628590248 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go @@ -11,7 +11,6 @@ import ( "unsafe" ) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go index 7286a9aa882b..33f7af38043d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index fc5543c5ffb4..c658871e3072 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go index 66f31210d083..2c8587691b4d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go @@ -10,7 +10,6 @@ import ( "unsafe" ) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 11d1f1698665..4964119af8fa 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 9d72a6b73a93..5bb51d7ae1e3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -1359,6 +1359,7 @@ const ( FAN_UNLIMITED_MARKS = 0x20 FAN_UNLIMITED_QUEUE = 0x10 FD_CLOEXEC = 0x1 + FD_PIDFS_ROOT = -0x2712 FD_SETSIZE = 0x400 FF0 = 0x0 FIB_RULE_DEV_DETACHED = 0x8 @@ -1970,6 +1971,8 @@ const ( MADV_DONTNEED = 0x4 MADV_DONTNEED_LOCKED = 0x18 MADV_FREE = 0x8 + MADV_GUARD_INSTALL = 0x66 + MADV_GUARD_REMOVE = 0x67 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_KEEPONFORK = 0x13 @@ -2114,7 +2117,7 @@ const ( MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOSYMFOLLOW = 0x100 - MS_NOUSER = -0x80000000 + MS_NOUSER = 0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 @@ -3786,6 +3789,9 @@ const ( TCPOPT_TIMESTAMP = 0x8 TCPOPT_TSTAMP_HDR = 0x101080a TCPOPT_WINDOW = 0x3 + TCP_AO_KEYF_EXCLUDE_OPT = 0x2 + TCP_AO_KEYF_IFINDEX = 0x1 + TCP_AO_MAXKEYLEN = 0x50 TCP_CC_INFO = 0x1a TCP_CM_INQ = 0x24 TCP_CONGESTION = 0xd diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 80f40e401357..5788c2a58d37 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -700,6 +700,23 @@ func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 4def3e9fcb0d..254f33988f0c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index fef2bc8ba9c9..27c05db1acb2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index a9fd76a88411..840d85bfc3ec 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -213,23 +213,6 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index 4600650280aa..fe414498b404 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go index c8987d264650..eb358ce05a01 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index 921f43061106..c437622f14f3 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset>>32), uintptr(offset), uintptr(length>>32), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index 44f067829c4d..bc4ca255820c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index e7fa0abf0d19..5051435ce7e3 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index 8c5125675e83..33aa5418a4fc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go index 7392fd45e433..3bef8ef1d251 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index 41180434e609..fc1bd4e2c45d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 40c6ce7ae543..d78fe7dabe9e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go index 2cfe34adb123..76dcf87d01c4 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 61e6f070971b..2cf020f2baa9 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 834b84204283..527637623d1a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 6c955cea158f..783621561ea2 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -1109,17 +1109,53 @@ const ( ) // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. +// +// Go pointers stored in a TrusteeValue must be pinned using [runtime.Pinner] +// for the lifetime of the TrusteeValue. type TrusteeValue uintptr +// TrusteeValueFromString is unsafe and should not be used. +// +// It returns a uintptr containing a reference to newly-allocated memory +// which will be freed by the garbage collector. +// There is no way for the caller to safely reference this memory. +// +// To create a [TrusteeValue] from a string, use: +// +// p, err := windows.UTF16PtrFromString(s) +// if err != nil { +// // handle error +// } +// +// // Pin the string for as long as it is used. +// var pinner runtime.Pinner +// pinner.Pin(p) +// defer pinner.Unpin() +// +// tv := TrusteeValue(unsafe.Pointer(p)) +// +// Deprecated: TrusteeValueFromString is unsafe and should not be used. func TrusteeValueFromString(str string) TrusteeValue { return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str))) } + +// TrusteeValueFromSID returns a [TrusteeValue] referencing sid. +// +// The caller must pin sid using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromSID(sid *SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(sid)) } + +// TrusteeValueFromObjectsAndSid returns a [TrusteeValue] referencing objectsAndSid. +// +// The caller must pin objectsAndSid using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndSid)) } + +// TrusteeValueFromObjectsAndName returns a [TrusteeValue] referencing objectsAndName. +// +// The caller must pin objectsAndName using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndName)) } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 9755bca9fd39..e6966b4c3276 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -1728,11 +1728,15 @@ func (s *NTUnicodeString) String() string { // the more common *uint16 string type. func NewNTString(s string) (*NTString, error) { var nts NTString - s8, err := BytePtrFromString(s) + s8, err := ByteSliceFromString(s) if err != nil { return nil, err } - RtlInitString(&nts, s8) + // The source string plus its terminating NUL must fit within MAX_USHORT. + if len(s8) > MAX_USHORT { + return nil, syscall.EINVAL + } + RtlInitString(&nts, &s8[0]) return &nts, nil } diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index d2574a73ee00..75a50b3165ee 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -169,6 +169,7 @@ const ( FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 + MAX_USHORT = 0xffff MAX_PATH = 260 MAX_LONG_PATH = 32768 diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo.go b/vendor/golang.org/x/text/unicode/norm/forminfo.go index f3a234e5f53e..b3cf5d9bdee2 100644 --- a/vendor/golang.org/x/text/unicode/norm/forminfo.go +++ b/vendor/golang.org/x/text/unicode/norm/forminfo.go @@ -121,8 +121,12 @@ func (p Properties) BoundaryAfter() bool { // // When all 6 bits are zero, the character is inert, meaning it is never // influenced by normalization. +// +// We set flags to 0x80 (high bit 7 unused in quick check data) to indicate an invalid rune. type qcInfo uint8 +func (p Properties) isInvalid() bool { return p.flags == 0x80 } + func (p Properties) isYesC() bool { return p.flags&0x10 == 0 } func (p Properties) isYesD() bool { return p.flags&0x4 == 0 } @@ -247,6 +251,9 @@ func (f Form) PropertiesString(s string) Properties { // to a Properties. See the comment at the top of the file // for more information on the format. func compInfo(v uint16, sz int) Properties { + if sz == 0 { + return Properties{flags: 0x80, size: 1} + } if v == 0 { return Properties{size: uint8(sz)} } else if v >= 0x8000 { @@ -254,7 +261,7 @@ func compInfo(v uint16, sz int) Properties { size: uint8(sz), ccc: uint8(v), tccc: uint8(v), - flags: qcInfo(v >> 8), + flags: qcInfo(v>>8) & 0x3f, } if p.ccc > 0 || p.combinesBackward() { p.nLead = uint8(p.flags & 0x3) diff --git a/vendor/golang.org/x/text/unicode/norm/iter.go b/vendor/golang.org/x/text/unicode/norm/iter.go index 417c6b26894d..3cc059224d9d 100644 --- a/vendor/golang.org/x/text/unicode/norm/iter.go +++ b/vendor/golang.org/x/text/unicode/norm/iter.go @@ -376,16 +376,12 @@ func nextComposed(i *Iter) []byte { goto doNorm } prevCC = i.info.tccc - sz := int(i.info.size) - if sz == 0 { - sz = 1 // illegal rune: copy byte-by-byte - } - p := outp + sz + p := outp + int(i.info.size) if p > len(i.buf) { break } outp = p - i.p += sz + i.p += int(i.info.size) if i.p >= i.rb.nsrc { i.setDone() break diff --git a/vendor/golang.org/x/text/unicode/norm/normalize.go b/vendor/golang.org/x/text/unicode/norm/normalize.go index 4747ad07a839..60b1511caa2b 100644 --- a/vendor/golang.org/x/text/unicode/norm/normalize.go +++ b/vendor/golang.org/x/text/unicode/norm/normalize.go @@ -148,7 +148,7 @@ func (f Form) IsNormalString(s string) bool { // patched buffer and whether the decomposition is still in progress. func patchTail(rb *reorderBuffer) bool { info, p := lastRuneStart(&rb.f, rb.out) - if p == -1 || info.size == 0 { + if p == -1 || info.isInvalid() { return true } end := p + int(info.size) @@ -225,7 +225,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte { } fd := &rb.f if doMerge { - var info Properties + info := Properties{flags: 0x80, size: 1} // invalid rune if p < n { info = fd.info(src, p) if !info.BoundaryBefore() || info.nLeadingNonStarters() > 0 { @@ -235,7 +235,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte { p = decomposeSegment(rb, p, true) } } - if info.size == 0 { + if info.isInvalid() { rb.doFlush() // Append incomplete UTF-8 encoding. return src.appendSlice(rb.out, p, n) @@ -314,7 +314,7 @@ func (f *formInfo) quickSpan(src input, i, end int, atEOF bool) (n int, ok bool) continue } info := f.info(src, i) - if info.size == 0 { + if info.isInvalid() { if atEOF { // include incomplete runes return n, true @@ -379,7 +379,7 @@ func (f Form) firstBoundary(src input, nsrc int) int { // CGJ insertion points correctly. Luckily it doesn't have to. for { info := fd.info(src, i) - if info.size == 0 { + if info.isInvalid() { return -1 } if s := ss.next(info); s != ssSuccess { @@ -424,7 +424,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int { } fd := formTable[f] info := fd.info(src, 0) - if info.size == 0 { + if info.isInvalid() { if atEOF { return 1 } @@ -435,7 +435,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int { for i := int(info.size); i < nsrc; i += int(info.size) { info = fd.info(src, i) - if info.size == 0 { + if info.isInvalid() { if atEOF { return i } @@ -465,7 +465,7 @@ func lastBoundary(fd *formInfo, b []byte) int { if p == -1 { return -1 } - if info.size == 0 { // ends with incomplete rune + if info.isInvalid() { // ends with incomplete rune if p == 0 { // starts with incomplete rune return -1 } @@ -504,7 +504,7 @@ func lastBoundary(fd *formInfo, b []byte) int { func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int { // Force one character to be consumed. info := rb.f.info(rb.src, sp) - if info.size == 0 { + if info.isInvalid() { return 0 } if s := rb.ss.next(info); s == ssStarter { @@ -528,7 +528,7 @@ func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int { break } info = rb.f.info(rb.src, sp) - if info.size == 0 { + if info.isInvalid() { if !atEOF { return int(iShortSrc) } diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 326888ae35aa..7e3dbaad2638 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -60,7 +60,7 @@ func Register(b Builder) { if !envconfig.CaseSensitiveBalancerRegistries { name = strings.ToLower(name) if name != b.Name() { - logger.Warningf("Balancer registered with name %q. grpc-go will be switching to case sensitive balancer registries soon. After 2 releases, we will enable the env var by default.", b.Name()) + logger.Warningf("Balancer registered with name %q. grpc-go has switched to case sensitive balancer registries. GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES env variable will be removed in release v1.82.0", b.Name()) } } m[name] = b @@ -85,7 +85,7 @@ func Get(name string) Builder { if !envconfig.CaseSensitiveBalancerRegistries { lowerName := strings.ToLower(name) if lowerName != name { - logger.Warningf("Balancer retrieved for name %q. grpc-go will be switching to case sensitive balancer registries soon. After 2 releases, we will enable the env var by default.", name) + logger.Warningf("Balancer retrieved for name %q. grpc-go has switched to case sensitive balancer registries. GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES env variable will be removed in release v1.82.0", name) } name = lowerName } diff --git a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go index 518a69d573de..d48bc304c2b9 100644 --- a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go +++ b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go @@ -35,9 +35,9 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/experimental/balancer/weight" expstats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/balancer/weight" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/pretty" diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 4ec5f9cd093a..3af08e1ab9c8 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -173,10 +173,8 @@ func newJoinDialOption(opts ...DialOption) DialOption { // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // -// # Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Deprecated: shared write buffer is enabled by default. WithSharedWriteBuffer +// will be removed in a future release. func WithSharedWriteBuffer(val bool) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.SharedWriteBuffer = val @@ -229,6 +227,14 @@ func WithInitialConnWindowSize(s int32) DialOption { // WithStaticStreamWindowSize returns a DialOption which sets the initial // stream window size to the value provided and disables dynamic flow control. +// +// Note that this also disables dynamic flow control for the connection, +// falling back to a default static connection-level window of 64KB. To +// use a larger connection-level window, you must also use the +// [WithStaticConnWindowSize] DialOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func WithStaticStreamWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialWindowSize = s @@ -239,6 +245,14 @@ func WithStaticStreamWindowSize(s int32) DialOption { // WithStaticConnWindowSize returns a DialOption which sets the initial // connection window size to the value provided and disables dynamic flow // control. +// +// Note that this also disables dynamic flow control for individual streams, +// falling back to a default static connection-level window of 64KB. To +// explicitly configure the stream-level window size, you must also use the +// [WithStaticStreamWindowSize] DialOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func WithStaticConnWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialConnWindowSize = s diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go index 296f38c3a804..bfa8b268fe8f 100644 --- a/vendor/google.golang.org/grpc/encoding/encoding.go +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -66,6 +66,9 @@ type Compressor interface { // Decompress reads data from r, decompresses it, and provides the // uncompressed data via the returned io.Reader. If an error occurs while // initializing the decompressor, that error is returned instead. + // + // The returned io.Reader may optionally implement io.ReadCloser, and if it + // does, gRPC will call Close() exactly once. Decompress(r io.Reader) (io.Reader, error) // Name is the name of the compression codec and is used to set the content // coding header. The result must be static; the result cannot change diff --git a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go index 153e4dbfbf7a..65908d9a2c45 100644 --- a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go +++ b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go @@ -81,6 +81,8 @@ func (z *writer) Close() error { return z.Writer.Close() } +var _ io.Closer = &reader{} + type reader struct { *gzip.Reader pool *sync.Pool @@ -102,14 +104,16 @@ func (c *compressor) Decompress(r io.Reader) (io.Reader, error) { return z, nil } -func (z *reader) Read(p []byte) (n int, err error) { - n, err = z.Reader.Read(p) - if err == io.EOF { - z.pool.Put(z) - } +func (r *reader) Read(p []byte) (n int, err error) { + n, err = r.Reader.Read(p) return n, err } +func (r *reader) Close() error { + defer r.pool.Put(r) + return r.Reader.Close() +} + func (c *compressor) Name() string { return Name } diff --git a/vendor/google.golang.org/grpc/internal/balancer/weight/weight.go b/vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go similarity index 71% rename from vendor/google.golang.org/grpc/internal/balancer/weight/weight.go rename to vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go index 11beb07d1498..beab9e07c964 100644 --- a/vendor/google.golang.org/grpc/internal/balancer/weight/weight.go +++ b/vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go @@ -16,23 +16,23 @@ * */ -// Package weight contains utilities to manage endpoint weights. Weights are -// used by LB policies such as ringhash to distribute load across multiple -// endpoints. +// Package weight contains utilities to manage endpoint weights. +// Weights may be used by LB policies to distribute load across +// multiple endpoints. +// +// # Experimental +// +// Notice: All APIs in this package are EXPERIMENTAL and may be changed +// or removed in a later release. package weight -import ( - "fmt" - - "google.golang.org/grpc/resolver" -) +import "google.golang.org/grpc/resolver" // attributeKey is the type used as the key to store EndpointInfo in the // Attributes field of resolver.Endpoint. type attributeKey struct{} -// EndpointInfo will be stored in the Attributes field of Endpoints in order to -// use the ringhash balancer. +// EndpointInfo will be stored in the Attributes field of Endpoints. type EndpointInfo struct { Weight uint32 } @@ -43,22 +43,16 @@ func (a EndpointInfo) Equal(o any) bool { return ok && oa.Weight == a.Weight } -// Set returns a copy of endpoint in which the Attributes field is updated with -// EndpointInfo. +// Set returns a copy of endpoint in which the Attributes field is +// updated with EndpointInfo. func Set(endpoint resolver.Endpoint, epInfo EndpointInfo) resolver.Endpoint { endpoint.Attributes = endpoint.Attributes.WithValue(attributeKey{}, epInfo) return endpoint } -// String returns a human-readable representation of EndpointInfo. -// This method is intended for logging, testing, and debugging purposes only. -// Do not rely on the output format, as it is not guaranteed to remain stable. -func (a EndpointInfo) String() string { - return fmt.Sprintf("Weight: %d", a.Weight) -} - -// FromEndpoint returns the EndpointInfo stored in the Attributes field of an -// endpoint. It returns an empty EndpointInfo if attribute is not found. +// FromEndpoint returns the EndpointInfo stored in the Attributes +// field of an endpoint. It returns an empty EndpointInfo if attribute +// is not found. func FromEndpoint(endpoint resolver.Endpoint) EndpointInfo { v := endpoint.Attributes.Value(attributeKey{}) ei, _ := v.(EndpointInfo) diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go index 9e10fdd2eb91..537ba0571c9b 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -17,7 +17,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.6.1 +// - protoc-gen-go-grpc v1.6.2 // - protoc v5.27.1 // source: grpc/health/v1/health.proto diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 8ca87a57a28d..29d332e7b671 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -59,6 +59,15 @@ var ( // unconditionally. XDSEndpointHashKeyBackwardCompat = boolFromEnv("GRPC_XDS_ENDPOINT_HASH_KEY_BACKWARD_COMPAT", false) + // LabelServerGoroutines controls setting [runtime/pprof.Labels] on the + // goroutines spawned by [grpc.Server] type. + // For now, this is limited to the goroutines spawned to handle incoming + // requests on the server. + // Set "GRPC_GO_SERVER_GOROUTINE_LABELS" to "grpc.method=true" to + // enable this grpc.method label, or "all" to enable all valid labels. + // This variable is a bit-field. + LabelServerGoroutines = goroutineLabelsFromEnv("GRPC_GO_SERVER_GOROUTINE_LABELS", 0) + // RingHashSetRequestHashKey is set if the ring hash balancer can get the // request hash header by setting the "requestHashHeader" field, according // to gRFC A76. It can be disabled by setting the environment variable @@ -78,12 +87,12 @@ var ( EnableDefaultPortForProxyTarget = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_DEFAULT_PORT_FOR_PROXY_TARGET", true) // CaseSensitiveBalancerRegistries is set if the balancer registry should be - // case-sensitive. This is disabled by default, but can be enabled by setting + // case-sensitive. This is enabled by default, but can be disabled by setting // the env variable "GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES" - // to "true". + // to "false". // - // TODO: After 2 releases, we will enable the env var by default. - CaseSensitiveBalancerRegistries = boolFromEnv("GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES", false) + // This env varible will be removed in release v1.82.0. + CaseSensitiveBalancerRegistries = boolFromEnv("GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES", true) // XDSAuthorityRewrite indicates whether xDS authority rewriting is enabled. // This feature is defined in gRFC A81 and is enabled by setting the @@ -104,22 +113,6 @@ var ( // to "false". XDSRecoverPanicInResourceParsing = boolFromEnv("GRPC_GO_EXPERIMENTAL_XDS_RESOURCE_PANIC_RECOVERY", true) - // DisableStrictPathChecking indicates whether strict path checking is - // disabled. This feature can be disabled by setting the environment - // variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING to "true". - // - // When strict path checking is enabled, gRPC will reject requests with - // paths that do not conform to the gRPC over HTTP/2 specification found at - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md. - // - // When disabled, gRPC will allow paths that do not contain a leading slash. - // Enabling strict path checking is recommended for security reasons, as it - // prevents potential path traversal vulnerabilities. - // - // A future release will remove this environment variable, enabling strict - // path checking behavior unconditionally. - DisableStrictPathChecking = boolFromEnv("GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING", false) - // EnablePriorityLBChildPolicyCache controls whether the priority balancer // should cache child balancers that are removed from the LB policy config, // for a period of 15 minutes. This is disabled by default, but can be @@ -127,6 +120,18 @@ var ( // GRPC_EXPERIMENTAL_ENABLE_PRIORITY_LB_CHILD_POLICY_CACHE to true. EnablePriorityLBChildPolicyCache = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_PRIORITY_LB_CHILD_POLICY_CACHE", false) + // Enable8KBDefaultHeaderListSize indicates that default maximum header list + // size is restricted to 8KB. This is disabled by default, but can be enabled + // by setting the environment variable + // "GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE" to "true". + // When disabled, the default maximum header list size of 16MB is used. + // + // When enabled, RPCs with a total size of headers exceeding 8KB will fail + // unless explicitly configured otherwise by the user. + // + // TODO: In release v1.82.0, env var will be enabled by default. + Enable8KBDefaultHeaderListSize = boolFromEnv("GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE", false) + // EnableHTTPFramerReadBufferPooling enables the use of the // readyreader.Reader interface to perform non-memory-pinning reads, // provided the underlying net.Conn supports it. This reduces memory usage @@ -136,6 +141,17 @@ var ( // feature if unforeseen issues arise, and it will be removed in a future // release. EnableHTTPFramerReadBufferPooling = boolFromEnv("GRPC_GO_EXPERIMENTAL_HTTP_FRAMER_READ_BUFFER_POOLING", true) + + // ControlBufferThrottleLimit is the maximum number of control frames that can + // be queued in the control buffer before throttling is applied. The value + // must be between 1 and 10,000, and is set to 100 by default. + // + // This environment variable serves as an escape hatch to increase the + // throttling limit if unforeseen issues arise, and it will be removed in a + // future release. + // + // TODO: Remove this env var once v1.83.0 is release. + ControlBufferThrottleLimit = uint64FromEnv("GRPC_GO_EXPERIMENTAL_CONTROL_BUFFER_THROTTLE_LIMIT", 100, 1, 10000) ) func boolFromEnv(envVar string, def bool) bool { @@ -160,3 +176,52 @@ func uint64FromEnv(envVar string, def, min, max uint64) uint64 { } return v } + +// GoroutineLabels is a bitfield indicating which goroutine labels are enabled. +type GoroutineLabels uint16 + +func goroutineLabelsFromEnv(envVar string, def GoroutineLabels) GoroutineLabels { + val := def + v := os.Getenv(envVar) + if strings.EqualFold(v, "all") { + return AllGoroutineLabels + } else if strings.EqualFold(v, "none") { + return 0 + } + for s := range strings.SplitSeq(v, ",") { + s = strings.TrimSpace(s) + if len(s) == 0 { + continue + } + pre, post, ok := strings.Cut(s, "=") + if !ok { + // no equals sign + continue + } + post = strings.TrimSpace(post) + pre = strings.TrimSpace(pre) + bitDesignator := GoroutineLabels(0) + switch { + case strings.EqualFold(pre, "grpc.method"): + bitDesignator = GoroutineLabelServerMethod + default: + continue + } + if strings.EqualFold(post, "true") { + val |= bitDesignator + } else if strings.EqualFold(post, "false") { + val &^= bitDesignator + } + } + return val +} + +const ( + // GoroutineLabelServerMethod sets the grpc.method label on new + // server-side gRPC streams. + GoroutineLabelServerMethod GoroutineLabels = 1 << iota +) + +// AllGoroutineLabels is an or'd together bitfield of all valid GoroutineLabels +// constant values (above). +const AllGoroutineLabels = GoroutineLabelServerMethod diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index 333d8a0b06a7..a2312f8eacf1 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -89,4 +89,14 @@ var ( // filtered and prefix-propagated to the LRS server. For more details, see: // https://github.com/grpc/proposal/blob/master/A85-lrs-custom-metrics-changes.md XDSORCAToLRSPropEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_ORCA_LRS_PROPAGATION", false) + + // XDSClientExtProcEnabled indicates whether ExtProc filter is enabled on + // the client side. For more details, see: + // https://github.com/grpc/proposal/blob/master/A93-xds-ext-proc.md + XDSClientExtProcEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_EXT_PROC_ON_CLIENT", false) + + // GCPAuthenticationFilterEnabled enables the xDS GCP Authentication + // filter. For more details, see: + // https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md + GCPAuthenticationFilterEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_GCP_AUTHENTICATION_FILTER", false) ) diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go b/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go index b25b0baec3cc..1cc43fc6b814 100644 --- a/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go +++ b/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go @@ -39,7 +39,6 @@ func div(d, r time.Duration) int64 { // // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests func EncodeDuration(t time.Duration) string { - // TODO: This is simplistic and not bandwidth efficient. Improve it. if t <= 0 { return "0n" } diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 3db62ccad24d..6320e9b576bb 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -106,14 +106,24 @@ type ClientStream interface { // ClientInterceptor is an interceptor for gRPC client streams. type ClientInterceptor interface { - // NewStream produces a ClientStream for an RPC which may optionally use - // the provided function to produce a stream for delegation. Note: - // RPCInfo.Context should not be used (will be nil). + // NewStream creates a ClientStream for an RPC. // - // done is invoked when the RPC is finished using its connection, or could - // not be assigned a connection. RPC operations may still occur on - // ClientStream after done is called, since the interceptor is invoked by - // application-layer operations. done must never be nil when called. + // Implementations must delegate stream creation to the provided newStream + // function. To intercept or override stream behavior, implementations + // may wrap the ClientStream returned by the delegate. + // + // Note: RPCInfo.Context is currently unused and will be nil. + // + // The done function is invoked when the RPC has finished using its + // underlying connection or if a connection could not be assigned. Because + // interceptors operate at the application layer, RPC operations may + // continue on the ClientStream even after done has been called. The + // caller must ensure done is non-nil. + // + // To ensure RPC completion notifications propagate through the entire + // interceptor chain, implementations must ensure that the done function + // passed to the delegate newStream invokes the done function passed to + // NewStream. NewStream(ctx context.Context, ri RPCInfo, done func(), newStream func(ctx context.Context, done func()) (ClientStream, error)) (ClientStream, error) // Close closes the interceptor. Once called, no new calls to NewStream are // accepted. Ongoing calls to NewStream are allowed to complete. diff --git a/vendor/google.golang.org/grpc/internal/stats/labels.go b/vendor/google.golang.org/grpc/internal/stats/labels.go index fd33af51ae89..5ea898cb5342 100644 --- a/vendor/google.golang.org/grpc/internal/stats/labels.go +++ b/vendor/google.golang.org/grpc/internal/stats/labels.go @@ -19,24 +19,56 @@ // Package stats provides internal stats related functionality. package stats -import "context" +import ( + "context" + "maps" +) -// Labels are the labels for metrics. -type Labels struct { - // TelemetryLabels are the telemetry labels to record. - TelemetryLabels map[string]string +// LabelCallback is a function that is executed when telemetry +// label keys are updated. +type LabelCallback func(map[string]string) +type telemetryLabelCallbackKey struct{} + +// UpdateLabels executes registered telemetry callbacks with the update labels. Labels +// are copied before being processed by any callbacks to ensure mutations are not +// shared among derived contexts. +// +// It is the responsibility of the registrant to handle conflicts or label resets. +func UpdateLabels(ctx context.Context, update map[string]string) { + executeTelemetryLabelCallbacks(ctx, update) } -type labelsKey struct{} +// RegisterTelemetryLabelCallback registers a callback function that is executed whenever +// telemetry labels are updated. +func RegisterTelemetryLabelCallback(ctx context.Context, callback LabelCallback) context.Context { + if callback == nil { + return ctx + } + + callbacks, ok := ctx.Value(telemetryLabelCallbackKey{}).([]LabelCallback) + if !ok { + return context.WithValue(ctx, telemetryLabelCallbackKey{}, []LabelCallback{callback}) + } + return context.WithValue(ctx, telemetryLabelCallbackKey{}, append(append([]LabelCallback(nil), callbacks...), callback)) -// GetLabels returns the Labels stored in the context, or nil if there is one. -func GetLabels(ctx context.Context) *Labels { - labels, _ := ctx.Value(labelsKey{}).(*Labels) - return labels } -// SetLabels sets the Labels in the context. -func SetLabels(ctx context.Context, labels *Labels) context.Context { - // could also append - return context.WithValue(ctx, labelsKey{}, labels) +// executeTelemetryLabelCallback runs the registered callbacks in the order they were +// registered on the context with the provided labels. If no callbacks are registered +// it does nothing. +// +// To ensure callbacks do not mutate the state of the provided label map it is copied +// before execution. +func executeTelemetryLabelCallbacks(ctx context.Context, labels map[string]string) { + callbacks, ok := ctx.Value(telemetryLabelCallbackKey{}).([]LabelCallback) + if !ok { + return + } + + labelsCopy := map[string]string{} + maps.Copy(labelsCopy, labels) + for _, callback := range callbacks { + callback(labelsCopy) + } + } diff --git a/vendor/google.golang.org/grpc/internal/transport/client_stream.go b/vendor/google.golang.org/grpc/internal/transport/client_stream.go index cd8152ef13c7..ad382b0fda1c 100644 --- a/vendor/google.golang.org/grpc/internal/transport/client_stream.go +++ b/vendor/google.golang.org/grpc/internal/transport/client_stream.go @@ -19,6 +19,7 @@ package transport import ( + "fmt" "sync/atomic" "golang.org/x/net/http2" @@ -28,6 +29,12 @@ import ( "google.golang.org/grpc/status" ) +// nonGRPCDataMaxLen is the maximum length of nonGRPCDataBuf. +// +// NOTE: If changed this value, you MUST update the corresponding test in: +// - /test/end2end_test.go:TestHTTPServerSendsNonGRPCHeaderSurfaceFurtherData +const nonGRPCDataMaxLen = 1024 + // ClientStream implements streaming functionality for a gRPC client. type ClientStream struct { Stream // Embed for common stream functionality. @@ -46,7 +53,11 @@ type ClientStream struct { // headerValid indicates whether a valid header was received. Only // meaningful after headerChan is closed (always call waitOnHeader() before // reading its value). - headerValid bool + headerValid bool + + nonGRPCStatus *status.Status // the initial status from the non-gRPC response header, finalized with collected data before closing. + nonGRPCDataBuf []byte // stores the data of a non-gRPC response. + noHeaders bool // set if the client never received headers (set only after the stream is done). headerChanClosed uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. bytesReceived atomic.Bool // indicates whether any bytes have been received on this stream @@ -54,6 +65,29 @@ type ClientStream struct { statsHandler stats.Handler // nil for internal streams (e.g., health check, ORCA) where telemetry is not supported. } +func (s *ClientStream) startNonGRPCDataCollection(st *status.Status) { + s.nonGRPCStatus = st + s.nonGRPCDataBuf = make([]byte, 0, nonGRPCDataMaxLen) +} + +// finalizeNonGRPCStatus builds the terminal status by appending the collected +// response body to the original non-gRPC status message. +func (s *ClientStream) finalizeNonGRPCStatus() *status.Status { + msg := fmt.Sprintf("%s\ndata: %q", s.nonGRPCStatus.Message(), s.nonGRPCDataBuf) + return status.New(s.nonGRPCStatus.Code(), msg) +} + +// handleNonGRPCData collects non-gRPC body from the given data frame. +// It returns non-nil value when the stream should be closed with it. +func (s *ClientStream) handleNonGRPCData(f *parsedDataFrame) *status.Status { + n := min(f.data.Len(), nonGRPCDataMaxLen-len(s.nonGRPCDataBuf)) + s.nonGRPCDataBuf = append(s.nonGRPCDataBuf, f.data.ReadOnlyData()[0:n]...) + if len(s.nonGRPCDataBuf) >= nonGRPCDataMaxLen || f.StreamEnded() { + return s.finalizeNonGRPCStatus() + } + return nil +} + // Read reads an n byte message from the input stream. func (s *ClientStream) Read(n int) (mem.BufferSlice, error) { b, err := s.Stream.read(n) diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index 7efa524785b1..b9bae02498ea 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -29,6 +29,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/mem" ) @@ -96,61 +97,70 @@ func (il *itemList) isEmpty() bool { return il.head == nil } -// The following defines various control items which could flow through -// the control buffer of transport. They represent different aspects of -// control tasks, e.g., flow control, settings, streaming resetting, etc. - -// maxQueuedTransportResponseFrames is the most queued "transport response" -// frames we will buffer before preventing new reads from occurring on the -// transport. These are control frames sent in response to client requests, -// such as RST_STREAM due to bad headers or settings acks. -const maxQueuedTransportResponseFrames = 50 +// maxQueuedControlBufferItems is the maximum number of frames (other than +// HEADERS and DATA) that we will buffer before preventing new reads from +// occurring on the transport. These are control frames sent in response to +// client requests, or frames that result in work being scheduled, such as +// RST_STREAM due to bad headers or settings acks. +var maxQueuedControlBufferItems = int(envconfig.ControlBufferThrottleLimit) type cbItem interface { - isTransportResponseFrame() bool + isThrottled() bool } +// throttledItem represents every item in the controlBuffer to which the overall +// throttling limit applies, other than outgoing HEADERS and DATA frames. +type throttledItem struct{} + +func (throttledItem) isThrottled() bool { return true } + +// The following defines various control items which could flow through +// the control buffer of transport. They represent different aspects of +// control tasks, e.g., flow control, settings, streaming resetting, etc. + // registerStream is used to register an incoming stream with loopy writer. type registerStream struct { + throttledItem streamID uint32 wq *writeQuota } -func (*registerStream) isTransportResponseFrame() bool { return false } - -// headerFrame is also used to register stream on the client-side. -type headerFrame struct { +type clientHeaders struct { streamID uint32 hf []hpack.HeaderField - endStream bool // Valid on server side. - initStream func(uint32) error // Used only on the client side. + initStream func(uint32) error onWrite func() - wq *writeQuota // write quota for the stream created. - cleanup *cleanupStream // Valid on the server side. - onOrphaned func(error) // Valid on client-side + wq *writeQuota + onOrphaned func(error) } -func (h *headerFrame) isTransportResponseFrame() bool { - return h.cleanup != nil && h.cleanup.rst // Results in a RST_STREAM +func (*clientHeaders) isThrottled() bool { return false } + +type serverHeaders struct { + streamID uint32 + hf []hpack.HeaderField + endStream bool + onWrite func() + cleanup *cleanupStream } +func (h *serverHeaders) isThrottled() bool { return false } + type cleanupStream struct { + throttledItem streamID uint32 rst bool rstCode http2.ErrCode onWrite func() } -func (c *cleanupStream) isTransportResponseFrame() bool { return c.rst } // Results in a RST_STREAM - type earlyAbortStream struct { + throttledItem streamID uint32 rst bool hf []hpack.HeaderField // Pre-built header fields } -func (*earlyAbortStream) isTransportResponseFrame() bool { return false } - type dataFrame struct { streamID uint32 endStream bool @@ -162,70 +172,60 @@ type dataFrame struct { onEachWrite func() } -func (*dataFrame) isTransportResponseFrame() bool { return false } +func (*dataFrame) isThrottled() bool { return false } type incomingWindowUpdate struct { + throttledItem streamID uint32 increment uint32 } -func (*incomingWindowUpdate) isTransportResponseFrame() bool { return false } - type outgoingWindowUpdate struct { + throttledItem streamID uint32 increment uint32 } -func (*outgoingWindowUpdate) isTransportResponseFrame() bool { - return false // window updates are throttled by thresholds -} - type incomingSettings struct { + throttledItem ss []http2.Setting } -func (*incomingSettings) isTransportResponseFrame() bool { return true } // Results in a settings ACK - type outgoingSettings struct { + throttledItem ss []http2.Setting } -func (*outgoingSettings) isTransportResponseFrame() bool { return false } - type incomingGoAway struct { + throttledItem } -func (*incomingGoAway) isTransportResponseFrame() bool { return false } - type goAway struct { + throttledItem code http2.ErrCode debugData []byte headsUp bool closeConn error // if set, loopyWriter will exit with this error } -func (*goAway) isTransportResponseFrame() bool { return false } - type ping struct { + throttledItem ack bool data [8]byte } -func (*ping) isTransportResponseFrame() bool { return true } - type outFlowControlSizeRequest struct { + throttledItem resp chan uint32 } -func (*outFlowControlSizeRequest) isTransportResponseFrame() bool { return false } - // closeConnection is an instruction to tell the loopy writer to flush the // framer and exit, which will cause the transport's connection to be closed // (by the client or server). The transport itself will close after the reader // encounters the EOF caused by the connection closure. -type closeConnection struct{} - -func (closeConnection) isTransportResponseFrame() bool { return false } +type closeConnection struct { + throttledItem +} type outStreamState int @@ -379,9 +379,9 @@ func (c *controlBuffer) executeAndPut(f func() bool, it cbItem) (bool, error) { c.consumerWaiting = false } c.list.enqueue(it) - if it.isTransportResponseFrame() { + if it.isThrottled() { c.transportResponseFrames++ - if c.transportResponseFrames == maxQueuedTransportResponseFrames { + if c.transportResponseFrames == maxQueuedControlBufferItems { // We are adding the frame that puts us over the threshold; create // a throttling channel. ch := make(chan struct{}) @@ -436,8 +436,8 @@ func (c *controlBuffer) getOnceLocked() (any, error) { return nil, nil } h := c.list.dequeue().(cbItem) - if h.isTransportResponseFrame() { - if c.transportResponseFrames == maxQueuedTransportResponseFrames { + if h.isThrottled() { + if c.transportResponseFrames == maxQueuedControlBufferItems { // We are removing the frame that put us over the // threshold; close and clear the throttling channel. ch := c.trfChan.Swap(nil) @@ -464,10 +464,8 @@ func (c *controlBuffer) finish() { // is still not aware of these yet. for head := c.list.dequeueAll(); head != nil; head = head.next { switch v := head.it.(type) { - case *headerFrame: - if v.onOrphaned != nil { // It will be nil on the server-side. - v.onOrphaned(ErrConnClosing) - } + case *clientHeaders: + v.onOrphaned(ErrConnClosing) case *dataFrame: if !v.processing { v.data.Free() @@ -680,42 +678,38 @@ func (l *loopyWriter) registerStreamHandler(h *registerStream) { l.estdStreams[h.streamID] = str } -func (l *loopyWriter) headerHandler(h *headerFrame) error { - if l.side == serverSide { - str, ok := l.estdStreams[h.streamID] - if !ok { - if l.logger.V(logLevel) { - l.logger.Infof("Unrecognized streamID %d in loopyWriter", h.streamID) - } - return nil - } - // Case 1.A: Server is responding back with headers. - if !h.endStream { - return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) +func (l *loopyWriter) serverHeaderHandler(hdr *serverHeaders) error { + str, ok := l.estdStreams[hdr.streamID] + if !ok { + if l.logger.V(logLevel) { + l.logger.Infof("Unrecognized streamID %d in loopyWriter", hdr.streamID) } - // else: Case 1.B: Server wants to close stream. + return nil + } - if str.state != empty { // either active or waiting on stream quota. - // add it str's list of items. - str.itl.enqueue(h) - return nil - } - if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { - return err - } - return l.cleanupStreamHandler(h.cleanup) + // Case 1: Server is responding back with headers. + if !hdr.endStream { + return l.writeHeader(hdr.streamID, hdr.endStream, hdr.hf, hdr.onWrite) + } + + // Case 2: Server is closing the stream. + if str.state != empty { // either active or waiting on stream quota. + str.itl.enqueue(hdr) + return nil + } + if err := l.writeHeader(hdr.streamID, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { + return err } - // Case 2: Client wants to originate stream. + return l.cleanupStreamHandler(hdr.cleanup) +} + +func (l *loopyWriter) clientHeaderHandler(hdr *clientHeaders) error { str := &outStream{ - id: h.streamID, + id: hdr.streamID, state: empty, itl: &itemList{}, - wq: h.wq, + wq: hdr.wq, } - return l.originateStream(str, h) -} - -func (l *loopyWriter) originateStream(str *outStream, hdr *headerFrame) error { // l.draining is set when handling GoAway. In which case, we want to avoid // creating new streams. if l.draining { @@ -726,7 +720,7 @@ func (l *loopyWriter) originateStream(str *outStream, hdr *headerFrame) error { if err := hdr.initStream(str.id); err != nil { return err } - if err := l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { + if err := l.writeHeader(str.id, false, hdr.hf, hdr.onWrite); err != nil { return err } l.estdStreams[str.id] = str @@ -882,8 +876,10 @@ func (l *loopyWriter) handle(i any) error { return l.incomingSettingsHandler(i) case *outgoingSettings: return l.outgoingSettingsHandler(i) - case *headerFrame: - return l.headerHandler(i) + case *clientHeaders: + return l.clientHeaderHandler(i) + case *serverHeaders: + return l.serverHeaderHandler(i) case *registerStream: l.registerStreamHandler(i) case *cleanupStream: @@ -956,39 +952,16 @@ func (l *loopyWriter) processData() (bool, error) { // from data is copied to h to make as big as the maximum possible HTTP2 frame // size. - if len(dataItem.h) == 0 && reader.Remaining() == 0 { // Empty data frame - // Client sends out empty data frame with endStream = true - if err := l.framer.writeData(dataItem.streamID, dataItem.endStream, nil); err != nil { - return false, err - } - str.itl.dequeue() // remove the empty data item from stream - reader.Close() - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err - } - } else { - l.activeStreams.enqueue(str) - } - return false, nil - } - + isEmpty := len(dataItem.h) == 0 && reader.Remaining() == 0 // Figure out the maximum size we can send maxSize := http2MaxFrameLen - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { // stream-level flow control. + strQuota := int(l.oiws) - str.bytesOutStanding + if strQuota <= 0 && !isEmpty { // stream-level flow control. str.state = waitingOnStreamQuota return false, nil - } else if maxSize > strQuota { - maxSize = strQuota - } - if maxSize > int(l.sendQuota) { // connection-level flow control. - maxSize = int(l.sendQuota) } + maxSize = min(maxSize, max(strQuota, 0)) + maxSize = min(maxSize, int(l.sendQuota)) // connection-level flow control. // Compute how much of the header and data we can send within quota and max frame length hSize := min(maxSize, len(dataItem.h)) dSize := min(maxSize-hSize, reader.Remaining()) @@ -1039,19 +1012,23 @@ func (l *loopyWriter) processData() (bool, error) { reader.Close() str.itl.dequeue() } + return false, l.updateStreamAfterWrite(str) +} + +func (l *loopyWriter) updateStreamAfterWrite(str *outStream) error { if str.itl.isEmpty() { str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. + } else if trailer, ok := str.itl.peek().(*serverHeaders); ok { // the next item is trailers. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err + return err } if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err + return err } } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. str.state = waitingOnStreamQuota } else { // Otherwise add it back to the list of active streams. l.activeStreams.enqueue(str) } - return false, nil + return nil } diff --git a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go index 7cfbc9637b88..98cef9ec2baf 100644 --- a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go +++ b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go @@ -115,7 +115,6 @@ func (f *trInFlow) getSize() uint32 { return atomic.LoadUint32(&f.effectiveWindowSize) } -// TODO(mmukhi): Simplify this code. // inFlow deals with inbound flow control type inFlow struct { mu sync.Mutex @@ -174,14 +173,14 @@ func (f *inFlow) maybeAdjust(n uint32) uint32 { // onData is invoked when some data frame is received. It updates pendingData. func (f *inFlow) onData(n uint32) error { f.mu.Lock() + defer f.mu.Unlock() + f.pendingData += n if f.pendingData+f.pendingUpdate > f.limit+f.delta { limit := f.limit rcvd := f.pendingData + f.pendingUpdate - f.mu.Unlock() return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) } - f.mu.Unlock() return nil } @@ -189,8 +188,9 @@ func (f *inFlow) onData(n uint32) error { // to be sent to the peer. func (f *inFlow) onRead(n uint32) uint32 { f.mu.Lock() + defer f.mu.Unlock() + if f.pendingData == 0 { - f.mu.Unlock() return 0 } f.pendingData -= n @@ -205,9 +205,7 @@ func (f *inFlow) onRead(n uint32) uint32 { if f.pendingUpdate >= f.limit/4 { wu := f.pendingUpdate f.pendingUpdate = 0 - f.mu.Unlock() return wu } - f.mu.Unlock() return 0 } diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index 7ab3422b8a27..a8356c9adbc1 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -479,8 +479,8 @@ func (ht *serverHandlerTransport) runStream() { func (ht *serverHandlerTransport) incrMsgRecv() {} -func (ht *serverHandlerTransport) Drain(string) { - panic("Drain() is not implemented") +func (ht *serverHandlerTransport) Drain(s string) { + ht.Close(errors.New(s)) } // mapRecvMsgError returns the non-nil err into the appropriate diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index d6bc6a6cc730..822c09ba621b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -39,6 +39,7 @@ import ( "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/channelz" icredentials "google.golang.org/grpc/internal/credentials" + "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" @@ -318,7 +319,13 @@ func NewHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } writeBufSize := opts.WriteBufferSize readBufSize := opts.ReadBufferSize + // The default header list size is moving from 16MB to 8KB. The 8KB limit + // is only used if Enable8KBDefaultHeaderListSize is true; otherwise, the + // old 16MB default is used. User-specified options always take precedence. maxHeaderListSize := defaultClientMaxHeaderListSize + if envconfig.Enable8KBDefaultHeaderListSize { + maxHeaderListSize = upcomingDefaultHeaderListSize + } if opts.MaxHeaderListSize != nil { maxHeaderListSize = *opts.MaxHeaderListSize } @@ -799,9 +806,8 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr, handler s close(s.headerChan) } } - hdr := &headerFrame{ - hf: headerFields, - endStream: false, + hdr := &clientHeaders{ + hf: headerFields, initStream: func(uint32) error { t.mu.Lock() // TODO: handle transport closure in loopy instead and remove this @@ -879,8 +885,8 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr, handler s return false } } - if sz > int64(upcomingDefaultHeaderListSize) { - t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In a future release, this will be restricted to %d bytes.", sz, upcomingDefaultHeaderListSize, upcomingDefaultHeaderListSize) + if !envconfig.Enable8KBDefaultHeaderListSize && sz > int64(upcomingDefaultHeaderListSize) { + t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In release v1.82.0, GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE will be enabled by default, enforcing this limit.", sz, upcomingDefaultHeaderListSize) } return true } @@ -1224,10 +1230,30 @@ func (t *http2Client) handleData(f *parsedDataFrame) { t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } + + if s.nonGRPCStatus != nil { + // The frame should be handled as a non-gRPC response body + st := s.handleNonGRPCData(f) + if st != nil { + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) + return + } + if w := s.fc.onRead(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) + } + return + } + dataLen := f.data.Len() if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(dataLen)); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) } } if dataLen > 0 { @@ -1468,6 +1494,17 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { return } + // If we are collecting non-gRPC response data and receive a trailing + // HEADERS frame with END_STREAM, finalize the buffered data and close + // the stream. + if s.nonGRPCStatus != nil { + if endStream { + st := s.finalizeNonGRPCStatus() + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) + } + return + } + var ( // If a gRPC Response-Headers has already been received, then it means // that the peer is speaking gRPC and we are in gRPC mode. @@ -1568,7 +1605,12 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { } se := status.New(grpcErrorCode, strings.Join(errs, "; ")) - t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) + if endStream { + t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, true) + return + } + + s.startNonGRPCDataCollection(se) return } @@ -1839,7 +1881,7 @@ func (t *http2Client) getOutFlowWindow() int64 { resp := make(chan uint32, 1) timer := time.NewTimer(time.Second) defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) + t.controlBuf.put(&outFlowControlSizeRequest{resp: resp}) select { case sz := <-resp: return int64(sz) diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 3a8c36e4f94f..be8ae9f9c54f 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -38,11 +38,13 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/pretty" istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/syscall" + transportinternal "google.golang.org/grpc/internal/transport/internal" "google.golang.org/grpc/mem" "google.golang.org/grpc/codes" @@ -165,7 +167,13 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, } writeBufSize := config.WriteBufferSize readBufSize := config.ReadBufferSize + // The default header list size is moving from 16MB to 8KB. The 8KB limit + // is only used if Enable8KBDefaultHeaderListSize is true; otherwise, the + // old 16MB default is used. User-specified options always take precedence. maxHeaderListSize := defaultServerMaxHeaderListSize + if envconfig.Enable8KBDefaultHeaderListSize { + maxHeaderListSize = upcomingDefaultHeaderListSize + } if config.MaxHeaderListSize != nil { maxHeaderListSize = *config.MaxHeaderListSize } @@ -802,7 +810,10 @@ func (t *http2Server) handleData(f *parsedDataFrame) { dataLen := f.data.Len() if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(dataLen)); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) } } if dataLen > 0 { @@ -948,8 +959,8 @@ func (t *http2Server) checkForHeaderListSize(hf []hpack.HeaderField) bool { return false } } - if sz > int64(upcomingDefaultHeaderListSize) { - t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In a future release, this will be restricted to %d bytes.", sz, upcomingDefaultHeaderListSize, upcomingDefaultHeaderListSize) + if !envconfig.Enable8KBDefaultHeaderListSize && sz > int64(upcomingDefaultHeaderListSize) { + t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In release v1.82.0, GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE will be enabled by default, enforcing this limit.", sz, upcomingDefaultHeaderListSize) } return true } @@ -1039,7 +1050,7 @@ func (t *http2Server) writeHeaderLocked(s *ServerStream) error { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress}) } headerFields = appendHeaderFieldsFromMD(headerFields, s.header) - hf := &headerFrame{ + hf := &serverHeaders{ streamID: s.id, hf: headerFields, endStream: false, @@ -1107,7 +1118,7 @@ func (t *http2Server) writeStatus(s *ServerStream, st *status.Status) error { // Attach the trailer metadata. headerFields = appendHeaderFieldsFromMD(headerFields, s.trailer) - trailingHeader := &headerFrame{ + trailingHeader := &serverHeaders{ streamID: s.id, hf: headerFields, endStream: true, @@ -1317,7 +1328,7 @@ func (t *http2Server) deleteStream(s *ServerStream, eosReceived bool) { } // finishStream closes the stream and puts the trailing headerFrame into controlbuf. -func (t *http2Server) finishStream(s *ServerStream, rst bool, rstCode http2.ErrCode, hdr *headerFrame, eosReceived bool) { +func (t *http2Server) finishStream(s *ServerStream, rst bool, rstCode http2.ErrCode, hdr *serverHeaders, eosReceived bool) { // In case stream sending and receiving are invoked in separate // goroutines (e.g., bi-directional streaming), cancel needs to be // called to interrupt the potential blocking on other goroutines. @@ -1441,14 +1452,14 @@ func (t *http2Server) socketMetrics() *channelz.EphemeralSocketMetrics { func (t *http2Server) incrMsgSent() { if channelz.IsOn() { t.channelz.SocketMetrics.MessagesSent.Add(1) - t.channelz.SocketMetrics.LastMessageSentTimestamp.Add(1) + t.channelz.SocketMetrics.LastMessageSentTimestamp.Store(transportinternal.TimeNowFunc()) } } func (t *http2Server) incrMsgRecv() { if channelz.IsOn() { t.channelz.SocketMetrics.MessagesReceived.Add(1) - t.channelz.SocketMetrics.LastMessageReceivedTimestamp.Add(1) + t.channelz.SocketMetrics.LastMessageReceivedTimestamp.Store(transportinternal.TimeNowFunc()) } } @@ -1456,7 +1467,7 @@ func (t *http2Server) getOutFlowWindow() int64 { resp := make(chan uint32, 1) timer := time.NewTimer(time.Second) defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) + t.controlBuf.put(&outFlowControlSizeRequest{resp: resp}) select { case sz := <-resp: return int64(sz) diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/regex.go b/vendor/google.golang.org/grpc/internal/transport/internal/internal.go similarity index 59% rename from vendor/google.golang.org/grpc/internal/grpcutil/regex.go rename to vendor/google.golang.org/grpc/internal/transport/internal/internal.go index 7a092b2b8041..a7c7c7d5a8d0 100644 --- a/vendor/google.golang.org/grpc/internal/grpcutil/regex.go +++ b/vendor/google.golang.org/grpc/internal/transport/internal/internal.go @@ -1,6 +1,6 @@ /* * - * Copyright 2021 gRPC authors. + * Copyright 2026 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,10 @@ * */ -package grpcutil +// Package internal contains functionality internal to the transport package. +package internal -import "regexp" - -// FullMatchWithRegex returns whether the full text matches the regex provided. -func FullMatchWithRegex(re *regexp.Regexp, text string) bool { - if len(text) == 0 { - return re.MatchString(text) - } - re.Longest() - rem := re.FindString(text) - return len(rem) == len(text) -} +// TimeNowFunc is a variable that can be set to override the default behavior of +// getting the current time in nanoseconds. It is used in transport code to set +// channelz timestamps, and is exposed here for testing purposes. +var TimeNowFunc func() int64 diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 1e224576e806..6dfae39849e4 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -35,6 +35,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" + "google.golang.org/grpc/internal/transport/internal" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" @@ -46,6 +47,10 @@ import ( const logLevel = 2 +func init() { + internal.TimeNowFunc = func() int64 { return time.Now().UnixNano() } +} + // recvMsg represents the received msg from the transport. All transport // protocol specific info has been removed. type recvMsg struct { diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index ee7f7dead1a3..52f4ea513df1 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -128,6 +128,16 @@ func NewGZIPDecompressor() Decompressor { } func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { + return d.doWithMaxSize(r, math.MaxInt64) +} + +// doWithMaxSize behaves like Do but caps the size of the decompressed +// payload at maxMessageSize+1 bytes. The Decompressor interface does not +// allow extra parameters, so callers inside the package type-assert to +// *gzipDecompressor to invoke this method directly. The +1 byte makes it +// possible for the caller to detect that the limit was exceeded and +// return ResourceExhausted instead of materializing an unbounded payload. +func (d *gzipDecompressor) doWithMaxSize(r io.Reader, maxMessageSize int64) ([]byte, error) { var z *gzip.Reader switch maybeZ := d.pool.Get().(type) { case nil: @@ -148,7 +158,11 @@ func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { z.Close() d.pool.Put(z) }() - return io.ReadAll(z) + var src io.Reader = z + if maxMessageSize < math.MaxInt64 { + src = io.LimitReader(z, maxMessageSize+1) + } + return io.ReadAll(src) } func (d *gzipDecompressor) Type() string { @@ -830,15 +844,15 @@ func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, if compressor != nil { z, err := compressor.Compress(w) if err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } for _, b := range in { if _, err := z.Write(b.ReadOnlyData()); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } if err := z.Close(); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } else { // This is obviously really inefficient since it fully materializes the data, but @@ -848,7 +862,7 @@ func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, buf := in.MaterializeToBuffer(pool) defer buf.Free() if err := cp.Do(w, buf.ReadOnlyData()); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } return out, compressionMade, nil @@ -971,7 +985,20 @@ func recvAndDecompress(p *parser, s recvCompressor, dc Decompressor, maxReceiveM func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompressor, maxReceiveMessageSize int, pool mem.BufferPool) (mem.BufferSlice, error) { if dc != nil { r := d.Reader() - uncompressed, err := dc.Do(r) + // For the built-in gzip decompressor, bound the decompressed output + // at maxReceiveMessageSize+1 so that a small but highly compressed + // payload (a "zip bomb") cannot expand to gigabytes in memory before + // the post-decompression size check below has a chance to fire. The + // Decompressor interface does not accept an extra size parameter, + // so we type-assert to invoke a size-aware helper. Third-party + // Decompressor implementations keep the original Do behavior. + var uncompressed []byte + var err error + if gd, ok := dc.(*gzipDecompressor); ok { + uncompressed, err = gd.doWithMaxSize(r, int64(maxReceiveMessageSize)) + } else { + uncompressed, err = dc.Do(r) + } if err != nil { r.Close() // ensure buffers are reused return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err) @@ -989,6 +1016,9 @@ func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompress r.Close() // ensure buffers are reused return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the message: %v", err) } + if closer, ok := dcReader.(io.Closer); ok { + defer closer.Close() + } // Read at most one byte more than the limit from the decompressor. // Unless the limit is MaxInt64, in which case, that's impossible, so diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 5229adf71174..cf0a2067190c 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -28,6 +28,7 @@ import ( "net/http" "reflect" "runtime" + "runtime/pprof" "strings" "sync" "sync/atomic" @@ -150,8 +151,6 @@ type Server struct { serverWorkerChannel chan func() serverWorkerChannelClose func() - - strictPathCheckingLogEmitted atomic.Bool } type serverOptions struct { @@ -250,10 +249,8 @@ func newJoinServerOption(opts ...ServerOption) ServerOption { // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // -// # Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Deprecated: shared write buffer is enabled by default. SharedWriteBuffer +// will be removed in a future release. func SharedWriteBuffer(val bool) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.sharedWriteBuffer = val @@ -302,6 +299,14 @@ func InitialConnWindowSize(s int32) ServerOption { // window size to the value provided and disables dynamic flow control. // The lower bound for window size is 64K and any value smaller than that // will be ignored. +// +// Note that this also disables dynamic flow control for the connection, +// falling back to a default static connection-level window of 64KB. To +// use a larger connection-level window, you must also use the +// [StaticConnWindowSize] ServerOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func StaticStreamWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialWindowSize = s @@ -313,6 +318,14 @@ func StaticStreamWindowSize(s int32) ServerOption { // window size to the value provided and disables dynamic flow control. // The lower bound for window size is 64K and any value smaller than that // will be ignored. +// +// Note that this also disables dynamic flow control for individual streams, +// falling back to a default static connection-level window of 64KB. To +// explicitly configure the stream-level window size, you must also use the +// [StaticStreamWindowSize] ServerOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func StaticConnWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialConnWindowSize = s @@ -1787,6 +1800,12 @@ func (s *Server) handleMalformedMethodName(stream *transport.ServerStream, ti *t func (s *Server) handleStream(t transport.ServerTransport, stream *transport.ServerStream) { ctx := stream.Context() ctx = contextWithServer(ctx, s) + if envconfig.LabelServerGoroutines&envconfig.GoroutineLabelServerMethod != 0 { + // This method always runs in its own goroutine, so we can set a + // goroutine label without needing to restore a previous context. + ctx = pprof.WithLabels(ctx, pprof.Labels("grpc.method", stream.Method())) + pprof.SetGoroutineLabels(ctx) + } var ti *traceInfo if EnableTracing { tr := newTrace("grpc.Recv."+methodFamily(stream.Method()), stream.Method()) @@ -1803,28 +1822,11 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Ser } } - sm := stream.Method() - if sm == "" { + sm, found := strings.CutPrefix(stream.Method(), "/") + if !found { s.handleMalformedMethodName(stream, ti) return } - if sm[0] != '/' { - // TODO(easwars): Add a link to the CVE in the below log messages once - // published. - if envconfig.DisableStrictPathChecking { - if old := s.strictPathCheckingLogEmitted.Swap(true); !old { - channelz.Warningf(logger, s.channelz, "grpc: Server.handleStream received malformed method name %q. Allowing it because the environment variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING is set to true, but this option will be removed in a future release.", sm) - } - } else { - if old := s.strictPathCheckingLogEmitted.Swap(true); !old { - channelz.Warningf(logger, s.channelz, "grpc: Server.handleStream rejected malformed method name %q. To temporarily allow such requests, set the environment variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING to true. Note that this is not recommended as it may allow requests to bypass security policies.", sm) - } - s.handleMalformedMethodName(stream, ti) - return - } - } else { - sm = sm[1:] - } pos := strings.LastIndex(sm, "/") if pos == -1 { s.handleMalformedMethodName(stream, ti) diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 3ccfe515f7cf..53c737feeb95 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.81.1" +const Version = "1.82.1" diff --git a/vendor/modules.txt b/vendor/modules.txt index c924f430f753..b5f6d9db5581 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -72,7 +72,7 @@ github.com/docker/distribution/registry/storage/cache/memory ## explicit; go 1.21 github.com/docker/docker-credential-helpers/client github.com/docker/docker-credential-helpers/credentials -# github.com/docker/go-connections v0.7.0 +# github.com/docker/go-connections v0.8.0 ## explicit; go 1.23 github.com/docker/go-connections/nat github.com/docker/go-connections/sockets @@ -146,7 +146,7 @@ github.com/grpc-ecosystem/grpc-gateway/v2/utilities # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap -# github.com/klauspost/compress v1.18.6 +# github.com/klauspost/compress v1.18.7 ## explicit; go 1.24 github.com/klauspost/compress github.com/klauspost/compress/fse @@ -162,8 +162,8 @@ github.com/mattn/go-runewidth # github.com/moby/docker-image-spec v1.3.1 ## explicit; go 1.18 github.com/moby/docker-image-spec/specs-go/v1 -# github.com/moby/go-archive v0.2.0 -## explicit; go 1.23.0 +# github.com/moby/go-archive v0.3.0 +## explicit; go 1.25 github.com/moby/go-archive github.com/moby/go-archive/compression github.com/moby/go-archive/tarheader @@ -189,7 +189,7 @@ github.com/moby/moby/api/types/storage github.com/moby/moby/api/types/swarm github.com/moby/moby/api/types/system github.com/moby/moby/api/types/volume -# github.com/moby/moby/client v0.5.0 +# github.com/moby/moby/client v0.5.1 ## explicit; go 1.24 github.com/moby/moby/client github.com/moby/moby/client/internal @@ -389,16 +389,16 @@ go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/metrics/v1 go.opentelemetry.io/proto/otlp/resource/v1 go.opentelemetry.io/proto/otlp/trace/v1 -# go.yaml.in/yaml/v3 v3.0.4 +# go.yaml.in/yaml/v3 v3.0.5 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/mod v0.37.0 +# golang.org/x/mod v0.38.0 ## explicit; go 1.25.0 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/net v0.56.0 +# golang.org/x/net v0.57.0 ## explicit; go 1.25.0 golang.org/x/net/http/httpguts golang.org/x/net/http2 @@ -408,19 +408,19 @@ golang.org/x/net/internal/httpcommon golang.org/x/net/internal/httpsfv golang.org/x/net/internal/timeseries golang.org/x/net/trace -# golang.org/x/sync v0.21.0 +# golang.org/x/sync v0.22.0 ## explicit; go 1.25.0 golang.org/x/sync/errgroup -# golang.org/x/sys v0.46.0 +# golang.org/x/sys v0.47.0 ## explicit; go 1.25.0 golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.44.0 +# golang.org/x/term v0.45.0 ## explicit; go 1.25.0 golang.org/x/term -# golang.org/x/text v0.38.0 +# golang.org/x/text v0.40.0 ## explicit; go 1.25.0 golang.org/x/text/secure/bidirule golang.org/x/text/transform @@ -437,7 +437,7 @@ google.golang.org/genproto/googleapis/api/httpbody ## explicit; go 1.25.0 google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.81.1 +# google.golang.org/grpc v1.82.1 ## explicit; go 1.25.0 google.golang.org/grpc google.golang.org/grpc/attributes @@ -459,6 +459,7 @@ google.golang.org/grpc/encoding google.golang.org/grpc/encoding/gzip google.golang.org/grpc/encoding/internal google.golang.org/grpc/encoding/proto +google.golang.org/grpc/experimental/balancer/weight google.golang.org/grpc/experimental/stats google.golang.org/grpc/grpclog google.golang.org/grpc/grpclog/internal @@ -466,7 +467,6 @@ google.golang.org/grpc/health/grpc_health_v1 google.golang.org/grpc/internal google.golang.org/grpc/internal/backoff google.golang.org/grpc/internal/balancer/gracefulswitch -google.golang.org/grpc/internal/balancer/weight google.golang.org/grpc/internal/balancerload google.golang.org/grpc/internal/binarylog google.golang.org/grpc/internal/buffer @@ -492,6 +492,7 @@ google.golang.org/grpc/internal/stats google.golang.org/grpc/internal/status google.golang.org/grpc/internal/syscall google.golang.org/grpc/internal/transport +google.golang.org/grpc/internal/transport/internal google.golang.org/grpc/internal/transport/networktype google.golang.org/grpc/internal/transport/readyreader google.golang.org/grpc/keepalive