From 80926c97bdde72a2bab4fe2724d9fd4f02c48d78 Mon Sep 17 00:00:00 2001 From: abtreece Date: Fri, 8 Dec 2023 21:29:19 -0600 Subject: [PATCH] Bump github.com/hashicorp/vault/api from 1.8.3 to 1.9.1 Bumps github.com/hashicorp/vault/api from 1.8.3 to 1.9.1. --- go.mod | 13 +- go.sum | 28 +- vendor/github.com/armon/go-radix/.gitignore | 22 - vendor/github.com/armon/go-radix/.travis.yml | 3 - vendor/github.com/armon/go-radix/LICENSE | 20 - vendor/github.com/armon/go-radix/README.md | 38 - vendor/github.com/armon/go-radix/radix.go | 540 ------- .../golang/protobuf/ptypes/empty/empty.pb.go | 62 - vendor/github.com/golang/snappy/.gitignore | 16 - vendor/github.com/golang/snappy/AUTHORS | 18 - vendor/github.com/golang/snappy/CONTRIBUTORS | 41 - vendor/github.com/golang/snappy/LICENSE | 27 - vendor/github.com/golang/snappy/README | 107 -- vendor/github.com/golang/snappy/decode.go | 264 ---- .../github.com/golang/snappy/decode_amd64.s | 490 ------ .../github.com/golang/snappy/decode_arm64.s | 494 ------ vendor/github.com/golang/snappy/decode_asm.go | 15 - .../github.com/golang/snappy/decode_other.go | 115 -- vendor/github.com/golang/snappy/encode.go | 289 ---- .../github.com/golang/snappy/encode_amd64.s | 730 --------- .../github.com/golang/snappy/encode_arm64.s | 722 --------- vendor/github.com/golang/snappy/encode_asm.go | 30 - .../github.com/golang/snappy/encode_other.go | 238 --- vendor/github.com/golang/snappy/snappy.go | 98 -- .../github.com/hashicorp/go-plugin/.gitignore | 2 - .../hashicorp/go-plugin/CHANGELOG.md | 19 - vendor/github.com/hashicorp/go-plugin/LICENSE | 353 ----- .../github.com/hashicorp/go-plugin/README.md | 164 -- .../github.com/hashicorp/go-plugin/client.go | 1055 ------------- .../hashicorp/go-plugin/discover.go | 28 - .../github.com/hashicorp/go-plugin/error.go | 24 - .../hashicorp/go-plugin/grpc_broker.go | 457 ------ .../hashicorp/go-plugin/grpc_client.go | 126 -- .../hashicorp/go-plugin/grpc_controller.go | 23 - .../hashicorp/go-plugin/grpc_server.go | 149 -- .../hashicorp/go-plugin/grpc_stdio.go | 207 --- .../go-plugin/internal/plugin/gen.go | 3 - .../internal/plugin/grpc_broker.pb.go | 203 --- .../internal/plugin/grpc_broker.proto | 13 - .../internal/plugin/grpc_controller.pb.go | 145 -- .../internal/plugin/grpc_controller.proto | 11 - .../internal/plugin/grpc_stdio.pb.go | 233 --- .../internal/plugin/grpc_stdio.proto | 30 - .../hashicorp/go-plugin/log_entry.go | 73 - vendor/github.com/hashicorp/go-plugin/mtls.go | 73 - .../hashicorp/go-plugin/mux_broker.go | 204 --- .../github.com/hashicorp/go-plugin/plugin.go | 58 - .../github.com/hashicorp/go-plugin/process.go | 24 - .../hashicorp/go-plugin/process_posix.go | 20 - .../hashicorp/go-plugin/process_windows.go | 30 - .../hashicorp/go-plugin/protocol.go | 45 - .../hashicorp/go-plugin/rpc_client.go | 170 -- .../hashicorp/go-plugin/rpc_server.go | 201 --- .../github.com/hashicorp/go-plugin/server.go | 591 ------- .../hashicorp/go-plugin/server_mux.go | 31 - .../github.com/hashicorp/go-plugin/stream.go | 18 - .../github.com/hashicorp/go-plugin/testing.go | 180 --- .../hashicorp/go-secure-stdlib/mlock/LICENSE | 363 ----- .../hashicorp/go-secure-stdlib/mlock/mlock.go | 15 - .../go-secure-stdlib/mlock/mlock_unavail.go | 13 - .../go-secure-stdlib/mlock/mlock_unix.go | 18 - .../github.com/hashicorp/go-uuid/.travis.yml | 12 - vendor/github.com/hashicorp/go-uuid/LICENSE | 365 ----- vendor/github.com/hashicorp/go-uuid/README.md | 8 - vendor/github.com/hashicorp/go-uuid/uuid.go | 83 - .../hashicorp/go-version/CHANGELOG.md | 45 - .../github.com/hashicorp/go-version/LICENSE | 354 ----- .../github.com/hashicorp/go-version/README.md | 66 - .../hashicorp/go-version/constraint.go | 296 ---- .../hashicorp/go-version/version.go | 407 ----- .../go-version/version_collection.go | 17 - .../hashicorp/golang-lru/.gitignore | 23 - vendor/github.com/hashicorp/golang-lru/2q.go | 223 --- .../github.com/hashicorp/golang-lru/README.md | 25 - vendor/github.com/hashicorp/golang-lru/arc.go | 257 --- vendor/github.com/hashicorp/golang-lru/doc.go | 21 - vendor/github.com/hashicorp/golang-lru/lru.go | 150 -- vendor/github.com/hashicorp/vault/api/auth.go | 5 +- .../hashicorp/vault/api/auth_token.go | 3 + .../github.com/hashicorp/vault/api/client.go | 62 +- vendor/github.com/hashicorp/vault/api/help.go | 3 + vendor/github.com/hashicorp/vault/api/kv.go | 3 + .../github.com/hashicorp/vault/api/kv_v1.go | 3 + .../github.com/hashicorp/vault/api/kv_v2.go | 3 + .../hashicorp/vault/api/lifetime_watcher.go | 53 +- .../github.com/hashicorp/vault/api/logical.go | 9 +- .../hashicorp/vault/api/output_policy.go | 35 +- .../hashicorp/vault/api/output_string.go | 3 + .../hashicorp/vault/api/plugin_helpers.go | 11 +- .../helper/consts => api}/plugin_types.go | 9 +- .../github.com/hashicorp/vault/api/request.go | 7 +- .../hashicorp/vault/api/response.go | 17 +- .../github.com/hashicorp/vault/api/secret.go | 31 +- vendor/github.com/hashicorp/vault/api/ssh.go | 3 + .../hashicorp/vault/api/ssh_agent.go | 33 +- vendor/github.com/hashicorp/vault/api/sys.go | 3 + .../hashicorp/vault/api/sys_audit.go | 3 + .../hashicorp/vault/api/sys_auth.go | 3 + .../hashicorp/vault/api/sys_capabilities.go | 3 + .../hashicorp/vault/api/sys_config_cors.go | 3 + .../hashicorp/vault/api/sys_generate_root.go | 3 + .../hashicorp/vault/api/sys_hastatus.go | 3 + .../hashicorp/vault/api/sys_health.go | 3 + .../hashicorp/vault/api/sys_init.go | 3 + .../hashicorp/vault/api/sys_leader.go | 3 + .../hashicorp/vault/api/sys_leases.go | 3 + .../github.com/hashicorp/vault/api/sys_mfa.go | 3 + .../hashicorp/vault/api/sys_monitor.go | 7 +- .../hashicorp/vault/api/sys_mounts.go | 3 + .../hashicorp/vault/api/sys_plugins.go | 28 +- .../hashicorp/vault/api/sys_policy.go | 3 + .../hashicorp/vault/api/sys_raft.go | 3 + .../hashicorp/vault/api/sys_rekey.go | 3 + .../hashicorp/vault/api/sys_rotate.go | 3 + .../hashicorp/vault/api/sys_seal.go | 3 + .../hashicorp/vault/api/sys_stepdown.go | 3 + vendor/github.com/hashicorp/vault/sdk/LICENSE | 365 ----- .../vault/sdk/helper/certutil/helpers.go | 1386 ----------------- .../vault/sdk/helper/certutil/types.go | 1015 ------------ .../vault/sdk/helper/compressutil/compress.go | 222 --- .../vault/sdk/helper/consts/agent.go | 12 - .../vault/sdk/helper/consts/consts.go | 39 - .../sdk/helper/consts/deprecation_status.go | 34 - .../vault/sdk/helper/consts/error.go | 25 - .../vault/sdk/helper/consts/replication.go | 159 -- .../vault/sdk/helper/consts/token_consts.go | 10 - .../vault/sdk/helper/cryptoutil/cryptoutil.go | 11 - .../vault/sdk/helper/errutil/error.go | 20 - .../hashicorp/vault/sdk/helper/hclutil/hcl.go | 36 - .../vault/sdk/helper/jsonutil/json.go | 100 -- .../vault/sdk/helper/license/feature.go | 10 - .../vault/sdk/helper/locksutil/locks.go | 58 - .../vault/sdk/helper/logging/logging.go | 78 - .../sdk/helper/pathmanager/pathmanager.go | 136 -- .../vault/sdk/helper/pluginutil/env.go | 77 - .../sdk/helper/pluginutil/multiplexing.go | 80 - .../sdk/helper/pluginutil/multiplexing.pb.go | 213 --- .../sdk/helper/pluginutil/multiplexing.proto | 13 - .../helper/pluginutil/multiplexing_grpc.pb.go | 101 -- .../vault/sdk/helper/pluginutil/run_config.go | 182 --- .../vault/sdk/helper/pluginutil/runner.go | 116 -- .../vault/sdk/helper/pluginutil/tls.go | 106 -- .../vault/sdk/helper/strutil/strutil.go | 94 -- .../vault/sdk/helper/wrapping/wrapinfo.go | 37 - .../hashicorp/vault/sdk/logical/audit.go | 19 - .../hashicorp/vault/sdk/logical/auth.go | 129 -- .../hashicorp/vault/sdk/logical/connection.go | 18 - .../vault/sdk/logical/controlgroup.go | 17 - .../hashicorp/vault/sdk/logical/error.go | 122 -- .../vault/sdk/logical/identity.pb.go | 709 --------- .../vault/sdk/logical/identity.proto | 91 -- .../hashicorp/vault/sdk/logical/lease.go | 53 - .../hashicorp/vault/sdk/logical/logical.go | 156 -- .../vault/sdk/logical/logical_storage.go | 52 - .../vault/sdk/logical/managed_key.go | 119 -- .../hashicorp/vault/sdk/logical/plugin.pb.go | 171 -- .../hashicorp/vault/sdk/logical/plugin.proto | 16 - .../hashicorp/vault/sdk/logical/request.go | 394 ----- .../hashicorp/vault/sdk/logical/response.go | 322 ---- .../vault/sdk/logical/response_util.go | 204 --- .../hashicorp/vault/sdk/logical/secret.go | 30 - .../hashicorp/vault/sdk/logical/storage.go | 158 -- .../vault/sdk/logical/storage_inmem.go | 87 -- .../vault/sdk/logical/storage_view.go | 110 -- .../vault/sdk/logical/system_view.go | 242 --- .../hashicorp/vault/sdk/logical/testing.go | 88 -- .../hashicorp/vault/sdk/logical/token.go | 304 ---- .../vault/sdk/logical/translate_response.go | 161 -- .../hashicorp/vault/sdk/logical/version.pb.go | 204 --- .../hashicorp/vault/sdk/logical/version.proto | 17 - .../vault/sdk/logical/version_grpc.pb.go | 103 -- .../hashicorp/vault/sdk/physical/cache.go | 260 ---- .../hashicorp/vault/sdk/physical/encoding.go | 108 -- .../hashicorp/vault/sdk/physical/entry.go | 20 - .../hashicorp/vault/sdk/physical/error.go | 110 -- .../vault/sdk/physical/inmem/inmem.go | 310 ---- .../vault/sdk/physical/inmem/inmem_ha.go | 167 -- .../hashicorp/vault/sdk/physical/latency.go | 113 -- .../hashicorp/vault/sdk/physical/physical.go | 134 -- .../vault/sdk/physical/physical_access.go | 40 - .../vault/sdk/physical/physical_view.go | 94 -- .../hashicorp/vault/sdk/physical/testing.go | 497 ------ .../vault/sdk/physical/transactions.go | 150 -- vendor/github.com/hashicorp/yamux/.gitignore | 23 - vendor/github.com/hashicorp/yamux/LICENSE | 362 ----- vendor/github.com/hashicorp/yamux/README.md | 86 - vendor/github.com/hashicorp/yamux/addr.go | 60 - vendor/github.com/hashicorp/yamux/const.go | 182 --- vendor/github.com/hashicorp/yamux/mux.go | 114 -- vendor/github.com/hashicorp/yamux/session.go | 732 --------- vendor/github.com/hashicorp/yamux/spec.md | 140 -- vendor/github.com/hashicorp/yamux/stream.go | 544 ------- vendor/github.com/hashicorp/yamux/util.go | 43 - .../mitchellh/copystructure/LICENSE | 21 - .../mitchellh/copystructure/README.md | 21 - .../mitchellh/copystructure/copier_time.go | 15 - .../mitchellh/copystructure/copystructure.go | 631 -------- .../go-testing-interface/.travis.yml | 12 - .../mitchellh/go-testing-interface/LICENSE | 21 - .../mitchellh/go-testing-interface/README.md | 60 - .../mitchellh/go-testing-interface/testing.go | 112 -- .../mitchellh/reflectwalk/.travis.yml | 1 - .../github.com/mitchellh/reflectwalk/LICENSE | 21 - .../mitchellh/reflectwalk/README.md | 6 - .../mitchellh/reflectwalk/location.go | 19 - .../mitchellh/reflectwalk/location_string.go | 16 - .../mitchellh/reflectwalk/reflectwalk.go | 420 ----- vendor/github.com/oklog/run/.gitignore | 14 - vendor/github.com/oklog/run/LICENSE | 201 --- vendor/github.com/oklog/run/README.md | 75 - vendor/github.com/oklog/run/actors.go | 38 - vendor/github.com/oklog/run/group.go | 62 - vendor/github.com/pierrec/lz4/.gitignore | 34 - vendor/github.com/pierrec/lz4/.travis.yml | 24 - vendor/github.com/pierrec/lz4/LICENSE | 28 - vendor/github.com/pierrec/lz4/README.md | 90 -- vendor/github.com/pierrec/lz4/block.go | 413 ----- vendor/github.com/pierrec/lz4/debug.go | 23 - vendor/github.com/pierrec/lz4/debug_stub.go | 7 - vendor/github.com/pierrec/lz4/decode_amd64.go | 8 - vendor/github.com/pierrec/lz4/decode_amd64.s | 375 ----- vendor/github.com/pierrec/lz4/decode_other.go | 98 -- vendor/github.com/pierrec/lz4/errors.go | 30 - .../pierrec/lz4/internal/xxh32/xxh32zero.go | 223 --- vendor/github.com/pierrec/lz4/lz4.go | 116 -- vendor/github.com/pierrec/lz4/lz4_go1.10.go | 29 - .../github.com/pierrec/lz4/lz4_notgo1.10.go | 29 - vendor/github.com/pierrec/lz4/reader.go | 335 ---- .../github.com/pierrec/lz4/reader_legacy.go | 207 --- vendor/github.com/pierrec/lz4/writer.go | 422 ----- .../github.com/pierrec/lz4/writer_legacy.go | 182 --- vendor/golang.org/x/crypto/blake2b/blake2b.go | 291 ---- .../x/crypto/blake2b/blake2bAVX2_amd64.go | 38 - .../x/crypto/blake2b/blake2bAVX2_amd64.s | 745 --------- .../x/crypto/blake2b/blake2b_amd64.go | 25 - .../x/crypto/blake2b/blake2b_amd64.s | 279 ---- .../x/crypto/blake2b/blake2b_generic.go | 182 --- .../x/crypto/blake2b/blake2b_ref.go | 12 - vendor/golang.org/x/crypto/blake2b/blake2x.go | 177 --- .../golang.org/x/crypto/blake2b/register.go | 33 - vendor/golang.org/x/crypto/cryptobyte/asn1.go | 824 ---------- .../x/crypto/cryptobyte/asn1/asn1.go | 46 - .../golang.org/x/crypto/cryptobyte/builder.go | 350 ----- .../golang.org/x/crypto/cryptobyte/string.go | 183 --- vendor/golang.org/x/net/context/context.go | 56 - vendor/golang.org/x/net/context/go17.go | 73 - vendor/golang.org/x/net/context/go19.go | 21 - vendor/golang.org/x/net/context/pre_go17.go | 301 ---- vendor/golang.org/x/net/context/pre_go19.go | 110 -- vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s | 18 - vendor/golang.org/x/sys/cpu/byteorder.go | 66 - vendor/golang.org/x/sys/cpu/cpu.go | 290 ---- vendor/golang.org/x/sys/cpu/cpu_aix.go | 34 - vendor/golang.org/x/sys/cpu/cpu_arm.go | 73 - vendor/golang.org/x/sys/cpu/cpu_arm64.go | 172 -- vendor/golang.org/x/sys/cpu/cpu_arm64.s | 32 - vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go | 12 - vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go | 22 - vendor/golang.org/x/sys/cpu/cpu_gc_x86.go | 17 - .../golang.org/x/sys/cpu/cpu_gccgo_arm64.go | 12 - .../golang.org/x/sys/cpu/cpu_gccgo_s390x.go | 23 - vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c | 39 - vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go | 33 - vendor/golang.org/x/sys/cpu/cpu_linux.go | 16 - vendor/golang.org/x/sys/cpu/cpu_linux_arm.go | 39 - .../golang.org/x/sys/cpu/cpu_linux_arm64.go | 111 -- .../golang.org/x/sys/cpu/cpu_linux_mips64x.go | 24 - .../golang.org/x/sys/cpu/cpu_linux_noinit.go | 10 - .../golang.org/x/sys/cpu/cpu_linux_ppc64x.go | 32 - .../golang.org/x/sys/cpu/cpu_linux_s390x.go | 40 - vendor/golang.org/x/sys/cpu/cpu_loong64.go | 13 - vendor/golang.org/x/sys/cpu/cpu_mips64x.go | 16 - vendor/golang.org/x/sys/cpu/cpu_mipsx.go | 12 - .../golang.org/x/sys/cpu/cpu_netbsd_arm64.go | 173 -- .../golang.org/x/sys/cpu/cpu_openbsd_arm64.go | 65 - .../golang.org/x/sys/cpu/cpu_openbsd_arm64.s | 11 - vendor/golang.org/x/sys/cpu/cpu_other_arm.go | 10 - .../golang.org/x/sys/cpu/cpu_other_arm64.go | 10 - .../golang.org/x/sys/cpu/cpu_other_mips64x.go | 13 - .../golang.org/x/sys/cpu/cpu_other_ppc64x.go | 15 - .../golang.org/x/sys/cpu/cpu_other_riscv64.go | 12 - vendor/golang.org/x/sys/cpu/cpu_ppc64x.go | 17 - vendor/golang.org/x/sys/cpu/cpu_riscv64.go | 12 - vendor/golang.org/x/sys/cpu/cpu_s390x.go | 172 -- vendor/golang.org/x/sys/cpu/cpu_s390x.s | 58 - vendor/golang.org/x/sys/cpu/cpu_wasm.go | 18 - vendor/golang.org/x/sys/cpu/cpu_x86.go | 152 -- vendor/golang.org/x/sys/cpu/cpu_x86.s | 28 - vendor/golang.org/x/sys/cpu/cpu_zos.go | 10 - vendor/golang.org/x/sys/cpu/cpu_zos_s390x.go | 25 - vendor/golang.org/x/sys/cpu/endian_big.go | 11 - vendor/golang.org/x/sys/cpu/endian_little.go | 11 - vendor/golang.org/x/sys/cpu/hwcap_linux.go | 71 - vendor/golang.org/x/sys/cpu/parse.go | 43 - .../x/sys/cpu/proc_cpuinfo_linux.go | 54 - vendor/golang.org/x/sys/cpu/runtime_auxv.go | 16 - .../x/sys/cpu/runtime_auxv_go121.go | 19 - .../golang.org/x/sys/cpu/syscall_aix_gccgo.go | 27 - .../x/sys/cpu/syscall_aix_ppc64_gc.go | 36 - .../google.golang.org/grpc/health/client.go | 117 -- .../grpc/health/grpc_health_v1/health.pb.go | 308 ---- .../health/grpc_health_v1/health_grpc.pb.go | 223 --- .../google.golang.org/grpc/health/logging.go | 23 - .../google.golang.org/grpc/health/server.go | 163 -- .../grpc/reflection/README.md | 18 - .../grpc_reflection_v1alpha/reflection.pb.go | 1028 ------------ .../reflection_grpc.pb.go | 161 -- .../grpc/reflection/serverreflection.go | 326 ---- .../protobuf/types/known/emptypb/empty.pb.go | 166 -- vendor/modules.txt | 67 +- 310 files changed, 305 insertions(+), 38374 deletions(-) delete mode 100644 vendor/github.com/armon/go-radix/.gitignore delete mode 100644 vendor/github.com/armon/go-radix/.travis.yml delete mode 100644 vendor/github.com/armon/go-radix/LICENSE delete mode 100644 vendor/github.com/armon/go-radix/README.md delete mode 100644 vendor/github.com/armon/go-radix/radix.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go delete mode 100644 vendor/github.com/golang/snappy/.gitignore delete mode 100644 vendor/github.com/golang/snappy/AUTHORS delete mode 100644 vendor/github.com/golang/snappy/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/snappy/LICENSE delete mode 100644 vendor/github.com/golang/snappy/README delete mode 100644 vendor/github.com/golang/snappy/decode.go delete mode 100644 vendor/github.com/golang/snappy/decode_amd64.s delete mode 100644 vendor/github.com/golang/snappy/decode_arm64.s delete mode 100644 vendor/github.com/golang/snappy/decode_asm.go delete mode 100644 vendor/github.com/golang/snappy/decode_other.go delete mode 100644 vendor/github.com/golang/snappy/encode.go delete mode 100644 vendor/github.com/golang/snappy/encode_amd64.s delete mode 100644 vendor/github.com/golang/snappy/encode_arm64.s delete mode 100644 vendor/github.com/golang/snappy/encode_asm.go delete mode 100644 vendor/github.com/golang/snappy/encode_other.go delete mode 100644 vendor/github.com/golang/snappy/snappy.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-plugin/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/go-plugin/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-plugin/README.md delete mode 100644 vendor/github.com/hashicorp/go-plugin/client.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/discover.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/error.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_broker.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_client.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_controller.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_server.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_stdio.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto delete mode 100644 vendor/github.com/hashicorp/go-plugin/log_entry.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/mtls.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/mux_broker.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/plugin.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/process.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/process_posix.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/process_windows.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/protocol.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/rpc_client.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/rpc_server.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/server.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/server_mux.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/stream.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/testing.go delete mode 100644 vendor/github.com/hashicorp/go-secure-stdlib/mlock/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock.go delete mode 100644 vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unavail.go delete mode 100644 vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unix.go delete mode 100644 vendor/github.com/hashicorp/go-uuid/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-uuid/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-uuid/README.md delete mode 100644 vendor/github.com/hashicorp/go-uuid/uuid.go delete mode 100644 vendor/github.com/hashicorp/go-version/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/go-version/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-version/README.md delete mode 100644 vendor/github.com/hashicorp/go-version/constraint.go delete mode 100644 vendor/github.com/hashicorp/go-version/version.go delete mode 100644 vendor/github.com/hashicorp/go-version/version_collection.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/.gitignore delete mode 100644 vendor/github.com/hashicorp/golang-lru/2q.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/README.md delete mode 100644 vendor/github.com/hashicorp/golang-lru/arc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/doc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/lru.go rename vendor/github.com/hashicorp/vault/{sdk/helper/consts => api}/plugin_types.go (84%) delete mode 100644 vendor/github.com/hashicorp/vault/sdk/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/certutil/helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/certutil/types.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/compressutil/compress.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/agent.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/consts.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/deprecation_status.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/error.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/replication.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/consts/token_consts.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/cryptoutil/cryptoutil.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/errutil/error.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/hclutil/hcl.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/jsonutil/json.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/license/feature.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/locksutil/locks.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/logging/logging.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pathmanager/pathmanager.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/env.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.proto delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing_grpc.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/run_config.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/runner.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/tls.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/strutil/strutil.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/helper/wrapping/wrapinfo.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/connection.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/controlgroup.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/error.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/identity.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/identity.proto delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/logical_storage.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/managed_key.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/plugin.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/plugin.proto delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/request.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/response.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/response_util.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/storage.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/storage_inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/storage_view.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/system_view.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/token.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/translate_response.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/version.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/version.proto delete mode 100644 vendor/github.com/hashicorp/vault/sdk/logical/version_grpc.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/cache.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/encoding.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/entry.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/error.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem_ha.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/latency.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/physical.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/physical_access.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/physical_view.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/sdk/physical/transactions.go delete mode 100644 vendor/github.com/hashicorp/yamux/.gitignore delete mode 100644 vendor/github.com/hashicorp/yamux/LICENSE delete mode 100644 vendor/github.com/hashicorp/yamux/README.md delete mode 100644 vendor/github.com/hashicorp/yamux/addr.go delete mode 100644 vendor/github.com/hashicorp/yamux/const.go delete mode 100644 vendor/github.com/hashicorp/yamux/mux.go delete mode 100644 vendor/github.com/hashicorp/yamux/session.go delete mode 100644 vendor/github.com/hashicorp/yamux/spec.md delete mode 100644 vendor/github.com/hashicorp/yamux/stream.go delete mode 100644 vendor/github.com/hashicorp/yamux/util.go delete mode 100644 vendor/github.com/mitchellh/copystructure/LICENSE delete mode 100644 vendor/github.com/mitchellh/copystructure/README.md delete mode 100644 vendor/github.com/mitchellh/copystructure/copier_time.go delete mode 100644 vendor/github.com/mitchellh/copystructure/copystructure.go delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/.travis.yml delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/README.md delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/testing.go delete mode 100644 vendor/github.com/mitchellh/reflectwalk/.travis.yml delete mode 100644 vendor/github.com/mitchellh/reflectwalk/LICENSE delete mode 100644 vendor/github.com/mitchellh/reflectwalk/README.md delete mode 100644 vendor/github.com/mitchellh/reflectwalk/location.go delete mode 100644 vendor/github.com/mitchellh/reflectwalk/location_string.go delete mode 100644 vendor/github.com/mitchellh/reflectwalk/reflectwalk.go delete mode 100644 vendor/github.com/oklog/run/.gitignore delete mode 100644 vendor/github.com/oklog/run/LICENSE delete mode 100644 vendor/github.com/oklog/run/README.md delete mode 100644 vendor/github.com/oklog/run/actors.go delete mode 100644 vendor/github.com/oklog/run/group.go delete mode 100644 vendor/github.com/pierrec/lz4/.gitignore delete mode 100644 vendor/github.com/pierrec/lz4/.travis.yml delete mode 100644 vendor/github.com/pierrec/lz4/LICENSE delete mode 100644 vendor/github.com/pierrec/lz4/README.md delete mode 100644 vendor/github.com/pierrec/lz4/block.go delete mode 100644 vendor/github.com/pierrec/lz4/debug.go delete mode 100644 vendor/github.com/pierrec/lz4/debug_stub.go delete mode 100644 vendor/github.com/pierrec/lz4/decode_amd64.go delete mode 100644 vendor/github.com/pierrec/lz4/decode_amd64.s delete mode 100644 vendor/github.com/pierrec/lz4/decode_other.go delete mode 100644 vendor/github.com/pierrec/lz4/errors.go delete mode 100644 vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go delete mode 100644 vendor/github.com/pierrec/lz4/lz4.go delete mode 100644 vendor/github.com/pierrec/lz4/lz4_go1.10.go delete mode 100644 vendor/github.com/pierrec/lz4/lz4_notgo1.10.go delete mode 100644 vendor/github.com/pierrec/lz4/reader.go delete mode 100644 vendor/github.com/pierrec/lz4/reader_legacy.go delete mode 100644 vendor/github.com/pierrec/lz4/writer.go delete mode 100644 vendor/github.com/pierrec/lz4/writer_legacy.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_generic.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_ref.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2x.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/register.go delete mode 100644 vendor/golang.org/x/crypto/cryptobyte/asn1.go delete mode 100644 vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go delete mode 100644 vendor/golang.org/x/crypto/cryptobyte/builder.go delete mode 100644 vendor/golang.org/x/crypto/cryptobyte/string.go delete mode 100644 vendor/golang.org/x/net/context/context.go delete mode 100644 vendor/golang.org/x/net/context/go17.go delete mode 100644 vendor/golang.org/x/net/context/go19.go delete mode 100644 vendor/golang.org/x/net/context/pre_go17.go delete mode 100644 vendor/golang.org/x/net/context/pre_go19.go delete mode 100644 vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s delete mode 100644 vendor/golang.org/x/sys/cpu/byteorder.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_aix.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_arm.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_arm64.s delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gc_x86.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_loong64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_mips64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_mipsx.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_arm.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_arm64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_riscv64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_s390x.s delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_wasm.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_x86.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_x86.s delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_zos.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/endian_big.go delete mode 100644 vendor/golang.org/x/sys/cpu/endian_little.go delete mode 100644 vendor/golang.org/x/sys/cpu/hwcap_linux.go delete mode 100644 vendor/golang.org/x/sys/cpu/parse.go delete mode 100644 vendor/golang.org/x/sys/cpu/proc_cpuinfo_linux.go delete mode 100644 vendor/golang.org/x/sys/cpu/runtime_auxv.go delete mode 100644 vendor/golang.org/x/sys/cpu/runtime_auxv_go121.go delete mode 100644 vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go delete mode 100644 vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go delete mode 100644 vendor/google.golang.org/grpc/health/client.go delete mode 100644 vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go delete mode 100644 vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go delete mode 100644 vendor/google.golang.org/grpc/health/logging.go delete mode 100644 vendor/google.golang.org/grpc/health/server.go delete mode 100644 vendor/google.golang.org/grpc/reflection/README.md delete mode 100644 vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go delete mode 100644 vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go delete mode 100644 vendor/google.golang.org/grpc/reflection/serverreflection.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go diff --git a/go.mod b/go.mod index c35eb5fef..dcf4d205f 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/go-zookeeper/zk v1.0.3 github.com/gomodule/redigo v1.8.9 github.com/hashicorp/consul/api v1.20.0 - github.com/hashicorp/vault/api v1.8.3 + github.com/hashicorp/vault/api v1.9.1 github.com/kelseyhightower/memkv v0.1.1 github.com/sirupsen/logrus v1.9.2 go.etcd.io/etcd/client/v3 v3.5.9 @@ -20,21 +20,17 @@ require ( ) require ( - github.com/armon/go-radix v1.0.0 // indirect github.com/cenkalti/backoff/v3 v3.2.2 // indirect github.com/coreos/go-systemd/v22 v22.3.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.3 // indirect - github.com/golang/snappy v0.0.4 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v1.3.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-plugin v1.4.5 // indirect github.com/hashicorp/go-retryablehttp v0.7.1 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect - github.com/hashicorp/go-secure-stdlib/mlock v0.1.2 // indirect github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7 // indirect github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect github.com/hashicorp/go-sockaddr v1.0.2 // indirect @@ -43,18 +39,11 @@ require ( github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/serf v0.10.1 // indirect - github.com/hashicorp/vault/sdk v0.7.0 // indirect - github.com/hashicorp/yamux v0.1.1 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.16 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/oklog/run v1.1.0 // indirect - github.com/pierrec/lz4 v2.6.1+incompatible // indirect github.com/ryanuber/go-glob v1.0.0 // indirect go.etcd.io/etcd/api/v3 v3.5.9 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.9 // indirect diff --git a/go.sum b/go.sum index 8ad8ebba0..af6c95a3c 100644 --- a/go.sum +++ b/go.sum @@ -10,7 +10,6 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.44.266 h1:MWd775dcYf7NrwgcHLtlsIbWoWkX8p4vomfNHr88zH0= github.com/aws/aws-sdk-go v1.44.266/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= @@ -35,8 +34,6 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= -github.com/frankban/quicktest v1.13.0 h1:yNZif1OkDfNoDfb9zZa9aXIpejNR4F23Wely0c+Qdqk= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= @@ -57,8 +54,6 @@ github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= @@ -90,15 +85,11 @@ github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHh github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.4.5 h1:oTE/oQR4eghggRg8VY7PAz3dr++VwDNBGCcOfIvHpBo= -github.com/hashicorp/go-plugin v1.4.5/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-retryablehttp v0.7.1 h1:sUiuQAnLlbvmExtFQs72iFW/HXeUn8Z1aJLQ4LJJbTQ= github.com/hashicorp/go-retryablehttp v0.7.1/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= -github.com/hashicorp/go-secure-stdlib/mlock v0.1.2 h1:p4AKXPPS24tO8Wc8i1gLvSKdmkiSY5xuju57czJ/IJQ= -github.com/hashicorp/go-secure-stdlib/mlock v0.1.2/go.mod h1:zq93CJChV6L9QTfGKtfBxKqD7BqqXx5O04A/ns2p5+I= github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7 h1:UpiO20jno/eV1eVZcxqWnUohyKRe1g8FPV/xH1s/2qs= github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7/go.mod h1:QmrqtbKuxxSWTN3ETMPuB+VtEiBJ/A9XhoYGv8E1uD8= github.com/hashicorp/go-secure-stdlib/strutil v0.1.1/go.mod h1:gKOamz3EwoIoJq7mlMIRBpVTAUn8qPCrEclOKKWhD3U= @@ -125,13 +116,8 @@ github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= -github.com/hashicorp/vault/api v1.8.3 h1:cHQOLcMhBR+aVI0HzhPxO62w2+gJhIrKguQNONPzu6o= -github.com/hashicorp/vault/api v1.8.3/go.mod h1:4g/9lj9lmuJQMtT6CmVMHC5FW1yENaVv+Nv4ZfG8fAg= -github.com/hashicorp/vault/sdk v0.7.0 h1:2pQRO40R1etpKkia5fb4kjrdYMx3BHklPxl1pxpxDHg= -github.com/hashicorp/vault/sdk v0.7.0/go.mod h1:KyfArJkhooyba7gYCKSq8v66QdqJmnbAxtV/OX1+JTs= -github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= -github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= -github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= +github.com/hashicorp/vault/api v1.9.1 h1:LtY/I16+5jVGU8rufyyAkwopgq/HpUnxFBg+QLOAV38= +github.com/hashicorp/vault/api v1.9.1/go.mod h1:78kktNcQYbBGSrOjQfHjXN32OhhxXnbYl3zxpd2uPUs= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= @@ -170,31 +156,21 @@ github.com/miekg/dns v1.1.41 h1:WMszZWJG0XmzbK9FEmzH2TVcqYzFesusSIB41b8KHxY= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= -github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= -github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pierrec/lz4 v2.6.1+incompatible h1:9UY3+iC23yxF0UfGaYrGplQ+79Rg+h/q9FV9ix19jjM= -github.com/pierrec/lz4 v2.6.1+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= diff --git a/vendor/github.com/armon/go-radix/.gitignore b/vendor/github.com/armon/go-radix/.gitignore deleted file mode 100644 index 00268614f..000000000 --- a/vendor/github.com/armon/go-radix/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/armon/go-radix/.travis.yml b/vendor/github.com/armon/go-radix/.travis.yml deleted file mode 100644 index 1a0bbea6c..000000000 --- a/vendor/github.com/armon/go-radix/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: go -go: - - tip diff --git a/vendor/github.com/armon/go-radix/LICENSE b/vendor/github.com/armon/go-radix/LICENSE deleted file mode 100644 index a5df10e67..000000000 --- a/vendor/github.com/armon/go-radix/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Armon Dadgar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/armon/go-radix/README.md b/vendor/github.com/armon/go-radix/README.md deleted file mode 100644 index 26f42a283..000000000 --- a/vendor/github.com/armon/go-radix/README.md +++ /dev/null @@ -1,38 +0,0 @@ -go-radix [![Build Status](https://travis-ci.org/armon/go-radix.png)](https://travis-ci.org/armon/go-radix) -========= - -Provides the `radix` package that implements a [radix tree](http://en.wikipedia.org/wiki/Radix_tree). -The package only provides a single `Tree` implementation, optimized for sparse nodes. - -As a radix tree, it provides the following: - * O(k) operations. In many cases, this can be faster than a hash table since - the hash function is an O(k) operation, and hash tables have very poor cache locality. - * Minimum / Maximum value lookups - * Ordered iteration - -For an immutable variant, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix). - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/armon/go-radix). - -Example -======= - -Below is a simple example of usage - -```go -// Create a tree -r := radix.New() -r.Insert("foo", 1) -r.Insert("bar", 2) -r.Insert("foobar", 2) - -// Find the longest prefix match -m, _, _ := r.LongestPrefix("foozip") -if m != "foo" { - panic("should be foo") -} -``` - diff --git a/vendor/github.com/armon/go-radix/radix.go b/vendor/github.com/armon/go-radix/radix.go deleted file mode 100644 index e2bb22eb9..000000000 --- a/vendor/github.com/armon/go-radix/radix.go +++ /dev/null @@ -1,540 +0,0 @@ -package radix - -import ( - "sort" - "strings" -) - -// WalkFn is used when walking the tree. Takes a -// key and value, returning if iteration should -// be terminated. -type WalkFn func(s string, v interface{}) bool - -// leafNode is used to represent a value -type leafNode struct { - key string - val interface{} -} - -// edge is used to represent an edge node -type edge struct { - label byte - node *node -} - -type node struct { - // leaf is used to store possible leaf - leaf *leafNode - - // prefix is the common prefix we ignore - prefix string - - // Edges should be stored in-order for iteration. - // We avoid a fully materialized slice to save memory, - // since in most cases we expect to be sparse - edges edges -} - -func (n *node) isLeaf() bool { - return n.leaf != nil -} - -func (n *node) addEdge(e edge) { - n.edges = append(n.edges, e) - n.edges.Sort() -} - -func (n *node) updateEdge(label byte, node *node) { - num := len(n.edges) - idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= label - }) - if idx < num && n.edges[idx].label == label { - n.edges[idx].node = node - return - } - panic("replacing missing edge") -} - -func (n *node) getEdge(label byte) *node { - num := len(n.edges) - idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= label - }) - if idx < num && n.edges[idx].label == label { - return n.edges[idx].node - } - return nil -} - -func (n *node) delEdge(label byte) { - num := len(n.edges) - idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= label - }) - if idx < num && n.edges[idx].label == label { - copy(n.edges[idx:], n.edges[idx+1:]) - n.edges[len(n.edges)-1] = edge{} - n.edges = n.edges[:len(n.edges)-1] - } -} - -type edges []edge - -func (e edges) Len() int { - return len(e) -} - -func (e edges) Less(i, j int) bool { - return e[i].label < e[j].label -} - -func (e edges) Swap(i, j int) { - e[i], e[j] = e[j], e[i] -} - -func (e edges) Sort() { - sort.Sort(e) -} - -// Tree implements a radix tree. This can be treated as a -// Dictionary abstract data type. The main advantage over -// a standard hash map is prefix-based lookups and -// ordered iteration, -type Tree struct { - root *node - size int -} - -// New returns an empty Tree -func New() *Tree { - return NewFromMap(nil) -} - -// NewFromMap returns a new tree containing the keys -// from an existing map -func NewFromMap(m map[string]interface{}) *Tree { - t := &Tree{root: &node{}} - for k, v := range m { - t.Insert(k, v) - } - return t -} - -// Len is used to return the number of elements in the tree -func (t *Tree) Len() int { - return t.size -} - -// longestPrefix finds the length of the shared prefix -// of two strings -func longestPrefix(k1, k2 string) int { - max := len(k1) - if l := len(k2); l < max { - max = l - } - var i int - for i = 0; i < max; i++ { - if k1[i] != k2[i] { - break - } - } - return i -} - -// Insert is used to add a newentry or update -// an existing entry. Returns if updated. -func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) { - var parent *node - n := t.root - search := s - for { - // Handle key exhaution - if len(search) == 0 { - if n.isLeaf() { - old := n.leaf.val - n.leaf.val = v - return old, true - } - - n.leaf = &leafNode{ - key: s, - val: v, - } - t.size++ - return nil, false - } - - // Look for the edge - parent = n - n = n.getEdge(search[0]) - - // No edge, create one - if n == nil { - e := edge{ - label: search[0], - node: &node{ - leaf: &leafNode{ - key: s, - val: v, - }, - prefix: search, - }, - } - parent.addEdge(e) - t.size++ - return nil, false - } - - // Determine longest prefix of the search key on match - commonPrefix := longestPrefix(search, n.prefix) - if commonPrefix == len(n.prefix) { - search = search[commonPrefix:] - continue - } - - // Split the node - t.size++ - child := &node{ - prefix: search[:commonPrefix], - } - parent.updateEdge(search[0], child) - - // Restore the existing node - child.addEdge(edge{ - label: n.prefix[commonPrefix], - node: n, - }) - n.prefix = n.prefix[commonPrefix:] - - // Create a new leaf node - leaf := &leafNode{ - key: s, - val: v, - } - - // If the new key is a subset, add to to this node - search = search[commonPrefix:] - if len(search) == 0 { - child.leaf = leaf - return nil, false - } - - // Create a new edge for the node - child.addEdge(edge{ - label: search[0], - node: &node{ - leaf: leaf, - prefix: search, - }, - }) - return nil, false - } -} - -// Delete is used to delete a key, returning the previous -// value and if it was deleted -func (t *Tree) Delete(s string) (interface{}, bool) { - var parent *node - var label byte - n := t.root - search := s - for { - // Check for key exhaution - if len(search) == 0 { - if !n.isLeaf() { - break - } - goto DELETE - } - - // Look for an edge - parent = n - label = search[0] - n = n.getEdge(label) - if n == nil { - break - } - - // Consume the search prefix - if strings.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } - return nil, false - -DELETE: - // Delete the leaf - leaf := n.leaf - n.leaf = nil - t.size-- - - // Check if we should delete this node from the parent - if parent != nil && len(n.edges) == 0 { - parent.delEdge(label) - } - - // Check if we should merge this node - if n != t.root && len(n.edges) == 1 { - n.mergeChild() - } - - // Check if we should merge the parent's other child - if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() { - parent.mergeChild() - } - - return leaf.val, true -} - -// DeletePrefix is used to delete the subtree under a prefix -// Returns how many nodes were deleted -// Use this to delete large subtrees efficiently -func (t *Tree) DeletePrefix(s string) int { - return t.deletePrefix(nil, t.root, s) -} - -// delete does a recursive deletion -func (t *Tree) deletePrefix(parent, n *node, prefix string) int { - // Check for key exhaustion - if len(prefix) == 0 { - // Remove the leaf node - subTreeSize := 0 - //recursively walk from all edges of the node to be deleted - recursiveWalk(n, func(s string, v interface{}) bool { - subTreeSize++ - return false - }) - if n.isLeaf() { - n.leaf = nil - } - n.edges = nil // deletes the entire subtree - - // Check if we should merge the parent's other child - if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() { - parent.mergeChild() - } - t.size -= subTreeSize - return subTreeSize - } - - // Look for an edge - label := prefix[0] - child := n.getEdge(label) - if child == nil || (!strings.HasPrefix(child.prefix, prefix) && !strings.HasPrefix(prefix, child.prefix)) { - return 0 - } - - // Consume the search prefix - if len(child.prefix) > len(prefix) { - prefix = prefix[len(prefix):] - } else { - prefix = prefix[len(child.prefix):] - } - return t.deletePrefix(n, child, prefix) -} - -func (n *node) mergeChild() { - e := n.edges[0] - child := e.node - n.prefix = n.prefix + child.prefix - n.leaf = child.leaf - n.edges = child.edges -} - -// Get is used to lookup a specific key, returning -// the value and if it was found -func (t *Tree) Get(s string) (interface{}, bool) { - n := t.root - search := s - for { - // Check for key exhaution - if len(search) == 0 { - if n.isLeaf() { - return n.leaf.val, true - } - break - } - - // Look for an edge - n = n.getEdge(search[0]) - if n == nil { - break - } - - // Consume the search prefix - if strings.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } - return nil, false -} - -// LongestPrefix is like Get, but instead of an -// exact match, it will return the longest prefix match. -func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) { - var last *leafNode - n := t.root - search := s - for { - // Look for a leaf node - if n.isLeaf() { - last = n.leaf - } - - // Check for key exhaution - if len(search) == 0 { - break - } - - // Look for an edge - n = n.getEdge(search[0]) - if n == nil { - break - } - - // Consume the search prefix - if strings.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } - if last != nil { - return last.key, last.val, true - } - return "", nil, false -} - -// Minimum is used to return the minimum value in the tree -func (t *Tree) Minimum() (string, interface{}, bool) { - n := t.root - for { - if n.isLeaf() { - return n.leaf.key, n.leaf.val, true - } - if len(n.edges) > 0 { - n = n.edges[0].node - } else { - break - } - } - return "", nil, false -} - -// Maximum is used to return the maximum value in the tree -func (t *Tree) Maximum() (string, interface{}, bool) { - n := t.root - for { - if num := len(n.edges); num > 0 { - n = n.edges[num-1].node - continue - } - if n.isLeaf() { - return n.leaf.key, n.leaf.val, true - } - break - } - return "", nil, false -} - -// Walk is used to walk the tree -func (t *Tree) Walk(fn WalkFn) { - recursiveWalk(t.root, fn) -} - -// WalkPrefix is used to walk the tree under a prefix -func (t *Tree) WalkPrefix(prefix string, fn WalkFn) { - n := t.root - search := prefix - for { - // Check for key exhaution - if len(search) == 0 { - recursiveWalk(n, fn) - return - } - - // Look for an edge - n = n.getEdge(search[0]) - if n == nil { - break - } - - // Consume the search prefix - if strings.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - - } else if strings.HasPrefix(n.prefix, search) { - // Child may be under our search prefix - recursiveWalk(n, fn) - return - } else { - break - } - } - -} - -// WalkPath is used to walk the tree, but only visiting nodes -// from the root down to a given leaf. Where WalkPrefix walks -// all the entries *under* the given prefix, this walks the -// entries *above* the given prefix. -func (t *Tree) WalkPath(path string, fn WalkFn) { - n := t.root - search := path - for { - // Visit the leaf values if any - if n.leaf != nil && fn(n.leaf.key, n.leaf.val) { - return - } - - // Check for key exhaution - if len(search) == 0 { - return - } - - // Look for an edge - n = n.getEdge(search[0]) - if n == nil { - return - } - - // Consume the search prefix - if strings.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } -} - -// recursiveWalk is used to do a pre-order walk of a node -// recursively. Returns true if the walk should be aborted -func recursiveWalk(n *node, fn WalkFn) bool { - // Visit the leaf values if any - if n.leaf != nil && fn(n.leaf.key, n.leaf.val) { - return true - } - - // Recurse on the children - for _, e := range n.edges { - if recursiveWalk(e.node, fn) { - return true - } - } - return false -} - -// ToMap is used to walk the tree and convert it into a map -func (t *Tree) ToMap() map[string]interface{} { - out := make(map[string]interface{}, t.size) - t.Walk(func(k string, v interface{}) bool { - out[k] = v - return false - }) - return out -} diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go deleted file mode 100644 index 16686a655..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/ptypes/empty/empty.proto - -package empty - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - emptypb "google.golang.org/protobuf/types/known/emptypb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/empty.proto. - -type Empty = emptypb.Empty - -var File_github_com_golang_protobuf_ptypes_empty_empty_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = []byte{ - 0x0a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, - 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x3b, 0x65, 0x6d, - 0x70, 0x74, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() } -func file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() { - if File_github_com_golang_protobuf_ptypes_empty_empty_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_ptypes_empty_empty_proto = out.File - file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = nil - file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = nil - file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = nil -} diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore deleted file mode 100644 index 042091d9b..000000000 --- a/vendor/github.com/golang/snappy/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -cmd/snappytool/snappytool -testdata/bench - -# These explicitly listed benchmark data files are for an obsolete version of -# snappy_test.go. -testdata/alice29.txt -testdata/asyoulik.txt -testdata/fireworks.jpeg -testdata/geo.protodata -testdata/html -testdata/html_x_4 -testdata/kppkn.gtb -testdata/lcet10.txt -testdata/paper-100k.pdf -testdata/plrabn12.txt -testdata/urls.10K diff --git a/vendor/github.com/golang/snappy/AUTHORS b/vendor/github.com/golang/snappy/AUTHORS deleted file mode 100644 index 52ccb5a93..000000000 --- a/vendor/github.com/golang/snappy/AUTHORS +++ /dev/null @@ -1,18 +0,0 @@ -# This is the official list of Snappy-Go authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Amazon.com, Inc -Damian Gryski -Eric Buth -Google Inc. -Jan Mercl <0xjnml@gmail.com> -Klaus Post -Rodolfo Carvalho -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/CONTRIBUTORS b/vendor/github.com/golang/snappy/CONTRIBUTORS deleted file mode 100644 index ea6524ddd..000000000 --- a/vendor/github.com/golang/snappy/CONTRIBUTORS +++ /dev/null @@ -1,41 +0,0 @@ -# This is the official list of people who can contribute -# (and typically have contributed) code to the Snappy-Go repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name - -# Please keep the list sorted. - -Alex Legg -Damian Gryski -Eric Buth -Jan Mercl <0xjnml@gmail.com> -Jonathan Swinney -Kai Backman -Klaus Post -Marc-Antoine Ruel -Nigel Tao -Rob Pike -Rodolfo Carvalho -Russ Cox -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/LICENSE b/vendor/github.com/golang/snappy/LICENSE deleted file mode 100644 index 6050c10f4..000000000 --- a/vendor/github.com/golang/snappy/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README deleted file mode 100644 index cea12879a..000000000 --- a/vendor/github.com/golang/snappy/README +++ /dev/null @@ -1,107 +0,0 @@ -The Snappy compression format in the Go programming language. - -To download and install from source: -$ go get github.com/golang/snappy - -Unless otherwise noted, the Snappy-Go source files are distributed -under the BSD-style license found in the LICENSE file. - - - -Benchmarks. - -The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten -or so files, the same set used by the C++ Snappy code (github.com/google/snappy -and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @ -3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29: - -"go test -test.bench=." - -_UFlat0-8 2.19GB/s ± 0% html -_UFlat1-8 1.41GB/s ± 0% urls -_UFlat2-8 23.5GB/s ± 2% jpg -_UFlat3-8 1.91GB/s ± 0% jpg_200 -_UFlat4-8 14.0GB/s ± 1% pdf -_UFlat5-8 1.97GB/s ± 0% html4 -_UFlat6-8 814MB/s ± 0% txt1 -_UFlat7-8 785MB/s ± 0% txt2 -_UFlat8-8 857MB/s ± 0% txt3 -_UFlat9-8 719MB/s ± 1% txt4 -_UFlat10-8 2.84GB/s ± 0% pb -_UFlat11-8 1.05GB/s ± 0% gaviota - -_ZFlat0-8 1.04GB/s ± 0% html -_ZFlat1-8 534MB/s ± 0% urls -_ZFlat2-8 15.7GB/s ± 1% jpg -_ZFlat3-8 740MB/s ± 3% jpg_200 -_ZFlat4-8 9.20GB/s ± 1% pdf -_ZFlat5-8 991MB/s ± 0% html4 -_ZFlat6-8 379MB/s ± 0% txt1 -_ZFlat7-8 352MB/s ± 0% txt2 -_ZFlat8-8 396MB/s ± 1% txt3 -_ZFlat9-8 327MB/s ± 1% txt4 -_ZFlat10-8 1.33GB/s ± 1% pb -_ZFlat11-8 605MB/s ± 1% gaviota - - - -"go test -test.bench=. -tags=noasm" - -_UFlat0-8 621MB/s ± 2% html -_UFlat1-8 494MB/s ± 1% urls -_UFlat2-8 23.2GB/s ± 1% jpg -_UFlat3-8 1.12GB/s ± 1% jpg_200 -_UFlat4-8 4.35GB/s ± 1% pdf -_UFlat5-8 609MB/s ± 0% html4 -_UFlat6-8 296MB/s ± 0% txt1 -_UFlat7-8 288MB/s ± 0% txt2 -_UFlat8-8 309MB/s ± 1% txt3 -_UFlat9-8 280MB/s ± 1% txt4 -_UFlat10-8 753MB/s ± 0% pb -_UFlat11-8 400MB/s ± 0% gaviota - -_ZFlat0-8 409MB/s ± 1% html -_ZFlat1-8 250MB/s ± 1% urls -_ZFlat2-8 12.3GB/s ± 1% jpg -_ZFlat3-8 132MB/s ± 0% jpg_200 -_ZFlat4-8 2.92GB/s ± 0% pdf -_ZFlat5-8 405MB/s ± 1% html4 -_ZFlat6-8 179MB/s ± 1% txt1 -_ZFlat7-8 170MB/s ± 1% txt2 -_ZFlat8-8 189MB/s ± 1% txt3 -_ZFlat9-8 164MB/s ± 1% txt4 -_ZFlat10-8 479MB/s ± 1% pb -_ZFlat11-8 270MB/s ± 1% gaviota - - - -For comparison (Go's encoded output is byte-for-byte identical to C++'s), here -are the numbers from C++ Snappy's - -make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log - -BM_UFlat/0 2.4GB/s html -BM_UFlat/1 1.4GB/s urls -BM_UFlat/2 21.8GB/s jpg -BM_UFlat/3 1.5GB/s jpg_200 -BM_UFlat/4 13.3GB/s pdf -BM_UFlat/5 2.1GB/s html4 -BM_UFlat/6 1.0GB/s txt1 -BM_UFlat/7 959.4MB/s txt2 -BM_UFlat/8 1.0GB/s txt3 -BM_UFlat/9 864.5MB/s txt4 -BM_UFlat/10 2.9GB/s pb -BM_UFlat/11 1.2GB/s gaviota - -BM_ZFlat/0 944.3MB/s html (22.31 %) -BM_ZFlat/1 501.6MB/s urls (47.78 %) -BM_ZFlat/2 14.3GB/s jpg (99.95 %) -BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %) -BM_ZFlat/4 8.3GB/s pdf (83.30 %) -BM_ZFlat/5 903.5MB/s html4 (22.52 %) -BM_ZFlat/6 336.0MB/s txt1 (57.88 %) -BM_ZFlat/7 312.3MB/s txt2 (61.91 %) -BM_ZFlat/8 353.1MB/s txt3 (54.99 %) -BM_ZFlat/9 289.9MB/s txt4 (66.26 %) -BM_ZFlat/10 1.2GB/s pb (19.68 %) -BM_ZFlat/11 527.4MB/s gaviota (37.72 %) diff --git a/vendor/github.com/golang/snappy/decode.go b/vendor/github.com/golang/snappy/decode.go deleted file mode 100644 index 23c6e26c6..000000000 --- a/vendor/github.com/golang/snappy/decode.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrTooLarge reports that the uncompressed length is too large. - ErrTooLarge = errors.New("snappy: decoded block is too large") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrTooLarge - } - return int(v), n, nil -} - -const ( - decodeErrCodeCorrupt = 1 - decodeErrCodeUnsupportedLiteralLength = 2 -) - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Decode handles the Snappy block format, not the Snappy stream format. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if dLen <= len(dst) { - dst = dst[:dLen] - } else { - dst = make([]byte, dLen) - } - switch decode(dst, src[s:]) { - case 0: - return dst, nil - case decodeErrCodeUnsupportedLiteralLength: - return nil, errUnsupportedLiteralLength - } - return nil, ErrCorrupt -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxBlockSize), - buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), - } -} - -// Reader is an io.Reader that can read Snappy-compressed bytes. -// -// Reader handles the Snappy stream format, not the Snappy block format. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrCorrupt - } - return false - } - return true -} - -func (r *Reader) fill() error { - for r.i >= r.j { - if !r.readFull(r.buf[:4], true) { - return r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.decoded[:n], false) { - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return r.err - } - } - - return nil -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil -} - -// ReadByte satisfies the io.ByteReader interface. -func (r *Reader) ReadByte() (byte, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - c := r.decoded[r.i] - r.i++ - return c, nil -} diff --git a/vendor/github.com/golang/snappy/decode_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s deleted file mode 100644 index e6179f65e..000000000 --- a/vendor/github.com/golang/snappy/decode_amd64.s +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The asm code generally follows the pure Go code in decode_other.go, except -// where marked with a "!!!". - -// func decode(dst, src []byte) int -// -// All local variables fit into registers. The non-zero stack size is only to -// spill registers and push args when issuing a CALL. The register allocation: -// - AX scratch -// - BX scratch -// - CX length or x -// - DX offset -// - SI &src[s] -// - DI &dst[d] -// + R8 dst_base -// + R9 dst_len -// + R10 dst_base + dst_len -// + R11 src_base -// + R12 src_len -// + R13 src_base + src_len -// - R14 used by doCopy -// - R15 used by doCopy -// -// The registers R8-R13 (marked with a "+") are set at the start of the -// function, and after a CALL returns, and are not otherwise modified. -// -// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI. -// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI. -TEXT ·decode(SB), NOSPLIT, $48-56 - // Initialize SI, DI and R8-R13. - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, DI - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, SI - MOVQ R11, R13 - ADDQ R12, R13 - -loop: - // for s < len(src) - CMPQ SI, R13 - JEQ end - - // CX = uint32(src[s]) - // - // switch src[s] & 0x03 - MOVBLZX (SI), CX - MOVL CX, BX - ANDL $3, BX - CMPL BX, $1 - JAE tagCopy - - // ---------------------------------------- - // The code below handles literal tags. - - // case tagLiteral: - // x := uint32(src[s] >> 2) - // switch - SHRL $2, CX - CMPL CX, $60 - JAE tagLit60Plus - - // case x < 60: - // s++ - INCQ SI - -doLit: - // This is the end of the inner "switch", when we have a literal tag. - // - // We assume that CX == x and x fits in a uint32, where x is the variable - // used in the pure Go decode_other.go code. - - // length = int(x) + 1 - // - // Unlike the pure Go code, we don't need to check if length <= 0 because - // CX can hold 64 bits, so the increment cannot overflow. - INCQ CX - - // Prepare to check if copying length bytes will run past the end of dst or - // src. - // - // AX = len(dst) - d - // BX = len(src) - s - MOVQ R10, AX - SUBQ DI, AX - MOVQ R13, BX - SUBQ SI, BX - - // !!! Try a faster technique for short (16 or fewer bytes) copies. - // - // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 { - // goto callMemmove // Fall back on calling runtime·memmove. - // } - // - // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s - // against 21 instead of 16, because it cannot assume that all of its input - // is contiguous in memory and so it needs to leave enough source bytes to - // read the next tag without refilling buffers, but Go's Decode assumes - // contiguousness (the src argument is a []byte). - CMPQ CX, $16 - JGT callMemmove - CMPQ AX, $16 - JLT callMemmove - CMPQ BX, $16 - JLT callMemmove - - // !!! Implement the copy from src to dst as a 16-byte load and store. - // (Decode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only length bytes, but that's - // OK. If the input is a valid Snappy encoding then subsequent iterations - // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a - // non-nil error), so the overrun will be ignored. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(SI), X0 - MOVOU X0, 0(DI) - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -callMemmove: - // if length > len(dst)-d || length > len(src)-s { etc } - CMPQ CX, AX - JGT errCorrupt - CMPQ CX, BX - JGT errCorrupt - - // copy(dst[d:], src[s:s+length]) - // - // This means calling runtime·memmove(&dst[d], &src[s], length), so we push - // DI, SI and CX as arguments. Coincidentally, we also need to spill those - // three registers to the stack, to save local variables across the CALL. - MOVQ DI, 0(SP) - MOVQ SI, 8(SP) - MOVQ CX, 16(SP) - MOVQ DI, 24(SP) - MOVQ SI, 32(SP) - MOVQ CX, 40(SP) - CALL runtime·memmove(SB) - - // Restore local variables: unspill registers from the stack and - // re-calculate R8-R13. - MOVQ 24(SP), DI - MOVQ 32(SP), SI - MOVQ 40(SP), CX - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, R13 - ADDQ R12, R13 - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -tagLit60Plus: - // !!! This fragment does the - // - // s += x - 58; if uint(s) > uint(len(src)) { etc } - // - // checks. In the asm version, we code it once instead of once per switch case. - ADDQ CX, SI - SUBQ $58, SI - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // case x == 60: - CMPL CX, $61 - JEQ tagLit61 - JA tagLit62Plus - - // x = uint32(src[s-1]) - MOVBLZX -1(SI), CX - JMP doLit - -tagLit61: - // case x == 61: - // x = uint32(src[s-2]) | uint32(src[s-1])<<8 - MOVWLZX -2(SI), CX - JMP doLit - -tagLit62Plus: - CMPL CX, $62 - JA tagLit63 - - // case x == 62: - // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - MOVWLZX -3(SI), CX - MOVBLZX -1(SI), BX - SHLL $16, BX - ORL BX, CX - JMP doLit - -tagLit63: - // case x == 63: - // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - MOVL -4(SI), CX - JMP doLit - -// The code above handles literal tags. -// ---------------------------------------- -// The code below handles copy tags. - -tagCopy4: - // case tagCopy4: - // s += 5 - ADDQ $5, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-5])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - MOVLQZX -4(SI), DX - JMP doCopy - -tagCopy2: - // case tagCopy2: - // s += 3 - ADDQ $3, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-3])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - MOVWQZX -2(SI), DX - JMP doCopy - -tagCopy: - // We have a copy tag. We assume that: - // - BX == src[s] & 0x03 - // - CX == src[s] - CMPQ BX, $2 - JEQ tagCopy2 - JA tagCopy4 - - // case tagCopy1: - // s += 2 - ADDQ $2, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - MOVQ CX, DX - ANDQ $0xe0, DX - SHLQ $3, DX - MOVBQZX -1(SI), BX - ORQ BX, DX - - // length = 4 + int(src[s-2])>>2&0x7 - SHRQ $2, CX - ANDQ $7, CX - ADDQ $4, CX - -doCopy: - // This is the end of the outer "switch", when we have a copy tag. - // - // We assume that: - // - CX == length && CX > 0 - // - DX == offset - - // if offset <= 0 { etc } - CMPQ DX, $0 - JLE errCorrupt - - // if d < offset { etc } - MOVQ DI, BX - SUBQ R8, BX - CMPQ BX, DX - JLT errCorrupt - - // if length > len(dst)-d { etc } - MOVQ R10, BX - SUBQ DI, BX - CMPQ CX, BX - JGT errCorrupt - - // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length - // - // Set: - // - R14 = len(dst)-d - // - R15 = &dst[d-offset] - MOVQ R10, R14 - SUBQ DI, R14 - MOVQ DI, R15 - SUBQ DX, R15 - - // !!! Try a faster technique for short (16 or fewer bytes) forward copies. - // - // First, try using two 8-byte load/stores, similar to the doLit technique - // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is - // still OK if offset >= 8. Note that this has to be two 8-byte load/stores - // and not one 16-byte load/store, and the first store has to be before the - // second load, due to the overlap if offset is in the range [8, 16). - // - // if length > 16 || offset < 8 || len(dst)-d < 16 { - // goto slowForwardCopy - // } - // copy 16 bytes - // d += length - CMPQ CX, $16 - JGT slowForwardCopy - CMPQ DX, $8 - JLT slowForwardCopy - CMPQ R14, $16 - JLT slowForwardCopy - MOVQ 0(R15), AX - MOVQ AX, 0(DI) - MOVQ 8(R15), BX - MOVQ BX, 8(DI) - ADDQ CX, DI - JMP loop - -slowForwardCopy: - // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we - // can still try 8-byte load stores, provided we can overrun up to 10 extra - // bytes. As above, the overrun will be fixed up by subsequent iterations - // of the outermost loop. - // - // The C++ snappy code calls this technique IncrementalCopyFastPath. Its - // commentary says: - // - // ---- - // - // The main part of this loop is a simple copy of eight bytes at a time - // until we've copied (at least) the requested amount of bytes. However, - // if d and d-offset are less than eight bytes apart (indicating a - // repeating pattern of length < 8), we first need to expand the pattern in - // order to get the correct results. For instance, if the buffer looks like - // this, with the eight-byte and patterns marked as - // intervals: - // - // abxxxxxxxxxxxx - // [------] d-offset - // [------] d - // - // a single eight-byte copy from to will repeat the pattern - // once, after which we can move two bytes without moving : - // - // ababxxxxxxxxxx - // [------] d-offset - // [------] d - // - // and repeat the exercise until the two no longer overlap. - // - // This allows us to do very well in the special case of one single byte - // repeated many times, without taking a big hit for more general cases. - // - // The worst case of extra writing past the end of the match occurs when - // offset == 1 and length == 1; the last copy will read from byte positions - // [0..7] and write to [4..11], whereas it was only supposed to write to - // position 1. Thus, ten excess bytes. - // - // ---- - // - // That "10 byte overrun" worst case is confirmed by Go's - // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy - // and finishSlowForwardCopy algorithm. - // - // if length > len(dst)-d-10 { - // goto verySlowForwardCopy - // } - SUBQ $10, R14 - CMPQ CX, R14 - JGT verySlowForwardCopy - -makeOffsetAtLeast8: - // !!! As above, expand the pattern so that offset >= 8 and we can use - // 8-byte load/stores. - // - // for offset < 8 { - // copy 8 bytes from dst[d-offset:] to dst[d:] - // length -= offset - // d += offset - // offset += offset - // // The two previous lines together means that d-offset, and therefore - // // R15, is unchanged. - // } - CMPQ DX, $8 - JGE fixUpSlowForwardCopy - MOVQ (R15), BX - MOVQ BX, (DI) - SUBQ DX, CX - ADDQ DX, DI - ADDQ DX, DX - JMP makeOffsetAtLeast8 - -fixUpSlowForwardCopy: - // !!! Add length (which might be negative now) to d (implied by DI being - // &dst[d]) so that d ends up at the right place when we jump back to the - // top of the loop. Before we do that, though, we save DI to AX so that, if - // length is positive, copying the remaining length bytes will write to the - // right place. - MOVQ DI, AX - ADDQ CX, DI - -finishSlowForwardCopy: - // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative - // length means that we overrun, but as above, that will be fixed up by - // subsequent iterations of the outermost loop. - CMPQ CX, $0 - JLE loop - MOVQ (R15), BX - MOVQ BX, (AX) - ADDQ $8, R15 - ADDQ $8, AX - SUBQ $8, CX - JMP finishSlowForwardCopy - -verySlowForwardCopy: - // verySlowForwardCopy is a simple implementation of forward copy. In C - // parlance, this is a do/while loop instead of a while loop, since we know - // that length > 0. In Go syntax: - // - // for { - // dst[d] = dst[d - offset] - // d++ - // length-- - // if length == 0 { - // break - // } - // } - MOVB (R15), BX - MOVB BX, (DI) - INCQ R15 - INCQ DI - DECQ CX - JNZ verySlowForwardCopy - JMP loop - -// The code above handles copy tags. -// ---------------------------------------- - -end: - // This is the end of the "for s < len(src)". - // - // if d != len(dst) { etc } - CMPQ DI, R10 - JNE errCorrupt - - // return 0 - MOVQ $0, ret+48(FP) - RET - -errCorrupt: - // return decodeErrCodeCorrupt - MOVQ $1, ret+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/decode_arm64.s b/vendor/github.com/golang/snappy/decode_arm64.s deleted file mode 100644 index 7a3ead17e..000000000 --- a/vendor/github.com/golang/snappy/decode_arm64.s +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The asm code generally follows the pure Go code in decode_other.go, except -// where marked with a "!!!". - -// func decode(dst, src []byte) int -// -// All local variables fit into registers. The non-zero stack size is only to -// spill registers and push args when issuing a CALL. The register allocation: -// - R2 scratch -// - R3 scratch -// - R4 length or x -// - R5 offset -// - R6 &src[s] -// - R7 &dst[d] -// + R8 dst_base -// + R9 dst_len -// + R10 dst_base + dst_len -// + R11 src_base -// + R12 src_len -// + R13 src_base + src_len -// - R14 used by doCopy -// - R15 used by doCopy -// -// The registers R8-R13 (marked with a "+") are set at the start of the -// function, and after a CALL returns, and are not otherwise modified. -// -// The d variable is implicitly R7 - R8, and len(dst)-d is R10 - R7. -// The s variable is implicitly R6 - R11, and len(src)-s is R13 - R6. -TEXT ·decode(SB), NOSPLIT, $56-56 - // Initialize R6, R7 and R8-R13. - MOVD dst_base+0(FP), R8 - MOVD dst_len+8(FP), R9 - MOVD R8, R7 - MOVD R8, R10 - ADD R9, R10, R10 - MOVD src_base+24(FP), R11 - MOVD src_len+32(FP), R12 - MOVD R11, R6 - MOVD R11, R13 - ADD R12, R13, R13 - -loop: - // for s < len(src) - CMP R13, R6 - BEQ end - - // R4 = uint32(src[s]) - // - // switch src[s] & 0x03 - MOVBU (R6), R4 - MOVW R4, R3 - ANDW $3, R3 - MOVW $1, R1 - CMPW R1, R3 - BGE tagCopy - - // ---------------------------------------- - // The code below handles literal tags. - - // case tagLiteral: - // x := uint32(src[s] >> 2) - // switch - MOVW $60, R1 - LSRW $2, R4, R4 - CMPW R4, R1 - BLS tagLit60Plus - - // case x < 60: - // s++ - ADD $1, R6, R6 - -doLit: - // This is the end of the inner "switch", when we have a literal tag. - // - // We assume that R4 == x and x fits in a uint32, where x is the variable - // used in the pure Go decode_other.go code. - - // length = int(x) + 1 - // - // Unlike the pure Go code, we don't need to check if length <= 0 because - // R4 can hold 64 bits, so the increment cannot overflow. - ADD $1, R4, R4 - - // Prepare to check if copying length bytes will run past the end of dst or - // src. - // - // R2 = len(dst) - d - // R3 = len(src) - s - MOVD R10, R2 - SUB R7, R2, R2 - MOVD R13, R3 - SUB R6, R3, R3 - - // !!! Try a faster technique for short (16 or fewer bytes) copies. - // - // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 { - // goto callMemmove // Fall back on calling runtime·memmove. - // } - // - // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s - // against 21 instead of 16, because it cannot assume that all of its input - // is contiguous in memory and so it needs to leave enough source bytes to - // read the next tag without refilling buffers, but Go's Decode assumes - // contiguousness (the src argument is a []byte). - CMP $16, R4 - BGT callMemmove - CMP $16, R2 - BLT callMemmove - CMP $16, R3 - BLT callMemmove - - // !!! Implement the copy from src to dst as a 16-byte load and store. - // (Decode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only length bytes, but that's - // OK. If the input is a valid Snappy encoding then subsequent iterations - // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a - // non-nil error), so the overrun will be ignored. - // - // Note that on arm64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - LDP 0(R6), (R14, R15) - STP (R14, R15), 0(R7) - - // d += length - // s += length - ADD R4, R7, R7 - ADD R4, R6, R6 - B loop - -callMemmove: - // if length > len(dst)-d || length > len(src)-s { etc } - CMP R2, R4 - BGT errCorrupt - CMP R3, R4 - BGT errCorrupt - - // copy(dst[d:], src[s:s+length]) - // - // This means calling runtime·memmove(&dst[d], &src[s], length), so we push - // R7, R6 and R4 as arguments. Coincidentally, we also need to spill those - // three registers to the stack, to save local variables across the CALL. - MOVD R7, 8(RSP) - MOVD R6, 16(RSP) - MOVD R4, 24(RSP) - MOVD R7, 32(RSP) - MOVD R6, 40(RSP) - MOVD R4, 48(RSP) - CALL runtime·memmove(SB) - - // Restore local variables: unspill registers from the stack and - // re-calculate R8-R13. - MOVD 32(RSP), R7 - MOVD 40(RSP), R6 - MOVD 48(RSP), R4 - MOVD dst_base+0(FP), R8 - MOVD dst_len+8(FP), R9 - MOVD R8, R10 - ADD R9, R10, R10 - MOVD src_base+24(FP), R11 - MOVD src_len+32(FP), R12 - MOVD R11, R13 - ADD R12, R13, R13 - - // d += length - // s += length - ADD R4, R7, R7 - ADD R4, R6, R6 - B loop - -tagLit60Plus: - // !!! This fragment does the - // - // s += x - 58; if uint(s) > uint(len(src)) { etc } - // - // checks. In the asm version, we code it once instead of once per switch case. - ADD R4, R6, R6 - SUB $58, R6, R6 - MOVD R6, R3 - SUB R11, R3, R3 - CMP R12, R3 - BGT errCorrupt - - // case x == 60: - MOVW $61, R1 - CMPW R1, R4 - BEQ tagLit61 - BGT tagLit62Plus - - // x = uint32(src[s-1]) - MOVBU -1(R6), R4 - B doLit - -tagLit61: - // case x == 61: - // x = uint32(src[s-2]) | uint32(src[s-1])<<8 - MOVHU -2(R6), R4 - B doLit - -tagLit62Plus: - CMPW $62, R4 - BHI tagLit63 - - // case x == 62: - // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - MOVHU -3(R6), R4 - MOVBU -1(R6), R3 - ORR R3<<16, R4 - B doLit - -tagLit63: - // case x == 63: - // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - MOVWU -4(R6), R4 - B doLit - - // The code above handles literal tags. - // ---------------------------------------- - // The code below handles copy tags. - -tagCopy4: - // case tagCopy4: - // s += 5 - ADD $5, R6, R6 - - // if uint(s) > uint(len(src)) { etc } - MOVD R6, R3 - SUB R11, R3, R3 - CMP R12, R3 - BGT errCorrupt - - // length = 1 + int(src[s-5])>>2 - MOVD $1, R1 - ADD R4>>2, R1, R4 - - // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - MOVWU -4(R6), R5 - B doCopy - -tagCopy2: - // case tagCopy2: - // s += 3 - ADD $3, R6, R6 - - // if uint(s) > uint(len(src)) { etc } - MOVD R6, R3 - SUB R11, R3, R3 - CMP R12, R3 - BGT errCorrupt - - // length = 1 + int(src[s-3])>>2 - MOVD $1, R1 - ADD R4>>2, R1, R4 - - // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - MOVHU -2(R6), R5 - B doCopy - -tagCopy: - // We have a copy tag. We assume that: - // - R3 == src[s] & 0x03 - // - R4 == src[s] - CMP $2, R3 - BEQ tagCopy2 - BGT tagCopy4 - - // case tagCopy1: - // s += 2 - ADD $2, R6, R6 - - // if uint(s) > uint(len(src)) { etc } - MOVD R6, R3 - SUB R11, R3, R3 - CMP R12, R3 - BGT errCorrupt - - // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - MOVD R4, R5 - AND $0xe0, R5 - MOVBU -1(R6), R3 - ORR R5<<3, R3, R5 - - // length = 4 + int(src[s-2])>>2&0x7 - MOVD $7, R1 - AND R4>>2, R1, R4 - ADD $4, R4, R4 - -doCopy: - // This is the end of the outer "switch", when we have a copy tag. - // - // We assume that: - // - R4 == length && R4 > 0 - // - R5 == offset - - // if offset <= 0 { etc } - MOVD $0, R1 - CMP R1, R5 - BLE errCorrupt - - // if d < offset { etc } - MOVD R7, R3 - SUB R8, R3, R3 - CMP R5, R3 - BLT errCorrupt - - // if length > len(dst)-d { etc } - MOVD R10, R3 - SUB R7, R3, R3 - CMP R3, R4 - BGT errCorrupt - - // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length - // - // Set: - // - R14 = len(dst)-d - // - R15 = &dst[d-offset] - MOVD R10, R14 - SUB R7, R14, R14 - MOVD R7, R15 - SUB R5, R15, R15 - - // !!! Try a faster technique for short (16 or fewer bytes) forward copies. - // - // First, try using two 8-byte load/stores, similar to the doLit technique - // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is - // still OK if offset >= 8. Note that this has to be two 8-byte load/stores - // and not one 16-byte load/store, and the first store has to be before the - // second load, due to the overlap if offset is in the range [8, 16). - // - // if length > 16 || offset < 8 || len(dst)-d < 16 { - // goto slowForwardCopy - // } - // copy 16 bytes - // d += length - CMP $16, R4 - BGT slowForwardCopy - CMP $8, R5 - BLT slowForwardCopy - CMP $16, R14 - BLT slowForwardCopy - MOVD 0(R15), R2 - MOVD R2, 0(R7) - MOVD 8(R15), R3 - MOVD R3, 8(R7) - ADD R4, R7, R7 - B loop - -slowForwardCopy: - // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we - // can still try 8-byte load stores, provided we can overrun up to 10 extra - // bytes. As above, the overrun will be fixed up by subsequent iterations - // of the outermost loop. - // - // The C++ snappy code calls this technique IncrementalCopyFastPath. Its - // commentary says: - // - // ---- - // - // The main part of this loop is a simple copy of eight bytes at a time - // until we've copied (at least) the requested amount of bytes. However, - // if d and d-offset are less than eight bytes apart (indicating a - // repeating pattern of length < 8), we first need to expand the pattern in - // order to get the correct results. For instance, if the buffer looks like - // this, with the eight-byte and patterns marked as - // intervals: - // - // abxxxxxxxxxxxx - // [------] d-offset - // [------] d - // - // a single eight-byte copy from to will repeat the pattern - // once, after which we can move two bytes without moving : - // - // ababxxxxxxxxxx - // [------] d-offset - // [------] d - // - // and repeat the exercise until the two no longer overlap. - // - // This allows us to do very well in the special case of one single byte - // repeated many times, without taking a big hit for more general cases. - // - // The worst case of extra writing past the end of the match occurs when - // offset == 1 and length == 1; the last copy will read from byte positions - // [0..7] and write to [4..11], whereas it was only supposed to write to - // position 1. Thus, ten excess bytes. - // - // ---- - // - // That "10 byte overrun" worst case is confirmed by Go's - // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy - // and finishSlowForwardCopy algorithm. - // - // if length > len(dst)-d-10 { - // goto verySlowForwardCopy - // } - SUB $10, R14, R14 - CMP R14, R4 - BGT verySlowForwardCopy - -makeOffsetAtLeast8: - // !!! As above, expand the pattern so that offset >= 8 and we can use - // 8-byte load/stores. - // - // for offset < 8 { - // copy 8 bytes from dst[d-offset:] to dst[d:] - // length -= offset - // d += offset - // offset += offset - // // The two previous lines together means that d-offset, and therefore - // // R15, is unchanged. - // } - CMP $8, R5 - BGE fixUpSlowForwardCopy - MOVD (R15), R3 - MOVD R3, (R7) - SUB R5, R4, R4 - ADD R5, R7, R7 - ADD R5, R5, R5 - B makeOffsetAtLeast8 - -fixUpSlowForwardCopy: - // !!! Add length (which might be negative now) to d (implied by R7 being - // &dst[d]) so that d ends up at the right place when we jump back to the - // top of the loop. Before we do that, though, we save R7 to R2 so that, if - // length is positive, copying the remaining length bytes will write to the - // right place. - MOVD R7, R2 - ADD R4, R7, R7 - -finishSlowForwardCopy: - // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative - // length means that we overrun, but as above, that will be fixed up by - // subsequent iterations of the outermost loop. - MOVD $0, R1 - CMP R1, R4 - BLE loop - MOVD (R15), R3 - MOVD R3, (R2) - ADD $8, R15, R15 - ADD $8, R2, R2 - SUB $8, R4, R4 - B finishSlowForwardCopy - -verySlowForwardCopy: - // verySlowForwardCopy is a simple implementation of forward copy. In C - // parlance, this is a do/while loop instead of a while loop, since we know - // that length > 0. In Go syntax: - // - // for { - // dst[d] = dst[d - offset] - // d++ - // length-- - // if length == 0 { - // break - // } - // } - MOVB (R15), R3 - MOVB R3, (R7) - ADD $1, R15, R15 - ADD $1, R7, R7 - SUB $1, R4, R4 - CBNZ R4, verySlowForwardCopy - B loop - - // The code above handles copy tags. - // ---------------------------------------- - -end: - // This is the end of the "for s < len(src)". - // - // if d != len(dst) { etc } - CMP R10, R7 - BNE errCorrupt - - // return 0 - MOVD $0, ret+48(FP) - RET - -errCorrupt: - // return decodeErrCodeCorrupt - MOVD $1, R2 - MOVD R2, ret+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/decode_asm.go b/vendor/github.com/golang/snappy/decode_asm.go deleted file mode 100644 index 7082b3491..000000000 --- a/vendor/github.com/golang/snappy/decode_asm.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm -// +build amd64 arm64 - -package snappy - -// decode has the same semantics as in decode_other.go. -// -//go:noescape -func decode(dst, src []byte) int diff --git a/vendor/github.com/golang/snappy/decode_other.go b/vendor/github.com/golang/snappy/decode_other.go deleted file mode 100644 index 2f672be55..000000000 --- a/vendor/github.com/golang/snappy/decode_other.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64,!arm64 appengine !gc noasm - -package snappy - -// decode writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read, and that len(dst) -// equals that length. -// -// It returns 0 on success or a decodeErrCodeXxx error code on failure. -func decode(dst, src []byte) int { - var d, s, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - length = int(x) + 1 - if length <= 0 { - return decodeErrCodeUnsupportedLiteralLength - } - if length > len(dst)-d || length > len(src)-s { - return decodeErrCodeCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - - case tagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - - case tagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - } - - if offset <= 0 || d < offset || length > len(dst)-d { - return decodeErrCodeCorrupt - } - // Copy from an earlier sub-slice of dst to a later sub-slice. - // If no overlap, use the built-in copy: - if offset >= length { - copy(dst[d:d+length], dst[d-offset:]) - d += length - continue - } - - // Unlike the built-in copy function, this byte-by-byte copy always runs - // forwards, even if the slices overlap. Conceptually, this is: - // - // d += forwardCopy(dst[d:d+length], dst[d-offset:]) - // - // We align the slices into a and b and show the compiler they are the same size. - // This allows the loop to run without bounds checks. - a := dst[d : d+length] - b := dst[d-offset:] - b = b[:len(a)] - for i := range a { - a[i] = b[i] - } - d += length - } - if d != len(dst) { - return decodeErrCodeCorrupt - } - return 0 -} diff --git a/vendor/github.com/golang/snappy/encode.go b/vendor/github.com/golang/snappy/encode.go deleted file mode 100644 index 7f2365707..000000000 --- a/vendor/github.com/golang/snappy/encode.go +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -// Encode returns the encoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire encoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Encode handles the Snappy block format, not the Snappy stream format. -func Encode(dst, src []byte) []byte { - if n := MaxEncodedLen(len(src)); n < 0 { - panic(ErrTooLarge) - } else if len(dst) < n { - dst = make([]byte, n) - } - - // The block starts with the varint-encoded length of the decompressed bytes. - d := binary.PutUvarint(dst, uint64(len(src))) - - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return dst[:d] -} - -// inputMargin is the minimum number of extra input bytes to keep, inside -// encodeBlock's inner loop. On some architectures, this margin lets us -// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) -// literals can be implemented as a single load to and store from a 16-byte -// register. That literal's actual length can be as short as 1 byte, so this -// can copy up to 15 bytes too much, but that's OK as subsequent iterations of -// the encoding loop will fix up the copy overrun, and this inputMargin ensures -// that we don't overrun the dst and src buffers. -const inputMargin = 16 - 1 - -// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that -// could be encoded with a copy tag. This is the minimum with respect to the -// algorithm used by encodeBlock, not a minimum enforced by the file format. -// -// The encoded output must start with at least a 1 byte literal, as there are -// no previous bytes to copy. A minimal (1 byte) copy after that, generated -// from an emitCopy call in encodeBlock's main loop, would require at least -// another inputMargin bytes, for the reason above: we want any emitLiteral -// calls inside encodeBlock's main loop to use the fast path if possible, which -// requires being able to overrun by inputMargin bytes. Thus, -// minNonLiteralBlockSize equals 1 + 1 + inputMargin. -// -// The C++ code doesn't use this exact threshold, but it could, as discussed at -// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion -// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an -// optimization. It should not affect the encoded form. This is tested by -// TestSameEncodingAsCppShortCopies. -const minNonLiteralBlockSize = 1 + 1 + inputMargin - -// MaxEncodedLen returns the maximum length of a snappy block, given its -// uncompressed length. -// -// It will return a negative value if srcLen is too large to encode. -func MaxEncodedLen(srcLen int) int { - n := uint64(srcLen) - if n > 0xffffffff { - return -1 - } - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // That is, 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - n = 32 + n + n/6 - if n > 0xffffffff { - return -1 - } - return int(n) -} - -var errClosed = errors.New("snappy: Writer is closed") - -// NewWriter returns a new Writer that compresses to w. -// -// The Writer returned does not buffer writes. There is no need to Flush or -// Close such a Writer. -// -// Deprecated: the Writer returned is not suitable for many small writes, only -// for few large writes. Use NewBufferedWriter instead, which is efficient -// regardless of the frequency and shape of the writes, and remember to Close -// that Writer when done. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - obuf: make([]byte, obufLen), - } -} - -// NewBufferedWriter returns a new Writer that compresses to w, using the -// framing format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -// -// The Writer returned buffers writes. Users must call Close to guarantee all -// data has been forwarded to the underlying io.Writer. They may also call -// Flush zero or more times before calling Close. -func NewBufferedWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - ibuf: make([]byte, 0, maxBlockSize), - obuf: make([]byte, obufLen), - } -} - -// Writer is an io.Writer that can write Snappy-compressed bytes. -// -// Writer handles the Snappy stream format, not the Snappy block format. -type Writer struct { - w io.Writer - err error - - // ibuf is a buffer for the incoming (uncompressed) bytes. - // - // Its use is optional. For backwards compatibility, Writers created by the - // NewWriter function have ibuf == nil, do not buffer incoming bytes, and - // therefore do not need to be Flush'ed or Close'd. - ibuf []byte - - // obuf is a buffer for the outgoing (compressed) bytes. - obuf []byte - - // wroteStreamHeader is whether we have written the stream header. - wroteStreamHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - if w.ibuf != nil { - w.ibuf = w.ibuf[:0] - } - w.wroteStreamHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (nRet int, errRet error) { - if w.ibuf == nil { - // Do not buffer incoming bytes. This does not perform or compress well - // if the caller of Writer.Write writes many small slices. This - // behavior is therefore deprecated, but still supported for backwards - // compatibility with code that doesn't explicitly Flush or Close. - return w.write(p) - } - - // The remainder of this method is based on bufio.Writer.Write from the - // standard library. - - for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { - var n int - if len(w.ibuf) == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, _ = w.write(p) - } else { - n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - w.Flush() - } - nRet += n - p = p[n:] - } - if w.err != nil { - return nRet, w.err - } - n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - nRet += n - return nRet, nil -} - -func (w *Writer) write(p []byte) (nRet int, errRet error) { - if w.err != nil { - return 0, w.err - } - for len(p) > 0 { - obufStart := len(magicChunk) - if !w.wroteStreamHeader { - w.wroteStreamHeader = true - copy(w.obuf, magicChunk) - obufStart = 0 - } - - var uncompressed []byte - if len(p) > maxBlockSize { - uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) - chunkType := uint8(chunkTypeCompressedData) - chunkLen := 4 + len(compressed) - obufEnd := obufHeaderLen + len(compressed) - if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { - chunkType = chunkTypeUncompressedData - chunkLen = 4 + len(uncompressed) - obufEnd = obufHeaderLen - } - - // Fill in the per-chunk header that comes before the body. - w.obuf[len(magicChunk)+0] = chunkType - w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) - w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) - w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) - w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) - w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) - w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) - w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) - - if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { - w.err = err - return nRet, err - } - if chunkType == chunkTypeUncompressedData { - if _, err := w.w.Write(uncompressed); err != nil { - w.err = err - return nRet, err - } - } - nRet += len(uncompressed) - } - return nRet, nil -} - -// Flush flushes the Writer to its underlying io.Writer. -func (w *Writer) Flush() error { - if w.err != nil { - return w.err - } - if len(w.ibuf) == 0 { - return nil - } - w.write(w.ibuf) - w.ibuf = w.ibuf[:0] - return w.err -} - -// Close calls Flush and then closes the Writer. -func (w *Writer) Close() error { - w.Flush() - ret := w.err - if w.err == nil { - w.err = errClosed - } - return ret -} diff --git a/vendor/github.com/golang/snappy/encode_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s deleted file mode 100644 index adfd979fe..000000000 --- a/vendor/github.com/golang/snappy/encode_amd64.s +++ /dev/null @@ -1,730 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The XXX lines assemble on Go 1.4, 1.5 and 1.7, but not 1.6, due to a -// Go toolchain regression. See https://github.com/golang/go/issues/15426 and -// https://github.com/golang/snappy/issues/29 -// -// As a workaround, the package was built with a known good assembler, and -// those instructions were disassembled by "objdump -d" to yield the -// 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 -// style comments, in AT&T asm syntax. Note that rsp here is a physical -// register, not Go/asm's SP pseudo-register (see https://golang.org/doc/asm). -// The instructions were then encoded as "BYTE $0x.." sequences, which assemble -// fine on Go 1.6. - -// The asm code generally follows the pure Go code in encode_other.go, except -// where marked with a "!!!". - -// ---------------------------------------------------------------------------- - -// func emitLiteral(dst, lit []byte) int -// -// All local variables fit into registers. The register allocation: -// - AX len(lit) -// - BX n -// - DX return value -// - DI &dst[i] -// - R10 &lit[0] -// -// The 24 bytes of stack space is to call runtime·memmove. -// -// The unusual register allocation of local variables, such as R10 for the -// source pointer, matches the allocation used at the call site in encodeBlock, -// which makes it easier to manually inline this function. -TEXT ·emitLiteral(SB), NOSPLIT, $24-56 - MOVQ dst_base+0(FP), DI - MOVQ lit_base+24(FP), R10 - MOVQ lit_len+32(FP), AX - MOVQ AX, DX - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT oneByte - CMPL BX, $256 - JLT twoBytes - -threeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - ADDQ $3, DX - JMP memmove - -twoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - ADDQ $2, DX - JMP memmove - -oneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - ADDQ $1, DX - -memmove: - MOVQ DX, ret+48(FP) - - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - CALL runtime·memmove(SB) - RET - -// ---------------------------------------------------------------------------- - -// func emitCopy(dst []byte, offset, length int) int -// -// All local variables fit into registers. The register allocation: -// - AX length -// - SI &dst[0] -// - DI &dst[i] -// - R11 offset -// -// The unusual register allocation of local variables, such as R11 for the -// offset, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·emitCopy(SB), NOSPLIT, $0-48 - MOVQ dst_base+0(FP), DI - MOVQ DI, SI - MOVQ offset+24(FP), R11 - MOVQ length+32(FP), AX - -loop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT step1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP loop0 - -step1: - // if length > 64 { etc } - CMPL AX, $64 - JLE step2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -step2: - // if length >= 12 || offset >= 2048 { goto step3 } - CMPL AX, $12 - JGE step3 - CMPL R11, $2048 - JGE step3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -step3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func extendMatch(src []byte, i, j int) int -// -// All local variables fit into registers. The register allocation: -// - DX &src[0] -// - SI &src[j] -// - R13 &src[len(src) - 8] -// - R14 &src[len(src)] -// - R15 &src[i] -// -// The unusual register allocation of local variables, such as R15 for a source -// pointer, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·extendMatch(SB), NOSPLIT, $0-48 - MOVQ src_base+0(FP), DX - MOVQ src_len+8(FP), R14 - MOVQ i+24(FP), R15 - MOVQ j+32(FP), SI - ADDQ DX, R14 - ADDQ DX, R15 - ADDQ DX, SI - MOVQ R14, R13 - SUBQ $8, R13 - -cmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA cmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE bsf - ADDQ $8, R15 - ADDQ $8, SI - JMP cmp8 - -bsf: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -cmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE extendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE extendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP cmp1 - -extendMatchEnd: - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func encodeBlock(dst, src []byte) (d int) -// -// All local variables fit into registers, other than "var table". The register -// allocation: -// - AX . . -// - BX . . -// - CX 56 shift (note that amd64 shifts by non-immediates must use CX). -// - DX 64 &src[0], tableSize -// - SI 72 &src[s] -// - DI 80 &dst[d] -// - R9 88 sLimit -// - R10 . &src[nextEmit] -// - R11 96 prevHash, currHash, nextHash, offset -// - R12 104 &src[base], skip -// - R13 . &src[nextS], &src[len(src) - 8] -// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x -// - R15 112 candidate -// -// The second column (56, 64, etc) is the stack offset to spill the registers -// when calling other functions. We could pack this slightly tighter, but it's -// simpler to have a dedicated spill map independent of the function called. -// -// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An -// extra 56 bytes, to call other functions, and an extra 64 bytes, to spill -// local variables (registers) during calls gives 32768 + 56 + 64 = 32888. -TEXT ·encodeBlock(SB), 0, $32888-56 - MOVQ dst_base+0(FP), DI - MOVQ src_base+24(FP), SI - MOVQ src_len+32(FP), R14 - - // shift, tableSize := uint32(32-8), 1<<8 - MOVQ $24, CX - MOVQ $256, DX - -calcShift: - // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - // shift-- - // } - CMPQ DX, $16384 - JGE varTable - CMPQ DX, R14 - JGE varTable - SUBQ $1, CX - SHLQ $1, DX - JMP calcShift - -varTable: - // var table [maxTableSize]uint16 - // - // In the asm code, unlike the Go code, we can zero-initialize only the - // first tableSize elements. Each uint16 element is 2 bytes and each MOVOU - // writes 16 bytes, so we can do only tableSize/8 writes instead of the - // 2048 writes that would zero-initialize all of table's 32768 bytes. - SHRQ $3, DX - LEAQ table-32768(SP), BX - PXOR X0, X0 - -memclr: - MOVOU X0, 0(BX) - ADDQ $16, BX - SUBQ $1, DX - JNZ memclr - - // !!! DX = &src[0] - MOVQ SI, DX - - // sLimit := len(src) - inputMargin - MOVQ R14, R9 - SUBQ $15, R9 - - // !!! Pre-emptively spill CX, DX and R9 to the stack. Their values don't - // change for the rest of the function. - MOVQ CX, 56(SP) - MOVQ DX, 64(SP) - MOVQ R9, 88(SP) - - // nextEmit := 0 - MOVQ DX, R10 - - // s := 1 - ADDQ $1, SI - - // nextHash := hash(load32(src, s), shift) - MOVL 0(SI), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - -outer: - // for { etc } - - // skip := 32 - MOVQ $32, R12 - - // nextS := s - MOVQ SI, R13 - - // candidate := 0 - MOVQ $0, R15 - -inner0: - // for { etc } - - // s := nextS - MOVQ R13, SI - - // bytesBetweenHashLookups := skip >> 5 - MOVQ R12, R14 - SHRQ $5, R14 - - // nextS = s + bytesBetweenHashLookups - ADDQ R14, R13 - - // skip += bytesBetweenHashLookups - ADDQ R14, R12 - - // if nextS > sLimit { goto emitRemainder } - MOVQ R13, AX - SUBQ DX, AX - CMPQ AX, R9 - JA emitRemainder - - // candidate = int(table[nextHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[nextHash] = uint16(s) - MOVQ SI, AX - SUBQ DX, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // nextHash = hash(load32(src, nextS), shift) - MOVL 0(R13), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // if load32(src, s) != load32(src, candidate) { continue } break - MOVL 0(SI), AX - MOVL (DX)(R15*1), BX - CMPL AX, BX - JNE inner0 - -fourByteMatch: - // As per the encode_other.go code: - // - // A 4-byte match has been found. We'll later see etc. - - // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment - // on inputMargin in encode.go. - MOVQ SI, AX - SUBQ R10, AX - CMPQ AX, $16 - JLE emitLiteralFastPath - - // ---------------------------------------- - // Begin inline of the emitLiteral call. - // - // d += emitLiteral(dst[d:], src[nextEmit:s]) - - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT inlineEmitLiteralOneByte - CMPL BX, $256 - JLT inlineEmitLiteralTwoBytes - -inlineEmitLiteralThreeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralTwoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralOneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - -inlineEmitLiteralMemmove: - // Spill local variables (registers) onto the stack; call; unspill. - // - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - ADDQ AX, DI // Finish the "d +=" part of "d += emitLiteral(etc)". - MOVQ SI, 72(SP) - MOVQ DI, 80(SP) - MOVQ R15, 112(SP) - CALL runtime·memmove(SB) - MOVQ 56(SP), CX - MOVQ 64(SP), DX - MOVQ 72(SP), SI - MOVQ 80(SP), DI - MOVQ 88(SP), R9 - MOVQ 112(SP), R15 - JMP inner1 - -inlineEmitLiteralEnd: - // End inline of the emitLiteral call. - // ---------------------------------------- - -emitLiteralFastPath: - // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2". - MOVB AX, BX - SUBB $1, BX - SHLB $2, BX - MOVB BX, (DI) - ADDQ $1, DI - - // !!! Implement the copy from lit to dst as a 16-byte load and store. - // (Encode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only len(lit) bytes, but that's - // OK. Subsequent iterations will fix up the overrun. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(R10), X0 - MOVOU X0, 0(DI) - ADDQ AX, DI - -inner1: - // for { etc } - - // base := s - MOVQ SI, R12 - - // !!! offset := base - candidate - MOVQ R12, R11 - SUBQ R15, R11 - SUBQ DX, R11 - - // ---------------------------------------- - // Begin inline of the extendMatch call. - // - // s = extendMatch(src, candidate+4, s+4) - - // !!! R14 = &src[len(src)] - MOVQ src_len+32(FP), R14 - ADDQ DX, R14 - - // !!! R13 = &src[len(src) - 8] - MOVQ R14, R13 - SUBQ $8, R13 - - // !!! R15 = &src[candidate + 4] - ADDQ $4, R15 - ADDQ DX, R15 - - // !!! s += 4 - ADDQ $4, SI - -inlineExtendMatchCmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA inlineExtendMatchCmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE inlineExtendMatchBSF - ADDQ $8, R15 - ADDQ $8, SI - JMP inlineExtendMatchCmp8 - -inlineExtendMatchBSF: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - JMP inlineExtendMatchEnd - -inlineExtendMatchCmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE inlineExtendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE inlineExtendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP inlineExtendMatchCmp1 - -inlineExtendMatchEnd: - // End inline of the extendMatch call. - // ---------------------------------------- - - // ---------------------------------------- - // Begin inline of the emitCopy call. - // - // d += emitCopy(dst[d:], base-candidate, s-base) - - // !!! length := s - base - MOVQ SI, AX - SUBQ R12, AX - -inlineEmitCopyLoop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT inlineEmitCopyStep1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP inlineEmitCopyLoop0 - -inlineEmitCopyStep1: - // if length > 64 { etc } - CMPL AX, $64 - JLE inlineEmitCopyStep2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -inlineEmitCopyStep2: - // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 } - CMPL AX, $12 - JGE inlineEmitCopyStep3 - CMPL R11, $2048 - JGE inlineEmitCopyStep3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - JMP inlineEmitCopyEnd - -inlineEmitCopyStep3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - -inlineEmitCopyEnd: - // End inline of the emitCopy call. - // ---------------------------------------- - - // nextEmit = s - MOVQ SI, R10 - - // if s >= sLimit { goto emitRemainder } - MOVQ SI, AX - SUBQ DX, AX - CMPQ AX, R9 - JAE emitRemainder - - // As per the encode_other.go code: - // - // We could immediately etc. - - // x := load64(src, s-1) - MOVQ -1(SI), R14 - - // prevHash := hash(uint32(x>>0), shift) - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // table[prevHash] = uint16(s-1) - MOVQ SI, AX - SUBQ DX, AX - SUBQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // currHash := hash(uint32(x>>8), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // candidate = int(table[currHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[currHash] = uint16(s) - ADDQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // if uint32(x>>8) == load32(src, candidate) { continue } - MOVL (DX)(R15*1), BX - CMPL R14, BX - JEQ inner1 - - // nextHash = hash(uint32(x>>16), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // s++ - ADDQ $1, SI - - // break out of the inner1 for loop, i.e. continue the outer loop. - JMP outer - -emitRemainder: - // if nextEmit < len(src) { etc } - MOVQ src_len+32(FP), AX - ADDQ DX, AX - CMPQ R10, AX - JEQ encodeBlockEnd - - // d += emitLiteral(dst[d:], src[nextEmit:]) - // - // Push args. - MOVQ DI, 0(SP) - MOVQ $0, 8(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ $0, 16(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ R10, 24(SP) - SUBQ R10, AX - MOVQ AX, 32(SP) - MOVQ AX, 40(SP) // Unnecessary, as the callee ignores it, but conservative. - - // Spill local variables (registers) onto the stack; call; unspill. - MOVQ DI, 80(SP) - CALL ·emitLiteral(SB) - MOVQ 80(SP), DI - - // Finish the "d +=" part of "d += emitLiteral(etc)". - ADDQ 48(SP), DI - -encodeBlockEnd: - MOVQ dst_base+0(FP), AX - SUBQ AX, DI - MOVQ DI, d+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/encode_arm64.s b/vendor/github.com/golang/snappy/encode_arm64.s deleted file mode 100644 index f8d54adfc..000000000 --- a/vendor/github.com/golang/snappy/encode_arm64.s +++ /dev/null @@ -1,722 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The asm code generally follows the pure Go code in encode_other.go, except -// where marked with a "!!!". - -// ---------------------------------------------------------------------------- - -// func emitLiteral(dst, lit []byte) int -// -// All local variables fit into registers. The register allocation: -// - R3 len(lit) -// - R4 n -// - R6 return value -// - R8 &dst[i] -// - R10 &lit[0] -// -// The 32 bytes of stack space is to call runtime·memmove. -// -// The unusual register allocation of local variables, such as R10 for the -// source pointer, matches the allocation used at the call site in encodeBlock, -// which makes it easier to manually inline this function. -TEXT ·emitLiteral(SB), NOSPLIT, $32-56 - MOVD dst_base+0(FP), R8 - MOVD lit_base+24(FP), R10 - MOVD lit_len+32(FP), R3 - MOVD R3, R6 - MOVW R3, R4 - SUBW $1, R4, R4 - - CMPW $60, R4 - BLT oneByte - CMPW $256, R4 - BLT twoBytes - -threeBytes: - MOVD $0xf4, R2 - MOVB R2, 0(R8) - MOVW R4, 1(R8) - ADD $3, R8, R8 - ADD $3, R6, R6 - B memmove - -twoBytes: - MOVD $0xf0, R2 - MOVB R2, 0(R8) - MOVB R4, 1(R8) - ADD $2, R8, R8 - ADD $2, R6, R6 - B memmove - -oneByte: - LSLW $2, R4, R4 - MOVB R4, 0(R8) - ADD $1, R8, R8 - ADD $1, R6, R6 - -memmove: - MOVD R6, ret+48(FP) - - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // R8, R10 and R3 as arguments. - MOVD R8, 8(RSP) - MOVD R10, 16(RSP) - MOVD R3, 24(RSP) - CALL runtime·memmove(SB) - RET - -// ---------------------------------------------------------------------------- - -// func emitCopy(dst []byte, offset, length int) int -// -// All local variables fit into registers. The register allocation: -// - R3 length -// - R7 &dst[0] -// - R8 &dst[i] -// - R11 offset -// -// The unusual register allocation of local variables, such as R11 for the -// offset, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·emitCopy(SB), NOSPLIT, $0-48 - MOVD dst_base+0(FP), R8 - MOVD R8, R7 - MOVD offset+24(FP), R11 - MOVD length+32(FP), R3 - -loop0: - // for length >= 68 { etc } - CMPW $68, R3 - BLT step1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVD $0xfe, R2 - MOVB R2, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - SUB $64, R3, R3 - B loop0 - -step1: - // if length > 64 { etc } - CMP $64, R3 - BLE step2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVD $0xee, R2 - MOVB R2, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - SUB $60, R3, R3 - -step2: - // if length >= 12 || offset >= 2048 { goto step3 } - CMP $12, R3 - BGE step3 - CMPW $2048, R11 - BGE step3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(R8) - LSRW $3, R11, R11 - AND $0xe0, R11, R11 - SUB $4, R3, R3 - LSLW $2, R3 - AND $0xff, R3, R3 - ORRW R3, R11, R11 - ORRW $1, R11, R11 - MOVB R11, 0(R8) - ADD $2, R8, R8 - - // Return the number of bytes written. - SUB R7, R8, R8 - MOVD R8, ret+40(FP) - RET - -step3: - // Emit the remaining copy, encoded as 3 bytes. - SUB $1, R3, R3 - AND $0xff, R3, R3 - LSLW $2, R3, R3 - ORRW $2, R3, R3 - MOVB R3, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - - // Return the number of bytes written. - SUB R7, R8, R8 - MOVD R8, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func extendMatch(src []byte, i, j int) int -// -// All local variables fit into registers. The register allocation: -// - R6 &src[0] -// - R7 &src[j] -// - R13 &src[len(src) - 8] -// - R14 &src[len(src)] -// - R15 &src[i] -// -// The unusual register allocation of local variables, such as R15 for a source -// pointer, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·extendMatch(SB), NOSPLIT, $0-48 - MOVD src_base+0(FP), R6 - MOVD src_len+8(FP), R14 - MOVD i+24(FP), R15 - MOVD j+32(FP), R7 - ADD R6, R14, R14 - ADD R6, R15, R15 - ADD R6, R7, R7 - MOVD R14, R13 - SUB $8, R13, R13 - -cmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMP R13, R7 - BHI cmp1 - MOVD (R15), R3 - MOVD (R7), R4 - CMP R4, R3 - BNE bsf - ADD $8, R15, R15 - ADD $8, R7, R7 - B cmp8 - -bsf: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. - // RBIT reverses the bit order, then CLZ counts the leading zeros, the - // combination of which finds the least significant bit which is set. - // The arm64 architecture is little-endian, and the shift by 3 converts - // a bit index to a byte index. - EOR R3, R4, R4 - RBIT R4, R4 - CLZ R4, R4 - ADD R4>>3, R7, R7 - - // Convert from &src[ret] to ret. - SUB R6, R7, R7 - MOVD R7, ret+40(FP) - RET - -cmp1: - // In src's tail, compare 1 byte at a time. - CMP R7, R14 - BLS extendMatchEnd - MOVB (R15), R3 - MOVB (R7), R4 - CMP R4, R3 - BNE extendMatchEnd - ADD $1, R15, R15 - ADD $1, R7, R7 - B cmp1 - -extendMatchEnd: - // Convert from &src[ret] to ret. - SUB R6, R7, R7 - MOVD R7, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func encodeBlock(dst, src []byte) (d int) -// -// All local variables fit into registers, other than "var table". The register -// allocation: -// - R3 . . -// - R4 . . -// - R5 64 shift -// - R6 72 &src[0], tableSize -// - R7 80 &src[s] -// - R8 88 &dst[d] -// - R9 96 sLimit -// - R10 . &src[nextEmit] -// - R11 104 prevHash, currHash, nextHash, offset -// - R12 112 &src[base], skip -// - R13 . &src[nextS], &src[len(src) - 8] -// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x -// - R15 120 candidate -// - R16 . hash constant, 0x1e35a7bd -// - R17 . &table -// - . 128 table -// -// The second column (64, 72, etc) is the stack offset to spill the registers -// when calling other functions. We could pack this slightly tighter, but it's -// simpler to have a dedicated spill map independent of the function called. -// -// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An -// extra 64 bytes, to call other functions, and an extra 64 bytes, to spill -// local variables (registers) during calls gives 32768 + 64 + 64 = 32896. -TEXT ·encodeBlock(SB), 0, $32896-56 - MOVD dst_base+0(FP), R8 - MOVD src_base+24(FP), R7 - MOVD src_len+32(FP), R14 - - // shift, tableSize := uint32(32-8), 1<<8 - MOVD $24, R5 - MOVD $256, R6 - MOVW $0xa7bd, R16 - MOVKW $(0x1e35<<16), R16 - -calcShift: - // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - // shift-- - // } - MOVD $16384, R2 - CMP R2, R6 - BGE varTable - CMP R14, R6 - BGE varTable - SUB $1, R5, R5 - LSL $1, R6, R6 - B calcShift - -varTable: - // var table [maxTableSize]uint16 - // - // In the asm code, unlike the Go code, we can zero-initialize only the - // first tableSize elements. Each uint16 element is 2 bytes and each - // iterations writes 64 bytes, so we can do only tableSize/32 writes - // instead of the 2048 writes that would zero-initialize all of table's - // 32768 bytes. This clear could overrun the first tableSize elements, but - // it won't overrun the allocated stack size. - ADD $128, RSP, R17 - MOVD R17, R4 - - // !!! R6 = &src[tableSize] - ADD R6<<1, R17, R6 - -memclr: - STP.P (ZR, ZR), 64(R4) - STP (ZR, ZR), -48(R4) - STP (ZR, ZR), -32(R4) - STP (ZR, ZR), -16(R4) - CMP R4, R6 - BHI memclr - - // !!! R6 = &src[0] - MOVD R7, R6 - - // sLimit := len(src) - inputMargin - MOVD R14, R9 - SUB $15, R9, R9 - - // !!! Pre-emptively spill R5, R6 and R9 to the stack. Their values don't - // change for the rest of the function. - MOVD R5, 64(RSP) - MOVD R6, 72(RSP) - MOVD R9, 96(RSP) - - // nextEmit := 0 - MOVD R6, R10 - - // s := 1 - ADD $1, R7, R7 - - // nextHash := hash(load32(src, s), shift) - MOVW 0(R7), R11 - MULW R16, R11, R11 - LSRW R5, R11, R11 - -outer: - // for { etc } - - // skip := 32 - MOVD $32, R12 - - // nextS := s - MOVD R7, R13 - - // candidate := 0 - MOVD $0, R15 - -inner0: - // for { etc } - - // s := nextS - MOVD R13, R7 - - // bytesBetweenHashLookups := skip >> 5 - MOVD R12, R14 - LSR $5, R14, R14 - - // nextS = s + bytesBetweenHashLookups - ADD R14, R13, R13 - - // skip += bytesBetweenHashLookups - ADD R14, R12, R12 - - // if nextS > sLimit { goto emitRemainder } - MOVD R13, R3 - SUB R6, R3, R3 - CMP R9, R3 - BHI emitRemainder - - // candidate = int(table[nextHash]) - MOVHU 0(R17)(R11<<1), R15 - - // table[nextHash] = uint16(s) - MOVD R7, R3 - SUB R6, R3, R3 - - MOVH R3, 0(R17)(R11<<1) - - // nextHash = hash(load32(src, nextS), shift) - MOVW 0(R13), R11 - MULW R16, R11 - LSRW R5, R11, R11 - - // if load32(src, s) != load32(src, candidate) { continue } break - MOVW 0(R7), R3 - MOVW (R6)(R15), R4 - CMPW R4, R3 - BNE inner0 - -fourByteMatch: - // As per the encode_other.go code: - // - // A 4-byte match has been found. We'll later see etc. - - // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment - // on inputMargin in encode.go. - MOVD R7, R3 - SUB R10, R3, R3 - CMP $16, R3 - BLE emitLiteralFastPath - - // ---------------------------------------- - // Begin inline of the emitLiteral call. - // - // d += emitLiteral(dst[d:], src[nextEmit:s]) - - MOVW R3, R4 - SUBW $1, R4, R4 - - MOVW $60, R2 - CMPW R2, R4 - BLT inlineEmitLiteralOneByte - MOVW $256, R2 - CMPW R2, R4 - BLT inlineEmitLiteralTwoBytes - -inlineEmitLiteralThreeBytes: - MOVD $0xf4, R1 - MOVB R1, 0(R8) - MOVW R4, 1(R8) - ADD $3, R8, R8 - B inlineEmitLiteralMemmove - -inlineEmitLiteralTwoBytes: - MOVD $0xf0, R1 - MOVB R1, 0(R8) - MOVB R4, 1(R8) - ADD $2, R8, R8 - B inlineEmitLiteralMemmove - -inlineEmitLiteralOneByte: - LSLW $2, R4, R4 - MOVB R4, 0(R8) - ADD $1, R8, R8 - -inlineEmitLiteralMemmove: - // Spill local variables (registers) onto the stack; call; unspill. - // - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // R8, R10 and R3 as arguments. - MOVD R8, 8(RSP) - MOVD R10, 16(RSP) - MOVD R3, 24(RSP) - - // Finish the "d +=" part of "d += emitLiteral(etc)". - ADD R3, R8, R8 - MOVD R7, 80(RSP) - MOVD R8, 88(RSP) - MOVD R15, 120(RSP) - CALL runtime·memmove(SB) - MOVD 64(RSP), R5 - MOVD 72(RSP), R6 - MOVD 80(RSP), R7 - MOVD 88(RSP), R8 - MOVD 96(RSP), R9 - MOVD 120(RSP), R15 - ADD $128, RSP, R17 - MOVW $0xa7bd, R16 - MOVKW $(0x1e35<<16), R16 - B inner1 - -inlineEmitLiteralEnd: - // End inline of the emitLiteral call. - // ---------------------------------------- - -emitLiteralFastPath: - // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2". - MOVB R3, R4 - SUBW $1, R4, R4 - AND $0xff, R4, R4 - LSLW $2, R4, R4 - MOVB R4, (R8) - ADD $1, R8, R8 - - // !!! Implement the copy from lit to dst as a 16-byte load and store. - // (Encode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only len(lit) bytes, but that's - // OK. Subsequent iterations will fix up the overrun. - // - // Note that on arm64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - LDP 0(R10), (R0, R1) - STP (R0, R1), 0(R8) - ADD R3, R8, R8 - -inner1: - // for { etc } - - // base := s - MOVD R7, R12 - - // !!! offset := base - candidate - MOVD R12, R11 - SUB R15, R11, R11 - SUB R6, R11, R11 - - // ---------------------------------------- - // Begin inline of the extendMatch call. - // - // s = extendMatch(src, candidate+4, s+4) - - // !!! R14 = &src[len(src)] - MOVD src_len+32(FP), R14 - ADD R6, R14, R14 - - // !!! R13 = &src[len(src) - 8] - MOVD R14, R13 - SUB $8, R13, R13 - - // !!! R15 = &src[candidate + 4] - ADD $4, R15, R15 - ADD R6, R15, R15 - - // !!! s += 4 - ADD $4, R7, R7 - -inlineExtendMatchCmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMP R13, R7 - BHI inlineExtendMatchCmp1 - MOVD (R15), R3 - MOVD (R7), R4 - CMP R4, R3 - BNE inlineExtendMatchBSF - ADD $8, R15, R15 - ADD $8, R7, R7 - B inlineExtendMatchCmp8 - -inlineExtendMatchBSF: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. - // RBIT reverses the bit order, then CLZ counts the leading zeros, the - // combination of which finds the least significant bit which is set. - // The arm64 architecture is little-endian, and the shift by 3 converts - // a bit index to a byte index. - EOR R3, R4, R4 - RBIT R4, R4 - CLZ R4, R4 - ADD R4>>3, R7, R7 - B inlineExtendMatchEnd - -inlineExtendMatchCmp1: - // In src's tail, compare 1 byte at a time. - CMP R7, R14 - BLS inlineExtendMatchEnd - MOVB (R15), R3 - MOVB (R7), R4 - CMP R4, R3 - BNE inlineExtendMatchEnd - ADD $1, R15, R15 - ADD $1, R7, R7 - B inlineExtendMatchCmp1 - -inlineExtendMatchEnd: - // End inline of the extendMatch call. - // ---------------------------------------- - - // ---------------------------------------- - // Begin inline of the emitCopy call. - // - // d += emitCopy(dst[d:], base-candidate, s-base) - - // !!! length := s - base - MOVD R7, R3 - SUB R12, R3, R3 - -inlineEmitCopyLoop0: - // for length >= 68 { etc } - MOVW $68, R2 - CMPW R2, R3 - BLT inlineEmitCopyStep1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVD $0xfe, R1 - MOVB R1, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - SUBW $64, R3, R3 - B inlineEmitCopyLoop0 - -inlineEmitCopyStep1: - // if length > 64 { etc } - MOVW $64, R2 - CMPW R2, R3 - BLE inlineEmitCopyStep2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVD $0xee, R1 - MOVB R1, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - SUBW $60, R3, R3 - -inlineEmitCopyStep2: - // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 } - MOVW $12, R2 - CMPW R2, R3 - BGE inlineEmitCopyStep3 - MOVW $2048, R2 - CMPW R2, R11 - BGE inlineEmitCopyStep3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(R8) - LSRW $8, R11, R11 - LSLW $5, R11, R11 - SUBW $4, R3, R3 - AND $0xff, R3, R3 - LSLW $2, R3, R3 - ORRW R3, R11, R11 - ORRW $1, R11, R11 - MOVB R11, 0(R8) - ADD $2, R8, R8 - B inlineEmitCopyEnd - -inlineEmitCopyStep3: - // Emit the remaining copy, encoded as 3 bytes. - SUBW $1, R3, R3 - LSLW $2, R3, R3 - ORRW $2, R3, R3 - MOVB R3, 0(R8) - MOVW R11, 1(R8) - ADD $3, R8, R8 - -inlineEmitCopyEnd: - // End inline of the emitCopy call. - // ---------------------------------------- - - // nextEmit = s - MOVD R7, R10 - - // if s >= sLimit { goto emitRemainder } - MOVD R7, R3 - SUB R6, R3, R3 - CMP R3, R9 - BLS emitRemainder - - // As per the encode_other.go code: - // - // We could immediately etc. - - // x := load64(src, s-1) - MOVD -1(R7), R14 - - // prevHash := hash(uint32(x>>0), shift) - MOVW R14, R11 - MULW R16, R11, R11 - LSRW R5, R11, R11 - - // table[prevHash] = uint16(s-1) - MOVD R7, R3 - SUB R6, R3, R3 - SUB $1, R3, R3 - - MOVHU R3, 0(R17)(R11<<1) - - // currHash := hash(uint32(x>>8), shift) - LSR $8, R14, R14 - MOVW R14, R11 - MULW R16, R11, R11 - LSRW R5, R11, R11 - - // candidate = int(table[currHash]) - MOVHU 0(R17)(R11<<1), R15 - - // table[currHash] = uint16(s) - ADD $1, R3, R3 - MOVHU R3, 0(R17)(R11<<1) - - // if uint32(x>>8) == load32(src, candidate) { continue } - MOVW (R6)(R15), R4 - CMPW R4, R14 - BEQ inner1 - - // nextHash = hash(uint32(x>>16), shift) - LSR $8, R14, R14 - MOVW R14, R11 - MULW R16, R11, R11 - LSRW R5, R11, R11 - - // s++ - ADD $1, R7, R7 - - // break out of the inner1 for loop, i.e. continue the outer loop. - B outer - -emitRemainder: - // if nextEmit < len(src) { etc } - MOVD src_len+32(FP), R3 - ADD R6, R3, R3 - CMP R3, R10 - BEQ encodeBlockEnd - - // d += emitLiteral(dst[d:], src[nextEmit:]) - // - // Push args. - MOVD R8, 8(RSP) - MOVD $0, 16(RSP) // Unnecessary, as the callee ignores it, but conservative. - MOVD $0, 24(RSP) // Unnecessary, as the callee ignores it, but conservative. - MOVD R10, 32(RSP) - SUB R10, R3, R3 - MOVD R3, 40(RSP) - MOVD R3, 48(RSP) // Unnecessary, as the callee ignores it, but conservative. - - // Spill local variables (registers) onto the stack; call; unspill. - MOVD R8, 88(RSP) - CALL ·emitLiteral(SB) - MOVD 88(RSP), R8 - - // Finish the "d +=" part of "d += emitLiteral(etc)". - MOVD 56(RSP), R1 - ADD R1, R8, R8 - -encodeBlockEnd: - MOVD dst_base+0(FP), R3 - SUB R3, R8, R8 - MOVD R8, d+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/encode_asm.go b/vendor/github.com/golang/snappy/encode_asm.go deleted file mode 100644 index 107c1e714..000000000 --- a/vendor/github.com/golang/snappy/encode_asm.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm -// +build amd64 arm64 - -package snappy - -// emitLiteral has the same semantics as in encode_other.go. -// -//go:noescape -func emitLiteral(dst, lit []byte) int - -// emitCopy has the same semantics as in encode_other.go. -// -//go:noescape -func emitCopy(dst []byte, offset, length int) int - -// extendMatch has the same semantics as in encode_other.go. -// -//go:noescape -func extendMatch(src []byte, i, j int) int - -// encodeBlock has the same semantics as in encode_other.go. -// -//go:noescape -func encodeBlock(dst, src []byte) (d int) diff --git a/vendor/github.com/golang/snappy/encode_other.go b/vendor/github.com/golang/snappy/encode_other.go deleted file mode 100644 index 296d7f0be..000000000 --- a/vendor/github.com/golang/snappy/encode_other.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64,!arm64 appengine !gc noasm - -package snappy - -func load32(b []byte, i int) uint32 { - b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load64(b []byte, i int) uint64 { - b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= len(lit) && len(lit) <= 65536 -func emitLiteral(dst, lit []byte) int { - i, n := 0, uint(len(lit)-1) - switch { - case n < 60: - dst[0] = uint8(n)<<2 | tagLiteral - i = 1 - case n < 1<<8: - dst[0] = 60<<2 | tagLiteral - dst[1] = uint8(n) - i = 2 - default: - dst[0] = 61<<2 | tagLiteral - dst[1] = uint8(n) - dst[2] = uint8(n >> 8) - i = 3 - } - return i + copy(dst[i:], lit) -} - -// emitCopy writes a copy chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= offset && offset <= 65535 -// 4 <= length && length <= 65535 -func emitCopy(dst []byte, offset, length int) int { - i := 0 - // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The - // threshold for this loop is a little higher (at 68 = 64 + 4), and the - // length emitted down below is is a little lower (at 60 = 64 - 4), because - // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed - // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as - // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as - // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a - // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an - // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. - for length >= 68 { - // Emit a length 64 copy, encoded as 3 bytes. - dst[i+0] = 63<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 64 - } - if length > 64 { - // Emit a length 60 copy, encoded as 3 bytes. - dst[i+0] = 59<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 60 - } - if length >= 12 || offset >= 2048 { - // Emit the remaining copy, encoded as 3 bytes. - dst[i+0] = uint8(length-1)<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - return i + 3 - } - // Emit the remaining copy, encoded as 2 bytes. - dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 - dst[i+1] = uint8(offset) - return i + 2 -} - -// extendMatch returns the largest k such that k <= len(src) and that -// src[i:i+k-j] and src[j:k] have the same contents. -// -// It assumes that: -// 0 <= i && i < j && j <= len(src) -func extendMatch(src []byte, i, j int) int { - for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { - } - return j -} - -func hash(u, shift uint32) uint32 { - return (u * 0x1e35a7bd) >> shift -} - -// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It -// assumes that the varint-encoded length of the decompressed bytes has already -// been written. -// -// It also assumes that: -// len(dst) >= MaxEncodedLen(len(src)) && -// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize -func encodeBlock(dst, src []byte) (d int) { - // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. - // The table element type is uint16, as s < sLimit and sLimit < len(src) - // and len(src) <= maxBlockSize and maxBlockSize == 65536. - const ( - maxTableSize = 1 << 14 - // tableMask is redundant, but helps the compiler eliminate bounds - // checks. - tableMask = maxTableSize - 1 - ) - shift := uint32(32 - 8) - for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - shift-- - } - // In Go, all array elements are zero-initialized, so there is no advantage - // to a smaller tableSize per se. However, it matches the C++ algorithm, - // and in the asm versions of this code, we can get away with zeroing only - // the first tableSize elements. - var table [maxTableSize]uint16 - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := len(src) - inputMargin - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := 0 - - // The encoded form must start with a literal, as there are no previous - // bytes to copy, so we start looking for hash matches at s == 1. - s := 1 - nextHash := hash(load32(src, s), shift) - - for { - // Copied from the C++ snappy implementation: - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match - // is found, immediately go back to looking at every byte. This is a - // small loss (~5% performance, ~0.1% density) for compressible data - // due to more bookkeeping, but for non-compressible data (such as - // JPEG) it's a huge win since the compressor quickly "realizes" the - // data is incompressible and doesn't bother looking for matches - // everywhere. - // - // The "skip" variable keeps track of how many bytes there are since - // the last match; dividing it by 32 (ie. right-shifting by five) gives - // the number of bytes to move ahead for each iteration. - skip := 32 - - nextS := s - candidate := 0 - for { - s = nextS - bytesBetweenHashLookups := skip >> 5 - nextS = s + bytesBetweenHashLookups - skip += bytesBetweenHashLookups - if nextS > sLimit { - goto emitRemainder - } - candidate = int(table[nextHash&tableMask]) - table[nextHash&tableMask] = uint16(s) - nextHash = hash(load32(src, nextS), shift) - if load32(src, s) == load32(src, candidate) { - break - } - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - d += emitLiteral(dst[d:], src[nextEmit:s]) - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - base := s - - // Extend the 4-byte match as long as possible. - // - // This is an inlined version of: - // s = extendMatch(src, candidate+4, s+4) - s += 4 - for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { - } - - d += emitCopy(dst[d:], base-candidate, s-base) - nextEmit = s - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load64(src, s-1) - prevHash := hash(uint32(x>>0), shift) - table[prevHash&tableMask] = uint16(s - 1) - currHash := hash(uint32(x>>8), shift) - candidate = int(table[currHash&tableMask]) - table[currHash&tableMask] = uint16(s) - if uint32(x>>8) != load32(src, candidate) { - nextHash = hash(uint32(x>>16), shift) - s++ - break - } - } - } - -emitRemainder: - if nextEmit < len(src) { - d += emitLiteral(dst[d:], src[nextEmit:]) - } - return d -} diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go deleted file mode 100644 index ece692ea4..000000000 --- a/vendor/github.com/golang/snappy/snappy.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package snappy implements the Snappy compression format. It aims for very -// high speeds and reasonable compression. -// -// There are actually two Snappy formats: block and stream. They are related, -// but different: trying to decompress block-compressed data as a Snappy stream -// will fail, and vice versa. The block format is the Decode and Encode -// functions and the stream format is the Reader and Writer types. -// -// The block format, the more common case, is used when the complete size (the -// number of bytes) of the original data is known upfront, at the time -// compression starts. The stream format, also known as the framing format, is -// for when that isn't always true. -// -// The canonical, C++ implementation is at https://github.com/google/snappy and -// it only implements the block format. -package snappy // import "github.com/golang/snappy" - -import ( - "hash/crc32" -) - -/* -Each encoded block begins with the varint-encoded length of the decoded data, -followed by a sequence of chunks. Chunks begin and end on byte boundaries. The -first byte of each chunk is broken into its 2 least and 6 most significant bits -called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. -Zero means a literal tag. All other values mean a copy tag. - -For literal tags: - - If m < 60, the next 1 + m bytes are literal bytes. - - Otherwise, let n be the little-endian unsigned integer denoted by the next - m - 59 bytes. The next 1 + n bytes after that are literal bytes. - -For copy tags, length bytes are copied from offset bytes ago, in the style of -Lempel-Ziv compression algorithms. In particular: - - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). - The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 - of the offset. The next byte is bits 0-7 of the offset. - - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). - The length is 1 + m. The offset is the little-endian unsigned integer - denoted by the next 2 bytes. - - For l == 3, this tag is a legacy format that is no longer issued by most - encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in - [1, 65). The length is 1 + m. The offset is the little-endian unsigned - integer denoted by the next 4 bytes. -*/ -const ( - tagLiteral = 0x00 - tagCopy1 = 0x01 - tagCopy2 = 0x02 - tagCopy4 = 0x03 -) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - - // maxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - maxBlockSize = 65536 - - // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - maxEncodedLenOfMaxBlockSize = 76490 - - obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize - obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/vendor/github.com/hashicorp/go-plugin/.gitignore b/vendor/github.com/hashicorp/go-plugin/.gitignore deleted file mode 100644 index 4befed30a..000000000 --- a/vendor/github.com/hashicorp/go-plugin/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.DS_Store -.idea diff --git a/vendor/github.com/hashicorp/go-plugin/CHANGELOG.md b/vendor/github.com/hashicorp/go-plugin/CHANGELOG.md deleted file mode 100644 index 7463b2c0f..000000000 --- a/vendor/github.com/hashicorp/go-plugin/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -## v1.4.5 - -ENHANCEMENTS: - -* client: log warning when SecureConfig is nil [[GH-207](https://github.com/hashicorp/go-plugin/pull/207)] - - -## v1.4.4 - -ENHANCEMENTS: - -* client: increase level of plugin exit logs [[GH-195](https://github.com/hashicorp/go-plugin/pull/195)] - -BUG FIXES: - -* Bidirectional communication: fix bidirectional communication when AutoMTLS is enabled [[GH-193](https://github.com/hashicorp/go-plugin/pull/193)] -* RPC: Trim a spurious log message for plugins using RPC [[GH-186](https://github.com/hashicorp/go-plugin/pull/186)] - - diff --git a/vendor/github.com/hashicorp/go-plugin/LICENSE b/vendor/github.com/hashicorp/go-plugin/LICENSE deleted file mode 100644 index 82b4de97c..000000000 --- a/vendor/github.com/hashicorp/go-plugin/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/go-plugin/README.md b/vendor/github.com/hashicorp/go-plugin/README.md deleted file mode 100644 index 39391f24f..000000000 --- a/vendor/github.com/hashicorp/go-plugin/README.md +++ /dev/null @@ -1,164 +0,0 @@ -# Go Plugin System over RPC - -`go-plugin` is a Go (golang) plugin system over RPC. It is the plugin system -that has been in use by HashiCorp tooling for over 4 years. While initially -created for [Packer](https://www.packer.io), it is additionally in use by -[Terraform](https://www.terraform.io), [Nomad](https://www.nomadproject.io), -[Vault](https://www.vaultproject.io), and -[Boundary](https://www.boundaryproject.io). - -While the plugin system is over RPC, it is currently only designed to work -over a local [reliable] network. Plugins over a real network are not supported -and will lead to unexpected behavior. - -This plugin system has been used on millions of machines across many different -projects and has proven to be battle hardened and ready for production use. - -## Features - -The HashiCorp plugin system supports a number of features: - -**Plugins are Go interface implementations.** This makes writing and consuming -plugins feel very natural. To a plugin author: you just implement an -interface as if it were going to run in the same process. For a plugin user: -you just use and call functions on an interface as if it were in the same -process. This plugin system handles the communication in between. - -**Cross-language support.** Plugins can be written (and consumed) by -almost every major language. This library supports serving plugins via -[gRPC](http://www.grpc.io). gRPC-based plugins enable plugins to be written -in any language. - -**Complex arguments and return values are supported.** This library -provides APIs for handling complex arguments and return values such -as interfaces, `io.Reader/Writer`, etc. We do this by giving you a library -(`MuxBroker`) for creating new connections between the client/server to -serve additional interfaces or transfer raw data. - -**Bidirectional communication.** Because the plugin system supports -complex arguments, the host process can send it interface implementations -and the plugin can call back into the host process. - -**Built-in Logging.** Any plugins that use the `log` standard library -will have log data automatically sent to the host process. The host -process will mirror this output prefixed with the path to the plugin -binary. This makes debugging with plugins simple. If the host system -uses [hclog](https://github.com/hashicorp/go-hclog) then the log data -will be structured. If the plugin also uses hclog, logs from the plugin -will be sent to the host hclog and be structured. - -**Protocol Versioning.** A very basic "protocol version" is supported that -can be incremented to invalidate any previous plugins. This is useful when -interface signatures are changing, protocol level changes are necessary, -etc. When a protocol version is incompatible, a human friendly error -message is shown to the end user. - -**Stdout/Stderr Syncing.** While plugins are subprocesses, they can continue -to use stdout/stderr as usual and the output will get mirrored back to -the host process. The host process can control what `io.Writer` these -streams go to to prevent this from happening. - -**TTY Preservation.** Plugin subprocesses are connected to the identical -stdin file descriptor as the host process, allowing software that requires -a TTY to work. For example, a plugin can execute `ssh` and even though there -are multiple subprocesses and RPC happening, it will look and act perfectly -to the end user. - -**Host upgrade while a plugin is running.** Plugins can be "reattached" -so that the host process can be upgraded while the plugin is still running. -This requires the host/plugin to know this is possible and daemonize -properly. `NewClient` takes a `ReattachConfig` to determine if and how to -reattach. - -**Cryptographically Secure Plugins.** Plugins can be verified with an expected -checksum and RPC communications can be configured to use TLS. The host process -must be properly secured to protect this configuration. - -## Architecture - -The HashiCorp plugin system works by launching subprocesses and communicating -over RPC (using standard `net/rpc` or [gRPC](http://www.grpc.io)). A single -connection is made between any plugin and the host process. For net/rpc-based -plugins, we use a [connection multiplexing](https://github.com/hashicorp/yamux) -library to multiplex any other connections on top. For gRPC-based plugins, -the HTTP2 protocol handles multiplexing. - -This architecture has a number of benefits: - - * Plugins can't crash your host process: A panic in a plugin doesn't - panic the plugin user. - - * Plugins are very easy to write: just write a Go application and `go build`. - Or use any other language to write a gRPC server with a tiny amount of - boilerplate to support go-plugin. - - * Plugins are very easy to install: just put the binary in a location where - the host will find it (depends on the host but this library also provides - helpers), and the plugin host handles the rest. - - * Plugins can be relatively secure: The plugin only has access to the - interfaces and args given to it, not to the entire memory space of the - process. Additionally, go-plugin can communicate with the plugin over - TLS. - -## Usage - -To use the plugin system, you must take the following steps. These are -high-level steps that must be done. Examples are available in the -`examples/` directory. - - 1. Choose the interface(s) you want to expose for plugins. - - 2. For each interface, implement an implementation of that interface - that communicates over a `net/rpc` connection or over a - [gRPC](http://www.grpc.io) connection or both. You'll have to implement - both a client and server implementation. - - 3. Create a `Plugin` implementation that knows how to create the RPC - client/server for a given plugin type. - - 4. Plugin authors call `plugin.Serve` to serve a plugin from the - `main` function. - - 5. Plugin users use `plugin.Client` to launch a subprocess and request - an interface implementation over RPC. - -That's it! In practice, step 2 is the most tedious and time consuming step. -Even so, it isn't very difficult and you can see examples in the `examples/` -directory as well as throughout our various open source projects. - -For complete API documentation, see [GoDoc](https://godoc.org/github.com/hashicorp/go-plugin). - -## Roadmap - -Our plugin system is constantly evolving. As we use the plugin system for -new projects or for new features in existing projects, we constantly find -improvements we can make. - -At this point in time, the roadmap for the plugin system is: - -**Semantic Versioning.** Plugins will be able to implement a semantic version. -This plugin system will give host processes a system for constraining -versions. This is in addition to the protocol versioning already present -which is more for larger underlying changes. - -## What About Shared Libraries? - -When we started using plugins (late 2012, early 2013), plugins over RPC -were the only option since Go didn't support dynamic library loading. Today, -Go supports the [plugin](https://golang.org/pkg/plugin/) standard library with -a number of limitations. Since 2012, our plugin system has stabilized -from tens of millions of users using it, and has many benefits we've come to -value greatly. - -For example, we use this plugin system in -[Vault](https://www.vaultproject.io) where dynamic library loading is -not acceptable for security reasons. That is an extreme -example, but we believe our library system has more upsides than downsides -over dynamic library loading and since we've had it built and tested for years, -we'll continue to use it. - -Shared libraries have one major advantage over our system which is much -higher performance. In real world scenarios across our various tools, -we've never required any more performance out of our plugin system and it -has seen very high throughput, so this isn't a concern for us at the moment. diff --git a/vendor/github.com/hashicorp/go-plugin/client.go b/vendor/github.com/hashicorp/go-plugin/client.go deleted file mode 100644 index 2e86f6213..000000000 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ /dev/null @@ -1,1055 +0,0 @@ -package plugin - -import ( - "bufio" - "context" - "crypto/subtle" - "crypto/tls" - "crypto/x509" - "encoding/base64" - "errors" - "fmt" - "hash" - "io" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-hclog" - "google.golang.org/grpc" -) - -// If this is 1, then we've called CleanupClients. This can be used -// by plugin RPC implementations to change error behavior since you -// can expected network connection errors at this point. This should be -// read by using sync/atomic. -var Killed uint32 = 0 - -// This is a slice of the "managed" clients which are cleaned up when -// calling Cleanup -var managedClients = make([]*Client, 0, 5) -var managedClientsLock sync.Mutex - -// Error types -var ( - // ErrProcessNotFound is returned when a client is instantiated to - // reattach to an existing process and it isn't found. - ErrProcessNotFound = errors.New("Reattachment process not found") - - // ErrChecksumsDoNotMatch is returned when binary's checksum doesn't match - // the one provided in the SecureConfig. - ErrChecksumsDoNotMatch = errors.New("checksums did not match") - - // ErrSecureNoChecksum is returned when an empty checksum is provided to the - // SecureConfig. - ErrSecureConfigNoChecksum = errors.New("no checksum provided") - - // ErrSecureNoHash is returned when a nil Hash object is provided to the - // SecureConfig. - ErrSecureConfigNoHash = errors.New("no hash implementation provided") - - // ErrSecureConfigAndReattach is returned when both Reattach and - // SecureConfig are set. - ErrSecureConfigAndReattach = errors.New("only one of Reattach or SecureConfig can be set") -) - -// Client handles the lifecycle of a plugin application. It launches -// plugins, connects to them, dispenses interface implementations, and handles -// killing the process. -// -// Plugin hosts should use one Client for each plugin executable. To -// dispense a plugin type, use the `Client.Client` function, and then -// cal `Dispense`. This awkward API is mostly historical but is used to split -// the client that deals with subprocess management and the client that -// does RPC management. -// -// See NewClient and ClientConfig for using a Client. -type Client struct { - config *ClientConfig - exited bool - l sync.Mutex - address net.Addr - process *os.Process - client ClientProtocol - protocol Protocol - logger hclog.Logger - doneCtx context.Context - ctxCancel context.CancelFunc - negotiatedVersion int - - // clientWaitGroup is used to manage the lifecycle of the plugin management - // goroutines. - clientWaitGroup sync.WaitGroup - - // stderrWaitGroup is used to prevent the command's Wait() function from - // being called before we've finished reading from the stderr pipe. - stderrWaitGroup sync.WaitGroup - - // processKilled is used for testing only, to flag when the process was - // forcefully killed. - processKilled bool -} - -// NegotiatedVersion returns the protocol version negotiated with the server. -// This is only valid after Start() is called. -func (c *Client) NegotiatedVersion() int { - return c.negotiatedVersion -} - -// ClientConfig is the configuration used to initialize a new -// plugin client. After being used to initialize a plugin client, -// that configuration must not be modified again. -type ClientConfig struct { - // HandshakeConfig is the configuration that must match servers. - HandshakeConfig - - // Plugins are the plugins that can be consumed. - // The implied version of this PluginSet is the Handshake.ProtocolVersion. - Plugins PluginSet - - // VersionedPlugins is a map of PluginSets for specific protocol versions. - // These can be used to negotiate a compatible version between client and - // server. If this is set, Handshake.ProtocolVersion is not required. - VersionedPlugins map[int]PluginSet - - // One of the following must be set, but not both. - // - // Cmd is the unstarted subprocess for starting the plugin. If this is - // set, then the Client starts the plugin process on its own and connects - // to it. - // - // Reattach is configuration for reattaching to an existing plugin process - // that is already running. This isn't common. - Cmd *exec.Cmd - Reattach *ReattachConfig - - // SecureConfig is configuration for verifying the integrity of the - // executable. It can not be used with Reattach. - SecureConfig *SecureConfig - - // TLSConfig is used to enable TLS on the RPC client. - TLSConfig *tls.Config - - // Managed represents if the client should be managed by the - // plugin package or not. If true, then by calling CleanupClients, - // it will automatically be cleaned up. Otherwise, the client - // user is fully responsible for making sure to Kill all plugin - // clients. By default the client is _not_ managed. - Managed bool - - // The minimum and maximum port to use for communicating with - // the subprocess. If not set, this defaults to 10,000 and 25,000 - // respectively. - MinPort, MaxPort uint - - // StartTimeout is the timeout to wait for the plugin to say it - // has started successfully. - StartTimeout time.Duration - - // If non-nil, then the stderr of the client will be written to here - // (as well as the log). This is the original os.Stderr of the subprocess. - // This isn't the output of synced stderr. - Stderr io.Writer - - // SyncStdout, SyncStderr can be set to override the - // respective os.Std* values in the plugin. Care should be taken to - // avoid races here. If these are nil, then this will be set to - // ioutil.Discard. - SyncStdout io.Writer - SyncStderr io.Writer - - // AllowedProtocols is a list of allowed protocols. If this isn't set, - // then only netrpc is allowed. This is so that older go-plugin systems - // can show friendly errors if they see a plugin with an unknown - // protocol. - // - // By setting this, you can cause an error immediately on plugin start - // if an unsupported protocol is used with a good error message. - // - // If this isn't set at all (nil value), then only net/rpc is accepted. - // This is done for legacy reasons. You must explicitly opt-in to - // new protocols. - AllowedProtocols []Protocol - - // Logger is the logger that the client will used. If none is provided, - // it will default to hclog's default logger. - Logger hclog.Logger - - // AutoMTLS has the client and server automatically negotiate mTLS for - // transport authentication. This ensures that only the original client will - // be allowed to connect to the server, and all other connections will be - // rejected. The client will also refuse to connect to any server that isn't - // the original instance started by the client. - // - // In this mode of operation, the client generates a one-time use tls - // certificate, sends the public x.509 certificate to the new server, and - // the server generates a one-time use tls certificate, and sends the public - // x.509 certificate back to the client. These are used to authenticate all - // rpc connections between the client and server. - // - // Setting AutoMTLS to true implies that the server must support the - // protocol, and correctly negotiate the tls certificates, or a connection - // failure will result. - // - // The client should not set TLSConfig, nor should the server set a - // TLSProvider, because AutoMTLS implies that a new certificate and tls - // configuration will be generated at startup. - // - // You cannot Reattach to a server with this option enabled. - AutoMTLS bool - - // GRPCDialOptions allows plugin users to pass custom grpc.DialOption - // to create gRPC connections. This only affects plugins using the gRPC - // protocol. - GRPCDialOptions []grpc.DialOption -} - -// ReattachConfig is used to configure a client to reattach to an -// already-running plugin process. You can retrieve this information by -// calling ReattachConfig on Client. -type ReattachConfig struct { - Protocol Protocol - ProtocolVersion int - Addr net.Addr - Pid int - - // Test is set to true if this is reattaching to to a plugin in "test mode" - // (see ServeConfig.Test). In this mode, client.Kill will NOT kill the - // process and instead will rely on the plugin to terminate itself. This - // should not be used in non-test environments. - Test bool -} - -// SecureConfig is used to configure a client to verify the integrity of an -// executable before running. It does this by verifying the checksum is -// expected. Hash is used to specify the hashing method to use when checksumming -// the file. The configuration is verified by the client by calling the -// SecureConfig.Check() function. -// -// The host process should ensure the checksum was provided by a trusted and -// authoritative source. The binary should be installed in such a way that it -// can not be modified by an unauthorized user between the time of this check -// and the time of execution. -type SecureConfig struct { - Checksum []byte - Hash hash.Hash -} - -// Check takes the filepath to an executable and returns true if the checksum of -// the file matches the checksum provided in the SecureConfig. -func (s *SecureConfig) Check(filePath string) (bool, error) { - if len(s.Checksum) == 0 { - return false, ErrSecureConfigNoChecksum - } - - if s.Hash == nil { - return false, ErrSecureConfigNoHash - } - - file, err := os.Open(filePath) - if err != nil { - return false, err - } - defer file.Close() - - _, err = io.Copy(s.Hash, file) - if err != nil { - return false, err - } - - sum := s.Hash.Sum(nil) - - return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil -} - -// This makes sure all the managed subprocesses are killed and properly -// logged. This should be called before the parent process running the -// plugins exits. -// -// This must only be called _once_. -func CleanupClients() { - // Set the killed to true so that we don't get unexpected panics - atomic.StoreUint32(&Killed, 1) - - // Kill all the managed clients in parallel and use a WaitGroup - // to wait for them all to finish up. - var wg sync.WaitGroup - managedClientsLock.Lock() - for _, client := range managedClients { - wg.Add(1) - - go func(client *Client) { - client.Kill() - wg.Done() - }(client) - } - managedClientsLock.Unlock() - - wg.Wait() -} - -// Creates a new plugin client which manages the lifecycle of an external -// plugin and gets the address for the RPC connection. -// -// The client must be cleaned up at some point by calling Kill(). If -// the client is a managed client (created with NewManagedClient) you -// can just call CleanupClients at the end of your program and they will -// be properly cleaned. -func NewClient(config *ClientConfig) (c *Client) { - if config.MinPort == 0 && config.MaxPort == 0 { - config.MinPort = 10000 - config.MaxPort = 25000 - } - - if config.StartTimeout == 0 { - config.StartTimeout = 1 * time.Minute - } - - if config.Stderr == nil { - config.Stderr = ioutil.Discard - } - - if config.SyncStdout == nil { - config.SyncStdout = ioutil.Discard - } - if config.SyncStderr == nil { - config.SyncStderr = ioutil.Discard - } - - if config.AllowedProtocols == nil { - config.AllowedProtocols = []Protocol{ProtocolNetRPC} - } - - if config.Logger == nil { - config.Logger = hclog.New(&hclog.LoggerOptions{ - Output: hclog.DefaultOutput, - Level: hclog.Trace, - Name: "plugin", - }) - } - - c = &Client{ - config: config, - logger: config.Logger, - } - if config.Managed { - managedClientsLock.Lock() - managedClients = append(managedClients, c) - managedClientsLock.Unlock() - } - - return -} - -// Client returns the protocol client for this connection. -// -// Subsequent calls to this will return the same client. -func (c *Client) Client() (ClientProtocol, error) { - _, err := c.Start() - if err != nil { - return nil, err - } - - c.l.Lock() - defer c.l.Unlock() - - if c.client != nil { - return c.client, nil - } - - switch c.protocol { - case ProtocolNetRPC: - c.client, err = newRPCClient(c) - - case ProtocolGRPC: - c.client, err = newGRPCClient(c.doneCtx, c) - - default: - return nil, fmt.Errorf("unknown server protocol: %s", c.protocol) - } - - if err != nil { - c.client = nil - return nil, err - } - - return c.client, nil -} - -// Tells whether or not the underlying process has exited. -func (c *Client) Exited() bool { - c.l.Lock() - defer c.l.Unlock() - return c.exited -} - -// killed is used in tests to check if a process failed to exit gracefully, and -// needed to be killed. -func (c *Client) killed() bool { - c.l.Lock() - defer c.l.Unlock() - return c.processKilled -} - -// End the executing subprocess (if it is running) and perform any cleanup -// tasks necessary such as capturing any remaining logs and so on. -// -// This method blocks until the process successfully exits. -// -// This method can safely be called multiple times. -func (c *Client) Kill() { - // Grab a lock to read some private fields. - c.l.Lock() - process := c.process - addr := c.address - c.l.Unlock() - - // If there is no process, there is nothing to kill. - if process == nil { - return - } - - defer func() { - // Wait for the all client goroutines to finish. - c.clientWaitGroup.Wait() - - // Make sure there is no reference to the old process after it has been - // killed. - c.l.Lock() - c.process = nil - c.l.Unlock() - }() - - // We need to check for address here. It is possible that the plugin - // started (process != nil) but has no address (addr == nil) if the - // plugin failed at startup. If we do have an address, we need to close - // the plugin net connections. - graceful := false - if addr != nil { - // Close the client to cleanly exit the process. - client, err := c.Client() - if err == nil { - err = client.Close() - - // If there is no error, then we attempt to wait for a graceful - // exit. If there was an error, we assume that graceful cleanup - // won't happen and just force kill. - graceful = err == nil - if err != nil { - // If there was an error just log it. We're going to force - // kill in a moment anyways. - c.logger.Warn("error closing client during Kill", "err", err) - } - } else { - c.logger.Error("client", "error", err) - } - } - - // If we're attempting a graceful exit, then we wait for a short period - // of time to allow that to happen. To wait for this we just wait on the - // doneCh which would be closed if the process exits. - if graceful { - select { - case <-c.doneCtx.Done(): - c.logger.Debug("plugin exited") - return - case <-time.After(2 * time.Second): - } - } - - // If graceful exiting failed, just kill it - c.logger.Warn("plugin failed to exit gracefully") - process.Kill() - - c.l.Lock() - c.processKilled = true - c.l.Unlock() -} - -// Starts the underlying subprocess, communicating with it to negotiate -// a port for RPC connections, and returning the address to connect via RPC. -// -// This method is safe to call multiple times. Subsequent calls have no effect. -// Once a client has been started once, it cannot be started again, even if -// it was killed. -func (c *Client) Start() (addr net.Addr, err error) { - c.l.Lock() - defer c.l.Unlock() - - if c.address != nil { - return c.address, nil - } - - // If one of cmd or reattach isn't set, then it is an error. We wrap - // this in a {} for scoping reasons, and hopeful that the escape - // analysis will pop the stack here. - { - cmdSet := c.config.Cmd != nil - attachSet := c.config.Reattach != nil - secureSet := c.config.SecureConfig != nil - if cmdSet == attachSet { - return nil, fmt.Errorf("Only one of Cmd or Reattach must be set") - } - - if secureSet && attachSet { - return nil, ErrSecureConfigAndReattach - } - } - - if c.config.Reattach != nil { - return c.reattach() - } - - if c.config.VersionedPlugins == nil { - c.config.VersionedPlugins = make(map[int]PluginSet) - } - - // handle all plugins as versioned, using the handshake config as the default. - version := int(c.config.ProtocolVersion) - - // Make sure we're not overwriting a real version 0. If ProtocolVersion was - // non-zero, then we have to just assume the user made sure that - // VersionedPlugins doesn't conflict. - if _, ok := c.config.VersionedPlugins[version]; !ok && c.config.Plugins != nil { - c.config.VersionedPlugins[version] = c.config.Plugins - } - - var versionStrings []string - for v := range c.config.VersionedPlugins { - versionStrings = append(versionStrings, strconv.Itoa(v)) - } - - env := []string{ - fmt.Sprintf("%s=%s", c.config.MagicCookieKey, c.config.MagicCookieValue), - fmt.Sprintf("PLUGIN_MIN_PORT=%d", c.config.MinPort), - fmt.Sprintf("PLUGIN_MAX_PORT=%d", c.config.MaxPort), - fmt.Sprintf("PLUGIN_PROTOCOL_VERSIONS=%s", strings.Join(versionStrings, ",")), - } - - cmd := c.config.Cmd - cmd.Env = append(cmd.Env, os.Environ()...) - cmd.Env = append(cmd.Env, env...) - cmd.Stdin = os.Stdin - - cmdStdout, err := cmd.StdoutPipe() - if err != nil { - return nil, err - } - cmdStderr, err := cmd.StderrPipe() - if err != nil { - return nil, err - } - - if c.config.SecureConfig == nil { - c.logger.Warn("plugin configured with a nil SecureConfig") - } else { - if ok, err := c.config.SecureConfig.Check(cmd.Path); err != nil { - return nil, fmt.Errorf("error verifying checksum: %s", err) - } else if !ok { - return nil, ErrChecksumsDoNotMatch - } - } - - // Setup a temporary certificate for client/server mtls, and send the public - // certificate to the plugin. - if c.config.AutoMTLS { - c.logger.Info("configuring client automatic mTLS") - certPEM, keyPEM, err := generateCert() - if err != nil { - c.logger.Error("failed to generate client certificate", "error", err) - return nil, err - } - cert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - c.logger.Error("failed to parse client certificate", "error", err) - return nil, err - } - - cmd.Env = append(cmd.Env, fmt.Sprintf("PLUGIN_CLIENT_CERT=%s", certPEM)) - - c.config.TLSConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - ClientAuth: tls.RequireAndVerifyClientCert, - MinVersion: tls.VersionTLS12, - ServerName: "localhost", - } - } - - c.logger.Debug("starting plugin", "path", cmd.Path, "args", cmd.Args) - err = cmd.Start() - if err != nil { - return - } - - // Set the process - c.process = cmd.Process - c.logger.Debug("plugin started", "path", cmd.Path, "pid", c.process.Pid) - - // Make sure the command is properly cleaned up if there is an error - defer func() { - r := recover() - - if err != nil || r != nil { - cmd.Process.Kill() - } - - if r != nil { - panic(r) - } - }() - - // Create a context for when we kill - c.doneCtx, c.ctxCancel = context.WithCancel(context.Background()) - - // Start goroutine that logs the stderr - c.clientWaitGroup.Add(1) - c.stderrWaitGroup.Add(1) - // logStderr calls Done() - go c.logStderr(cmdStderr) - - c.clientWaitGroup.Add(1) - go func() { - // ensure the context is cancelled when we're done - defer c.ctxCancel() - - defer c.clientWaitGroup.Done() - - // get the cmd info early, since the process information will be removed - // in Kill. - pid := c.process.Pid - path := cmd.Path - - // wait to finish reading from stderr since the stderr pipe reader - // will be closed by the subsequent call to cmd.Wait(). - c.stderrWaitGroup.Wait() - - // Wait for the command to end. - err := cmd.Wait() - - msgArgs := []interface{}{ - "path", path, - "pid", pid, - } - if err != nil { - msgArgs = append(msgArgs, - []interface{}{"error", err.Error()}...) - c.logger.Error("plugin process exited", msgArgs...) - } else { - // Log and make sure to flush the logs right away - c.logger.Info("plugin process exited", msgArgs...) - } - - os.Stderr.Sync() - - // Set that we exited, which takes a lock - c.l.Lock() - defer c.l.Unlock() - c.exited = true - }() - - // Start a goroutine that is going to be reading the lines - // out of stdout - linesCh := make(chan string) - c.clientWaitGroup.Add(1) - go func() { - defer c.clientWaitGroup.Done() - defer close(linesCh) - - scanner := bufio.NewScanner(cmdStdout) - for scanner.Scan() { - linesCh <- scanner.Text() - } - }() - - // Make sure after we exit we read the lines from stdout forever - // so they don't block since it is a pipe. - // The scanner goroutine above will close this, but track it with a wait - // group for completeness. - c.clientWaitGroup.Add(1) - defer func() { - go func() { - defer c.clientWaitGroup.Done() - for range linesCh { - } - }() - }() - - // Some channels for the next step - timeout := time.After(c.config.StartTimeout) - - // Start looking for the address - c.logger.Debug("waiting for RPC address", "path", cmd.Path) - select { - case <-timeout: - err = errors.New("timeout while waiting for plugin to start") - case <-c.doneCtx.Done(): - err = errors.New("plugin exited before we could connect") - case line := <-linesCh: - // Trim the line and split by "|" in order to get the parts of - // the output. - line = strings.TrimSpace(line) - parts := strings.SplitN(line, "|", 6) - if len(parts) < 4 { - err = fmt.Errorf( - "Unrecognized remote plugin message: %s\n\n"+ - "This usually means that the plugin is either invalid or simply\n"+ - "needs to be recompiled to support the latest protocol.", line) - return - } - - // Check the core protocol. Wrapped in a {} for scoping. - { - var coreProtocol int - coreProtocol, err = strconv.Atoi(parts[0]) - if err != nil { - err = fmt.Errorf("Error parsing core protocol version: %s", err) - return - } - - if coreProtocol != CoreProtocolVersion { - err = fmt.Errorf("Incompatible core API version with plugin. "+ - "Plugin version: %s, Core version: %d\n\n"+ - "To fix this, the plugin usually only needs to be recompiled.\n"+ - "Please report this to the plugin author.", parts[0], CoreProtocolVersion) - return - } - } - - // Test the API version - version, pluginSet, err := c.checkProtoVersion(parts[1]) - if err != nil { - return addr, err - } - - // set the Plugins value to the compatible set, so the version - // doesn't need to be passed through to the ClientProtocol - // implementation. - c.config.Plugins = pluginSet - c.negotiatedVersion = version - c.logger.Debug("using plugin", "version", version) - - switch parts[2] { - case "tcp": - addr, err = net.ResolveTCPAddr("tcp", parts[3]) - case "unix": - addr, err = net.ResolveUnixAddr("unix", parts[3]) - default: - err = fmt.Errorf("Unknown address type: %s", parts[3]) - } - - // If we have a server type, then record that. We default to net/rpc - // for backwards compatibility. - c.protocol = ProtocolNetRPC - if len(parts) >= 5 { - c.protocol = Protocol(parts[4]) - } - - found := false - for _, p := range c.config.AllowedProtocols { - if p == c.protocol { - found = true - break - } - } - if !found { - err = fmt.Errorf("Unsupported plugin protocol %q. Supported: %v", - c.protocol, c.config.AllowedProtocols) - return addr, err - } - - // See if we have a TLS certificate from the server. - // Checking if the length is > 50 rules out catching the unused "extra" - // data returned from some older implementations. - if len(parts) >= 6 && len(parts[5]) > 50 { - err := c.loadServerCert(parts[5]) - if err != nil { - return nil, fmt.Errorf("error parsing server cert: %s", err) - } - } - } - - c.address = addr - return -} - -// loadServerCert is used by AutoMTLS to read an x.509 cert returned by the -// server, and load it as the RootCA and ClientCA for the client TLSConfig. -func (c *Client) loadServerCert(cert string) error { - certPool := x509.NewCertPool() - - asn1, err := base64.RawStdEncoding.DecodeString(cert) - if err != nil { - return err - } - - x509Cert, err := x509.ParseCertificate([]byte(asn1)) - if err != nil { - return err - } - - certPool.AddCert(x509Cert) - - c.config.TLSConfig.RootCAs = certPool - c.config.TLSConfig.ClientCAs = certPool - return nil -} - -func (c *Client) reattach() (net.Addr, error) { - // Verify the process still exists. If not, then it is an error - p, err := os.FindProcess(c.config.Reattach.Pid) - if err != nil { - // On Unix systems, FindProcess never returns an error. - // On Windows, for non-existent pids it returns: - // os.SyscallError - 'OpenProcess: the paremter is incorrect' - return nil, ErrProcessNotFound - } - - // Attempt to connect to the addr since on Unix systems FindProcess - // doesn't actually return an error if it can't find the process. - conn, err := net.Dial( - c.config.Reattach.Addr.Network(), - c.config.Reattach.Addr.String()) - if err != nil { - p.Kill() - return nil, ErrProcessNotFound - } - conn.Close() - - // Create a context for when we kill - c.doneCtx, c.ctxCancel = context.WithCancel(context.Background()) - - c.clientWaitGroup.Add(1) - // Goroutine to mark exit status - go func(pid int) { - defer c.clientWaitGroup.Done() - - // ensure the context is cancelled when we're done - defer c.ctxCancel() - - // Wait for the process to die - pidWait(pid) - - // Log so we can see it - c.logger.Debug("reattached plugin process exited") - - // Mark it - c.l.Lock() - defer c.l.Unlock() - c.exited = true - }(p.Pid) - - // Set the address and protocol - c.address = c.config.Reattach.Addr - c.protocol = c.config.Reattach.Protocol - if c.protocol == "" { - // Default the protocol to net/rpc for backwards compatibility - c.protocol = ProtocolNetRPC - } - - if c.config.Reattach.Test { - c.negotiatedVersion = c.config.Reattach.ProtocolVersion - } - - // If we're in test mode, we do NOT set the process. This avoids the - // process being killed (the only purpose we have for c.process), since - // in test mode the process is responsible for exiting on its own. - if !c.config.Reattach.Test { - c.process = p - } - - return c.address, nil -} - -// checkProtoVersion returns the negotiated version and PluginSet. -// This returns an error if the server returned an incompatible protocol -// version, or an invalid handshake response. -func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) { - serverVersion, err := strconv.Atoi(protoVersion) - if err != nil { - return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err) - } - - // record these for the error message - var clientVersions []int - - // all versions, including the legacy ProtocolVersion have been added to - // the versions set - for version, plugins := range c.config.VersionedPlugins { - clientVersions = append(clientVersions, version) - - if serverVersion != version { - continue - } - return version, plugins, nil - } - - return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+ - "Plugin version: %d, Client versions: %d", serverVersion, clientVersions) -} - -// ReattachConfig returns the information that must be provided to NewClient -// to reattach to the plugin process that this client started. This is -// useful for plugins that detach from their parent process. -// -// If this returns nil then the process hasn't been started yet. Please -// call Start or Client before calling this. -func (c *Client) ReattachConfig() *ReattachConfig { - c.l.Lock() - defer c.l.Unlock() - - if c.address == nil { - return nil - } - - if c.config.Cmd != nil && c.config.Cmd.Process == nil { - return nil - } - - // If we connected via reattach, just return the information as-is - if c.config.Reattach != nil { - return c.config.Reattach - } - - return &ReattachConfig{ - Protocol: c.protocol, - Addr: c.address, - Pid: c.config.Cmd.Process.Pid, - } -} - -// Protocol returns the protocol of server on the remote end. This will -// start the plugin process if it isn't already started. Errors from -// starting the plugin are surpressed and ProtocolInvalid is returned. It -// is recommended you call Start explicitly before calling Protocol to ensure -// no errors occur. -func (c *Client) Protocol() Protocol { - _, err := c.Start() - if err != nil { - return ProtocolInvalid - } - - return c.protocol -} - -func netAddrDialer(addr net.Addr) func(string, time.Duration) (net.Conn, error) { - return func(_ string, _ time.Duration) (net.Conn, error) { - // Connect to the client - conn, err := net.Dial(addr.Network(), addr.String()) - if err != nil { - return nil, err - } - if tcpConn, ok := conn.(*net.TCPConn); ok { - // Make sure to set keep alive so that the connection doesn't die - tcpConn.SetKeepAlive(true) - } - - return conn, nil - } -} - -// dialer is compatible with grpc.WithDialer and creates the connection -// to the plugin. -func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) { - conn, err := netAddrDialer(c.address)("", timeout) - if err != nil { - return nil, err - } - - // If we have a TLS config we wrap our connection. We only do this - // for net/rpc since gRPC uses its own mechanism for TLS. - if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil { - conn = tls.Client(conn, c.config.TLSConfig) - } - - return conn, nil -} - -var stdErrBufferSize = 64 * 1024 - -func (c *Client) logStderr(r io.Reader) { - defer c.clientWaitGroup.Done() - defer c.stderrWaitGroup.Done() - l := c.logger.Named(filepath.Base(c.config.Cmd.Path)) - - reader := bufio.NewReaderSize(r, stdErrBufferSize) - // continuation indicates the previous line was a prefix - continuation := false - - for { - line, isPrefix, err := reader.ReadLine() - switch { - case err == io.EOF: - return - case err != nil: - l.Error("reading plugin stderr", "error", err) - return - } - - c.config.Stderr.Write(line) - - // The line was longer than our max token size, so it's likely - // incomplete and won't unmarshal. - if isPrefix || continuation { - l.Debug(string(line)) - - // if we're finishing a continued line, add the newline back in - if !isPrefix { - c.config.Stderr.Write([]byte{'\n'}) - } - - continuation = isPrefix - continue - } - - c.config.Stderr.Write([]byte{'\n'}) - - entry, err := parseJSON(line) - // If output is not JSON format, print directly to Debug - if err != nil { - // Attempt to infer the desired log level from the commonly used - // string prefixes - switch line := string(line); { - case strings.HasPrefix(line, "[TRACE]"): - l.Trace(line) - case strings.HasPrefix(line, "[DEBUG]"): - l.Debug(line) - case strings.HasPrefix(line, "[INFO]"): - l.Info(line) - case strings.HasPrefix(line, "[WARN]"): - l.Warn(line) - case strings.HasPrefix(line, "[ERROR]"): - l.Error(line) - default: - l.Debug(line) - } - } else { - out := flattenKVPairs(entry.KVPairs) - - out = append(out, "timestamp", entry.Timestamp.Format(hclog.TimeFormat)) - switch hclog.LevelFromString(entry.Level) { - case hclog.Trace: - l.Trace(entry.Message, out...) - case hclog.Debug: - l.Debug(entry.Message, out...) - case hclog.Info: - l.Info(entry.Message, out...) - case hclog.Warn: - l.Warn(entry.Message, out...) - case hclog.Error: - l.Error(entry.Message, out...) - default: - // if there was no log level, it's likely this is unexpected - // json from something other than hclog, and we should output - // it verbatim. - l.Debug(string(line)) - } - } - } -} diff --git a/vendor/github.com/hashicorp/go-plugin/discover.go b/vendor/github.com/hashicorp/go-plugin/discover.go deleted file mode 100644 index d22c566ed..000000000 --- a/vendor/github.com/hashicorp/go-plugin/discover.go +++ /dev/null @@ -1,28 +0,0 @@ -package plugin - -import ( - "path/filepath" -) - -// Discover discovers plugins that are in a given directory. -// -// The directory doesn't need to be absolute. For example, "." will work fine. -// -// This currently assumes any file matching the glob is a plugin. -// In the future this may be smarter about checking that a file is -// executable and so on. -// -// TODO: test -func Discover(glob, dir string) ([]string, error) { - var err error - - // Make the directory absolute if it isn't already - if !filepath.IsAbs(dir) { - dir, err = filepath.Abs(dir) - if err != nil { - return nil, err - } - } - - return filepath.Glob(filepath.Join(dir, glob)) -} diff --git a/vendor/github.com/hashicorp/go-plugin/error.go b/vendor/github.com/hashicorp/go-plugin/error.go deleted file mode 100644 index 22a7baa6a..000000000 --- a/vendor/github.com/hashicorp/go-plugin/error.go +++ /dev/null @@ -1,24 +0,0 @@ -package plugin - -// This is a type that wraps error types so that they can be messaged -// across RPC channels. Since "error" is an interface, we can't always -// gob-encode the underlying structure. This is a valid error interface -// implementer that we will push across. -type BasicError struct { - Message string -} - -// NewBasicError is used to create a BasicError. -// -// err is allowed to be nil. -func NewBasicError(err error) *BasicError { - if err == nil { - return nil - } - - return &BasicError{err.Error()} -} - -func (e *BasicError) Error() string { - return e.Message -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_broker.go b/vendor/github.com/hashicorp/go-plugin/grpc_broker.go deleted file mode 100644 index daf142d17..000000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_broker.go +++ /dev/null @@ -1,457 +0,0 @@ -package plugin - -import ( - "context" - "crypto/tls" - "errors" - "fmt" - "log" - "net" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-plugin/internal/plugin" - - "github.com/oklog/run" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" -) - -// streamer interface is used in the broker to send/receive connection -// information. -type streamer interface { - Send(*plugin.ConnInfo) error - Recv() (*plugin.ConnInfo, error) - Close() -} - -// sendErr is used to pass errors back during a send. -type sendErr struct { - i *plugin.ConnInfo - ch chan error -} - -// gRPCBrokerServer is used by the plugin to start a stream and to send -// connection information to/from the plugin. Implements GRPCBrokerServer and -// streamer interfaces. -type gRPCBrokerServer struct { - // send is used to send connection info to the gRPC stream. - send chan *sendErr - - // recv is used to receive connection info from the gRPC stream. - recv chan *plugin.ConnInfo - - // quit closes down the stream. - quit chan struct{} - - // o is used to ensure we close the quit channel only once. - o sync.Once -} - -func newGRPCBrokerServer() *gRPCBrokerServer { - return &gRPCBrokerServer{ - send: make(chan *sendErr), - recv: make(chan *plugin.ConnInfo), - quit: make(chan struct{}), - } -} - -// StartStream implements the GRPCBrokerServer interface and will block until -// the quit channel is closed or the context reports Done. The stream will pass -// connection information to/from the client. -func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error { - doneCh := stream.Context().Done() - defer s.Close() - - // Proccess send stream - go func() { - for { - select { - case <-doneCh: - return - case <-s.quit: - return - case se := <-s.send: - err := stream.Send(se.i) - se.ch <- err - } - } - }() - - // Process receive stream - for { - i, err := stream.Recv() - if err != nil { - return err - } - select { - case <-doneCh: - return nil - case <-s.quit: - return nil - case s.recv <- i: - } - } - - return nil -} - -// Send is used by the GRPCBroker to pass connection information into the stream -// to the client. -func (s *gRPCBrokerServer) Send(i *plugin.ConnInfo) error { - ch := make(chan error) - defer close(ch) - - select { - case <-s.quit: - return errors.New("broker closed") - case s.send <- &sendErr{ - i: i, - ch: ch, - }: - } - - return <-ch -} - -// Recv is used by the GRPCBroker to pass connection information that has been -// sent from the client from the stream to the broker. -func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) { - select { - case <-s.quit: - return nil, errors.New("broker closed") - case i := <-s.recv: - return i, nil - } -} - -// Close closes the quit channel, shutting down the stream. -func (s *gRPCBrokerServer) Close() { - s.o.Do(func() { - close(s.quit) - }) -} - -// gRPCBrokerClientImpl is used by the client to start a stream and to send -// connection information to/from the client. Implements GRPCBrokerClient and -// streamer interfaces. -type gRPCBrokerClientImpl struct { - // client is the underlying GRPC client used to make calls to the server. - client plugin.GRPCBrokerClient - - // send is used to send connection info to the gRPC stream. - send chan *sendErr - - // recv is used to receive connection info from the gRPC stream. - recv chan *plugin.ConnInfo - - // quit closes down the stream. - quit chan struct{} - - // o is used to ensure we close the quit channel only once. - o sync.Once -} - -func newGRPCBrokerClient(conn *grpc.ClientConn) *gRPCBrokerClientImpl { - return &gRPCBrokerClientImpl{ - client: plugin.NewGRPCBrokerClient(conn), - send: make(chan *sendErr), - recv: make(chan *plugin.ConnInfo), - quit: make(chan struct{}), - } -} - -// StartStream implements the GRPCBrokerClient interface and will block until -// the quit channel is closed or the context reports Done. The stream will pass -// connection information to/from the plugin. -func (s *gRPCBrokerClientImpl) StartStream() error { - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - defer s.Close() - - stream, err := s.client.StartStream(ctx) - if err != nil { - return err - } - doneCh := stream.Context().Done() - - go func() { - for { - select { - case <-doneCh: - return - case <-s.quit: - return - case se := <-s.send: - err := stream.Send(se.i) - se.ch <- err - } - } - }() - - for { - i, err := stream.Recv() - if err != nil { - return err - } - select { - case <-doneCh: - return nil - case <-s.quit: - return nil - case s.recv <- i: - } - } - - return nil -} - -// Send is used by the GRPCBroker to pass connection information into the stream -// to the plugin. -func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error { - ch := make(chan error) - defer close(ch) - - select { - case <-s.quit: - return errors.New("broker closed") - case s.send <- &sendErr{ - i: i, - ch: ch, - }: - } - - return <-ch -} - -// Recv is used by the GRPCBroker to pass connection information that has been -// sent from the plugin to the broker. -func (s *gRPCBrokerClientImpl) Recv() (*plugin.ConnInfo, error) { - select { - case <-s.quit: - return nil, errors.New("broker closed") - case i := <-s.recv: - return i, nil - } -} - -// Close closes the quit channel, shutting down the stream. -func (s *gRPCBrokerClientImpl) Close() { - s.o.Do(func() { - close(s.quit) - }) -} - -// GRPCBroker is responsible for brokering connections by unique ID. -// -// It is used by plugins to create multiple gRPC connections and data -// streams between the plugin process and the host process. -// -// This allows a plugin to request a channel with a specific ID to connect to -// or accept a connection from, and the broker handles the details of -// holding these channels open while they're being negotiated. -// -// The Plugin interface has access to these for both Server and Client. -// The broker can be used by either (optionally) to reserve and connect to -// new streams. This is useful for complex args and return values, -// or anything else you might need a data stream for. -type GRPCBroker struct { - nextId uint32 - streamer streamer - streams map[uint32]*gRPCBrokerPending - tls *tls.Config - doneCh chan struct{} - o sync.Once - - sync.Mutex -} - -type gRPCBrokerPending struct { - ch chan *plugin.ConnInfo - doneCh chan struct{} -} - -func newGRPCBroker(s streamer, tls *tls.Config) *GRPCBroker { - return &GRPCBroker{ - streamer: s, - streams: make(map[uint32]*gRPCBrokerPending), - tls: tls, - doneCh: make(chan struct{}), - } -} - -// Accept accepts a connection by ID. -// -// This should not be called multiple times with the same ID at one time. -func (b *GRPCBroker) Accept(id uint32) (net.Listener, error) { - listener, err := serverListener() - if err != nil { - return nil, err - } - - err = b.streamer.Send(&plugin.ConnInfo{ - ServiceId: id, - Network: listener.Addr().Network(), - Address: listener.Addr().String(), - }) - if err != nil { - return nil, err - } - - return listener, nil -} - -// AcceptAndServe is used to accept a specific stream ID and immediately -// serve a gRPC server on that stream ID. This is used to easily serve -// complex arguments. Each AcceptAndServe call opens a new listener socket and -// sends the connection info down the stream to the dialer. Since a new -// connection is opened every call, these calls should be used sparingly. -// Multiple gRPC server implementations can be registered to a single -// AcceptAndServe call. -func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) { - listener, err := b.Accept(id) - if err != nil { - log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) - return - } - defer listener.Close() - - var opts []grpc.ServerOption - if b.tls != nil { - opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))} - } - - server := s(opts) - - // Here we use a run group to close this goroutine if the server is shutdown - // or the broker is shutdown. - var g run.Group - { - // Serve on the listener, if shutting down call GracefulStop. - g.Add(func() error { - return server.Serve(listener) - }, func(err error) { - server.GracefulStop() - }) - } - { - // block on the closeCh or the doneCh. If we are shutting down close the - // closeCh. - closeCh := make(chan struct{}) - g.Add(func() error { - select { - case <-b.doneCh: - case <-closeCh: - } - return nil - }, func(err error) { - close(closeCh) - }) - } - - // Block until we are done - g.Run() -} - -// Close closes the stream and all servers. -func (b *GRPCBroker) Close() error { - b.streamer.Close() - b.o.Do(func() { - close(b.doneCh) - }) - return nil -} - -// Dial opens a connection by ID. -func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error) { - var c *plugin.ConnInfo - - // Open the stream - p := b.getStream(id) - select { - case c = <-p.ch: - close(p.doneCh) - case <-time.After(5 * time.Second): - return nil, fmt.Errorf("timeout waiting for connection info") - } - - var addr net.Addr - switch c.Network { - case "tcp": - addr, err = net.ResolveTCPAddr("tcp", c.Address) - case "unix": - addr, err = net.ResolveUnixAddr("unix", c.Address) - default: - err = fmt.Errorf("Unknown address type: %s", c.Address) - } - if err != nil { - return nil, err - } - - return dialGRPCConn(b.tls, netAddrDialer(addr)) -} - -// NextId returns a unique ID to use next. -// -// It is possible for very long-running plugin hosts to wrap this value, -// though it would require a very large amount of calls. In practice -// we've never seen it happen. -func (m *GRPCBroker) NextId() uint32 { - return atomic.AddUint32(&m.nextId, 1) -} - -// Run starts the brokering and should be executed in a goroutine, since it -// blocks forever, or until the session closes. -// -// Uses of GRPCBroker never need to call this. It is called internally by -// the plugin host/client. -func (m *GRPCBroker) Run() { - for { - stream, err := m.streamer.Recv() - if err != nil { - // Once we receive an error, just exit - break - } - - // Initialize the waiter - p := m.getStream(stream.ServiceId) - select { - case p.ch <- stream: - default: - } - - go m.timeoutWait(stream.ServiceId, p) - } -} - -func (m *GRPCBroker) getStream(id uint32) *gRPCBrokerPending { - m.Lock() - defer m.Unlock() - - p, ok := m.streams[id] - if ok { - return p - } - - m.streams[id] = &gRPCBrokerPending{ - ch: make(chan *plugin.ConnInfo, 1), - doneCh: make(chan struct{}), - } - return m.streams[id] -} - -func (m *GRPCBroker) timeoutWait(id uint32, p *gRPCBrokerPending) { - // Wait for the stream to either be picked up and connected, or - // for a timeout. - select { - case <-p.doneCh: - case <-time.After(5 * time.Second): - } - - m.Lock() - defer m.Unlock() - - // Delete the stream so no one else can grab it - delete(m.streams, id) -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_client.go b/vendor/github.com/hashicorp/go-plugin/grpc_client.go deleted file mode 100644 index 842903c92..000000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_client.go +++ /dev/null @@ -1,126 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "fmt" - "math" - "net" - "time" - - "github.com/hashicorp/go-plugin/internal/plugin" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/health/grpc_health_v1" -) - -func dialGRPCConn(tls *tls.Config, dialer func(string, time.Duration) (net.Conn, error), dialOpts ...grpc.DialOption) (*grpc.ClientConn, error) { - // Build dialing options. - opts := make([]grpc.DialOption, 0) - - // We use a custom dialer so that we can connect over unix domain sockets. - opts = append(opts, grpc.WithDialer(dialer)) - - // Fail right away - opts = append(opts, grpc.FailOnNonTempDialError(true)) - - // If we have no TLS configuration set, we need to explicitly tell grpc - // that we're connecting with an insecure connection. - if tls == nil { - opts = append(opts, grpc.WithInsecure()) - } else { - opts = append(opts, grpc.WithTransportCredentials( - credentials.NewTLS(tls))) - } - - opts = append(opts, - grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(math.MaxInt32)), - grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(math.MaxInt32))) - - // Add our custom options if we have any - opts = append(opts, dialOpts...) - - // Connect. Note the first parameter is unused because we use a custom - // dialer that has the state to see the address. - conn, err := grpc.Dial("unused", opts...) - if err != nil { - return nil, err - } - - return conn, nil -} - -// newGRPCClient creates a new GRPCClient. The Client argument is expected -// to be successfully started already with a lock held. -func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) { - conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer, c.config.GRPCDialOptions...) - if err != nil { - return nil, err - } - - // Start the broker. - brokerGRPCClient := newGRPCBrokerClient(conn) - broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig) - go broker.Run() - go brokerGRPCClient.StartStream() - - // Start the stdio client - stdioClient, err := newGRPCStdioClient(doneCtx, c.logger.Named("stdio"), conn) - if err != nil { - return nil, err - } - go stdioClient.Run(c.config.SyncStdout, c.config.SyncStderr) - - cl := &GRPCClient{ - Conn: conn, - Plugins: c.config.Plugins, - doneCtx: doneCtx, - broker: broker, - controller: plugin.NewGRPCControllerClient(conn), - } - - return cl, nil -} - -// GRPCClient connects to a GRPCServer over gRPC to dispense plugin types. -type GRPCClient struct { - Conn *grpc.ClientConn - Plugins map[string]Plugin - - doneCtx context.Context - broker *GRPCBroker - - controller plugin.GRPCControllerClient -} - -// ClientProtocol impl. -func (c *GRPCClient) Close() error { - c.broker.Close() - c.controller.Shutdown(c.doneCtx, &plugin.Empty{}) - return c.Conn.Close() -} - -// ClientProtocol impl. -func (c *GRPCClient) Dispense(name string) (interface{}, error) { - raw, ok := c.Plugins[name] - if !ok { - return nil, fmt.Errorf("unknown plugin type: %s", name) - } - - p, ok := raw.(GRPCPlugin) - if !ok { - return nil, fmt.Errorf("plugin %q doesn't support gRPC", name) - } - - return p.GRPCClient(c.doneCtx, c.broker, c.Conn) -} - -// ClientProtocol impl. -func (c *GRPCClient) Ping() error { - client := grpc_health_v1.NewHealthClient(c.Conn) - _, err := client.Check(context.Background(), &grpc_health_v1.HealthCheckRequest{ - Service: GRPCServiceName, - }) - - return err -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_controller.go b/vendor/github.com/hashicorp/go-plugin/grpc_controller.go deleted file mode 100644 index 1a8a8e70e..000000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_controller.go +++ /dev/null @@ -1,23 +0,0 @@ -package plugin - -import ( - "context" - - "github.com/hashicorp/go-plugin/internal/plugin" -) - -// GRPCControllerServer handles shutdown calls to terminate the server when the -// plugin client is closed. -type grpcControllerServer struct { - server *GRPCServer -} - -// Shutdown stops the grpc server. It first will attempt a graceful stop, then a -// full stop on the server. -func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) { - resp := &plugin.Empty{} - - // TODO: figure out why GracefullStop doesn't work. - s.server.Stop() - return resp, nil -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_server.go b/vendor/github.com/hashicorp/go-plugin/grpc_server.go deleted file mode 100644 index 387628bf4..000000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_server.go +++ /dev/null @@ -1,149 +0,0 @@ -package plugin - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "net" - - hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin/internal/plugin" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/health" - "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/reflection" -) - -// GRPCServiceName is the name of the service that the health check should -// return as passing. -const GRPCServiceName = "plugin" - -// DefaultGRPCServer can be used with the "GRPCServer" field for Server -// as a default factory method to create a gRPC server with no extra options. -func DefaultGRPCServer(opts []grpc.ServerOption) *grpc.Server { - return grpc.NewServer(opts...) -} - -// GRPCServer is a ServerType implementation that serves plugins over -// gRPC. This allows plugins to easily be written for other languages. -// -// The GRPCServer outputs a custom configuration as a base64-encoded -// JSON structure represented by the GRPCServerConfig config structure. -type GRPCServer struct { - // Plugins are the list of plugins to serve. - Plugins map[string]Plugin - - // Server is the actual server that will accept connections. This - // will be used for plugin registration as well. - Server func([]grpc.ServerOption) *grpc.Server - - // TLS should be the TLS configuration if available. If this is nil, - // the connection will not have transport security. - TLS *tls.Config - - // DoneCh is the channel that is closed when this server has exited. - DoneCh chan struct{} - - // Stdout/StderrLis are the readers for stdout/stderr that will be copied - // to the stdout/stderr connection that is output. - Stdout io.Reader - Stderr io.Reader - - config GRPCServerConfig - server *grpc.Server - broker *GRPCBroker - stdioServer *grpcStdioServer - - logger hclog.Logger -} - -// ServerProtocol impl. -func (s *GRPCServer) Init() error { - // Create our server - var opts []grpc.ServerOption - if s.TLS != nil { - opts = append(opts, grpc.Creds(credentials.NewTLS(s.TLS))) - } - s.server = s.Server(opts) - - // Register the health service - healthCheck := health.NewServer() - healthCheck.SetServingStatus( - GRPCServiceName, grpc_health_v1.HealthCheckResponse_SERVING) - grpc_health_v1.RegisterHealthServer(s.server, healthCheck) - - // Register the reflection service - reflection.Register(s.server) - - // Register the broker service - brokerServer := newGRPCBrokerServer() - plugin.RegisterGRPCBrokerServer(s.server, brokerServer) - s.broker = newGRPCBroker(brokerServer, s.TLS) - go s.broker.Run() - - // Register the controller - controllerServer := &grpcControllerServer{server: s} - plugin.RegisterGRPCControllerServer(s.server, controllerServer) - - // Register the stdio service - s.stdioServer = newGRPCStdioServer(s.logger, s.Stdout, s.Stderr) - plugin.RegisterGRPCStdioServer(s.server, s.stdioServer) - - // Register all our plugins onto the gRPC server. - for k, raw := range s.Plugins { - p, ok := raw.(GRPCPlugin) - if !ok { - return fmt.Errorf("%q is not a GRPC-compatible plugin", k) - } - - if err := p.GRPCServer(s.broker, s.server); err != nil { - return fmt.Errorf("error registering %q: %s", k, err) - } - } - - return nil -} - -// Stop calls Stop on the underlying grpc.Server -func (s *GRPCServer) Stop() { - s.server.Stop() -} - -// GracefulStop calls GracefulStop on the underlying grpc.Server -func (s *GRPCServer) GracefulStop() { - s.server.GracefulStop() -} - -// Config is the GRPCServerConfig encoded as JSON then base64. -func (s *GRPCServer) Config() string { - // Create a buffer that will contain our final contents - var buf bytes.Buffer - - // Wrap the base64 encoding with JSON encoding. - if err := json.NewEncoder(&buf).Encode(s.config); err != nil { - // We panic since ths shouldn't happen under any scenario. We - // carefully control the structure being encoded here and it should - // always be successful. - panic(err) - } - - return buf.String() -} - -func (s *GRPCServer) Serve(lis net.Listener) { - defer close(s.DoneCh) - err := s.server.Serve(lis) - if err != nil { - s.logger.Error("grpc server", "error", err) - } -} - -// GRPCServerConfig is the extra configuration passed along for consumers -// to facilitate using GRPC plugins. -type GRPCServerConfig struct { - StdoutAddr string `json:"stdout_addr"` - StderrAddr string `json:"stderr_addr"` -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go b/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go deleted file mode 100644 index a58218150..000000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go +++ /dev/null @@ -1,207 +0,0 @@ -package plugin - -import ( - "bufio" - "bytes" - "context" - "io" - - empty "github.com/golang/protobuf/ptypes/empty" - hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin/internal/plugin" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// grpcStdioBuffer is the buffer size we try to fill when sending a chunk of -// stdio data. This is currently 1 KB for no reason other than that seems like -// enough (stdio data isn't that common) and is fairly low. -const grpcStdioBuffer = 1 * 1024 - -// grpcStdioServer implements the Stdio service and streams stdiout/stderr. -type grpcStdioServer struct { - stdoutCh <-chan []byte - stderrCh <-chan []byte -} - -// newGRPCStdioServer creates a new grpcStdioServer and starts the stream -// copying for the given out and err readers. -// -// This must only be called ONCE per srcOut, srcErr. -func newGRPCStdioServer(log hclog.Logger, srcOut, srcErr io.Reader) *grpcStdioServer { - stdoutCh := make(chan []byte) - stderrCh := make(chan []byte) - - // Begin copying the streams - go copyChan(log, stdoutCh, srcOut) - go copyChan(log, stderrCh, srcErr) - - // Construct our server - return &grpcStdioServer{ - stdoutCh: stdoutCh, - stderrCh: stderrCh, - } -} - -// StreamStdio streams our stdout/err as the response. -func (s *grpcStdioServer) StreamStdio( - _ *empty.Empty, - srv plugin.GRPCStdio_StreamStdioServer, -) error { - // Share the same data value between runs. Sending this over the wire - // marshals it so we can reuse this. - var data plugin.StdioData - - for { - // Read our data - select { - case data.Data = <-s.stdoutCh: - data.Channel = plugin.StdioData_STDOUT - - case data.Data = <-s.stderrCh: - data.Channel = plugin.StdioData_STDERR - - case <-srv.Context().Done(): - return nil - } - - // Not sure if this is possible, but if we somehow got here and - // we didn't populate any data at all, then just continue. - if len(data.Data) == 0 { - continue - } - - // Send our data to the client. - if err := srv.Send(&data); err != nil { - return err - } - } -} - -// grpcStdioClient wraps the stdio service as a client to copy -// the stdio data to output writers. -type grpcStdioClient struct { - log hclog.Logger - stdioClient plugin.GRPCStdio_StreamStdioClient -} - -// newGRPCStdioClient creates a grpcStdioClient. This will perform the -// initial connection to the stdio service. If the stdio service is unavailable -// then this will be a no-op. This allows this to work without error for -// plugins that don't support this. -func newGRPCStdioClient( - ctx context.Context, - log hclog.Logger, - conn *grpc.ClientConn, -) (*grpcStdioClient, error) { - client := plugin.NewGRPCStdioClient(conn) - - // Connect immediately to the endpoint - stdioClient, err := client.StreamStdio(ctx, &empty.Empty{}) - - // If we get an Unavailable or Unimplemented error, this means that the plugin isn't - // updated and linking to the latest version of go-plugin that supports - // this. We fall back to the previous behavior of just not syncing anything. - if status.Code(err) == codes.Unavailable || status.Code(err) == codes.Unimplemented { - log.Warn("stdio service not available, stdout/stderr syncing unavailable") - stdioClient = nil - err = nil - } - if err != nil { - return nil, err - } - - return &grpcStdioClient{ - log: log, - stdioClient: stdioClient, - }, nil -} - -// Run starts the loop that receives stdio data and writes it to the given -// writers. This blocks and should be run in a goroutine. -func (c *grpcStdioClient) Run(stdout, stderr io.Writer) { - // This will be nil if stdio is not supported by the plugin - if c.stdioClient == nil { - c.log.Warn("stdio service unavailable, run will do nothing") - return - } - - for { - c.log.Trace("waiting for stdio data") - data, err := c.stdioClient.Recv() - if err != nil { - if err == io.EOF || - status.Code(err) == codes.Unavailable || - status.Code(err) == codes.Canceled || - status.Code(err) == codes.Unimplemented || - err == context.Canceled { - c.log.Debug("received EOF, stopping recv loop", "err", err) - return - } - - c.log.Error("error receiving data", "err", err) - return - } - - // Determine our output writer based on channel - var w io.Writer - switch data.Channel { - case plugin.StdioData_STDOUT: - w = stdout - - case plugin.StdioData_STDERR: - w = stderr - - default: - c.log.Warn("unknown channel, dropping", "channel", data.Channel) - continue - } - - // Write! In the event of an error we just continue. - if c.log.IsTrace() { - c.log.Trace("received data", "channel", data.Channel.String(), "len", len(data.Data)) - } - if _, err := io.Copy(w, bytes.NewReader(data.Data)); err != nil { - c.log.Error("failed to copy all bytes", "err", err) - } - } -} - -// copyChan copies an io.Reader into a channel. -func copyChan(log hclog.Logger, dst chan<- []byte, src io.Reader) { - bufsrc := bufio.NewReader(src) - - for { - // Make our data buffer. We allocate a new one per loop iteration - // so that we can send it over the channel. - var data [1024]byte - - // Read the data, this will block until data is available - n, err := bufsrc.Read(data[:]) - - // We have to check if we have data BEFORE err != nil. The bufio - // docs guarantee n == 0 on EOF but its better to be safe here. - if n > 0 { - // We have data! Send it on the channel. This will block if there - // is no reader on the other side. We expect that go-plugin will - // connect immediately to the stdio server to drain this so we want - // this block to happen for backpressure. - dst <- data[:n] - } - - // If we hit EOF we're done copying - if err == io.EOF { - log.Debug("stdio EOF, exiting copy loop") - return - } - - // Any other error we just exit the loop. We don't expect there to - // be errors since our use case for this is reading/writing from - // a in-process pipe (os.Pipe). - if err != nil { - log.Warn("error copying stdio data, stopping copy", "err", err) - return - } - } -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go deleted file mode 100644 index fb9d41525..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate protoc -I ./ ./grpc_broker.proto ./grpc_controller.proto ./grpc_stdio.proto --go_out=plugins=grpc:. - -package plugin diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go deleted file mode 100644 index 6bf103859..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go +++ /dev/null @@ -1,203 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_broker.proto - -package plugin - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ConnInfo struct { - ServiceId uint32 `protobuf:"varint,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"` - Network string `protobuf:"bytes,2,opt,name=network,proto3" json:"network,omitempty"` - Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ConnInfo) Reset() { *m = ConnInfo{} } -func (m *ConnInfo) String() string { return proto.CompactTextString(m) } -func (*ConnInfo) ProtoMessage() {} -func (*ConnInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_broker_3322b07398605250, []int{0} -} -func (m *ConnInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ConnInfo.Unmarshal(m, b) -} -func (m *ConnInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ConnInfo.Marshal(b, m, deterministic) -} -func (dst *ConnInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConnInfo.Merge(dst, src) -} -func (m *ConnInfo) XXX_Size() int { - return xxx_messageInfo_ConnInfo.Size(m) -} -func (m *ConnInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ConnInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ConnInfo proto.InternalMessageInfo - -func (m *ConnInfo) GetServiceId() uint32 { - if m != nil { - return m.ServiceId - } - return 0 -} - -func (m *ConnInfo) GetNetwork() string { - if m != nil { - return m.Network - } - return "" -} - -func (m *ConnInfo) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func init() { - proto.RegisterType((*ConnInfo)(nil), "plugin.ConnInfo") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// GRPCBrokerClient is the client API for GRPCBroker service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type GRPCBrokerClient interface { - StartStream(ctx context.Context, opts ...grpc.CallOption) (GRPCBroker_StartStreamClient, error) -} - -type gRPCBrokerClient struct { - cc *grpc.ClientConn -} - -func NewGRPCBrokerClient(cc *grpc.ClientConn) GRPCBrokerClient { - return &gRPCBrokerClient{cc} -} - -func (c *gRPCBrokerClient) StartStream(ctx context.Context, opts ...grpc.CallOption) (GRPCBroker_StartStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_GRPCBroker_serviceDesc.Streams[0], "/plugin.GRPCBroker/StartStream", opts...) - if err != nil { - return nil, err - } - x := &gRPCBrokerStartStreamClient{stream} - return x, nil -} - -type GRPCBroker_StartStreamClient interface { - Send(*ConnInfo) error - Recv() (*ConnInfo, error) - grpc.ClientStream -} - -type gRPCBrokerStartStreamClient struct { - grpc.ClientStream -} - -func (x *gRPCBrokerStartStreamClient) Send(m *ConnInfo) error { - return x.ClientStream.SendMsg(m) -} - -func (x *gRPCBrokerStartStreamClient) Recv() (*ConnInfo, error) { - m := new(ConnInfo) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// GRPCBrokerServer is the server API for GRPCBroker service. -type GRPCBrokerServer interface { - StartStream(GRPCBroker_StartStreamServer) error -} - -func RegisterGRPCBrokerServer(s *grpc.Server, srv GRPCBrokerServer) { - s.RegisterService(&_GRPCBroker_serviceDesc, srv) -} - -func _GRPCBroker_StartStream_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(GRPCBrokerServer).StartStream(&gRPCBrokerStartStreamServer{stream}) -} - -type GRPCBroker_StartStreamServer interface { - Send(*ConnInfo) error - Recv() (*ConnInfo, error) - grpc.ServerStream -} - -type gRPCBrokerStartStreamServer struct { - grpc.ServerStream -} - -func (x *gRPCBrokerStartStreamServer) Send(m *ConnInfo) error { - return x.ServerStream.SendMsg(m) -} - -func (x *gRPCBrokerStartStreamServer) Recv() (*ConnInfo, error) { - m := new(ConnInfo) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _GRPCBroker_serviceDesc = grpc.ServiceDesc{ - ServiceName: "plugin.GRPCBroker", - HandlerType: (*GRPCBrokerServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "StartStream", - Handler: _GRPCBroker_StartStream_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_broker.proto", -} - -func init() { proto.RegisterFile("grpc_broker.proto", fileDescriptor_grpc_broker_3322b07398605250) } - -var fileDescriptor_grpc_broker_3322b07398605250 = []byte{ - // 175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0x2f, 0x2a, 0x48, - 0x8e, 0x4f, 0x2a, 0xca, 0xcf, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, - 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x8a, 0xe5, 0xe2, 0x70, 0xce, 0xcf, 0xcb, 0xf3, 0xcc, 0x4b, - 0xcb, 0x17, 0x92, 0xe5, 0xe2, 0x2a, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x8d, 0xcf, 0x4c, 0x91, - 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0d, 0xe2, 0x84, 0x8a, 0x78, 0xa6, 0x08, 0x49, 0x70, 0xb1, 0xe7, - 0xa5, 0x96, 0x94, 0xe7, 0x17, 0x65, 0x4b, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xb8, 0x20, - 0x99, 0xc4, 0x94, 0x94, 0xa2, 0xd4, 0xe2, 0x62, 0x09, 0x66, 0x88, 0x0c, 0x94, 0x6b, 0xe4, 0xcc, - 0xc5, 0xe5, 0x1e, 0x14, 0xe0, 0xec, 0x04, 0xb6, 0x5a, 0xc8, 0x94, 0x8b, 0x3b, 0xb8, 0x24, 0xb1, - 0xa8, 0x24, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0x57, 0x48, 0x40, 0x0f, 0xe2, 0x08, 0x3d, 0x98, 0x0b, - 0xa4, 0x30, 0x44, 0x34, 0x18, 0x0d, 0x18, 0x9d, 0x38, 0xa2, 0xa0, 0xae, 0x4d, 0x62, 0x03, 0x3b, - 0xde, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x10, 0x15, 0x39, 0x47, 0xd1, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto deleted file mode 100644 index aa3df4630..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; -package plugin; -option go_package = "plugin"; - -message ConnInfo { - uint32 service_id = 1; - string network = 2; - string address = 3; -} - -service GRPCBroker { - rpc StartStream(stream ConnInfo) returns (stream ConnInfo); -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go deleted file mode 100644 index 3e39da95a..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_controller.proto - -package plugin - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_controller_08f8296ef6d80436, []int{0} -} -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Empty)(nil), "plugin.Empty") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// GRPCControllerClient is the client API for GRPCController service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type GRPCControllerClient interface { - Shutdown(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) -} - -type gRPCControllerClient struct { - cc *grpc.ClientConn -} - -func NewGRPCControllerClient(cc *grpc.ClientConn) GRPCControllerClient { - return &gRPCControllerClient{cc} -} - -func (c *gRPCControllerClient) Shutdown(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/plugin.GRPCController/Shutdown", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// GRPCControllerServer is the server API for GRPCController service. -type GRPCControllerServer interface { - Shutdown(context.Context, *Empty) (*Empty, error) -} - -func RegisterGRPCControllerServer(s *grpc.Server, srv GRPCControllerServer) { - s.RegisterService(&_GRPCController_serviceDesc, srv) -} - -func _GRPCController_Shutdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(GRPCControllerServer).Shutdown(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/plugin.GRPCController/Shutdown", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GRPCControllerServer).Shutdown(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _GRPCController_serviceDesc = grpc.ServiceDesc{ - ServiceName: "plugin.GRPCController", - HandlerType: (*GRPCControllerServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Shutdown", - Handler: _GRPCController_Shutdown_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc_controller.proto", -} - -func init() { - proto.RegisterFile("grpc_controller.proto", fileDescriptor_grpc_controller_08f8296ef6d80436) -} - -var fileDescriptor_grpc_controller_08f8296ef6d80436 = []byte{ - // 108 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2f, 0x2a, 0x48, - 0x8e, 0x4f, 0xce, 0xcf, 0x2b, 0x29, 0xca, 0xcf, 0xc9, 0x49, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x62, 0x2b, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x62, 0xe7, 0x62, 0x75, 0xcd, 0x2d, - 0x28, 0xa9, 0x34, 0xb2, 0xe2, 0xe2, 0x73, 0x0f, 0x0a, 0x70, 0x76, 0x86, 0x2b, 0x14, 0xd2, 0xe0, - 0xe2, 0x08, 0xce, 0x28, 0x2d, 0x49, 0xc9, 0x2f, 0xcf, 0x13, 0xe2, 0xd5, 0x83, 0xa8, 0xd7, 0x03, - 0x2b, 0x96, 0x42, 0xe5, 0x3a, 0x71, 0x44, 0x41, 0x8d, 0x4b, 0x62, 0x03, 0x9b, 0x6e, 0x0c, 0x08, - 0x00, 0x00, 0xff, 0xff, 0xab, 0x7c, 0x27, 0xe5, 0x76, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto deleted file mode 100644 index 345d0a1c1..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto +++ /dev/null @@ -1,11 +0,0 @@ -syntax = "proto3"; -package plugin; -option go_package = "plugin"; - -message Empty { -} - -// The GRPCController is responsible for telling the plugin server to shutdown. -service GRPCController { - rpc Shutdown(Empty) returns (Empty); -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go deleted file mode 100644 index c8f94921b..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go +++ /dev/null @@ -1,233 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_stdio.proto - -package plugin - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import empty "github.com/golang/protobuf/ptypes/empty" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type StdioData_Channel int32 - -const ( - StdioData_INVALID StdioData_Channel = 0 - StdioData_STDOUT StdioData_Channel = 1 - StdioData_STDERR StdioData_Channel = 2 -) - -var StdioData_Channel_name = map[int32]string{ - 0: "INVALID", - 1: "STDOUT", - 2: "STDERR", -} -var StdioData_Channel_value = map[string]int32{ - "INVALID": 0, - "STDOUT": 1, - "STDERR": 2, -} - -func (x StdioData_Channel) String() string { - return proto.EnumName(StdioData_Channel_name, int32(x)) -} -func (StdioData_Channel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_grpc_stdio_db2934322ca63bd5, []int{0, 0} -} - -// StdioData is a single chunk of stdout or stderr data that is streamed -// from GRPCStdio. -type StdioData struct { - Channel StdioData_Channel `protobuf:"varint,1,opt,name=channel,proto3,enum=plugin.StdioData_Channel" json:"channel,omitempty"` - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StdioData) Reset() { *m = StdioData{} } -func (m *StdioData) String() string { return proto.CompactTextString(m) } -func (*StdioData) ProtoMessage() {} -func (*StdioData) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_stdio_db2934322ca63bd5, []int{0} -} -func (m *StdioData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StdioData.Unmarshal(m, b) -} -func (m *StdioData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StdioData.Marshal(b, m, deterministic) -} -func (dst *StdioData) XXX_Merge(src proto.Message) { - xxx_messageInfo_StdioData.Merge(dst, src) -} -func (m *StdioData) XXX_Size() int { - return xxx_messageInfo_StdioData.Size(m) -} -func (m *StdioData) XXX_DiscardUnknown() { - xxx_messageInfo_StdioData.DiscardUnknown(m) -} - -var xxx_messageInfo_StdioData proto.InternalMessageInfo - -func (m *StdioData) GetChannel() StdioData_Channel { - if m != nil { - return m.Channel - } - return StdioData_INVALID -} - -func (m *StdioData) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*StdioData)(nil), "plugin.StdioData") - proto.RegisterEnum("plugin.StdioData_Channel", StdioData_Channel_name, StdioData_Channel_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// GRPCStdioClient is the client API for GRPCStdio service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type GRPCStdioClient interface { - // StreamStdio returns a stream that contains all the stdout/stderr. - // This RPC endpoint must only be called ONCE. Once stdio data is consumed - // it is not sent again. - // - // Callers should connect early to prevent blocking on the plugin process. - StreamStdio(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (GRPCStdio_StreamStdioClient, error) -} - -type gRPCStdioClient struct { - cc *grpc.ClientConn -} - -func NewGRPCStdioClient(cc *grpc.ClientConn) GRPCStdioClient { - return &gRPCStdioClient{cc} -} - -func (c *gRPCStdioClient) StreamStdio(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (GRPCStdio_StreamStdioClient, error) { - stream, err := c.cc.NewStream(ctx, &_GRPCStdio_serviceDesc.Streams[0], "/plugin.GRPCStdio/StreamStdio", opts...) - if err != nil { - return nil, err - } - x := &gRPCStdioStreamStdioClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type GRPCStdio_StreamStdioClient interface { - Recv() (*StdioData, error) - grpc.ClientStream -} - -type gRPCStdioStreamStdioClient struct { - grpc.ClientStream -} - -func (x *gRPCStdioStreamStdioClient) Recv() (*StdioData, error) { - m := new(StdioData) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// GRPCStdioServer is the server API for GRPCStdio service. -type GRPCStdioServer interface { - // StreamStdio returns a stream that contains all the stdout/stderr. - // This RPC endpoint must only be called ONCE. Once stdio data is consumed - // it is not sent again. - // - // Callers should connect early to prevent blocking on the plugin process. - StreamStdio(*empty.Empty, GRPCStdio_StreamStdioServer) error -} - -func RegisterGRPCStdioServer(s *grpc.Server, srv GRPCStdioServer) { - s.RegisterService(&_GRPCStdio_serviceDesc, srv) -} - -func _GRPCStdio_StreamStdio_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(empty.Empty) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(GRPCStdioServer).StreamStdio(m, &gRPCStdioStreamStdioServer{stream}) -} - -type GRPCStdio_StreamStdioServer interface { - Send(*StdioData) error - grpc.ServerStream -} - -type gRPCStdioStreamStdioServer struct { - grpc.ServerStream -} - -func (x *gRPCStdioStreamStdioServer) Send(m *StdioData) error { - return x.ServerStream.SendMsg(m) -} - -var _GRPCStdio_serviceDesc = grpc.ServiceDesc{ - ServiceName: "plugin.GRPCStdio", - HandlerType: (*GRPCStdioServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamStdio", - Handler: _GRPCStdio_StreamStdio_Handler, - ServerStreams: true, - }, - }, - Metadata: "grpc_stdio.proto", -} - -func init() { proto.RegisterFile("grpc_stdio.proto", fileDescriptor_grpc_stdio_db2934322ca63bd5) } - -var fileDescriptor_grpc_stdio_db2934322ca63bd5 = []byte{ - // 221 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x48, 0x2f, 0x2a, 0x48, - 0x8e, 0x2f, 0x2e, 0x49, 0xc9, 0xcc, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, 0xc8, - 0x29, 0x4d, 0xcf, 0xcc, 0x93, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x07, 0x8b, 0x26, - 0x95, 0xa6, 0xe9, 0xa7, 0xe6, 0x16, 0x94, 0x54, 0x42, 0x14, 0x29, 0xb5, 0x30, 0x72, 0x71, 0x06, - 0x83, 0x34, 0xb9, 0x24, 0x96, 0x24, 0x0a, 0x19, 0x73, 0xb1, 0x27, 0x67, 0x24, 0xe6, 0xe5, 0xa5, - 0xe6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0x49, 0xea, 0x41, 0x0c, 0xd1, 0x83, 0xab, 0xd1, - 0x73, 0x86, 0x28, 0x08, 0x82, 0xa9, 0x14, 0x12, 0xe2, 0x62, 0x49, 0x49, 0x2c, 0x49, 0x94, 0x60, - 0x52, 0x60, 0xd4, 0xe0, 0x09, 0x02, 0xb3, 0x95, 0xf4, 0xb8, 0xd8, 0xa1, 0xea, 0x84, 0xb8, 0xb9, - 0xd8, 0x3d, 0xfd, 0xc2, 0x1c, 0x7d, 0x3c, 0x5d, 0x04, 0x18, 0x84, 0xb8, 0xb8, 0xd8, 0x82, 0x43, - 0x5c, 0xfc, 0x43, 0x43, 0x04, 0x18, 0xa1, 0x6c, 0xd7, 0xa0, 0x20, 0x01, 0x26, 0x23, 0x77, 0x2e, - 0x4e, 0xf7, 0xa0, 0x00, 0x67, 0xb0, 0x2d, 0x42, 0x56, 0x5c, 0xdc, 0xc1, 0x25, 0x45, 0xa9, 0x89, - 0xb9, 0x10, 0xae, 0x98, 0x1e, 0xc4, 0x03, 0x7a, 0x30, 0x0f, 0xe8, 0xb9, 0x82, 0x3c, 0x20, 0x25, - 0x88, 0xe1, 0x36, 0x03, 0x46, 0x27, 0x8e, 0x28, 0xa8, 0xb7, 0x93, 0xd8, 0xc0, 0xca, 0x8d, 0x01, - 0x01, 0x00, 0x00, 0xff, 0xff, 0x5d, 0xbb, 0xe0, 0x69, 0x19, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto deleted file mode 100644 index ce1a12230..000000000 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; -package plugin; -option go_package = "plugin"; - -import "google/protobuf/empty.proto"; - -// GRPCStdio is a service that is automatically run by the plugin process -// to stream any stdout/err data so that it can be mirrored on the plugin -// host side. -service GRPCStdio { - // StreamStdio returns a stream that contains all the stdout/stderr. - // This RPC endpoint must only be called ONCE. Once stdio data is consumed - // it is not sent again. - // - // Callers should connect early to prevent blocking on the plugin process. - rpc StreamStdio(google.protobuf.Empty) returns (stream StdioData); -} - -// StdioData is a single chunk of stdout or stderr data that is streamed -// from GRPCStdio. -message StdioData { - enum Channel { - INVALID = 0; - STDOUT = 1; - STDERR = 2; - } - - Channel channel = 1; - bytes data = 2; -} diff --git a/vendor/github.com/hashicorp/go-plugin/log_entry.go b/vendor/github.com/hashicorp/go-plugin/log_entry.go deleted file mode 100644 index fb2ef930c..000000000 --- a/vendor/github.com/hashicorp/go-plugin/log_entry.go +++ /dev/null @@ -1,73 +0,0 @@ -package plugin - -import ( - "encoding/json" - "time" -) - -// logEntry is the JSON payload that gets sent to Stderr from the plugin to the host -type logEntry struct { - Message string `json:"@message"` - Level string `json:"@level"` - Timestamp time.Time `json:"timestamp"` - KVPairs []*logEntryKV `json:"kv_pairs"` -} - -// logEntryKV is a key value pair within the Output payload -type logEntryKV struct { - Key string `json:"key"` - Value interface{} `json:"value"` -} - -// flattenKVPairs is used to flatten KVPair slice into []interface{} -// for hclog consumption. -func flattenKVPairs(kvs []*logEntryKV) []interface{} { - var result []interface{} - for _, kv := range kvs { - result = append(result, kv.Key) - result = append(result, kv.Value) - } - - return result -} - -// parseJSON handles parsing JSON output -func parseJSON(input []byte) (*logEntry, error) { - var raw map[string]interface{} - entry := &logEntry{} - - err := json.Unmarshal(input, &raw) - if err != nil { - return nil, err - } - - // Parse hclog-specific objects - if v, ok := raw["@message"]; ok { - entry.Message = v.(string) - delete(raw, "@message") - } - - if v, ok := raw["@level"]; ok { - entry.Level = v.(string) - delete(raw, "@level") - } - - if v, ok := raw["@timestamp"]; ok { - t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string)) - if err != nil { - return nil, err - } - entry.Timestamp = t - delete(raw, "@timestamp") - } - - // Parse dynamic KV args from the hclog payload. - for k, v := range raw { - entry.KVPairs = append(entry.KVPairs, &logEntryKV{ - Key: k, - Value: v, - }) - } - - return entry, nil -} diff --git a/vendor/github.com/hashicorp/go-plugin/mtls.go b/vendor/github.com/hashicorp/go-plugin/mtls.go deleted file mode 100644 index 889552458..000000000 --- a/vendor/github.com/hashicorp/go-plugin/mtls.go +++ /dev/null @@ -1,73 +0,0 @@ -package plugin - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "time" -) - -// generateCert generates a temporary certificate for plugin authentication. The -// certificate and private key are returns in PEM format. -func generateCert() (cert []byte, privateKey []byte, err error) { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - return nil, nil, err - } - - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - sn, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - return nil, nil, err - } - - host := "localhost" - - template := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: host, - Organization: []string{"HashiCorp"}, - }, - DNSNames: []string{host}, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageClientAuth, - x509.ExtKeyUsageServerAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign, - BasicConstraintsValid: true, - SerialNumber: sn, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - IsCA: true, - } - - der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) - if err != nil { - return nil, nil, err - } - - var certOut bytes.Buffer - if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { - return nil, nil, err - } - - keyBytes, err := x509.MarshalECPrivateKey(key) - if err != nil { - return nil, nil, err - } - - var keyOut bytes.Buffer - if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil { - return nil, nil, err - } - - cert = certOut.Bytes() - privateKey = keyOut.Bytes() - - return cert, privateKey, nil -} diff --git a/vendor/github.com/hashicorp/go-plugin/mux_broker.go b/vendor/github.com/hashicorp/go-plugin/mux_broker.go deleted file mode 100644 index 01c45ad7c..000000000 --- a/vendor/github.com/hashicorp/go-plugin/mux_broker.go +++ /dev/null @@ -1,204 +0,0 @@ -package plugin - -import ( - "encoding/binary" - "fmt" - "log" - "net" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/yamux" -) - -// MuxBroker is responsible for brokering multiplexed connections by unique ID. -// -// It is used by plugins to multiplex multiple RPC connections and data -// streams on top of a single connection between the plugin process and the -// host process. -// -// This allows a plugin to request a channel with a specific ID to connect to -// or accept a connection from, and the broker handles the details of -// holding these channels open while they're being negotiated. -// -// The Plugin interface has access to these for both Server and Client. -// The broker can be used by either (optionally) to reserve and connect to -// new multiplexed streams. This is useful for complex args and return values, -// or anything else you might need a data stream for. -type MuxBroker struct { - nextId uint32 - session *yamux.Session - streams map[uint32]*muxBrokerPending - - sync.Mutex -} - -type muxBrokerPending struct { - ch chan net.Conn - doneCh chan struct{} -} - -func newMuxBroker(s *yamux.Session) *MuxBroker { - return &MuxBroker{ - session: s, - streams: make(map[uint32]*muxBrokerPending), - } -} - -// Accept accepts a connection by ID. -// -// This should not be called multiple times with the same ID at one time. -func (m *MuxBroker) Accept(id uint32) (net.Conn, error) { - var c net.Conn - p := m.getStream(id) - select { - case c = <-p.ch: - close(p.doneCh) - case <-time.After(5 * time.Second): - m.Lock() - defer m.Unlock() - delete(m.streams, id) - - return nil, fmt.Errorf("timeout waiting for accept") - } - - // Ack our connection - if err := binary.Write(c, binary.LittleEndian, id); err != nil { - c.Close() - return nil, err - } - - return c, nil -} - -// AcceptAndServe is used to accept a specific stream ID and immediately -// serve an RPC server on that stream ID. This is used to easily serve -// complex arguments. -// -// The served interface is always registered to the "Plugin" name. -func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) { - conn, err := m.Accept(id) - if err != nil { - log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) - return - } - - serve(conn, "Plugin", v) -} - -// Close closes the connection and all sub-connections. -func (m *MuxBroker) Close() error { - return m.session.Close() -} - -// Dial opens a connection by ID. -func (m *MuxBroker) Dial(id uint32) (net.Conn, error) { - // Open the stream - stream, err := m.session.OpenStream() - if err != nil { - return nil, err - } - - // Write the stream ID onto the wire. - if err := binary.Write(stream, binary.LittleEndian, id); err != nil { - stream.Close() - return nil, err - } - - // Read the ack that we connected. Then we're off! - var ack uint32 - if err := binary.Read(stream, binary.LittleEndian, &ack); err != nil { - stream.Close() - return nil, err - } - if ack != id { - stream.Close() - return nil, fmt.Errorf("bad ack: %d (expected %d)", ack, id) - } - - return stream, nil -} - -// NextId returns a unique ID to use next. -// -// It is possible for very long-running plugin hosts to wrap this value, -// though it would require a very large amount of RPC calls. In practice -// we've never seen it happen. -func (m *MuxBroker) NextId() uint32 { - return atomic.AddUint32(&m.nextId, 1) -} - -// Run starts the brokering and should be executed in a goroutine, since it -// blocks forever, or until the session closes. -// -// Uses of MuxBroker never need to call this. It is called internally by -// the plugin host/client. -func (m *MuxBroker) Run() { - for { - stream, err := m.session.AcceptStream() - if err != nil { - // Once we receive an error, just exit - break - } - - // Read the stream ID from the stream - var id uint32 - if err := binary.Read(stream, binary.LittleEndian, &id); err != nil { - stream.Close() - continue - } - - // Initialize the waiter - p := m.getStream(id) - select { - case p.ch <- stream: - default: - } - - // Wait for a timeout - go m.timeoutWait(id, p) - } -} - -func (m *MuxBroker) getStream(id uint32) *muxBrokerPending { - m.Lock() - defer m.Unlock() - - p, ok := m.streams[id] - if ok { - return p - } - - m.streams[id] = &muxBrokerPending{ - ch: make(chan net.Conn, 1), - doneCh: make(chan struct{}), - } - return m.streams[id] -} - -func (m *MuxBroker) timeoutWait(id uint32, p *muxBrokerPending) { - // Wait for the stream to either be picked up and connected, or - // for a timeout. - timeout := false - select { - case <-p.doneCh: - case <-time.After(5 * time.Second): - timeout = true - } - - m.Lock() - defer m.Unlock() - - // Delete the stream so no one else can grab it - delete(m.streams, id) - - // If we timed out, then check if we have a channel in the buffer, - // and if so, close it. - if timeout { - select { - case s := <-p.ch: - s.Close() - } - } -} diff --git a/vendor/github.com/hashicorp/go-plugin/plugin.go b/vendor/github.com/hashicorp/go-plugin/plugin.go deleted file mode 100644 index 79d967463..000000000 --- a/vendor/github.com/hashicorp/go-plugin/plugin.go +++ /dev/null @@ -1,58 +0,0 @@ -// The plugin package exposes functions and helpers for communicating to -// plugins which are implemented as standalone binary applications. -// -// plugin.Client fully manages the lifecycle of executing the application, -// connecting to it, and returning the RPC client for dispensing plugins. -// -// plugin.Serve fully manages listeners to expose an RPC server from a binary -// that plugin.Client can connect to. -package plugin - -import ( - "context" - "errors" - "net/rpc" - - "google.golang.org/grpc" -) - -// Plugin is the interface that is implemented to serve/connect to an -// inteface implementation. -type Plugin interface { - // Server should return the RPC server compatible struct to serve - // the methods that the Client calls over net/rpc. - Server(*MuxBroker) (interface{}, error) - - // Client returns an interface implementation for the plugin you're - // serving that communicates to the server end of the plugin. - Client(*MuxBroker, *rpc.Client) (interface{}, error) -} - -// GRPCPlugin is the interface that is implemented to serve/connect to -// a plugin over gRPC. -type GRPCPlugin interface { - // GRPCServer should register this plugin for serving with the - // given GRPCServer. Unlike Plugin.Server, this is only called once - // since gRPC plugins serve singletons. - GRPCServer(*GRPCBroker, *grpc.Server) error - - // GRPCClient should return the interface implementation for the plugin - // you're serving via gRPC. The provided context will be canceled by - // go-plugin in the event of the plugin process exiting. - GRPCClient(context.Context, *GRPCBroker, *grpc.ClientConn) (interface{}, error) -} - -// NetRPCUnsupportedPlugin implements Plugin but returns errors for the -// Server and Client functions. This will effectively disable support for -// net/rpc based plugins. -// -// This struct can be embedded in your struct. -type NetRPCUnsupportedPlugin struct{} - -func (p NetRPCUnsupportedPlugin) Server(*MuxBroker) (interface{}, error) { - return nil, errors.New("net/rpc plugin protocol not supported") -} - -func (p NetRPCUnsupportedPlugin) Client(*MuxBroker, *rpc.Client) (interface{}, error) { - return nil, errors.New("net/rpc plugin protocol not supported") -} diff --git a/vendor/github.com/hashicorp/go-plugin/process.go b/vendor/github.com/hashicorp/go-plugin/process.go deleted file mode 100644 index 88c999a58..000000000 --- a/vendor/github.com/hashicorp/go-plugin/process.go +++ /dev/null @@ -1,24 +0,0 @@ -package plugin - -import ( - "time" -) - -// pidAlive checks whether a pid is alive. -func pidAlive(pid int) bool { - return _pidAlive(pid) -} - -// pidWait blocks for a process to exit. -func pidWait(pid int) error { - ticker := time.NewTicker(1 * time.Second) - defer ticker.Stop() - - for range ticker.C { - if !pidAlive(pid) { - break - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/go-plugin/process_posix.go b/vendor/github.com/hashicorp/go-plugin/process_posix.go deleted file mode 100644 index 185957f8d..000000000 --- a/vendor/github.com/hashicorp/go-plugin/process_posix.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build !windows -// +build !windows - -package plugin - -import ( - "os" - "syscall" -) - -// _pidAlive tests whether a process is alive or not by sending it Signal 0, -// since Go otherwise has no way to test this. -func _pidAlive(pid int) bool { - proc, err := os.FindProcess(pid) - if err == nil { - err = proc.Signal(syscall.Signal(0)) - } - - return err == nil -} diff --git a/vendor/github.com/hashicorp/go-plugin/process_windows.go b/vendor/github.com/hashicorp/go-plugin/process_windows.go deleted file mode 100644 index 0eaa7705d..000000000 --- a/vendor/github.com/hashicorp/go-plugin/process_windows.go +++ /dev/null @@ -1,30 +0,0 @@ -package plugin - -import ( - "syscall" -) - -const ( - // Weird name but matches the MSDN docs - exit_STILL_ACTIVE = 259 - - processDesiredAccess = syscall.STANDARD_RIGHTS_READ | - syscall.PROCESS_QUERY_INFORMATION | - syscall.SYNCHRONIZE -) - -// _pidAlive tests whether a process is alive or not -func _pidAlive(pid int) bool { - h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid)) - if err != nil { - return false - } - defer syscall.CloseHandle(h) - - var ec uint32 - if e := syscall.GetExitCodeProcess(h, &ec); e != nil { - return false - } - - return ec == exit_STILL_ACTIVE -} diff --git a/vendor/github.com/hashicorp/go-plugin/protocol.go b/vendor/github.com/hashicorp/go-plugin/protocol.go deleted file mode 100644 index 0cfc19e52..000000000 --- a/vendor/github.com/hashicorp/go-plugin/protocol.go +++ /dev/null @@ -1,45 +0,0 @@ -package plugin - -import ( - "io" - "net" -) - -// Protocol is an enum representing the types of protocols. -type Protocol string - -const ( - ProtocolInvalid Protocol = "" - ProtocolNetRPC Protocol = "netrpc" - ProtocolGRPC Protocol = "grpc" -) - -// ServerProtocol is an interface that must be implemented for new plugin -// protocols to be servers. -type ServerProtocol interface { - // Init is called once to configure and initialize the protocol, but - // not start listening. This is the point at which all validation should - // be done and errors returned. - Init() error - - // Config is extra configuration to be outputted to stdout. This will - // be automatically base64 encoded to ensure it can be parsed properly. - // This can be an empty string if additional configuration is not needed. - Config() string - - // Serve is called to serve connections on the given listener. This should - // continue until the listener is closed. - Serve(net.Listener) -} - -// ClientProtocol is an interface that must be implemented for new plugin -// protocols to be clients. -type ClientProtocol interface { - io.Closer - - // Dispense dispenses a new instance of the plugin with the given name. - Dispense(string) (interface{}, error) - - // Ping checks that the client connection is still healthy. - Ping() error -} diff --git a/vendor/github.com/hashicorp/go-plugin/rpc_client.go b/vendor/github.com/hashicorp/go-plugin/rpc_client.go deleted file mode 100644 index f30a4b1d3..000000000 --- a/vendor/github.com/hashicorp/go-plugin/rpc_client.go +++ /dev/null @@ -1,170 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "fmt" - "io" - "net" - "net/rpc" - - "github.com/hashicorp/yamux" -) - -// RPCClient connects to an RPCServer over net/rpc to dispense plugin types. -type RPCClient struct { - broker *MuxBroker - control *rpc.Client - plugins map[string]Plugin - - // These are the streams used for the various stdout/err overrides - stdout, stderr net.Conn -} - -// newRPCClient creates a new RPCClient. The Client argument is expected -// to be successfully started already with a lock held. -func newRPCClient(c *Client) (*RPCClient, error) { - // Connect to the client - conn, err := net.Dial(c.address.Network(), c.address.String()) - if err != nil { - return nil, err - } - if tcpConn, ok := conn.(*net.TCPConn); ok { - // Make sure to set keep alive so that the connection doesn't die - tcpConn.SetKeepAlive(true) - } - - if c.config.TLSConfig != nil { - conn = tls.Client(conn, c.config.TLSConfig) - } - - // Create the actual RPC client - result, err := NewRPCClient(conn, c.config.Plugins) - if err != nil { - conn.Close() - return nil, err - } - - // Begin the stream syncing so that stdin, out, err work properly - err = result.SyncStreams( - c.config.SyncStdout, - c.config.SyncStderr) - if err != nil { - result.Close() - return nil, err - } - - return result, nil -} - -// NewRPCClient creates a client from an already-open connection-like value. -// Dial is typically used instead. -func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) { - // Create the yamux client so we can multiplex - mux, err := yamux.Client(conn, nil) - if err != nil { - conn.Close() - return nil, err - } - - // Connect to the control stream. - control, err := mux.Open() - if err != nil { - mux.Close() - return nil, err - } - - // Connect stdout, stderr streams - stdstream := make([]net.Conn, 2) - for i, _ := range stdstream { - stdstream[i], err = mux.Open() - if err != nil { - mux.Close() - return nil, err - } - } - - // Create the broker and start it up - broker := newMuxBroker(mux) - go broker.Run() - - // Build the client using our broker and control channel. - return &RPCClient{ - broker: broker, - control: rpc.NewClient(control), - plugins: plugins, - stdout: stdstream[0], - stderr: stdstream[1], - }, nil -} - -// SyncStreams should be called to enable syncing of stdout, -// stderr with the plugin. -// -// This will return immediately and the syncing will continue to happen -// in the background. You do not need to launch this in a goroutine itself. -// -// This should never be called multiple times. -func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error { - go copyStream("stdout", stdout, c.stdout) - go copyStream("stderr", stderr, c.stderr) - return nil -} - -// Close closes the connection. The client is no longer usable after this -// is called. -func (c *RPCClient) Close() error { - // Call the control channel and ask it to gracefully exit. If this - // errors, then we save it so that we always return an error but we - // want to try to close the other channels anyways. - var empty struct{} - returnErr := c.control.Call("Control.Quit", true, &empty) - - // Close the other streams we have - if err := c.control.Close(); err != nil { - return err - } - if err := c.stdout.Close(); err != nil { - return err - } - if err := c.stderr.Close(); err != nil { - return err - } - if err := c.broker.Close(); err != nil { - return err - } - - // Return back the error we got from Control.Quit. This is very important - // since we MUST return non-nil error if this fails so that Client.Kill - // will properly try a process.Kill. - return returnErr -} - -func (c *RPCClient) Dispense(name string) (interface{}, error) { - p, ok := c.plugins[name] - if !ok { - return nil, fmt.Errorf("unknown plugin type: %s", name) - } - - var id uint32 - if err := c.control.Call( - "Dispenser.Dispense", name, &id); err != nil { - return nil, err - } - - conn, err := c.broker.Dial(id) - if err != nil { - return nil, err - } - - return p.Client(c.broker, rpc.NewClient(conn)) -} - -// Ping pings the connection to ensure it is still alive. -// -// The error from the RPC call is returned exactly if you want to inspect -// it for further error analysis. Any error returned from here would indicate -// that the connection to the plugin is not healthy. -func (c *RPCClient) Ping() error { - var empty struct{} - return c.control.Call("Control.Ping", true, &empty) -} diff --git a/vendor/github.com/hashicorp/go-plugin/rpc_server.go b/vendor/github.com/hashicorp/go-plugin/rpc_server.go deleted file mode 100644 index 449ba6cc1..000000000 --- a/vendor/github.com/hashicorp/go-plugin/rpc_server.go +++ /dev/null @@ -1,201 +0,0 @@ -package plugin - -import ( - "errors" - "fmt" - "io" - "log" - "net" - "net/rpc" - "sync" - - "github.com/hashicorp/yamux" -) - -// RPCServer listens for network connections and then dispenses interface -// implementations over net/rpc. -// -// After setting the fields below, they shouldn't be read again directly -// from the structure which may be reading/writing them concurrently. -type RPCServer struct { - Plugins map[string]Plugin - - // Stdout, Stderr are what this server will use instead of the - // normal stdin/out/err. This is because due to the multi-process nature - // of our plugin system, we can't use the normal process values so we - // make our own custom one we pipe across. - Stdout io.Reader - Stderr io.Reader - - // DoneCh should be set to a non-nil channel that will be closed - // when the control requests the RPC server to end. - DoneCh chan<- struct{} - - lock sync.Mutex -} - -// ServerProtocol impl. -func (s *RPCServer) Init() error { return nil } - -// ServerProtocol impl. -func (s *RPCServer) Config() string { return "" } - -// ServerProtocol impl. -func (s *RPCServer) Serve(lis net.Listener) { - for { - conn, err := lis.Accept() - if err != nil { - severity := "ERR" - if errors.Is(err, net.ErrClosed) { - severity = "DEBUG" - } - log.Printf("[%s] plugin: plugin server: %s", severity, err) - return - } - - go s.ServeConn(conn) - } -} - -// ServeConn runs a single connection. -// -// ServeConn blocks, serving the connection until the client hangs up. -func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) { - // First create the yamux server to wrap this connection - mux, err := yamux.Server(conn, nil) - if err != nil { - conn.Close() - log.Printf("[ERR] plugin: error creating yamux server: %s", err) - return - } - - // Accept the control connection - control, err := mux.Accept() - if err != nil { - mux.Close() - if err != io.EOF { - log.Printf("[ERR] plugin: error accepting control connection: %s", err) - } - - return - } - - // Connect the stdstreams (in, out, err) - stdstream := make([]net.Conn, 2) - for i, _ := range stdstream { - stdstream[i], err = mux.Accept() - if err != nil { - mux.Close() - log.Printf("[ERR] plugin: accepting stream %d: %s", i, err) - return - } - } - - // Copy std streams out to the proper place - go copyStream("stdout", stdstream[0], s.Stdout) - go copyStream("stderr", stdstream[1], s.Stderr) - - // Create the broker and start it up - broker := newMuxBroker(mux) - go broker.Run() - - // Use the control connection to build the dispenser and serve the - // connection. - server := rpc.NewServer() - server.RegisterName("Control", &controlServer{ - server: s, - }) - server.RegisterName("Dispenser", &dispenseServer{ - broker: broker, - plugins: s.Plugins, - }) - server.ServeConn(control) -} - -// done is called internally by the control server to trigger the -// doneCh to close which is listened to by the main process to cleanly -// exit. -func (s *RPCServer) done() { - s.lock.Lock() - defer s.lock.Unlock() - - if s.DoneCh != nil { - close(s.DoneCh) - s.DoneCh = nil - } -} - -// dispenseServer dispenses variousinterface implementations for Terraform. -type controlServer struct { - server *RPCServer -} - -// Ping can be called to verify the connection (and likely the binary) -// is still alive to a plugin. -func (c *controlServer) Ping( - null bool, response *struct{}) error { - *response = struct{}{} - return nil -} - -func (c *controlServer) Quit( - null bool, response *struct{}) error { - // End the server - c.server.done() - - // Always return true - *response = struct{}{} - - return nil -} - -// dispenseServer dispenses variousinterface implementations for Terraform. -type dispenseServer struct { - broker *MuxBroker - plugins map[string]Plugin -} - -func (d *dispenseServer) Dispense( - name string, response *uint32) error { - // Find the function to create this implementation - p, ok := d.plugins[name] - if !ok { - return fmt.Errorf("unknown plugin type: %s", name) - } - - // Create the implementation first so we know if there is an error. - impl, err := p.Server(d.broker) - if err != nil { - // We turn the error into an errors error so that it works across RPC - return errors.New(err.Error()) - } - - // Reserve an ID for our implementation - id := d.broker.NextId() - *response = id - - // Run the rest in a goroutine since it can only happen once this RPC - // call returns. We wait for a connection for the plugin implementation - // and serve it. - go func() { - conn, err := d.broker.Accept(id) - if err != nil { - log.Printf("[ERR] go-plugin: plugin dispense error: %s: %s", name, err) - return - } - - serve(conn, "Plugin", impl) - }() - - return nil -} - -func serve(conn io.ReadWriteCloser, name string, v interface{}) { - server := rpc.NewServer() - if err := server.RegisterName(name, v); err != nil { - log.Printf("[ERR] go-plugin: plugin dispense error: %s", err) - return - } - - server.ServeConn(conn) -} diff --git a/vendor/github.com/hashicorp/go-plugin/server.go b/vendor/github.com/hashicorp/go-plugin/server.go deleted file mode 100644 index e13499910..000000000 --- a/vendor/github.com/hashicorp/go-plugin/server.go +++ /dev/null @@ -1,591 +0,0 @@ -package plugin - -import ( - "context" - "crypto/tls" - "crypto/x509" - "encoding/base64" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "os/signal" - "runtime" - "sort" - "strconv" - "strings" - - hclog "github.com/hashicorp/go-hclog" - "google.golang.org/grpc" -) - -// CoreProtocolVersion is the ProtocolVersion of the plugin system itself. -// We will increment this whenever we change any protocol behavior. This -// will invalidate any prior plugins but will at least allow us to iterate -// on the core in a safe way. We will do our best to do this very -// infrequently. -const CoreProtocolVersion = 1 - -// HandshakeConfig is the configuration used by client and servers to -// handshake before starting a plugin connection. This is embedded by -// both ServeConfig and ClientConfig. -// -// In practice, the plugin host creates a HandshakeConfig that is exported -// and plugins then can easily consume it. -type HandshakeConfig struct { - // ProtocolVersion is the version that clients must match on to - // agree they can communicate. This should match the ProtocolVersion - // set on ClientConfig when using a plugin. - // This field is not required if VersionedPlugins are being used in the - // Client or Server configurations. - ProtocolVersion uint - - // MagicCookieKey and value are used as a very basic verification - // that a plugin is intended to be launched. This is not a security - // measure, just a UX feature. If the magic cookie doesn't match, - // we show human-friendly output. - MagicCookieKey string - MagicCookieValue string -} - -// PluginSet is a set of plugins provided to be registered in the plugin -// server. -type PluginSet map[string]Plugin - -// ServeConfig configures what sorts of plugins are served. -type ServeConfig struct { - // HandshakeConfig is the configuration that must match clients. - HandshakeConfig - - // TLSProvider is a function that returns a configured tls.Config. - TLSProvider func() (*tls.Config, error) - - // Plugins are the plugins that are served. - // The implied version of this PluginSet is the Handshake.ProtocolVersion. - Plugins PluginSet - - // VersionedPlugins is a map of PluginSets for specific protocol versions. - // These can be used to negotiate a compatible version between client and - // server. If this is set, Handshake.ProtocolVersion is not required. - VersionedPlugins map[int]PluginSet - - // GRPCServer should be non-nil to enable serving the plugins over - // gRPC. This is a function to create the server when needed with the - // given server options. The server options populated by go-plugin will - // be for TLS if set. You may modify the input slice. - // - // Note that the grpc.Server will automatically be registered with - // the gRPC health checking service. This is not optional since go-plugin - // relies on this to implement Ping(). - GRPCServer func([]grpc.ServerOption) *grpc.Server - - // Logger is used to pass a logger into the server. If none is provided the - // server will create a default logger. - Logger hclog.Logger - - // Test, if non-nil, will put plugin serving into "test mode". This is - // meant to be used as part of `go test` within a plugin's codebase to - // launch the plugin in-process and output a ReattachConfig. - // - // This changes the behavior of the server in a number of ways to - // accomodate the expectation of running in-process: - // - // * The handshake cookie is not validated. - // * Stdout/stderr will receive plugin reads and writes - // * Connection information will not be sent to stdout - // - Test *ServeTestConfig -} - -// ServeTestConfig configures plugin serving for test mode. See ServeConfig.Test. -type ServeTestConfig struct { - // Context, if set, will force the plugin serving to end when cancelled. - // This is only a test configuration because the non-test configuration - // expects to take over the process and therefore end on an interrupt or - // kill signal. For tests, we need to kill the plugin serving routinely - // and this provides a way to do so. - // - // If you want to wait for the plugin process to close before moving on, - // you can wait on CloseCh. - Context context.Context - - // If this channel is non-nil, we will send the ReattachConfig via - // this channel. This can be encoded (via JSON recommended) to the - // plugin client to attach to this plugin. - ReattachConfigCh chan<- *ReattachConfig - - // CloseCh, if non-nil, will be closed when serving exits. This can be - // used along with Context to determine when the server is fully shut down. - // If this is not set, you can still use Context on its own, but note there - // may be a period of time between canceling the context and the plugin - // server being shut down. - CloseCh chan<- struct{} - - // SyncStdio, if true, will enable the client side "SyncStdout/Stderr" - // functionality to work. This defaults to false because the implementation - // of making this work within test environments is particularly messy - // and SyncStdio functionality is fairly rare, so we default to the simple - // scenario. - SyncStdio bool -} - -// protocolVersion determines the protocol version and plugin set to be used by -// the server. In the event that there is no suitable version, the last version -// in the config is returned leaving the client to report the incompatibility. -func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) { - protoVersion := int(opts.ProtocolVersion) - pluginSet := opts.Plugins - protoType := ProtocolNetRPC - // Check if the client sent a list of acceptable versions - var clientVersions []int - if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" { - for _, s := range strings.Split(vs, ",") { - v, err := strconv.Atoi(s) - if err != nil { - fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s) - continue - } - clientVersions = append(clientVersions, v) - } - } - - // We want to iterate in reverse order, to ensure we match the newest - // compatible plugin version. - sort.Sort(sort.Reverse(sort.IntSlice(clientVersions))) - - // set the old un-versioned fields as if they were versioned plugins - if opts.VersionedPlugins == nil { - opts.VersionedPlugins = make(map[int]PluginSet) - } - - if pluginSet != nil { - opts.VersionedPlugins[protoVersion] = pluginSet - } - - // Sort the version to make sure we match the latest first - var versions []int - for v := range opts.VersionedPlugins { - versions = append(versions, v) - } - - sort.Sort(sort.Reverse(sort.IntSlice(versions))) - - // See if we have multiple versions of Plugins to choose from - for _, version := range versions { - // Record each version, since we guarantee that this returns valid - // values even if they are not a protocol match. - protoVersion = version - pluginSet = opts.VersionedPlugins[version] - - // If we have a configured gRPC server we should select a protocol - if opts.GRPCServer != nil { - // All plugins in a set must use the same transport, so check the first - // for the protocol type - for _, p := range pluginSet { - switch p.(type) { - case GRPCPlugin: - protoType = ProtocolGRPC - default: - protoType = ProtocolNetRPC - } - break - } - } - - for _, clientVersion := range clientVersions { - if clientVersion == protoVersion { - return protoVersion, protoType, pluginSet - } - } - } - - // Return the lowest version as the fallback. - // Since we iterated over all the versions in reverse order above, these - // values are from the lowest version number plugins (which may be from - // a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins - // fields). This allows serving the oldest version of our plugins to a - // legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list. - return protoVersion, protoType, pluginSet -} - -// Serve serves the plugins given by ServeConfig. -// -// Serve doesn't return until the plugin is done being executed. Any -// fixable errors will be output to os.Stderr and the process will -// exit with a status code of 1. Serve will panic for unexpected -// conditions where a user's fix is unknown. -// -// This is the method that plugins should call in their main() functions. -func Serve(opts *ServeConfig) { - exitCode := -1 - // We use this to trigger an `os.Exit` so that we can execute our other - // deferred functions. In test mode, we just output the err to stderr - // and return. - defer func() { - if opts.Test == nil && exitCode >= 0 { - os.Exit(exitCode) - } - - if opts.Test != nil && opts.Test.CloseCh != nil { - close(opts.Test.CloseCh) - } - }() - - if opts.Test == nil { - // Validate the handshake config - if opts.MagicCookieKey == "" || opts.MagicCookieValue == "" { - fmt.Fprintf(os.Stderr, - "Misconfigured ServeConfig given to serve this plugin: no magic cookie\n"+ - "key or value was set. Please notify the plugin author and report\n"+ - "this as a bug.\n") - exitCode = 1 - return - } - - // First check the cookie - if os.Getenv(opts.MagicCookieKey) != opts.MagicCookieValue { - fmt.Fprintf(os.Stderr, - "This binary is a plugin. These are not meant to be executed directly.\n"+ - "Please execute the program that consumes these plugins, which will\n"+ - "load any plugins automatically\n") - exitCode = 1 - return - } - } - - // negotiate the version and plugins - // start with default version in the handshake config - protoVersion, protoType, pluginSet := protocolVersion(opts) - - logger := opts.Logger - if logger == nil { - // internal logger to os.Stderr - logger = hclog.New(&hclog.LoggerOptions{ - Level: hclog.Trace, - Output: os.Stderr, - JSONFormat: true, - }) - } - - // Register a listener so we can accept a connection - listener, err := serverListener() - if err != nil { - logger.Error("plugin init error", "error", err) - return - } - - // Close the listener on return. We wrap this in a func() on purpose - // because the "listener" reference may change to TLS. - defer func() { - listener.Close() - }() - - var tlsConfig *tls.Config - if opts.TLSProvider != nil { - tlsConfig, err = opts.TLSProvider() - if err != nil { - logger.Error("plugin tls init", "error", err) - return - } - } - - var serverCert string - clientCert := os.Getenv("PLUGIN_CLIENT_CERT") - // If the client is configured using AutoMTLS, the certificate will be here, - // and we need to generate our own in response. - if tlsConfig == nil && clientCert != "" { - logger.Info("configuring server automatic mTLS") - clientCertPool := x509.NewCertPool() - if !clientCertPool.AppendCertsFromPEM([]byte(clientCert)) { - logger.Error("client cert provided but failed to parse", "cert", clientCert) - } - - certPEM, keyPEM, err := generateCert() - if err != nil { - logger.Error("failed to generate server certificate", "error", err) - panic(err) - } - - cert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - logger.Error("failed to parse server certificate", "error", err) - panic(err) - } - - tlsConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - ClientAuth: tls.RequireAndVerifyClientCert, - ClientCAs: clientCertPool, - MinVersion: tls.VersionTLS12, - RootCAs: clientCertPool, - ServerName: "localhost", - } - - // We send back the raw leaf cert data for the client rather than the - // PEM, since the protocol can't handle newlines. - serverCert = base64.RawStdEncoding.EncodeToString(cert.Certificate[0]) - } - - // Create the channel to tell us when we're done - doneCh := make(chan struct{}) - - // Create our new stdout, stderr files. These will override our built-in - // stdout/stderr so that it works across the stream boundary. - var stdout_r, stderr_r io.Reader - stdout_r, stdout_w, err := os.Pipe() - if err != nil { - fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) - os.Exit(1) - } - stderr_r, stderr_w, err := os.Pipe() - if err != nil { - fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) - os.Exit(1) - } - - // If we're in test mode, we tee off the reader and write the data - // as-is to our normal Stdout and Stderr so that they continue working - // while stdio works. This is because in test mode, we assume we're running - // in `go test` or some equivalent and we want output to go to standard - // locations. - if opts.Test != nil { - // TODO(mitchellh): This isn't super ideal because a TeeReader - // only works if the reader side is actively read. If we never - // connect via a plugin client, the output still gets swallowed. - stdout_r = io.TeeReader(stdout_r, os.Stdout) - stderr_r = io.TeeReader(stderr_r, os.Stderr) - } - - // Build the server type - var server ServerProtocol - switch protoType { - case ProtocolNetRPC: - // If we have a TLS configuration then we wrap the listener - // ourselves and do it at that level. - if tlsConfig != nil { - listener = tls.NewListener(listener, tlsConfig) - } - - // Create the RPC server to dispense - server = &RPCServer{ - Plugins: pluginSet, - Stdout: stdout_r, - Stderr: stderr_r, - DoneCh: doneCh, - } - - case ProtocolGRPC: - // Create the gRPC server - server = &GRPCServer{ - Plugins: pluginSet, - Server: opts.GRPCServer, - TLS: tlsConfig, - Stdout: stdout_r, - Stderr: stderr_r, - DoneCh: doneCh, - logger: logger, - } - - default: - panic("unknown server protocol: " + protoType) - } - - // Initialize the servers - if err := server.Init(); err != nil { - logger.Error("protocol init", "error", err) - return - } - - logger.Debug("plugin address", "network", listener.Addr().Network(), "address", listener.Addr().String()) - - // Output the address and service name to stdout so that the client can - // bring it up. In test mode, we don't do this because clients will - // attach via a reattach config. - if opts.Test == nil { - fmt.Printf("%d|%d|%s|%s|%s|%s\n", - CoreProtocolVersion, - protoVersion, - listener.Addr().Network(), - listener.Addr().String(), - protoType, - serverCert) - os.Stdout.Sync() - } else if ch := opts.Test.ReattachConfigCh; ch != nil { - // Send back the reattach config that can be used. This isn't - // quite ready if they connect immediately but the client should - // retry a few times. - ch <- &ReattachConfig{ - Protocol: protoType, - ProtocolVersion: protoVersion, - Addr: listener.Addr(), - Pid: os.Getpid(), - Test: true, - } - } - - // Eat the interrupts. In test mode we disable this so that go test - // can be cancelled properly. - if opts.Test == nil { - ch := make(chan os.Signal, 1) - signal.Notify(ch, os.Interrupt) - go func() { - count := 0 - for { - <-ch - count++ - logger.Trace("plugin received interrupt signal, ignoring", "count", count) - } - }() - } - - // Set our stdout, stderr to the stdio stream that clients can retrieve - // using ClientConfig.SyncStdout/err. We only do this for non-test mode - // or if the test mode explicitly requests it. - // - // In test mode, we use a multiwriter so that the data continues going - // to the normal stdout/stderr so output can show up in test logs. We - // also send to the stdio stream so that clients can continue working - // if they depend on that. - if opts.Test == nil || opts.Test.SyncStdio { - if opts.Test != nil { - // In test mode we need to maintain the original values so we can - // reset it. - defer func(out, err *os.File) { - os.Stdout = out - os.Stderr = err - }(os.Stdout, os.Stderr) - } - os.Stdout = stdout_w - os.Stderr = stderr_w - } - - // Accept connections and wait for completion - go server.Serve(listener) - - ctx := context.Background() - if opts.Test != nil && opts.Test.Context != nil { - ctx = opts.Test.Context - } - select { - case <-ctx.Done(): - // Cancellation. We can stop the server by closing the listener. - // This isn't graceful at all but this is currently only used by - // tests and its our only way to stop. - listener.Close() - - // If this is a grpc server, then we also ask the server itself to - // end which will kill all connections. There isn't an easy way to do - // this for net/rpc currently but net/rpc is more and more unused. - if s, ok := server.(*GRPCServer); ok { - s.Stop() - } - - // Wait for the server itself to shut down - <-doneCh - - case <-doneCh: - // Note that given the documentation of Serve we should probably be - // setting exitCode = 0 and using os.Exit here. That's how it used to - // work before extracting this library. However, for years we've done - // this so we'll keep this functionality. - } -} - -func serverListener() (net.Listener, error) { - if runtime.GOOS == "windows" { - return serverListener_tcp() - } - - return serverListener_unix() -} - -func serverListener_tcp() (net.Listener, error) { - envMinPort := os.Getenv("PLUGIN_MIN_PORT") - envMaxPort := os.Getenv("PLUGIN_MAX_PORT") - - var minPort, maxPort int64 - var err error - - switch { - case len(envMinPort) == 0: - minPort = 0 - default: - minPort, err = strconv.ParseInt(envMinPort, 10, 32) - if err != nil { - return nil, fmt.Errorf("Couldn't get value from PLUGIN_MIN_PORT: %v", err) - } - } - - switch { - case len(envMaxPort) == 0: - maxPort = 0 - default: - maxPort, err = strconv.ParseInt(envMaxPort, 10, 32) - if err != nil { - return nil, fmt.Errorf("Couldn't get value from PLUGIN_MAX_PORT: %v", err) - } - } - - if minPort > maxPort { - return nil, fmt.Errorf("PLUGIN_MIN_PORT value of %d is greater than PLUGIN_MAX_PORT value of %d", minPort, maxPort) - } - - for port := minPort; port <= maxPort; port++ { - address := fmt.Sprintf("127.0.0.1:%d", port) - listener, err := net.Listen("tcp", address) - if err == nil { - return listener, nil - } - } - - return nil, errors.New("Couldn't bind plugin TCP listener") -} - -func serverListener_unix() (net.Listener, error) { - tf, err := ioutil.TempFile("", "plugin") - if err != nil { - return nil, err - } - path := tf.Name() - - // Close the file and remove it because it has to not exist for - // the domain socket. - if err := tf.Close(); err != nil { - return nil, err - } - if err := os.Remove(path); err != nil { - return nil, err - } - - l, err := net.Listen("unix", path) - if err != nil { - return nil, err - } - - // Wrap the listener in rmListener so that the Unix domain socket file - // is removed on close. - return &rmListener{ - Listener: l, - Path: path, - }, nil -} - -// rmListener is an implementation of net.Listener that forwards most -// calls to the listener but also removes a file as part of the close. We -// use this to cleanup the unix domain socket on close. -type rmListener struct { - net.Listener - Path string -} - -func (l *rmListener) Close() error { - // Close the listener itself - if err := l.Listener.Close(); err != nil { - return err - } - - // Remove the file - return os.Remove(l.Path) -} diff --git a/vendor/github.com/hashicorp/go-plugin/server_mux.go b/vendor/github.com/hashicorp/go-plugin/server_mux.go deleted file mode 100644 index 033079ea0..000000000 --- a/vendor/github.com/hashicorp/go-plugin/server_mux.go +++ /dev/null @@ -1,31 +0,0 @@ -package plugin - -import ( - "fmt" - "os" -) - -// ServeMuxMap is the type that is used to configure ServeMux -type ServeMuxMap map[string]*ServeConfig - -// ServeMux is like Serve, but serves multiple types of plugins determined -// by the argument given on the command-line. -// -// This command doesn't return until the plugin is done being executed. Any -// errors are logged or output to stderr. -func ServeMux(m ServeMuxMap) { - if len(os.Args) != 2 { - fmt.Fprintf(os.Stderr, - "Invoked improperly. This is an internal command that shouldn't\n"+ - "be manually invoked.\n") - os.Exit(1) - } - - opts, ok := m[os.Args[1]] - if !ok { - fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1]) - os.Exit(1) - } - - Serve(opts) -} diff --git a/vendor/github.com/hashicorp/go-plugin/stream.go b/vendor/github.com/hashicorp/go-plugin/stream.go deleted file mode 100644 index 1d547aaaa..000000000 --- a/vendor/github.com/hashicorp/go-plugin/stream.go +++ /dev/null @@ -1,18 +0,0 @@ -package plugin - -import ( - "io" - "log" -) - -func copyStream(name string, dst io.Writer, src io.Reader) { - if src == nil { - panic(name + ": src is nil") - } - if dst == nil { - panic(name + ": dst is nil") - } - if _, err := io.Copy(dst, src); err != nil && err != io.EOF { - log.Printf("[ERR] plugin: stream copy '%s' error: %s", name, err) - } -} diff --git a/vendor/github.com/hashicorp/go-plugin/testing.go b/vendor/github.com/hashicorp/go-plugin/testing.go deleted file mode 100644 index e36f2eb2b..000000000 --- a/vendor/github.com/hashicorp/go-plugin/testing.go +++ /dev/null @@ -1,180 +0,0 @@ -package plugin - -import ( - "bytes" - "context" - "io" - "net" - "net/rpc" - - hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin/internal/plugin" - "github.com/mitchellh/go-testing-interface" - "google.golang.org/grpc" -) - -// TestOptions allows specifying options that can affect the behavior of the -// test functions -type TestOptions struct { - //ServerStdout causes the given value to be used in place of a blank buffer - //for RPCServer's Stdout - ServerStdout io.ReadCloser - - //ServerStderr causes the given value to be used in place of a blank buffer - //for RPCServer's Stderr - ServerStderr io.ReadCloser -} - -// The testing file contains test helpers that you can use outside of -// this package for making it easier to test plugins themselves. - -// TestConn is a helper function for returning a client and server -// net.Conn connected to each other. -func TestConn(t testing.T) (net.Conn, net.Conn) { - // Listen to any local port. This listener will be closed - // after a single connection is established. - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %s", err) - } - - // Start a goroutine to accept our client connection - var serverConn net.Conn - doneCh := make(chan struct{}) - go func() { - defer close(doneCh) - defer l.Close() - var err error - serverConn, err = l.Accept() - if err != nil { - t.Fatalf("err: %s", err) - } - }() - - // Connect to the server - clientConn, err := net.Dial("tcp", l.Addr().String()) - if err != nil { - t.Fatalf("err: %s", err) - } - - // Wait for the server side to acknowledge it has connected - <-doneCh - - return clientConn, serverConn -} - -// TestRPCConn returns a rpc client and server connected to each other. -func TestRPCConn(t testing.T) (*rpc.Client, *rpc.Server) { - clientConn, serverConn := TestConn(t) - - server := rpc.NewServer() - go server.ServeConn(serverConn) - - client := rpc.NewClient(clientConn) - return client, server -} - -// TestPluginRPCConn returns a plugin RPC client and server that are connected -// together and configured. -func TestPluginRPCConn(t testing.T, ps map[string]Plugin, opts *TestOptions) (*RPCClient, *RPCServer) { - // Create two net.Conns we can use to shuttle our control connection - clientConn, serverConn := TestConn(t) - - // Start up the server - server := &RPCServer{Plugins: ps, Stdout: new(bytes.Buffer), Stderr: new(bytes.Buffer)} - if opts != nil { - if opts.ServerStdout != nil { - server.Stdout = opts.ServerStdout - } - if opts.ServerStderr != nil { - server.Stderr = opts.ServerStderr - } - } - go server.ServeConn(serverConn) - - // Connect the client to the server - client, err := NewRPCClient(clientConn, ps) - if err != nil { - t.Fatalf("err: %s", err) - } - - return client, server -} - -// TestGRPCConn returns a gRPC client conn and grpc server that are connected -// together and configured. The register function is used to register services -// prior to the Serve call. This is used to test gRPC connections. -func TestGRPCConn(t testing.T, register func(*grpc.Server)) (*grpc.ClientConn, *grpc.Server) { - // Create a listener - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %s", err) - } - - server := grpc.NewServer() - register(server) - go server.Serve(l) - - // Connect to the server - conn, err := grpc.Dial( - l.Addr().String(), - grpc.WithBlock(), - grpc.WithInsecure()) - if err != nil { - t.Fatalf("err: %s", err) - } - - // Connection successful, close the listener - l.Close() - - return conn, server -} - -// TestPluginGRPCConn returns a plugin gRPC client and server that are connected -// together and configured. This is used to test gRPC connections. -func TestPluginGRPCConn(t testing.T, ps map[string]Plugin) (*GRPCClient, *GRPCServer) { - // Create a listener - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %s", err) - } - - // Start up the server - server := &GRPCServer{ - Plugins: ps, - DoneCh: make(chan struct{}), - Server: DefaultGRPCServer, - Stdout: new(bytes.Buffer), - Stderr: new(bytes.Buffer), - logger: hclog.Default(), - } - if err := server.Init(); err != nil { - t.Fatalf("err: %s", err) - } - go server.Serve(l) - - // Connect to the server - conn, err := grpc.Dial( - l.Addr().String(), - grpc.WithBlock(), - grpc.WithInsecure()) - if err != nil { - t.Fatalf("err: %s", err) - } - - brokerGRPCClient := newGRPCBrokerClient(conn) - broker := newGRPCBroker(brokerGRPCClient, nil) - go broker.Run() - go brokerGRPCClient.StartStream() - - // Create the client - client := &GRPCClient{ - Conn: conn, - Plugins: ps, - broker: broker, - doneCtx: context.Background(), - controller: plugin.NewGRPCControllerClient(conn), - } - - return client, server -} diff --git a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/LICENSE b/vendor/github.com/hashicorp/go-secure-stdlib/mlock/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock.go b/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock.go deleted file mode 100644 index 1675633d3..000000000 --- a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock.go +++ /dev/null @@ -1,15 +0,0 @@ -package mlock - -// This should be set by the OS-specific packages to tell whether LockMemory -// is supported or not. -var supported bool - -// Supported returns true if LockMemory is functional on this system. -func Supported() bool { - return supported -} - -// LockMemory prevents any memory from being swapped to disk. -func LockMemory() error { - return lockMemory() -} diff --git a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unavail.go b/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unavail.go deleted file mode 100644 index 941eb2d7b..000000000 --- a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unavail.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build darwin nacl netbsd plan9 windows - -package mlock - -func init() { - supported = false -} - -func lockMemory() error { - // XXX: No good way to do this on Windows. There is the VirtualLock - // method, but it requires a specific address and offset. - return nil -} diff --git a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unix.go b/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unix.go deleted file mode 100644 index af0a69d48..000000000 --- a/vendor/github.com/hashicorp/go-secure-stdlib/mlock/mlock_unix.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build dragonfly freebsd linux openbsd solaris - -package mlock - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -func init() { - supported = true -} - -func lockMemory() error { - // Mlockall prevents all current and future pages from being swapped out. - return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) -} diff --git a/vendor/github.com/hashicorp/go-uuid/.travis.yml b/vendor/github.com/hashicorp/go-uuid/.travis.yml deleted file mode 100644 index 769849071..000000000 --- a/vendor/github.com/hashicorp/go-uuid/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go - -sudo: false - -go: - - 1.4 - - 1.5 - - 1.6 - - tip - -script: - - go test -bench . -benchmem -v ./... diff --git a/vendor/github.com/hashicorp/go-uuid/LICENSE b/vendor/github.com/hashicorp/go-uuid/LICENSE deleted file mode 100644 index a320b309c..000000000 --- a/vendor/github.com/hashicorp/go-uuid/LICENSE +++ /dev/null @@ -1,365 +0,0 @@ -Copyright © 2015-2022 HashiCorp, Inc. - -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-uuid/README.md b/vendor/github.com/hashicorp/go-uuid/README.md deleted file mode 100644 index fbde8b9ae..000000000 --- a/vendor/github.com/hashicorp/go-uuid/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# uuid [![Build Status](https://travis-ci.org/hashicorp/go-uuid.svg?branch=master)](https://travis-ci.org/hashicorp/go-uuid) - -Generates UUID-format strings using high quality, _purely random_ bytes. It is **not** intended to be RFC compliant, merely to use a well-understood string representation of a 128-bit value. It can also parse UUID-format strings into their component bytes. - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-uuid). diff --git a/vendor/github.com/hashicorp/go-uuid/uuid.go b/vendor/github.com/hashicorp/go-uuid/uuid.go deleted file mode 100644 index 0c10c4e9f..000000000 --- a/vendor/github.com/hashicorp/go-uuid/uuid.go +++ /dev/null @@ -1,83 +0,0 @@ -package uuid - -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "io" -) - -// GenerateRandomBytes is used to generate random bytes of given size. -func GenerateRandomBytes(size int) ([]byte, error) { - return GenerateRandomBytesWithReader(size, rand.Reader) -} - -// GenerateRandomBytesWithReader is used to generate random bytes of given size read from a given reader. -func GenerateRandomBytesWithReader(size int, reader io.Reader) ([]byte, error) { - if reader == nil { - return nil, fmt.Errorf("provided reader is nil") - } - buf := make([]byte, size) - if _, err := io.ReadFull(reader, buf); err != nil { - return nil, fmt.Errorf("failed to read random bytes: %v", err) - } - return buf, nil -} - - -const uuidLen = 16 - -// GenerateUUID is used to generate a random UUID -func GenerateUUID() (string, error) { - return GenerateUUIDWithReader(rand.Reader) -} - -// GenerateUUIDWithReader is used to generate a random UUID with a given Reader -func GenerateUUIDWithReader(reader io.Reader) (string, error) { - if reader == nil { - return "", fmt.Errorf("provided reader is nil") - } - buf, err := GenerateRandomBytesWithReader(uuidLen, reader) - if err != nil { - return "", err - } - return FormatUUID(buf) -} - -func FormatUUID(buf []byte) (string, error) { - if buflen := len(buf); buflen != uuidLen { - return "", fmt.Errorf("wrong length byte slice (%d)", buflen) - } - - return fmt.Sprintf("%x-%x-%x-%x-%x", - buf[0:4], - buf[4:6], - buf[6:8], - buf[8:10], - buf[10:16]), nil -} - -func ParseUUID(uuid string) ([]byte, error) { - if len(uuid) != 2 * uuidLen + 4 { - return nil, fmt.Errorf("uuid string is wrong length") - } - - if uuid[8] != '-' || - uuid[13] != '-' || - uuid[18] != '-' || - uuid[23] != '-' { - return nil, fmt.Errorf("uuid is improperly formatted") - } - - hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36] - - ret, err := hex.DecodeString(hexStr) - if err != nil { - return nil, err - } - if len(ret) != uuidLen { - return nil, fmt.Errorf("decoded hex is the wrong length") - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/vendor/github.com/hashicorp/go-version/CHANGELOG.md deleted file mode 100644 index 5f16dd140..000000000 --- a/vendor/github.com/hashicorp/go-version/CHANGELOG.md +++ /dev/null @@ -1,45 +0,0 @@ -# 1.6.0 (June 28, 2022) - -FEATURES: - -- Add `Prerelease` function to `Constraint` to return true if the version includes a prerelease field ([#100](https://github.com/hashicorp/go-version/pull/100)) - -# 1.5.0 (May 18, 2022) - -FEATURES: - -- Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents ([#95](https://github.com/hashicorp/go-version/pull/95)) -- Add JSON handlers to allow parsing from/to JSON ([#93](https://github.com/hashicorp/go-version/pull/93)) - -# 1.4.0 (January 5, 2022) - -FEATURES: - - - Introduce `MustConstraints()` ([#87](https://github.com/hashicorp/go-version/pull/87)) - - `Constraints`: Introduce `Equals()` and `sort.Interface` methods ([#88](https://github.com/hashicorp/go-version/pull/88)) - -# 1.3.0 (March 31, 2021) - -Please note that CHANGELOG.md does not exist in the source code prior to this release. - -FEATURES: - - Add `Core` function to return a version without prerelease or metadata ([#85](https://github.com/hashicorp/go-version/pull/85)) - -# 1.2.1 (June 17, 2020) - -BUG FIXES: - - Prevent `Version.Equal` method from panicking on `nil` encounter ([#73](https://github.com/hashicorp/go-version/pull/73)) - -# 1.2.0 (April 23, 2019) - -FEATURES: - - Add `GreaterThanOrEqual` and `LessThanOrEqual` helper methods ([#53](https://github.com/hashicorp/go-version/pull/53)) - -# 1.1.0 (Jan 07, 2019) - -FEATURES: - - Add `NewSemver` constructor ([#45](https://github.com/hashicorp/go-version/pull/45)) - -# 1.0.0 (August 24, 2018) - -Initial release. diff --git a/vendor/github.com/hashicorp/go-version/LICENSE b/vendor/github.com/hashicorp/go-version/LICENSE deleted file mode 100644 index c33dcc7c9..000000000 --- a/vendor/github.com/hashicorp/go-version/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md deleted file mode 100644 index 4d2505090..000000000 --- a/vendor/github.com/hashicorp/go-version/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# Versioning Library for Go -[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) -[![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) - -go-version is a library for parsing versions and version constraints, -and verifying versions against a set of constraints. go-version -can sort a collection of versions properly, handles prerelease/beta -versions, can increment versions, etc. - -Versions used with go-version must follow [SemVer](http://semver.org/). - -## Installation and Usage - -Package documentation can be found on -[GoDoc](http://godoc.org/github.com/hashicorp/go-version). - -Installation can be done with a normal `go get`: - -``` -$ go get github.com/hashicorp/go-version -``` - -#### Version Parsing and Comparison - -```go -v1, err := version.NewVersion("1.2") -v2, err := version.NewVersion("1.5+metadata") - -// Comparison example. There is also GreaterThan, Equal, and just -// a simple Compare that returns an int allowing easy >=, <=, etc. -if v1.LessThan(v2) { - fmt.Printf("%s is less than %s", v1, v2) -} -``` - -#### Version Constraints - -```go -v1, err := version.NewVersion("1.2") - -// Constraints example. -constraints, err := version.NewConstraint(">= 1.0, < 1.4") -if constraints.Check(v1) { - fmt.Printf("%s satisfies constraints %s", v1, constraints) -} -``` - -#### Version Sorting - -```go -versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"} -versions := make([]*version.Version, len(versionsRaw)) -for i, raw := range versionsRaw { - v, _ := version.NewVersion(raw) - versions[i] = v -} - -// After this, the versions are properly sorted -sort.Sort(version.Collection(versions)) -``` - -## Issues and Contributing - -If you find an issue with this library, please report an issue. If you'd -like, we welcome any contributions. Fork this library and submit a pull -request. diff --git a/vendor/github.com/hashicorp/go-version/constraint.go b/vendor/github.com/hashicorp/go-version/constraint.go deleted file mode 100644 index da5d1aca1..000000000 --- a/vendor/github.com/hashicorp/go-version/constraint.go +++ /dev/null @@ -1,296 +0,0 @@ -package version - -import ( - "fmt" - "reflect" - "regexp" - "sort" - "strings" -) - -// Constraint represents a single constraint for a version, such as -// ">= 1.0". -type Constraint struct { - f constraintFunc - op operator - check *Version - original string -} - -func (c *Constraint) Equals(con *Constraint) bool { - return c.op == con.op && c.check.Equal(con.check) -} - -// Constraints is a slice of constraints. We make a custom type so that -// we can add methods to it. -type Constraints []*Constraint - -type constraintFunc func(v, c *Version) bool - -var constraintOperators map[string]constraintOperation - -type constraintOperation struct { - op operator - f constraintFunc -} - -var constraintRegexp *regexp.Regexp - -func init() { - constraintOperators = map[string]constraintOperation{ - "": {op: equal, f: constraintEqual}, - "=": {op: equal, f: constraintEqual}, - "!=": {op: notEqual, f: constraintNotEqual}, - ">": {op: greaterThan, f: constraintGreaterThan}, - "<": {op: lessThan, f: constraintLessThan}, - ">=": {op: greaterThanEqual, f: constraintGreaterThanEqual}, - "<=": {op: lessThanEqual, f: constraintLessThanEqual}, - "~>": {op: pessimistic, f: constraintPessimistic}, - } - - ops := make([]string, 0, len(constraintOperators)) - for k := range constraintOperators { - ops = append(ops, regexp.QuoteMeta(k)) - } - - constraintRegexp = regexp.MustCompile(fmt.Sprintf( - `^\s*(%s)\s*(%s)\s*$`, - strings.Join(ops, "|"), - VersionRegexpRaw)) -} - -// NewConstraint will parse one or more constraints from the given -// constraint string. The string must be a comma-separated list of -// constraints. -func NewConstraint(v string) (Constraints, error) { - vs := strings.Split(v, ",") - result := make([]*Constraint, len(vs)) - for i, single := range vs { - c, err := parseSingle(single) - if err != nil { - return nil, err - } - - result[i] = c - } - - return Constraints(result), nil -} - -// MustConstraints is a helper that wraps a call to a function -// returning (Constraints, error) and panics if error is non-nil. -func MustConstraints(c Constraints, err error) Constraints { - if err != nil { - panic(err) - } - - return c -} - -// Check tests if a version satisfies all the constraints. -func (cs Constraints) Check(v *Version) bool { - for _, c := range cs { - if !c.Check(v) { - return false - } - } - - return true -} - -// Equals compares Constraints with other Constraints -// for equality. This may not represent logical equivalence -// of compared constraints. -// e.g. even though '>0.1,>0.2' is logically equivalent -// to '>0.2' it is *NOT* treated as equal. -// -// Missing operator is treated as equal to '=', whitespaces -// are ignored and constraints are sorted before comaparison. -func (cs Constraints) Equals(c Constraints) bool { - if len(cs) != len(c) { - return false - } - - // make copies to retain order of the original slices - left := make(Constraints, len(cs)) - copy(left, cs) - sort.Stable(left) - right := make(Constraints, len(c)) - copy(right, c) - sort.Stable(right) - - // compare sorted slices - for i, con := range left { - if !con.Equals(right[i]) { - return false - } - } - - return true -} - -func (cs Constraints) Len() int { - return len(cs) -} - -func (cs Constraints) Less(i, j int) bool { - if cs[i].op < cs[j].op { - return true - } - if cs[i].op > cs[j].op { - return false - } - - return cs[i].check.LessThan(cs[j].check) -} - -func (cs Constraints) Swap(i, j int) { - cs[i], cs[j] = cs[j], cs[i] -} - -// Returns the string format of the constraints -func (cs Constraints) String() string { - csStr := make([]string, len(cs)) - for i, c := range cs { - csStr[i] = c.String() - } - - return strings.Join(csStr, ",") -} - -// Check tests if a constraint is validated by the given version. -func (c *Constraint) Check(v *Version) bool { - return c.f(v, c.check) -} - -// Prerelease returns true if the version underlying this constraint -// contains a prerelease field. -func (c *Constraint) Prerelease() bool { - return len(c.check.Prerelease()) > 0 -} - -func (c *Constraint) String() string { - return c.original -} - -func parseSingle(v string) (*Constraint, error) { - matches := constraintRegexp.FindStringSubmatch(v) - if matches == nil { - return nil, fmt.Errorf("Malformed constraint: %s", v) - } - - check, err := NewVersion(matches[2]) - if err != nil { - return nil, err - } - - cop := constraintOperators[matches[1]] - - return &Constraint{ - f: cop.f, - op: cop.op, - check: check, - original: v, - }, nil -} - -func prereleaseCheck(v, c *Version) bool { - switch vPre, cPre := v.Prerelease() != "", c.Prerelease() != ""; { - case cPre && vPre: - // A constraint with a pre-release can only match a pre-release version - // with the same base segments. - return reflect.DeepEqual(c.Segments64(), v.Segments64()) - - case !cPre && vPre: - // A constraint without a pre-release can only match a version without a - // pre-release. - return false - - case cPre && !vPre: - // OK, except with the pessimistic operator - case !cPre && !vPre: - // OK - } - return true -} - -//------------------------------------------------------------------- -// Constraint functions -//------------------------------------------------------------------- - -type operator rune - -const ( - equal operator = '=' - notEqual operator = '≠' - greaterThan operator = '>' - lessThan operator = '<' - greaterThanEqual operator = '≥' - lessThanEqual operator = '≤' - pessimistic operator = '~' -) - -func constraintEqual(v, c *Version) bool { - return v.Equal(c) -} - -func constraintNotEqual(v, c *Version) bool { - return !v.Equal(c) -} - -func constraintGreaterThan(v, c *Version) bool { - return prereleaseCheck(v, c) && v.Compare(c) == 1 -} - -func constraintLessThan(v, c *Version) bool { - return prereleaseCheck(v, c) && v.Compare(c) == -1 -} - -func constraintGreaterThanEqual(v, c *Version) bool { - return prereleaseCheck(v, c) && v.Compare(c) >= 0 -} - -func constraintLessThanEqual(v, c *Version) bool { - return prereleaseCheck(v, c) && v.Compare(c) <= 0 -} - -func constraintPessimistic(v, c *Version) bool { - // Using a pessimistic constraint with a pre-release, restricts versions to pre-releases - if !prereleaseCheck(v, c) || (c.Prerelease() != "" && v.Prerelease() == "") { - return false - } - - // If the version being checked is naturally less than the constraint, then there - // is no way for the version to be valid against the constraint - if v.LessThan(c) { - return false - } - // We'll use this more than once, so grab the length now so it's a little cleaner - // to write the later checks - cs := len(c.segments) - - // If the version being checked has less specificity than the constraint, then there - // is no way for the version to be valid against the constraint - if cs > len(v.segments) { - return false - } - - // Check the segments in the constraint against those in the version. If the version - // being checked, at any point, does not have the same values in each index of the - // constraints segments, then it cannot be valid against the constraint. - for i := 0; i < c.si-1; i++ { - if v.segments[i] != c.segments[i] { - return false - } - } - - // Check the last part of the segment in the constraint. If the version segment at - // this index is less than the constraints segment at this index, then it cannot - // be valid against the constraint - if c.segments[cs-1] > v.segments[cs-1] { - return false - } - - // If nothing has rejected the version by now, it's valid - return true -} diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go deleted file mode 100644 index e87df6990..000000000 --- a/vendor/github.com/hashicorp/go-version/version.go +++ /dev/null @@ -1,407 +0,0 @@ -package version - -import ( - "bytes" - "fmt" - "reflect" - "regexp" - "strconv" - "strings" -) - -// The compiled regular expression used to test the validity of a version. -var ( - versionRegexp *regexp.Regexp - semverRegexp *regexp.Regexp -) - -// The raw regular expression string used for testing the validity -// of a version. -const ( - VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + - `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-?([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + - `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + - `?` - - // SemverRegexpRaw requires a separator between version and prerelease - SemverRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + - `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + - `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + - `?` -) - -// Version represents a single version. -type Version struct { - metadata string - pre string - segments []int64 - si int - original string -} - -func init() { - versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$") - semverRegexp = regexp.MustCompile("^" + SemverRegexpRaw + "$") -} - -// NewVersion parses the given version and returns a new -// Version. -func NewVersion(v string) (*Version, error) { - return newVersion(v, versionRegexp) -} - -// NewSemver parses the given version and returns a new -// Version that adheres strictly to SemVer specs -// https://semver.org/ -func NewSemver(v string) (*Version, error) { - return newVersion(v, semverRegexp) -} - -func newVersion(v string, pattern *regexp.Regexp) (*Version, error) { - matches := pattern.FindStringSubmatch(v) - if matches == nil { - return nil, fmt.Errorf("Malformed version: %s", v) - } - segmentsStr := strings.Split(matches[1], ".") - segments := make([]int64, len(segmentsStr)) - for i, str := range segmentsStr { - val, err := strconv.ParseInt(str, 10, 64) - if err != nil { - return nil, fmt.Errorf( - "Error parsing version: %s", err) - } - - segments[i] = val - } - - // Even though we could support more than three segments, if we - // got less than three, pad it with 0s. This is to cover the basic - // default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum - for i := len(segments); i < 3; i++ { - segments = append(segments, 0) - } - - pre := matches[7] - if pre == "" { - pre = matches[4] - } - - return &Version{ - metadata: matches[10], - pre: pre, - segments: segments, - si: len(segmentsStr), - original: v, - }, nil -} - -// Must is a helper that wraps a call to a function returning (*Version, error) -// and panics if error is non-nil. -func Must(v *Version, err error) *Version { - if err != nil { - panic(err) - } - - return v -} - -// Compare compares this version to another version. This -// returns -1, 0, or 1 if this version is smaller, equal, -// or larger than the other version, respectively. -// -// If you want boolean results, use the LessThan, Equal, -// GreaterThan, GreaterThanOrEqual or LessThanOrEqual methods. -func (v *Version) Compare(other *Version) int { - // A quick, efficient equality check - if v.String() == other.String() { - return 0 - } - - segmentsSelf := v.Segments64() - segmentsOther := other.Segments64() - - // If the segments are the same, we must compare on prerelease info - if reflect.DeepEqual(segmentsSelf, segmentsOther) { - preSelf := v.Prerelease() - preOther := other.Prerelease() - if preSelf == "" && preOther == "" { - return 0 - } - if preSelf == "" { - return 1 - } - if preOther == "" { - return -1 - } - - return comparePrereleases(preSelf, preOther) - } - - // Get the highest specificity (hS), or if they're equal, just use segmentSelf length - lenSelf := len(segmentsSelf) - lenOther := len(segmentsOther) - hS := lenSelf - if lenSelf < lenOther { - hS = lenOther - } - // Compare the segments - // Because a constraint could have more/less specificity than the version it's - // checking, we need to account for a lopsided or jagged comparison - for i := 0; i < hS; i++ { - if i > lenSelf-1 { - // This means Self had the lower specificity - // Check to see if the remaining segments in Other are all zeros - if !allZero(segmentsOther[i:]) { - // if not, it means that Other has to be greater than Self - return -1 - } - break - } else if i > lenOther-1 { - // this means Other had the lower specificity - // Check to see if the remaining segments in Self are all zeros - - if !allZero(segmentsSelf[i:]) { - //if not, it means that Self has to be greater than Other - return 1 - } - break - } - lhs := segmentsSelf[i] - rhs := segmentsOther[i] - if lhs == rhs { - continue - } else if lhs < rhs { - return -1 - } - // Otherwis, rhs was > lhs, they're not equal - return 1 - } - - // if we got this far, they're equal - return 0 -} - -func allZero(segs []int64) bool { - for _, s := range segs { - if s != 0 { - return false - } - } - return true -} - -func comparePart(preSelf string, preOther string) int { - if preSelf == preOther { - return 0 - } - - var selfInt int64 - selfNumeric := true - selfInt, err := strconv.ParseInt(preSelf, 10, 64) - if err != nil { - selfNumeric = false - } - - var otherInt int64 - otherNumeric := true - otherInt, err = strconv.ParseInt(preOther, 10, 64) - if err != nil { - otherNumeric = false - } - - // if a part is empty, we use the other to decide - if preSelf == "" { - if otherNumeric { - return -1 - } - return 1 - } - - if preOther == "" { - if selfNumeric { - return 1 - } - return -1 - } - - if selfNumeric && !otherNumeric { - return -1 - } else if !selfNumeric && otherNumeric { - return 1 - } else if !selfNumeric && !otherNumeric && preSelf > preOther { - return 1 - } else if selfInt > otherInt { - return 1 - } - - return -1 -} - -func comparePrereleases(v string, other string) int { - // the same pre release! - if v == other { - return 0 - } - - // split both pre releases for analyse their parts - selfPreReleaseMeta := strings.Split(v, ".") - otherPreReleaseMeta := strings.Split(other, ".") - - selfPreReleaseLen := len(selfPreReleaseMeta) - otherPreReleaseLen := len(otherPreReleaseMeta) - - biggestLen := otherPreReleaseLen - if selfPreReleaseLen > otherPreReleaseLen { - biggestLen = selfPreReleaseLen - } - - // loop for parts to find the first difference - for i := 0; i < biggestLen; i = i + 1 { - partSelfPre := "" - if i < selfPreReleaseLen { - partSelfPre = selfPreReleaseMeta[i] - } - - partOtherPre := "" - if i < otherPreReleaseLen { - partOtherPre = otherPreReleaseMeta[i] - } - - compare := comparePart(partSelfPre, partOtherPre) - // if parts are equals, continue the loop - if compare != 0 { - return compare - } - } - - return 0 -} - -// Core returns a new version constructed from only the MAJOR.MINOR.PATCH -// segments of the version, without prerelease or metadata. -func (v *Version) Core() *Version { - segments := v.Segments64() - segmentsOnly := fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2]) - return Must(NewVersion(segmentsOnly)) -} - -// Equal tests if two versions are equal. -func (v *Version) Equal(o *Version) bool { - if v == nil || o == nil { - return v == o - } - - return v.Compare(o) == 0 -} - -// GreaterThan tests if this version is greater than another version. -func (v *Version) GreaterThan(o *Version) bool { - return v.Compare(o) > 0 -} - -// GreaterThanOrEqual tests if this version is greater than or equal to another version. -func (v *Version) GreaterThanOrEqual(o *Version) bool { - return v.Compare(o) >= 0 -} - -// LessThan tests if this version is less than another version. -func (v *Version) LessThan(o *Version) bool { - return v.Compare(o) < 0 -} - -// LessThanOrEqual tests if this version is less than or equal to another version. -func (v *Version) LessThanOrEqual(o *Version) bool { - return v.Compare(o) <= 0 -} - -// Metadata returns any metadata that was part of the version -// string. -// -// Metadata is anything that comes after the "+" in the version. -// For example, with "1.2.3+beta", the metadata is "beta". -func (v *Version) Metadata() string { - return v.metadata -} - -// Prerelease returns any prerelease data that is part of the version, -// or blank if there is no prerelease data. -// -// Prerelease information is anything that comes after the "-" in the -// version (but before any metadata). For example, with "1.2.3-beta", -// the prerelease information is "beta". -func (v *Version) Prerelease() string { - return v.pre -} - -// Segments returns the numeric segments of the version as a slice of ints. -// -// This excludes any metadata or pre-release information. For example, -// for a version "1.2.3-beta", segments will return a slice of -// 1, 2, 3. -func (v *Version) Segments() []int { - segmentSlice := make([]int, len(v.segments)) - for i, v := range v.segments { - segmentSlice[i] = int(v) - } - return segmentSlice -} - -// Segments64 returns the numeric segments of the version as a slice of int64s. -// -// This excludes any metadata or pre-release information. For example, -// for a version "1.2.3-beta", segments will return a slice of -// 1, 2, 3. -func (v *Version) Segments64() []int64 { - result := make([]int64, len(v.segments)) - copy(result, v.segments) - return result -} - -// String returns the full version string included pre-release -// and metadata information. -// -// This value is rebuilt according to the parsed segments and other -// information. Therefore, ambiguities in the version string such as -// prefixed zeroes (1.04.0 => 1.4.0), `v` prefix (v1.0.0 => 1.0.0), and -// missing parts (1.0 => 1.0.0) will be made into a canonicalized form -// as shown in the parenthesized examples. -func (v *Version) String() string { - var buf bytes.Buffer - fmtParts := make([]string, len(v.segments)) - for i, s := range v.segments { - // We can ignore err here since we've pre-parsed the values in segments - str := strconv.FormatInt(s, 10) - fmtParts[i] = str - } - fmt.Fprintf(&buf, strings.Join(fmtParts, ".")) - if v.pre != "" { - fmt.Fprintf(&buf, "-%s", v.pre) - } - if v.metadata != "" { - fmt.Fprintf(&buf, "+%s", v.metadata) - } - - return buf.String() -} - -// Original returns the original parsed version as-is, including any -// potential whitespace, `v` prefix, etc. -func (v *Version) Original() string { - return v.original -} - -// UnmarshalText implements encoding.TextUnmarshaler interface. -func (v *Version) UnmarshalText(b []byte) error { - temp, err := NewVersion(string(b)) - if err != nil { - return err - } - - *v = *temp - - return nil -} - -// MarshalText implements encoding.TextMarshaler interface. -func (v *Version) MarshalText() ([]byte, error) { - return []byte(v.String()), nil -} diff --git a/vendor/github.com/hashicorp/go-version/version_collection.go b/vendor/github.com/hashicorp/go-version/version_collection.go deleted file mode 100644 index cc888d43e..000000000 --- a/vendor/github.com/hashicorp/go-version/version_collection.go +++ /dev/null @@ -1,17 +0,0 @@ -package version - -// Collection is a type that implements the sort.Interface interface -// so that versions can be sorted. -type Collection []*Version - -func (v Collection) Len() int { - return len(v) -} - -func (v Collection) Less(i, j int) bool { - return v[i].LessThan(v[j]) -} - -func (v Collection) Swap(i, j int) { - v[i], v[j] = v[j], v[i] -} diff --git a/vendor/github.com/hashicorp/golang-lru/.gitignore b/vendor/github.com/hashicorp/golang-lru/.gitignore deleted file mode 100644 index 836562412..000000000 --- a/vendor/github.com/hashicorp/golang-lru/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test diff --git a/vendor/github.com/hashicorp/golang-lru/2q.go b/vendor/github.com/hashicorp/golang-lru/2q.go deleted file mode 100644 index e474cd075..000000000 --- a/vendor/github.com/hashicorp/golang-lru/2q.go +++ /dev/null @@ -1,223 +0,0 @@ -package lru - -import ( - "fmt" - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -const ( - // Default2QRecentRatio is the ratio of the 2Q cache dedicated - // to recently added entries that have only been accessed once. - Default2QRecentRatio = 0.25 - - // Default2QGhostEntries is the default ratio of ghost - // entries kept to track entries recently evicted - Default2QGhostEntries = 0.50 -) - -// TwoQueueCache is a thread-safe fixed size 2Q cache. -// 2Q is an enhancement over the standard LRU cache -// in that it tracks both frequently and recently used -// entries separately. This avoids a burst in access to new -// entries from evicting frequently used entries. It adds some -// additional tracking overhead to the standard LRU cache, and is -// computationally about 2x the cost, and adds some metadata over -// head. The ARCCache is similar, but does not require setting any -// parameters. -type TwoQueueCache struct { - size int - recentSize int - - recent simplelru.LRUCache - frequent simplelru.LRUCache - recentEvict simplelru.LRUCache - lock sync.RWMutex -} - -// New2Q creates a new TwoQueueCache using the default -// values for the parameters. -func New2Q(size int) (*TwoQueueCache, error) { - return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries) -} - -// New2QParams creates a new TwoQueueCache using the provided -// parameter values. -func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) { - if size <= 0 { - return nil, fmt.Errorf("invalid size") - } - if recentRatio < 0.0 || recentRatio > 1.0 { - return nil, fmt.Errorf("invalid recent ratio") - } - if ghostRatio < 0.0 || ghostRatio > 1.0 { - return nil, fmt.Errorf("invalid ghost ratio") - } - - // Determine the sub-sizes - recentSize := int(float64(size) * recentRatio) - evictSize := int(float64(size) * ghostRatio) - - // Allocate the LRUs - recent, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - frequent, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - recentEvict, err := simplelru.NewLRU(evictSize, nil) - if err != nil { - return nil, err - } - - // Initialize the cache - c := &TwoQueueCache{ - size: size, - recentSize: recentSize, - recent: recent, - frequent: frequent, - recentEvict: recentEvict, - } - return c, nil -} - -// Get looks up a key's value from the cache. -func (c *TwoQueueCache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if this is a frequent value - if val, ok := c.frequent.Get(key); ok { - return val, ok - } - - // If the value is contained in recent, then we - // promote it to frequent - if val, ok := c.recent.Peek(key); ok { - c.recent.Remove(key) - c.frequent.Add(key, val) - return val, ok - } - - // No hit - return nil, false -} - -// Add adds a value to the cache. -func (c *TwoQueueCache) Add(key, value interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the value is frequently used already, - // and just update the value - if c.frequent.Contains(key) { - c.frequent.Add(key, value) - return - } - - // Check if the value is recently used, and promote - // the value into the frequent list - if c.recent.Contains(key) { - c.recent.Remove(key) - c.frequent.Add(key, value) - return - } - - // If the value was recently evicted, add it to the - // frequently used list - if c.recentEvict.Contains(key) { - c.ensureSpace(true) - c.recentEvict.Remove(key) - c.frequent.Add(key, value) - return - } - - // Add to the recently seen list - c.ensureSpace(false) - c.recent.Add(key, value) - return -} - -// ensureSpace is used to ensure we have space in the cache -func (c *TwoQueueCache) ensureSpace(recentEvict bool) { - // If we have space, nothing to do - recentLen := c.recent.Len() - freqLen := c.frequent.Len() - if recentLen+freqLen < c.size { - return - } - - // If the recent buffer is larger than - // the target, evict from there - if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) { - k, _, _ := c.recent.RemoveOldest() - c.recentEvict.Add(k, nil) - return - } - - // Remove from the frequent list otherwise - c.frequent.RemoveOldest() -} - -// Len returns the number of items in the cache. -func (c *TwoQueueCache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.recent.Len() + c.frequent.Len() -} - -// Keys returns a slice of the keys in the cache. -// The frequently used keys are first in the returned slice. -func (c *TwoQueueCache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - k1 := c.frequent.Keys() - k2 := c.recent.Keys() - return append(k1, k2...) -} - -// Remove removes the provided key from the cache. -func (c *TwoQueueCache) Remove(key interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - if c.frequent.Remove(key) { - return - } - if c.recent.Remove(key) { - return - } - if c.recentEvict.Remove(key) { - return - } -} - -// Purge is used to completely clear the cache. -func (c *TwoQueueCache) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - c.recent.Purge() - c.frequent.Purge() - c.recentEvict.Purge() -} - -// Contains is used to check if the cache contains a key -// without updating recency or frequency. -func (c *TwoQueueCache) Contains(key interface{}) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.frequent.Contains(key) || c.recent.Contains(key) -} - -// Peek is used to inspect the cache value of a key -// without updating recency or frequency. -func (c *TwoQueueCache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - if val, ok := c.frequent.Peek(key); ok { - return val, ok - } - return c.recent.Peek(key) -} diff --git a/vendor/github.com/hashicorp/golang-lru/README.md b/vendor/github.com/hashicorp/golang-lru/README.md deleted file mode 100644 index 33e58cfaf..000000000 --- a/vendor/github.com/hashicorp/golang-lru/README.md +++ /dev/null @@ -1,25 +0,0 @@ -golang-lru -========== - -This provides the `lru` package which implements a fixed-size -thread safe LRU cache. It is based on the cache in Groupcache. - -Documentation -============= - -Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru) - -Example -======= - -Using the LRU is very simple: - -```go -l, _ := New(128) -for i := 0; i < 256; i++ { - l.Add(i, nil) -} -if l.Len() != 128 { - panic(fmt.Sprintf("bad len: %v", l.Len())) -} -``` diff --git a/vendor/github.com/hashicorp/golang-lru/arc.go b/vendor/github.com/hashicorp/golang-lru/arc.go deleted file mode 100644 index 555225a21..000000000 --- a/vendor/github.com/hashicorp/golang-lru/arc.go +++ /dev/null @@ -1,257 +0,0 @@ -package lru - -import ( - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC). -// ARC is an enhancement over the standard LRU cache in that tracks both -// frequency and recency of use. This avoids a burst in access to new -// entries from evicting the frequently used older entries. It adds some -// additional tracking overhead to a standard LRU cache, computationally -// it is roughly 2x the cost, and the extra memory overhead is linear -// with the size of the cache. ARC has been patented by IBM, but is -// similar to the TwoQueueCache (2Q) which requires setting parameters. -type ARCCache struct { - size int // Size is the total capacity of the cache - p int // P is the dynamic preference towards T1 or T2 - - t1 simplelru.LRUCache // T1 is the LRU for recently accessed items - b1 simplelru.LRUCache // B1 is the LRU for evictions from t1 - - t2 simplelru.LRUCache // T2 is the LRU for frequently accessed items - b2 simplelru.LRUCache // B2 is the LRU for evictions from t2 - - lock sync.RWMutex -} - -// NewARC creates an ARC of the given size -func NewARC(size int) (*ARCCache, error) { - // Create the sub LRUs - b1, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - b2, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - t1, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - t2, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - - // Initialize the ARC - c := &ARCCache{ - size: size, - p: 0, - t1: t1, - b1: b1, - t2: t2, - b2: b2, - } - return c, nil -} - -// Get looks up a key's value from the cache. -func (c *ARCCache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - - // If the value is contained in T1 (recent), then - // promote it to T2 (frequent) - if val, ok := c.t1.Peek(key); ok { - c.t1.Remove(key) - c.t2.Add(key, val) - return val, ok - } - - // Check if the value is contained in T2 (frequent) - if val, ok := c.t2.Get(key); ok { - return val, ok - } - - // No hit - return nil, false -} - -// Add adds a value to the cache. -func (c *ARCCache) Add(key, value interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the value is contained in T1 (recent), and potentially - // promote it to frequent T2 - if c.t1.Contains(key) { - c.t1.Remove(key) - c.t2.Add(key, value) - return - } - - // Check if the value is already in T2 (frequent) and update it - if c.t2.Contains(key) { - c.t2.Add(key, value) - return - } - - // Check if this value was recently evicted as part of the - // recently used list - if c.b1.Contains(key) { - // T1 set is too small, increase P appropriately - delta := 1 - b1Len := c.b1.Len() - b2Len := c.b2.Len() - if b2Len > b1Len { - delta = b2Len / b1Len - } - if c.p+delta >= c.size { - c.p = c.size - } else { - c.p += delta - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(false) - } - - // Remove from B1 - c.b1.Remove(key) - - // Add the key to the frequently used list - c.t2.Add(key, value) - return - } - - // Check if this value was recently evicted as part of the - // frequently used list - if c.b2.Contains(key) { - // T2 set is too small, decrease P appropriately - delta := 1 - b1Len := c.b1.Len() - b2Len := c.b2.Len() - if b1Len > b2Len { - delta = b1Len / b2Len - } - if delta >= c.p { - c.p = 0 - } else { - c.p -= delta - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(true) - } - - // Remove from B2 - c.b2.Remove(key) - - // Add the key to the frequently used list - c.t2.Add(key, value) - return - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(false) - } - - // Keep the size of the ghost buffers trim - if c.b1.Len() > c.size-c.p { - c.b1.RemoveOldest() - } - if c.b2.Len() > c.p { - c.b2.RemoveOldest() - } - - // Add to the recently seen list - c.t1.Add(key, value) - return -} - -// replace is used to adaptively evict from either T1 or T2 -// based on the current learned value of P -func (c *ARCCache) replace(b2ContainsKey bool) { - t1Len := c.t1.Len() - if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) { - k, _, ok := c.t1.RemoveOldest() - if ok { - c.b1.Add(k, nil) - } - } else { - k, _, ok := c.t2.RemoveOldest() - if ok { - c.b2.Add(k, nil) - } - } -} - -// Len returns the number of cached entries -func (c *ARCCache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.t1.Len() + c.t2.Len() -} - -// Keys returns all the cached keys -func (c *ARCCache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - k1 := c.t1.Keys() - k2 := c.t2.Keys() - return append(k1, k2...) -} - -// Remove is used to purge a key from the cache -func (c *ARCCache) Remove(key interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - if c.t1.Remove(key) { - return - } - if c.t2.Remove(key) { - return - } - if c.b1.Remove(key) { - return - } - if c.b2.Remove(key) { - return - } -} - -// Purge is used to clear the cache -func (c *ARCCache) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - c.t1.Purge() - c.t2.Purge() - c.b1.Purge() - c.b2.Purge() -} - -// Contains is used to check if the cache contains a key -// without updating recency or frequency. -func (c *ARCCache) Contains(key interface{}) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.t1.Contains(key) || c.t2.Contains(key) -} - -// Peek is used to inspect the cache value of a key -// without updating recency or frequency. -func (c *ARCCache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - if val, ok := c.t1.Peek(key); ok { - return val, ok - } - return c.t2.Peek(key) -} diff --git a/vendor/github.com/hashicorp/golang-lru/doc.go b/vendor/github.com/hashicorp/golang-lru/doc.go deleted file mode 100644 index 2547df979..000000000 --- a/vendor/github.com/hashicorp/golang-lru/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package lru provides three different LRU caches of varying sophistication. -// -// Cache is a simple LRU cache. It is based on the -// LRU implementation in groupcache: -// https://github.com/golang/groupcache/tree/master/lru -// -// TwoQueueCache tracks frequently used and recently used entries separately. -// This avoids a burst of accesses from taking out frequently used entries, -// at the cost of about 2x computational overhead and some extra bookkeeping. -// -// ARCCache is an adaptive replacement cache. It tracks recent evictions as -// well as recent usage in both the frequent and recent caches. Its -// computational overhead is comparable to TwoQueueCache, but the memory -// overhead is linear with the size of the cache. -// -// ARC has been patented by IBM, so do not use it if that is problematic for -// your program. -// -// All caches in this package take locks while operating, and are therefore -// thread-safe for consumers. -package lru diff --git a/vendor/github.com/hashicorp/golang-lru/lru.go b/vendor/github.com/hashicorp/golang-lru/lru.go deleted file mode 100644 index 4e5e9d8fd..000000000 --- a/vendor/github.com/hashicorp/golang-lru/lru.go +++ /dev/null @@ -1,150 +0,0 @@ -package lru - -import ( - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -// Cache is a thread-safe fixed size LRU cache. -type Cache struct { - lru simplelru.LRUCache - lock sync.RWMutex -} - -// New creates an LRU of the given size. -func New(size int) (*Cache, error) { - return NewWithEvict(size, nil) -} - -// NewWithEvict constructs a fixed size cache with the given eviction -// callback. -func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) { - lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted)) - if err != nil { - return nil, err - } - c := &Cache{ - lru: lru, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *Cache) Purge() { - c.lock.Lock() - c.lru.Purge() - c.lock.Unlock() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *Cache) Add(key, value interface{}) (evicted bool) { - c.lock.Lock() - evicted = c.lru.Add(key, value) - c.lock.Unlock() - return evicted -} - -// Get looks up a key's value from the cache. -func (c *Cache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - value, ok = c.lru.Get(key) - c.lock.Unlock() - return value, ok -} - -// Contains checks if a key is in the cache, without updating the -// recent-ness or deleting it for being stale. -func (c *Cache) Contains(key interface{}) bool { - c.lock.RLock() - containKey := c.lru.Contains(key) - c.lock.RUnlock() - return containKey -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - value, ok = c.lru.Peek(key) - c.lock.RUnlock() - return value, ok -} - -// ContainsOrAdd checks if a key is in the cache without updating the -// recent-ness or deleting it for being stale, and if not, adds the value. -// Returns whether found and whether an eviction occurred. -func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) { - c.lock.Lock() - defer c.lock.Unlock() - - if c.lru.Contains(key) { - return true, false - } - evicted = c.lru.Add(key, value) - return false, evicted -} - -// PeekOrAdd checks if a key is in the cache without updating the -// recent-ness or deleting it for being stale, and if not, adds the value. -// Returns whether found and whether an eviction occurred. -func (c *Cache) PeekOrAdd(key, value interface{}) (previous interface{}, ok, evicted bool) { - c.lock.Lock() - defer c.lock.Unlock() - - previous, ok = c.lru.Peek(key) - if ok { - return previous, true, false - } - - evicted = c.lru.Add(key, value) - return nil, false, evicted -} - -// Remove removes the provided key from the cache. -func (c *Cache) Remove(key interface{}) (present bool) { - c.lock.Lock() - present = c.lru.Remove(key) - c.lock.Unlock() - return -} - -// Resize changes the cache size. -func (c *Cache) Resize(size int) (evicted int) { - c.lock.Lock() - evicted = c.lru.Resize(size) - c.lock.Unlock() - return evicted -} - -// RemoveOldest removes the oldest item from the cache. -func (c *Cache) RemoveOldest() (key interface{}, value interface{}, ok bool) { - c.lock.Lock() - key, value, ok = c.lru.RemoveOldest() - c.lock.Unlock() - return -} - -// GetOldest returns the oldest entry -func (c *Cache) GetOldest() (key interface{}, value interface{}, ok bool) { - c.lock.Lock() - key, value, ok = c.lru.GetOldest() - c.lock.Unlock() - return -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *Cache) Keys() []interface{} { - c.lock.RLock() - keys := c.lru.Keys() - c.lock.RUnlock() - return keys -} - -// Len returns the number of items in the cache. -func (c *Cache) Len() int { - c.lock.RLock() - length := c.lru.Len() - c.lock.RUnlock() - return length -} diff --git a/vendor/github.com/hashicorp/vault/api/auth.go b/vendor/github.com/hashicorp/vault/api/auth.go index fa92de4b3..c1ef7a779 100644 --- a/vendor/github.com/hashicorp/vault/api/auth.go +++ b/vendor/github.com/hashicorp/vault/api/auth.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -63,7 +66,7 @@ func (a *Auth) MFAValidate(ctx context.Context, mfaSecret *Secret, payload map[s return nil, fmt.Errorf("secret does not contain MFARequirements") } - s, err := a.c.Sys().MFAValidateWithContext(ctx, mfaSecret.Auth.MFARequirement.GetMFARequestID(), payload) + s, err := a.c.Sys().MFAValidateWithContext(ctx, mfaSecret.Auth.MFARequirement.MFARequestID, payload) if err != nil { return nil, err } diff --git a/vendor/github.com/hashicorp/vault/api/auth_token.go b/vendor/github.com/hashicorp/vault/api/auth_token.go index 52be1e785..1980be06e 100644 --- a/vendor/github.com/hashicorp/vault/api/auth_token.go +++ b/vendor/github.com/hashicorp/vault/api/auth_token.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/client.go b/vendor/github.com/hashicorp/vault/api/client.go index 26d291914..c5ddee1c3 100644 --- a/vendor/github.com/hashicorp/vault/api/client.go +++ b/vendor/github.com/hashicorp/vault/api/client.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -24,12 +27,9 @@ import ( "github.com/hashicorp/go-retryablehttp" "github.com/hashicorp/go-rootcerts" "github.com/hashicorp/go-secure-stdlib/parseutil" + "github.com/hashicorp/go-secure-stdlib/strutil" "golang.org/x/net/http2" "golang.org/x/time/rate" - - "github.com/hashicorp/vault/sdk/helper/consts" - "github.com/hashicorp/vault/sdk/helper/strutil" - "github.com/hashicorp/vault/sdk/logical" ) const ( @@ -56,7 +56,19 @@ const ( HeaderIndex = "X-Vault-Index" HeaderForward = "X-Vault-Forward" HeaderInconsistent = "X-Vault-Inconsistent" - TLSErrorString = "This error usually means that the server is running with TLS disabled\n" + + + // NamespaceHeaderName is the header set to specify which namespace the + // request is indented for. + NamespaceHeaderName = "X-Vault-Namespace" + + // AuthHeaderName is the name of the header containing the token. + AuthHeaderName = "X-Vault-Token" + + // RequestHeaderName is the name of the header used by the Agent for + // SSRF protection. + RequestHeaderName = "X-Vault-Request" + + TLSErrorString = "This error usually means that the server is running with TLS disabled\n" + "but the client is configured to use TLS. Please either enable TLS\n" + "on the server or run the client with -address set to an address\n" + "that uses the http protocol:\n\n" + @@ -191,6 +203,7 @@ type Config struct { // commands such as 'vault operator raft snapshot' as this redirects to the // primary node. DisableRedirects bool + clientTLSConfig *tls.Config } // TLSConfig contains the parameters needed to configure TLS on the HTTP client @@ -325,10 +338,17 @@ func (c *Config) configureTLS(t *TLSConfig) error { if t.TLSServerName != "" { clientTLSConfig.ServerName = t.TLSServerName } + c.clientTLSConfig = clientTLSConfig return nil } +func (c *Config) TLSConfig() *tls.Config { + c.modifyLock.RLock() + defer c.modifyLock.RUnlock() + return c.clientTLSConfig.Clone() +} + // ConfigureTLS takes a set of TLS configurations and applies those to the // HTTP client. func (c *Config) ConfigureTLS(t *TLSConfig) error { @@ -621,7 +641,7 @@ func NewClient(c *Config) (*Client, error) { } // Add the VaultRequest SSRF protection header - client.headers[consts.RequestHeaderName] = []string{"true"} + client.headers[RequestHeaderName] = []string{"true"} if token := os.Getenv(EnvVaultToken); token != "" { client.token = token @@ -653,6 +673,7 @@ func (c *Client) CloneConfig() *Config { newConfig.CloneHeaders = c.config.CloneHeaders newConfig.CloneToken = c.config.CloneToken newConfig.ReadYourWrites = c.config.ReadYourWrites + newConfig.clientTLSConfig = c.config.clientTLSConfig // we specifically want a _copy_ of the client here, not a pointer to the original one newClient := *c.config.HttpClient @@ -938,7 +959,7 @@ func (c *Client) setNamespace(namespace string) { c.headers = make(http.Header) } - c.headers.Set(consts.NamespaceHeaderName, namespace) + c.headers.Set(NamespaceHeaderName, namespace) } // ClearNamespace removes the namespace header if set. @@ -946,7 +967,7 @@ func (c *Client) ClearNamespace() { c.modifyLock.Lock() defer c.modifyLock.Unlock() if c.headers != nil { - c.headers.Del(consts.NamespaceHeaderName) + c.headers.Del(NamespaceHeaderName) } } @@ -958,7 +979,7 @@ func (c *Client) Namespace() string { if c.headers == nil { return "" } - return c.headers.Get(consts.NamespaceHeaderName) + return c.headers.Get(NamespaceHeaderName) } // WithNamespace makes a shallow copy of Client, modifies it to use @@ -1292,7 +1313,7 @@ func (c *Client) rawRequestWithContext(ctx context.Context, r *Request) (*Respon checkRetry := c.config.CheckRetry backoff := c.config.Backoff httpClient := c.config.HttpClient - ns := c.headers.Get(consts.NamespaceHeaderName) + ns := c.headers.Get(NamespaceHeaderName) outputCurlString := c.config.OutputCurlString outputPolicy := c.config.OutputPolicy logger := c.config.Logger @@ -1305,9 +1326,9 @@ func (c *Client) rawRequestWithContext(ctx context.Context, r *Request) (*Respon // e.g. calls using (*Client).WithNamespace switch ns { case "": - r.Headers.Del(consts.NamespaceHeaderName) + r.Headers.Del(NamespaceHeaderName) default: - r.Headers.Set(consts.NamespaceHeaderName, ns) + r.Headers.Set(NamespaceHeaderName, ns) } for _, cb := range c.requestCallbacks { @@ -1353,6 +1374,7 @@ START: LastOutputPolicyError = &OutputPolicyError{ method: req.Method, path: strings.TrimPrefix(req.URL.Path, "/v1"), + params: req.URL.Query(), } return nil, LastOutputPolicyError } @@ -1460,8 +1482,8 @@ func (c *Client) httpRequestWithContext(ctx context.Context, r *Request) (*Respo } } // explicitly set the namespace header to current client - if ns := c.headers.Get(consts.NamespaceHeaderName); ns != "" { - r.Headers.Set(consts.NamespaceHeaderName, ns) + if ns := c.headers.Get(NamespaceHeaderName); ns != "" { + r.Headers.Set(NamespaceHeaderName, ns) } } @@ -1482,7 +1504,7 @@ func (c *Client) httpRequestWithContext(ctx context.Context, r *Request) (*Respo req.Host = r.URL.Host if len(r.ClientToken) != 0 { - req.Header.Set(consts.AuthHeaderName, r.ClientToken) + req.Header.Set(AuthHeaderName, r.ClientToken) } if len(r.WrapTTL) != 0 { @@ -1672,7 +1694,13 @@ func MergeReplicationStates(old []string, new string) []string { return strutil.RemoveDuplicates(ret, false) } -func ParseReplicationState(raw string, hmacKey []byte) (*logical.WALState, error) { +type WALState struct { + ClusterID string + LocalIndex uint64 + ReplicatedIndex uint64 +} + +func ParseReplicationState(raw string, hmacKey []byte) (*WALState, error) { cooked, err := base64.StdEncoding.DecodeString(raw) if err != nil { return nil, err @@ -1710,7 +1738,7 @@ func ParseReplicationState(raw string, hmacKey []byte) (*logical.WALState, error return nil, fmt.Errorf("invalid replicated index in state header: %w", err) } - return &logical.WALState{ + return &WALState{ ClusterID: pieces[1], LocalIndex: localIndex, ReplicatedIndex: replicatedIndex, diff --git a/vendor/github.com/hashicorp/vault/api/help.go b/vendor/github.com/hashicorp/vault/api/help.go index 0988ebcd1..c119f6c3c 100644 --- a/vendor/github.com/hashicorp/vault/api/help.go +++ b/vendor/github.com/hashicorp/vault/api/help.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/kv.go b/vendor/github.com/hashicorp/vault/api/kv.go index 37699df26..20862fbfd 100644 --- a/vendor/github.com/hashicorp/vault/api/kv.go +++ b/vendor/github.com/hashicorp/vault/api/kv.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import "errors" diff --git a/vendor/github.com/hashicorp/vault/api/kv_v1.go b/vendor/github.com/hashicorp/vault/api/kv_v1.go index 22ba99238..a914e0357 100644 --- a/vendor/github.com/hashicorp/vault/api/kv_v1.go +++ b/vendor/github.com/hashicorp/vault/api/kv_v1.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/kv_v2.go b/vendor/github.com/hashicorp/vault/api/kv_v2.go index 335c21001..72c29eaa4 100644 --- a/vendor/github.com/hashicorp/vault/api/kv_v2.go +++ b/vendor/github.com/hashicorp/vault/api/kv_v2.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/lifetime_watcher.go b/vendor/github.com/hashicorp/vault/api/lifetime_watcher.go index 5f3eadbff..5c060e5a1 100644 --- a/vendor/github.com/hashicorp/vault/api/lifetime_watcher.go +++ b/vendor/github.com/hashicorp/vault/api/lifetime_watcher.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -147,6 +150,13 @@ func (c *Client) NewLifetimeWatcher(i *LifetimeWatcherInput) (*LifetimeWatcher, random := i.Rand if random == nil { + // NOTE: + // Rather than a cryptographically secure random number generator (RNG), + // the default behavior uses the math/rand package. The random number is + // used to introduce a slight jitter when calculating the grace period + // for a monitored secret monitoring. This is intended to stagger renewal + // requests to the Vault server, but in a semi-predictable way, so there + // is no need to use a cryptographically secure RNG. random = rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) } @@ -337,25 +347,15 @@ func (r *LifetimeWatcher) doRenewWithOptions(tokenMode bool, nonRenewable bool, var sleepDuration time.Duration - if errorBackoff != nil { - sleepDuration = errorBackoff.NextBackOff() - if sleepDuration == backoff.Stop { - return err - } - } else { - // We keep evaluating a new grace period so long as the lease is - // extending. Once it stops extending, we've hit the max and need to - // rely on the grace duration. - if remainingLeaseDuration > priorDuration { - r.calculateGrace(remainingLeaseDuration, time.Duration(r.increment)*time.Second) - } - priorDuration = remainingLeaseDuration - - // The sleep duration is set to 2/3 of the current lease duration plus - // 1/3 of the current grace period, which adds jitter. - sleepDuration = time.Duration(float64(remainingLeaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) + if errorBackoff == nil { + sleepDuration = r.calculateSleepDuration(remainingLeaseDuration, priorDuration) + } else if errorBackoff.NextBackOff() == backoff.Stop { + return err } + // remainingLeaseDuration becomes the priorDuration for the next loop + priorDuration = remainingLeaseDuration + // If we are within grace, return now; or, if the amount of time we // would sleep would land us in the grace period. This helps with short // tokens; for example, you don't want a current lease duration of 4 @@ -366,15 +366,32 @@ func (r *LifetimeWatcher) doRenewWithOptions(tokenMode bool, nonRenewable bool, return nil } + timer := time.NewTimer(sleepDuration) select { case <-r.stopCh: + timer.Stop() return nil - case <-time.After(sleepDuration): + case <-timer.C: continue } } } +// calculateSleepDuration calculates the amount of time the LifeTimeWatcher should sleep +// before re-entering its loop. +func (r *LifetimeWatcher) calculateSleepDuration(remainingLeaseDuration, priorDuration time.Duration) time.Duration { + // We keep evaluating a new grace period so long as the lease is + // extending. Once it stops extending, we've hit the max and need to + // rely on the grace duration. + if remainingLeaseDuration > priorDuration { + r.calculateGrace(remainingLeaseDuration, time.Duration(r.increment)*time.Second) + } + + // The sleep duration is set to 2/3 of the current lease duration plus + // 1/3 of the current grace period, which adds jitter. + return time.Duration(float64(remainingLeaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) +} + // calculateGrace calculates the grace period based on the minimum of the // remaining lease duration and the token increment value; it also adds some // jitter to not have clients be in sync. diff --git a/vendor/github.com/hashicorp/vault/api/logical.go b/vendor/github.com/hashicorp/vault/api/logical.go index e36fde8c9..927dd168e 100644 --- a/vendor/github.com/hashicorp/vault/api/logical.go +++ b/vendor/github.com/hashicorp/vault/api/logical.go @@ -1,8 +1,12 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( "bytes" "context" + "encoding/json" "fmt" "io" "net/http" @@ -11,7 +15,6 @@ import ( "strings" "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/sdk/helper/jsonutil" ) const ( @@ -390,7 +393,9 @@ func (c *Logical) UnwrapWithContext(ctx context.Context, wrappingToken string) ( wrappedSecret := new(Secret) buf := bytes.NewBufferString(secret.Data["response"].(string)) - if err := jsonutil.DecodeJSONFromReader(buf, wrappedSecret); err != nil { + dec := json.NewDecoder(buf) + dec.UseNumber() + if err := dec.Decode(wrappedSecret); err != nil { return nil, errwrap.Wrapf("error unmarshalling wrapped secret: {{err}}", err) } diff --git a/vendor/github.com/hashicorp/vault/api/output_policy.go b/vendor/github.com/hashicorp/vault/api/output_policy.go index 85d1617e5..c3ec52289 100644 --- a/vendor/github.com/hashicorp/vault/api/output_policy.go +++ b/vendor/github.com/hashicorp/vault/api/output_policy.go @@ -1,9 +1,13 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( "fmt" "net/http" "net/url" + "strconv" "strings" ) @@ -16,6 +20,7 @@ var LastOutputPolicyError *OutputPolicyError type OutputPolicyError struct { method string path string + params url.Values finalHCLString string } @@ -44,8 +49,22 @@ func (d *OutputPolicyError) HCLString() (string, error) { // Builds a sample policy document from the request func (d *OutputPolicyError) buildSamplePolicy() (string, error) { + operation := d.method + // List is often defined as a URL param instead of as an http.Method + // this will check for the header and properly switch off of the intended functionality + if d.params.Has("list") { + isList, err := strconv.ParseBool(d.params.Get("list")) + if err != nil { + return "", fmt.Errorf("the value of the list url param is not a bool: %v", err) + } + + if isList { + operation = "LIST" + } + } + var capabilities []string - switch d.method { + switch operation { case http.MethodGet, "": capabilities = append(capabilities, "read") case http.MethodPost, http.MethodPut: @@ -59,17 +78,15 @@ func (d *OutputPolicyError) buildSamplePolicy() (string, error) { capabilities = append(capabilities, "list") } - // sanitize, then trim the Vault address and v1 from the front of the path - path, err := url.PathUnescape(d.path) - if err != nil { - return "", fmt.Errorf("failed to unescape request URL characters: %v", err) - } - // determine whether to add sudo capability - if IsSudoPath(path) { + if IsSudoPath(d.path) { capabilities = append(capabilities, "sudo") } + return formatOutputPolicy(d.path, capabilities), nil +} + +func formatOutputPolicy(path string, capabilities []string) string { // the OpenAPI response has a / in front of each path, // but policies need the path without that leading slash path = strings.TrimLeft(path, "/") @@ -78,5 +95,5 @@ func (d *OutputPolicyError) buildSamplePolicy() (string, error) { return fmt.Sprintf( `path "%s" { capabilities = ["%s"] -}`, path, capStr), nil +}`, path, capStr) } diff --git a/vendor/github.com/hashicorp/vault/api/output_string.go b/vendor/github.com/hashicorp/vault/api/output_string.go index 80c591f20..d7777712d 100644 --- a/vendor/github.com/hashicorp/vault/api/output_string.go +++ b/vendor/github.com/hashicorp/vault/api/output_string.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/plugin_helpers.go b/vendor/github.com/hashicorp/vault/api/plugin_helpers.go index 6602a044b..2d6416d70 100644 --- a/vendor/github.com/hashicorp/vault/api/plugin_helpers.go +++ b/vendor/github.com/hashicorp/vault/api/plugin_helpers.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -37,7 +40,7 @@ const ( // path matches that path or not (useful specifically for the paths that // contain templated fields.) var sudoPaths = map[string]*regexp.Regexp{ - "/auth/token/accessors/": regexp.MustCompile(`^/auth/token/accessors/$`), + "/auth/token/accessors/": regexp.MustCompile(`^/auth/token/accessors/?$`), "/pki/root": regexp.MustCompile(`^/pki/root$`), "/pki/root/sign-self-issued": regexp.MustCompile(`^/pki/root/sign-self-issued$`), "/sys/audit": regexp.MustCompile(`^/sys/audit$`), @@ -47,10 +50,10 @@ var sudoPaths = map[string]*regexp.Regexp{ "/sys/config/auditing/request-headers": regexp.MustCompile(`^/sys/config/auditing/request-headers$`), "/sys/config/auditing/request-headers/{header}": regexp.MustCompile(`^/sys/config/auditing/request-headers/.+$`), "/sys/config/cors": regexp.MustCompile(`^/sys/config/cors$`), - "/sys/config/ui/headers/": regexp.MustCompile(`^/sys/config/ui/headers/$`), + "/sys/config/ui/headers/": regexp.MustCompile(`^/sys/config/ui/headers/?$`), "/sys/config/ui/headers/{header}": regexp.MustCompile(`^/sys/config/ui/headers/.+$`), "/sys/leases": regexp.MustCompile(`^/sys/leases$`), - "/sys/leases/lookup/": regexp.MustCompile(`^/sys/leases/lookup/$`), + "/sys/leases/lookup/": regexp.MustCompile(`^/sys/leases/lookup/?$`), "/sys/leases/lookup/{prefix}": regexp.MustCompile(`^/sys/leases/lookup/.+$`), "/sys/leases/revoke-force/{prefix}": regexp.MustCompile(`^/sys/leases/revoke-force/.+$`), "/sys/leases/revoke-prefix/{prefix}": regexp.MustCompile(`^/sys/leases/revoke-prefix/.+$`), @@ -70,7 +73,7 @@ var sudoPaths = map[string]*regexp.Regexp{ "/sys/replication/performance/primary/secondary-token": regexp.MustCompile(`^/sys/replication/performance/primary/secondary-token$`), "/sys/replication/primary/secondary-token": regexp.MustCompile(`^/sys/replication/primary/secondary-token$`), "/sys/replication/reindex": regexp.MustCompile(`^/sys/replication/reindex$`), - "/sys/storage/raft/snapshot-auto/config/": regexp.MustCompile(`^/sys/storage/raft/snapshot-auto/config/$`), + "/sys/storage/raft/snapshot-auto/config/": regexp.MustCompile(`^/sys/storage/raft/snapshot-auto/config/?$`), "/sys/storage/raft/snapshot-auto/config/{name}": regexp.MustCompile(`^/sys/storage/raft/snapshot-auto/config/[^/]+$`), } diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/plugin_types.go b/vendor/github.com/hashicorp/vault/api/plugin_types.go similarity index 84% rename from vendor/github.com/hashicorp/vault/sdk/helper/consts/plugin_types.go rename to vendor/github.com/hashicorp/vault/api/plugin_types.go index e0a00e486..4c759a2de 100644 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/plugin_types.go +++ b/vendor/github.com/hashicorp/vault/api/plugin_types.go @@ -1,4 +1,11 @@ -package consts +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +// NOTE: this file was copied from +// https://github.com/hashicorp/vault/blob/main/sdk/helper/consts/plugin_types.go +// Any changes made should be made to both files at the same time. import "fmt" diff --git a/vendor/github.com/hashicorp/vault/api/request.go b/vendor/github.com/hashicorp/vault/api/request.go index 1cbbc62f9..ecf783701 100644 --- a/vendor/github.com/hashicorp/vault/api/request.go +++ b/vendor/github.com/hashicorp/vault/api/request.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -8,8 +11,6 @@ import ( "net/http" "net/url" - "github.com/hashicorp/vault/sdk/helper/consts" - retryablehttp "github.com/hashicorp/go-retryablehttp" ) @@ -127,7 +128,7 @@ func (r *Request) toRetryableHTTP() (*retryablehttp.Request, error) { } if len(r.ClientToken) != 0 { - req.Header.Set(consts.AuthHeaderName, r.ClientToken) + req.Header.Set(AuthHeaderName, r.ClientToken) } if len(r.WrapTTL) != 0 { diff --git a/vendor/github.com/hashicorp/vault/api/response.go b/vendor/github.com/hashicorp/vault/api/response.go index 9ce3d12aa..2842c1255 100644 --- a/vendor/github.com/hashicorp/vault/api/response.go +++ b/vendor/github.com/hashicorp/vault/api/response.go @@ -1,14 +1,15 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( "bytes" + "encoding/json" "fmt" "io" "io/ioutil" "net/http" - - "github.com/hashicorp/vault/sdk/helper/consts" - "github.com/hashicorp/vault/sdk/helper/jsonutil" ) // Response is a raw response that wraps an HTTP response. @@ -20,7 +21,9 @@ type Response struct { // will consume the response body, but will not close it. Close must // still be called. func (r *Response) DecodeJSON(out interface{}) error { - return jsonutil.DecodeJSONFromReader(r.Body, out) + dec := json.NewDecoder(r.Body) + dec.UseNumber() + return dec.Decode(out) } // Error returns an error response if there is one. If there is an error, @@ -42,7 +45,7 @@ func (r *Response) Error() error { r.Body.Close() r.Body = ioutil.NopCloser(bodyBuf) - ns := r.Header.Get(consts.NamespaceHeaderName) + ns := r.Header.Get(NamespaceHeaderName) // Build up the error object respErr := &ResponseError{ @@ -56,7 +59,9 @@ func (r *Response) Error() error { // in a bytes.Reader here so that the JSON decoder doesn't move the // read pointer for the original buffer. var resp ErrorResponse - if err := jsonutil.DecodeJSON(bodyBuf.Bytes(), &resp); err != nil { + dec := json.NewDecoder(bytes.NewReader(bodyBuf.Bytes())) + dec.UseNumber() + if err := dec.Decode(&resp); err != nil { // Store the fact that we couldn't decode the errors respErr.RawError = true respErr.Errors = []string{bodyBuf.String()} diff --git a/vendor/github.com/hashicorp/vault/api/secret.go b/vendor/github.com/hashicorp/vault/api/secret.go index 37e60892e..be159d706 100644 --- a/vendor/github.com/hashicorp/vault/api/secret.go +++ b/vendor/github.com/hashicorp/vault/api/secret.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -11,8 +14,6 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/go-secure-stdlib/parseutil" - "github.com/hashicorp/vault/sdk/helper/jsonutil" - "github.com/hashicorp/vault/sdk/logical" ) // Secret is the structure returned for every secret within Vault. @@ -283,6 +284,22 @@ type SecretWrapInfo struct { WrappedAccessor string `json:"wrapped_accessor"` } +type MFAMethodID struct { + Type string `json:"type,omitempty"` + ID string `json:"id,omitempty"` + UsesPasscode bool `json:"uses_passcode,omitempty"` + Name string `json:"name,omitempty"` +} + +type MFAConstraintAny struct { + Any []*MFAMethodID `json:"any,omitempty"` +} + +type MFARequirement struct { + MFARequestID string `json:"mfa_request_id,omitempty"` + MFAConstraints map[string]*MFAConstraintAny `json:"mfa_constraints,omitempty"` +} + // SecretAuth is the structure containing auth information if we have it. type SecretAuth struct { ClientToken string `json:"client_token"` @@ -297,7 +314,7 @@ type SecretAuth struct { LeaseDuration int `json:"lease_duration"` Renewable bool `json:"renewable"` - MFARequirement *logical.MFARequirement `json:"mfa_requirement"` + MFARequirement *MFARequirement `json:"mfa_requirement"` } // ParseSecret is used to parse a secret value from JSON from an io.Reader. @@ -323,14 +340,18 @@ func ParseSecret(r io.Reader) (*Secret, error) { // First decode the JSON into a map[string]interface{} var secret Secret - if err := jsonutil.DecodeJSONFromReader(&buf, &secret); err != nil { + dec := json.NewDecoder(&buf) + dec.UseNumber() + if err := dec.Decode(&secret); err != nil { return nil, err } // If the secret is null, add raw data to secret data if present if reflect.DeepEqual(secret, Secret{}) { data := make(map[string]interface{}) - if err := jsonutil.DecodeJSONFromReader(&teebuf, &data); err != nil { + dec := json.NewDecoder(&teebuf) + dec.UseNumber() + if err := dec.Decode(&data); err != nil { return nil, err } errRaw, errPresent := data["errors"] diff --git a/vendor/github.com/hashicorp/vault/api/ssh.go b/vendor/github.com/hashicorp/vault/api/ssh.go index b832e2748..28510eecc 100644 --- a/vendor/github.com/hashicorp/vault/api/ssh.go +++ b/vendor/github.com/hashicorp/vault/api/ssh.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/ssh_agent.go b/vendor/github.com/hashicorp/vault/api/ssh_agent.go index 03fe2bea5..e61503772 100644 --- a/vendor/github.com/hashicorp/vault/api/ssh_agent.go +++ b/vendor/github.com/hashicorp/vault/api/ssh_agent.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -15,7 +18,6 @@ import ( rootcerts "github.com/hashicorp/go-rootcerts" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/sdk/helper/hclutil" "github.com/mitchellh/mapstructure" ) @@ -169,7 +171,7 @@ func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { "tls_skip_verify", "tls_server_name", } - if err := hclutil.CheckHCLKeys(list, valid); err != nil { + if err := CheckHCLKeys(list, valid); err != nil { return nil, multierror.Prefix(err, "ssh_helper:") } @@ -185,6 +187,33 @@ func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { return &c, nil } +func CheckHCLKeys(node ast.Node, valid []string) error { + var list *ast.ObjectList + switch n := node.(type) { + case *ast.ObjectList: + list = n + case *ast.ObjectType: + list = n.List + default: + return fmt.Errorf("cannot check HCL keys of type %T", n) + } + + validMap := make(map[string]struct{}, len(valid)) + for _, v := range valid { + validMap[v] = struct{}{} + } + + var result error + for _, item := range list.Items { + key := item.Keys[0].Token.Value().(string) + if _, ok := validMap[key]; !ok { + result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) + } + } + + return result +} + // SSHHelper creates an SSHHelper object which can talk to Vault server with SSH backend // mounted at default path ("ssh"). func (c *Client) SSHHelper() *SSHHelper { diff --git a/vendor/github.com/hashicorp/vault/api/sys.go b/vendor/github.com/hashicorp/vault/api/sys.go index 5fb111887..81ebb3a25 100644 --- a/vendor/github.com/hashicorp/vault/api/sys.go +++ b/vendor/github.com/hashicorp/vault/api/sys.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // Sys is used to perform system-related operations on Vault. diff --git a/vendor/github.com/hashicorp/vault/api/sys_audit.go b/vendor/github.com/hashicorp/vault/api/sys_audit.go index 82d9aab0b..2244087aa 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_audit.go +++ b/vendor/github.com/hashicorp/vault/api/sys_audit.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_auth.go b/vendor/github.com/hashicorp/vault/api/sys_auth.go index 238bd5e46..e81441219 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_auth.go +++ b/vendor/github.com/hashicorp/vault/api/sys_auth.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go b/vendor/github.com/hashicorp/vault/api/sys_capabilities.go index af306a07f..6310d42fc 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go +++ b/vendor/github.com/hashicorp/vault/api/sys_capabilities.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go b/vendor/github.com/hashicorp/vault/api/sys_config_cors.go index 1e2cda4f4..e80aa9d8b 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go +++ b/vendor/github.com/hashicorp/vault/api/sys_config_cors.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go b/vendor/github.com/hashicorp/vault/api/sys_generate_root.go index 096cadb79..da4ad2f9b 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go +++ b/vendor/github.com/hashicorp/vault/api/sys_generate_root.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_hastatus.go b/vendor/github.com/hashicorp/vault/api/sys_hastatus.go index d89d59651..2b2aa7c3e 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_hastatus.go +++ b/vendor/github.com/hashicorp/vault/api/sys_hastatus.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_health.go b/vendor/github.com/hashicorp/vault/api/sys_health.go index 953c1c21e..13fd8d4d3 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_health.go +++ b/vendor/github.com/hashicorp/vault/api/sys_health.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_init.go b/vendor/github.com/hashicorp/vault/api/sys_init.go index 05dea86f6..13fa94806 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_init.go +++ b/vendor/github.com/hashicorp/vault/api/sys_init.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_leader.go b/vendor/github.com/hashicorp/vault/api/sys_leader.go index a74e206eb..868914d3b 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_leader.go +++ b/vendor/github.com/hashicorp/vault/api/sys_leader.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_leases.go b/vendor/github.com/hashicorp/vault/api/sys_leases.go index c02402f53..c46f07e64 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_leases.go +++ b/vendor/github.com/hashicorp/vault/api/sys_leases.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_mfa.go b/vendor/github.com/hashicorp/vault/api/sys_mfa.go index a1ba1bd80..2be669584 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_mfa.go +++ b/vendor/github.com/hashicorp/vault/api/sys_mfa.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_monitor.go b/vendor/github.com/hashicorp/vault/api/sys_monitor.go index 6813799f0..15a8a13d1 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_monitor.go +++ b/vendor/github.com/hashicorp/vault/api/sys_monitor.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -5,8 +8,6 @@ import ( "context" "fmt" "net/http" - - "github.com/hashicorp/vault/sdk/helper/logging" ) // Monitor returns a channel that outputs strings containing the log messages @@ -20,7 +21,7 @@ func (c *Sys) Monitor(ctx context.Context, logLevel string, logFormat string) (c r.Params.Add("log_level", logLevel) } - if logFormat == "" || logFormat == logging.UnspecifiedFormat.String() { + if logFormat == "" { r.Params.Add("log_format", "standard") } else { r.Params.Add("log_format", logFormat) diff --git a/vendor/github.com/hashicorp/vault/api/sys_mounts.go b/vendor/github.com/hashicorp/vault/api/sys_mounts.go index f55133cec..a6c2a0f54 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_mounts.go +++ b/vendor/github.com/hashicorp/vault/api/sys_mounts.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_plugins.go b/vendor/github.com/hashicorp/vault/api/sys_plugins.go index 989c78f1d..2ee024d9d 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_plugins.go +++ b/vendor/github.com/hashicorp/vault/api/sys_plugins.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -7,20 +10,19 @@ import ( "net/http" "time" - "github.com/hashicorp/vault/sdk/helper/consts" "github.com/mitchellh/mapstructure" ) // ListPluginsInput is used as input to the ListPlugins function. type ListPluginsInput struct { // Type of the plugin. Required. - Type consts.PluginType `json:"type"` + Type PluginType `json:"type"` } // ListPluginsResponse is the response from the ListPlugins call. type ListPluginsResponse struct { // PluginsByType is the list of plugins by type. - PluginsByType map[consts.PluginType][]string `json:"types"` + PluginsByType map[PluginType][]string `json:"types"` Details []PluginDetails `json:"details,omitempty"` @@ -68,11 +70,11 @@ func (c *Sys) ListPluginsWithContext(ctx context.Context, i *ListPluginsInput) ( } result := &ListPluginsResponse{ - PluginsByType: make(map[consts.PluginType][]string), + PluginsByType: make(map[PluginType][]string), } switch i.Type { - case consts.PluginTypeUnknown: - for _, pluginType := range consts.PluginTypes { + case PluginTypeUnknown: + for _, pluginType := range PluginTypes { pluginsRaw, ok := secret.Data[pluginType.String()] if !ok { continue @@ -113,7 +115,7 @@ func (c *Sys) ListPluginsWithContext(ctx context.Context, i *ListPluginsInput) ( } switch i.Type { - case consts.PluginTypeUnknown: + case PluginTypeUnknown: result.Details = details default: // Filter for just the queried type. @@ -133,8 +135,8 @@ type GetPluginInput struct { Name string `json:"-"` // Type of the plugin. Required. - Type consts.PluginType `json:"type"` - Version string `json:"version"` + Type PluginType `json:"type"` + Version string `json:"version"` } // GetPluginResponse is the response from the GetPlugin call. @@ -186,7 +188,7 @@ type RegisterPluginInput struct { Name string `json:"-"` // Type of the plugin. Required. - Type consts.PluginType `json:"type"` + Type PluginType `json:"type"` // Args is the list of args to spawn the process with. Args []string `json:"args,omitempty"` @@ -231,7 +233,7 @@ type DeregisterPluginInput struct { Name string `json:"-"` // Type of the plugin. Required. - Type consts.PluginType `json:"type"` + Type PluginType `json:"type"` // Version of the plugin. Optional. Version string `json:"version,omitempty"` @@ -368,11 +370,11 @@ func (c *Sys) ReloadPluginStatusWithContext(ctx context.Context, reloadStatusInp } // catalogPathByType is a helper to construct the proper API path by plugin type -func catalogPathByType(pluginType consts.PluginType, name string) string { +func catalogPathByType(pluginType PluginType, name string) string { path := fmt.Sprintf("/v1/sys/plugins/catalog/%s/%s", pluginType, name) // Backwards compat, if type is not provided then use old path - if pluginType == consts.PluginTypeUnknown { + if pluginType == PluginTypeUnknown { path = fmt.Sprintf("/v1/sys/plugins/catalog/%s", name) } diff --git a/vendor/github.com/hashicorp/vault/api/sys_policy.go b/vendor/github.com/hashicorp/vault/api/sys_policy.go index 4a4f91b08..9ddffe4ec 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_policy.go +++ b/vendor/github.com/hashicorp/vault/api/sys_policy.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_raft.go b/vendor/github.com/hashicorp/vault/api/sys_raft.go index 7806a1418..29bfed0f5 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_raft.go +++ b/vendor/github.com/hashicorp/vault/api/sys_raft.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_rekey.go b/vendor/github.com/hashicorp/vault/api/sys_rekey.go index 2ac8a4743..573201751 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_rekey.go +++ b/vendor/github.com/hashicorp/vault/api/sys_rekey.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_rotate.go b/vendor/github.com/hashicorp/vault/api/sys_rotate.go index fa86886c3..295d989f9 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_rotate.go +++ b/vendor/github.com/hashicorp/vault/api/sys_rotate.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_seal.go b/vendor/github.com/hashicorp/vault/api/sys_seal.go index 0522f2a42..7a9c5621e 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_seal.go +++ b/vendor/github.com/hashicorp/vault/api/sys_seal.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go b/vendor/github.com/hashicorp/vault/api/sys_stepdown.go index 833f31a6f..c55ed1e66 100644 --- a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go +++ b/vendor/github.com/hashicorp/vault/api/sys_stepdown.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/vault/sdk/LICENSE b/vendor/github.com/hashicorp/vault/sdk/LICENSE deleted file mode 100644 index f4f97ee58..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/LICENSE +++ /dev/null @@ -1,365 +0,0 @@ -Copyright (c) 2015 HashiCorp, Inc. - -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/certutil/helpers.go b/vendor/github.com/hashicorp/vault/sdk/helper/certutil/helpers.go deleted file mode 100644 index eace1aafd..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/certutil/helpers.go +++ /dev/null @@ -1,1386 +0,0 @@ -package certutil - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "errors" - "fmt" - "io" - "io/ioutil" - "math/big" - "net" - "net/url" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/sdk/helper/errutil" - "github.com/hashicorp/vault/sdk/helper/jsonutil" - "github.com/mitchellh/mapstructure" - "golang.org/x/crypto/cryptobyte" - cbasn1 "golang.org/x/crypto/cryptobyte/asn1" -) - -const rsaMinimumSecureKeySize = 2048 - -// Mapping of key types to default key lengths -var defaultAlgorithmKeyBits = map[string]int{ - "rsa": 2048, - "ec": 256, -} - -// Mapping of NIST P-Curve's key length to expected signature bits. -var expectedNISTPCurveHashBits = map[int]int{ - 224: 256, - 256: 256, - 384: 384, - 521: 512, -} - -// Mapping of constant names<->constant values for SignatureAlgorithm -var SignatureAlgorithmNames = map[string]x509.SignatureAlgorithm{ - "sha256withrsa": x509.SHA256WithRSA, - "sha384withrsa": x509.SHA384WithRSA, - "sha512withrsa": x509.SHA512WithRSA, - "ecdsawithsha256": x509.ECDSAWithSHA256, - "ecdsawithsha384": x509.ECDSAWithSHA384, - "ecdsawithsha512": x509.ECDSAWithSHA512, - "sha256withrsapss": x509.SHA256WithRSAPSS, - "sha384withrsapss": x509.SHA384WithRSAPSS, - "sha512withrsapss": x509.SHA512WithRSAPSS, - "pureed25519": x509.PureEd25519, - "ed25519": x509.PureEd25519, // Duplicated for clarity; most won't expect the "Pure" prefix. -} - -// Mapping of constant values<->constant names for SignatureAlgorithm -var InvSignatureAlgorithmNames = map[x509.SignatureAlgorithm]string{ - x509.SHA256WithRSA: "SHA256WithRSA", - x509.SHA384WithRSA: "SHA384WithRSA", - x509.SHA512WithRSA: "SHA512WithRSA", - x509.ECDSAWithSHA256: "ECDSAWithSHA256", - x509.ECDSAWithSHA384: "ECDSAWithSHA384", - x509.ECDSAWithSHA512: "ECDSAWithSHA512", - x509.SHA256WithRSAPSS: "SHA256WithRSAPSS", - x509.SHA384WithRSAPSS: "SHA384WithRSAPSS", - x509.SHA512WithRSAPSS: "SHA512WithRSAPSS", - x509.PureEd25519: "Ed25519", -} - -// OID for RFC 5280 Delta CRL Indicator CRL extension. -// -// > id-ce-deltaCRLIndicator OBJECT IDENTIFIER ::= { id-ce 27 } -var DeltaCRLIndicatorOID = asn1.ObjectIdentifier([]int{2, 5, 29, 27}) - -// GetHexFormatted returns the byte buffer formatted in hex with -// the specified separator between bytes. -func GetHexFormatted(buf []byte, sep string) string { - var ret bytes.Buffer - for _, cur := range buf { - if ret.Len() > 0 { - fmt.Fprintf(&ret, sep) - } - fmt.Fprintf(&ret, "%02x", cur) - } - return ret.String() -} - -// ParseHexFormatted returns the raw bytes from a formatted hex string -func ParseHexFormatted(in, sep string) []byte { - var ret bytes.Buffer - var err error - var inBits uint64 - inBytes := strings.Split(in, sep) - for _, inByte := range inBytes { - if inBits, err = strconv.ParseUint(inByte, 16, 8); err != nil { - return nil - } - ret.WriteByte(uint8(inBits)) - } - return ret.Bytes() -} - -// GetSubjKeyID returns the subject key ID. The computed ID is the SHA-1 hash of -// the marshaled public key according to -// https://tools.ietf.org/html/rfc5280#section-4.2.1.2 (1) -func GetSubjKeyID(privateKey crypto.Signer) ([]byte, error) { - if privateKey == nil { - return nil, errutil.InternalError{Err: "passed-in private key is nil"} - } - return getSubjectKeyID(privateKey.Public()) -} - -// Returns the explicit SKID when used for cross-signing, else computes a new -// SKID from the key itself. -func getSubjectKeyIDFromBundle(data *CreationBundle) ([]byte, error) { - if len(data.Params.SKID) > 0 { - return data.Params.SKID, nil - } - - return getSubjectKeyID(data.CSR.PublicKey) -} - -func getSubjectKeyID(pub interface{}) ([]byte, error) { - var publicKeyBytes []byte - switch pub := pub.(type) { - case *rsa.PublicKey: - type pkcs1PublicKey struct { - N *big.Int - E int - } - - var err error - publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{ - N: pub.N, - E: pub.E, - }) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error marshalling public key: %s", err)} - } - case *ecdsa.PublicKey: - publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) - case ed25519.PublicKey: - publicKeyBytes = pub - default: - return nil, errutil.InternalError{Err: fmt.Sprintf("unsupported public key type: %T", pub)} - } - skid := sha1.Sum(publicKeyBytes) - return skid[:], nil -} - -// ParsePKIMap takes a map (for instance, the Secret.Data -// returned from the PKI backend) and returns a ParsedCertBundle. -func ParsePKIMap(data map[string]interface{}) (*ParsedCertBundle, error) { - result := &CertBundle{} - err := mapstructure.Decode(data, result) - if err != nil { - return nil, errutil.UserError{Err: err.Error()} - } - - return result.ToParsedCertBundle() -} - -// ParsePKIJSON takes a JSON-encoded string and returns a ParsedCertBundle. -// -// This can be either the output of an -// issue call from the PKI backend or just its data member; or, -// JSON not coming from the PKI backend. -func ParsePKIJSON(input []byte) (*ParsedCertBundle, error) { - result := &CertBundle{} - err := jsonutil.DecodeJSON(input, &result) - - if err == nil { - return result.ToParsedCertBundle() - } - - var secret Secret - err = jsonutil.DecodeJSON(input, &secret) - - if err == nil { - return ParsePKIMap(secret.Data) - } - - return nil, errutil.UserError{Err: "unable to parse out of either secret data or a secret object"} -} - -func ParseDERKey(privateKeyBytes []byte) (signer crypto.Signer, format BlockType, err error) { - var firstError error - if signer, firstError = x509.ParseECPrivateKey(privateKeyBytes); firstError == nil { - format = ECBlock - return - } - - var secondError error - if signer, secondError = x509.ParsePKCS1PrivateKey(privateKeyBytes); secondError == nil { - format = PKCS1Block - return - } - - var thirdError error - var rawKey interface{} - if rawKey, thirdError = x509.ParsePKCS8PrivateKey(privateKeyBytes); thirdError == nil { - switch rawSigner := rawKey.(type) { - case *rsa.PrivateKey: - signer = rawSigner - case *ecdsa.PrivateKey: - signer = rawSigner - case ed25519.PrivateKey: - signer = rawSigner - default: - return nil, UnknownBlock, errutil.InternalError{Err: "unknown type for parsed PKCS8 Private Key"} - } - - format = PKCS8Block - return - } - - return nil, UnknownBlock, fmt.Errorf("got errors attempting to parse DER private key:\n1. %v\n2. %v\n3. %v", firstError, secondError, thirdError) -} - -func ParsePEMKey(keyPem string) (crypto.Signer, BlockType, error) { - pemBlock, _ := pem.Decode([]byte(keyPem)) - if pemBlock == nil { - return nil, UnknownBlock, errutil.UserError{Err: "no data found in PEM block"} - } - - return ParseDERKey(pemBlock.Bytes) -} - -// ParsePEMBundle takes a string of concatenated PEM-format certificate -// and private key values and decodes/parses them, checking validity along -// the way. The first certificate must be the subject certificate and issuing -// certificates may follow. There must be at most one private key. -func ParsePEMBundle(pemBundle string) (*ParsedCertBundle, error) { - if len(pemBundle) == 0 { - return nil, errutil.UserError{Err: "empty pem bundle"} - } - - pemBytes := []byte(pemBundle) - var pemBlock *pem.Block - parsedBundle := &ParsedCertBundle{} - var certPath []*CertBlock - - for len(pemBytes) > 0 { - pemBlock, pemBytes = pem.Decode(pemBytes) - if pemBlock == nil { - return nil, errutil.UserError{Err: "no data found in PEM block"} - } - - if signer, format, err := ParseDERKey(pemBlock.Bytes); err == nil { - if parsedBundle.PrivateKeyType != UnknownPrivateKey { - return nil, errutil.UserError{Err: "more than one private key given; provide only one private key in the bundle"} - } - - parsedBundle.PrivateKeyFormat = format - parsedBundle.PrivateKeyType = GetPrivateKeyTypeFromSigner(signer) - if parsedBundle.PrivateKeyType == UnknownPrivateKey { - return nil, errutil.UserError{Err: "Unknown type of private key included in the bundle: %v"} - } - - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKey = signer - } else if certificates, err := x509.ParseCertificates(pemBlock.Bytes); err == nil { - certPath = append(certPath, &CertBlock{ - Certificate: certificates[0], - Bytes: pemBlock.Bytes, - }) - } else if x509.IsEncryptedPEMBlock(pemBlock) { - return nil, errutil.UserError{Err: "Encrypted private key given; provide only decrypted private key in the bundle"} - } - } - - for i, certBlock := range certPath { - if i == 0 { - parsedBundle.Certificate = certBlock.Certificate - parsedBundle.CertificateBytes = certBlock.Bytes - } else { - parsedBundle.CAChain = append(parsedBundle.CAChain, certBlock) - } - } - - if err := parsedBundle.Verify(); err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("verification of parsed bundle failed: %s", err)} - } - - return parsedBundle, nil -} - -// GeneratePrivateKey generates a private key with the specified type and key bits. -func GeneratePrivateKey(keyType string, keyBits int, container ParsedPrivateKeyContainer) error { - return generatePrivateKey(keyType, keyBits, container, nil) -} - -// GeneratePrivateKeyWithRandomSource generates a private key with the specified type and key bits. -// GeneratePrivateKeyWithRandomSource uses randomness from the entropyReader to generate the private key. -func GeneratePrivateKeyWithRandomSource(keyType string, keyBits int, container ParsedPrivateKeyContainer, entropyReader io.Reader) error { - return generatePrivateKey(keyType, keyBits, container, entropyReader) -} - -// generatePrivateKey generates a private key with the specified type and key bits. -// generatePrivateKey uses randomness from the entropyReader to generate the private key. -func generatePrivateKey(keyType string, keyBits int, container ParsedPrivateKeyContainer, entropyReader io.Reader) error { - var err error - var privateKeyType PrivateKeyType - var privateKeyBytes []byte - var privateKey crypto.Signer - - var randReader io.Reader = rand.Reader - if entropyReader != nil { - randReader = entropyReader - } - - switch keyType { - case "rsa": - // XXX: there is a false-positive CodeQL path here around keyBits; - // because of a default zero value in the TypeDurationSecond and - // TypeSignedDurationSecond cases of schema.DefaultOrZero(), it - // thinks it is possible to end up with < 2048 bit RSA Key here. - // While this is true for SSH keys, it isn't true for PKI keys - // due to ValidateKeyTypeLength(...) below. While we could close - // the report as a false-positive, enforcing a minimum keyBits size - // here of 2048 would ensure no other paths exist. - if keyBits < 2048 { - return errutil.InternalError{Err: fmt.Sprintf("insecure bit length for RSA private key: %d", keyBits)} - } - privateKeyType = RSAPrivateKey - privateKey, err = rsa.GenerateKey(randReader, keyBits) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error generating RSA private key: %v", err)} - } - privateKeyBytes = x509.MarshalPKCS1PrivateKey(privateKey.(*rsa.PrivateKey)) - case "ec": - privateKeyType = ECPrivateKey - var curve elliptic.Curve - switch keyBits { - case 224: - curve = elliptic.P224() - case 256: - curve = elliptic.P256() - case 384: - curve = elliptic.P384() - case 521: - curve = elliptic.P521() - default: - return errutil.UserError{Err: fmt.Sprintf("unsupported bit length for EC key: %d", keyBits)} - } - privateKey, err = ecdsa.GenerateKey(curve, randReader) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error generating EC private key: %v", err)} - } - privateKeyBytes, err = x509.MarshalECPrivateKey(privateKey.(*ecdsa.PrivateKey)) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error marshalling EC private key: %v", err)} - } - case "ed25519": - privateKeyType = Ed25519PrivateKey - _, privateKey, err = ed25519.GenerateKey(randReader) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error generating ed25519 private key: %v", err)} - } - privateKeyBytes, err = x509.MarshalPKCS8PrivateKey(privateKey.(ed25519.PrivateKey)) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error marshalling Ed25519 private key: %v", err)} - } - default: - return errutil.UserError{Err: fmt.Sprintf("unknown key type: %s", keyType)} - } - - container.SetParsedPrivateKey(privateKey, privateKeyType, privateKeyBytes) - return nil -} - -// GenerateSerialNumber generates a serial number suitable for a certificate -func GenerateSerialNumber() (*big.Int, error) { - return generateSerialNumber(rand.Reader) -} - -// GenerateSerialNumberWithRandomSource generates a serial number suitable -// for a certificate with custom entropy. -func GenerateSerialNumberWithRandomSource(randReader io.Reader) (*big.Int, error) { - return generateSerialNumber(randReader) -} - -func generateSerialNumber(randReader io.Reader) (*big.Int, error) { - serial, err := rand.Int(randReader, (&big.Int{}).Exp(big.NewInt(2), big.NewInt(159), nil)) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error generating serial number: %v", err)} - } - return serial, nil -} - -// ComparePublicKeysAndType compares two public keys and returns true if they match, -// false if their types or contents differ, and an error on unsupported key types. -func ComparePublicKeysAndType(key1Iface, key2Iface crypto.PublicKey) (bool, error) { - equal, err := ComparePublicKeys(key1Iface, key2Iface) - if err != nil { - if strings.Contains(err.Error(), "key types do not match:") { - return false, nil - } - } - - return equal, err -} - -// ComparePublicKeys compares two public keys and returns true if they match, -// returns an error if public key types are mismatched, or they are an unsupported key type. -func ComparePublicKeys(key1Iface, key2Iface crypto.PublicKey) (bool, error) { - switch key1Iface.(type) { - case *rsa.PublicKey: - key1 := key1Iface.(*rsa.PublicKey) - key2, ok := key2Iface.(*rsa.PublicKey) - if !ok { - return false, fmt.Errorf("key types do not match: %T and %T", key1Iface, key2Iface) - } - if key1.N.Cmp(key2.N) != 0 || - key1.E != key2.E { - return false, nil - } - return true, nil - - case *ecdsa.PublicKey: - key1 := key1Iface.(*ecdsa.PublicKey) - key2, ok := key2Iface.(*ecdsa.PublicKey) - if !ok { - return false, fmt.Errorf("key types do not match: %T and %T", key1Iface, key2Iface) - } - if key1.X.Cmp(key2.X) != 0 || - key1.Y.Cmp(key2.Y) != 0 { - return false, nil - } - key1Params := key1.Params() - key2Params := key2.Params() - if key1Params.P.Cmp(key2Params.P) != 0 || - key1Params.N.Cmp(key2Params.N) != 0 || - key1Params.B.Cmp(key2Params.B) != 0 || - key1Params.Gx.Cmp(key2Params.Gx) != 0 || - key1Params.Gy.Cmp(key2Params.Gy) != 0 || - key1Params.BitSize != key2Params.BitSize { - return false, nil - } - return true, nil - case ed25519.PublicKey: - key1 := key1Iface.(ed25519.PublicKey) - key2, ok := key2Iface.(ed25519.PublicKey) - if !ok { - return false, fmt.Errorf("key types do not match: %T and %T", key1Iface, key2Iface) - } - if !key1.Equal(key2) { - return false, nil - } - return true, nil - default: - return false, fmt.Errorf("cannot compare key with type %T", key1Iface) - } -} - -// ParsePublicKeyPEM is used to parse RSA and ECDSA public keys from PEMs -func ParsePublicKeyPEM(data []byte) (interface{}, error) { - block, data := pem.Decode(data) - if block != nil { - if len(bytes.TrimSpace(data)) > 0 { - return nil, errutil.UserError{Err: "unexpected trailing data after parsed PEM block"} - } - var rawKey interface{} - var err error - if rawKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - rawKey = cert.PublicKey - } else { - return nil, err - } - } - - switch key := rawKey.(type) { - case *rsa.PublicKey: - return key, nil - case *ecdsa.PublicKey: - return key, nil - case ed25519.PublicKey: - return key, nil - } - } - return nil, errors.New("data does not contain any valid public keys") -} - -// AddPolicyIdentifiers adds certificate policies extension, based on CreationBundle -func AddPolicyIdentifiers(data *CreationBundle, certTemplate *x509.Certificate) { - oidOnly := true - for _, oidStr := range data.Params.PolicyIdentifiers { - oid, err := StringToOid(oidStr) - if err == nil { - certTemplate.PolicyIdentifiers = append(certTemplate.PolicyIdentifiers, oid) - } - if err != nil { - oidOnly = false - } - } - if !oidOnly { // Because all policy information is held in the same extension, when we use an extra extension to - // add policy qualifier information, that overwrites any information in the PolicyIdentifiers field on the Cert - // Template, so we need to reparse all the policy identifiers here - extension, err := CreatePolicyInformationExtensionFromStorageStrings(data.Params.PolicyIdentifiers) - if err == nil { - // If this errors out, don't add it, rely on the OIDs parsed into PolicyIdentifiers above - certTemplate.ExtraExtensions = append(certTemplate.ExtraExtensions, *extension) - } - } -} - -// AddExtKeyUsageOids adds custom extended key usage OIDs to certificate -func AddExtKeyUsageOids(data *CreationBundle, certTemplate *x509.Certificate) { - for _, oidstr := range data.Params.ExtKeyUsageOIDs { - oid, err := StringToOid(oidstr) - if err == nil { - certTemplate.UnknownExtKeyUsage = append(certTemplate.UnknownExtKeyUsage, oid) - } - } -} - -func HandleOtherCSRSANs(in *x509.CertificateRequest, sans map[string][]string) error { - certTemplate := &x509.Certificate{ - DNSNames: in.DNSNames, - IPAddresses: in.IPAddresses, - EmailAddresses: in.EmailAddresses, - URIs: in.URIs, - } - if err := HandleOtherSANs(certTemplate, sans); err != nil { - return err - } - if len(certTemplate.ExtraExtensions) > 0 { - for _, v := range certTemplate.ExtraExtensions { - in.ExtraExtensions = append(in.ExtraExtensions, v) - } - } - return nil -} - -func HandleOtherSANs(in *x509.Certificate, sans map[string][]string) error { - // If other SANs is empty we return which causes normal Go stdlib parsing - // of the other SAN types - if len(sans) == 0 { - return nil - } - - var rawValues []asn1.RawValue - - // We need to generate an IMPLICIT sequence for compatibility with OpenSSL - // -- it's an open question what the default for RFC 5280 actually is, see - // https://github.com/openssl/openssl/issues/5091 -- so we have to use - // cryptobyte because using the asn1 package's marshaling always produces - // an EXPLICIT sequence. Note that asn1 is way too magical according to - // agl, and cryptobyte is modeled after the CBB/CBS bits that agl put into - // boringssl. - for oid, vals := range sans { - for _, val := range vals { - var b cryptobyte.Builder - oidStr, err := StringToOid(oid) - if err != nil { - return err - } - b.AddASN1ObjectIdentifier(oidStr) - b.AddASN1(cbasn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { - b.AddASN1(cbasn1.UTF8String, func(b *cryptobyte.Builder) { - b.AddBytes([]byte(val)) - }) - }) - m, err := b.Bytes() - if err != nil { - return err - } - rawValues = append(rawValues, asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: m}) - } - } - - // If other SANs is empty we return which causes normal Go stdlib parsing - // of the other SAN types - if len(rawValues) == 0 { - return nil - } - - // Append any existing SANs, sans marshalling - rawValues = append(rawValues, marshalSANs(in.DNSNames, in.EmailAddresses, in.IPAddresses, in.URIs)...) - - // Marshal and add to ExtraExtensions - ext := pkix.Extension{ - // This is the defined OID for subjectAltName - Id: asn1.ObjectIdentifier{2, 5, 29, 17}, - } - var err error - ext.Value, err = asn1.Marshal(rawValues) - if err != nil { - return err - } - in.ExtraExtensions = append(in.ExtraExtensions, ext) - - return nil -} - -// Note: Taken from the Go source code since it's not public, and used in the -// modified function below (which also uses these consts upstream) -const ( - nameTypeEmail = 1 - nameTypeDNS = 2 - nameTypeURI = 6 - nameTypeIP = 7 -) - -// Note: Taken from the Go source code since it's not public, plus changed to not marshal -// marshalSANs marshals a list of addresses into a the contents of an X.509 -// SubjectAlternativeName extension. -func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) []asn1.RawValue { - var rawValues []asn1.RawValue - for _, name := range dnsNames { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)}) - } - for _, email := range emailAddresses { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)}) - } - for _, rawIP := range ipAddresses { - // If possible, we always want to encode IPv4 addresses in 4 bytes. - ip := rawIP.To4() - if ip == nil { - ip = rawIP - } - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip}) - } - for _, uri := range uris { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())}) - } - return rawValues -} - -func StringToOid(in string) (asn1.ObjectIdentifier, error) { - split := strings.Split(in, ".") - ret := make(asn1.ObjectIdentifier, 0, len(split)) - for _, v := range split { - i, err := strconv.Atoi(v) - if err != nil { - return nil, err - } - ret = append(ret, i) - } - return asn1.ObjectIdentifier(ret), nil -} - -// Returns default key bits for the specified key type, or the present value -// if keyBits is non-zero. -func DefaultOrValueKeyBits(keyType string, keyBits int) (int, error) { - if keyBits == 0 { - newValue, present := defaultAlgorithmKeyBits[keyType] - if present { - keyBits = newValue - } /* else { - // We cannot return an error here as ed25519 (and potentially ed448 - // in the future) aren't in defaultAlgorithmKeyBits -- the value of - // the keyBits parameter is ignored under that algorithm. - } */ - } - - return keyBits, nil -} - -// Returns default signature hash bit length for the specified key type and -// bits, or the present value if hashBits is non-zero. Returns an error under -// certain internal circumstances. -func DefaultOrValueHashBits(keyType string, keyBits int, hashBits int) (int, error) { - if keyType == "ec" { - // Enforcement of curve moved to selectSignatureAlgorithmForECDSA. See - // note there about why. - } else if keyType == "rsa" && hashBits == 0 { - // To match previous behavior (and ignoring NIST's recommendations for - // hash size to align with RSA key sizes), default to SHA-2-256. - hashBits = 256 - } else if keyType == "ed25519" || keyType == "ed448" || keyType == "any" { - // No-op; ed25519 and ed448 internally specify their own hash and - // we do not need to select one. Double hashing isn't supported in - // certificate signing. Additionally, the any key type can't know - // what hash algorithm to use yet, so default to zero. - return 0, nil - } - - return hashBits, nil -} - -// Validates that the combination of keyType, keyBits, and hashBits are -// valid together; replaces individual calls to ValidateSignatureLength and -// ValidateKeyTypeLength. Also updates the value of keyBits and hashBits on -// return. -func ValidateDefaultOrValueKeyTypeSignatureLength(keyType string, keyBits int, hashBits int) (int, int, error) { - var err error - - if keyBits, err = DefaultOrValueKeyBits(keyType, keyBits); err != nil { - return keyBits, hashBits, err - } - - if err = ValidateKeyTypeLength(keyType, keyBits); err != nil { - return keyBits, hashBits, err - } - - if hashBits, err = DefaultOrValueHashBits(keyType, keyBits, hashBits); err != nil { - return keyBits, hashBits, err - } - - // Note that this check must come after we've selected a value for - // hashBits above, in the event it was left as the default, but we - // were allowed to update it. - if err = ValidateSignatureLength(keyType, hashBits); err != nil { - return keyBits, hashBits, err - } - - return keyBits, hashBits, nil -} - -// Validates that the length of the hash (in bits) used in the signature -// calculation is a known, approved value. -func ValidateSignatureLength(keyType string, hashBits int) error { - if keyType == "any" || keyType == "ec" || keyType == "ed25519" || keyType == "ed448" { - // ed25519 and ed448 include built-in hashing and is not externally - // configurable. There are three modes for each of these schemes: - // - // 1. Built-in hash (default, used in TLS, x509). - // 2. Double hash (notably used in some block-chain implementations, - // but largely regarded as a specialized use case with security - // concerns). - // 3. No hash (bring your own hash function, less commonly used). - // - // In all cases, we won't have a hash algorithm to validate here, so - // return nil. - // - // Additionally, when KeyType is any, we can't yet validate the - // signature algorithm size, so it takes the default zero value. - // - // When KeyType is ec, we also can't validate this value as we're - // forcefully ignoring the users' choice and specifying a value based - // on issuer type. - return nil - } - - switch hashBits { - case 256: - case 384: - case 512: - default: - return fmt.Errorf("unsupported hash signature algorithm: %d", hashBits) - } - - return nil -} - -func ValidateKeyTypeLength(keyType string, keyBits int) error { - switch keyType { - case "rsa": - if keyBits < rsaMinimumSecureKeySize { - return fmt.Errorf("RSA keys < %d bits are unsafe and not supported: got %d", rsaMinimumSecureKeySize, keyBits) - } - - switch keyBits { - case 2048: - case 3072: - case 4096: - case 8192: - default: - return fmt.Errorf("unsupported bit length for RSA key: %d", keyBits) - } - case "ec": - _, present := expectedNISTPCurveHashBits[keyBits] - if !present { - return fmt.Errorf("unsupported bit length for EC key: %d", keyBits) - } - case "any", "ed25519": - default: - return fmt.Errorf("unknown key type %s", keyType) - } - - return nil -} - -// CreateCertificate uses CreationBundle and the default rand.Reader to -// generate a cert/keypair. -func CreateCertificate(data *CreationBundle) (*ParsedCertBundle, error) { - return createCertificate(data, rand.Reader, generatePrivateKey) -} - -// CreateCertificateWithRandomSource uses CreationBundle and a custom -// io.Reader for randomness to generate a cert/keypair. -func CreateCertificateWithRandomSource(data *CreationBundle, randReader io.Reader) (*ParsedCertBundle, error) { - return createCertificate(data, randReader, generatePrivateKey) -} - -// KeyGenerator Allow us to override how/what generates the private key -type KeyGenerator func(keyType string, keyBits int, container ParsedPrivateKeyContainer, entropyReader io.Reader) error - -func CreateCertificateWithKeyGenerator(data *CreationBundle, randReader io.Reader, keyGenerator KeyGenerator) (*ParsedCertBundle, error) { - return createCertificate(data, randReader, keyGenerator) -} - -// Set correct RSA sig algo -func certTemplateSetSigAlgo(certTemplate *x509.Certificate, data *CreationBundle) { - if data.Params.UsePSS { - switch data.Params.SignatureBits { - case 256: - certTemplate.SignatureAlgorithm = x509.SHA256WithRSAPSS - case 384: - certTemplate.SignatureAlgorithm = x509.SHA384WithRSAPSS - case 512: - certTemplate.SignatureAlgorithm = x509.SHA512WithRSAPSS - } - } else { - switch data.Params.SignatureBits { - case 256: - certTemplate.SignatureAlgorithm = x509.SHA256WithRSA - case 384: - certTemplate.SignatureAlgorithm = x509.SHA384WithRSA - case 512: - certTemplate.SignatureAlgorithm = x509.SHA512WithRSA - } - } -} - -// selectSignatureAlgorithmForRSA returns the proper x509.SignatureAlgorithm based on various properties set in the -// Creation Bundle parameter. This method will default to a SHA256 signature algorithm if the requested signature -// bits is not set/unknown. -func selectSignatureAlgorithmForRSA(data *CreationBundle) x509.SignatureAlgorithm { - if data.Params.UsePSS { - switch data.Params.SignatureBits { - case 256: - return x509.SHA256WithRSAPSS - case 384: - return x509.SHA384WithRSAPSS - case 512: - return x509.SHA512WithRSAPSS - default: - return x509.SHA256WithRSAPSS - } - } - - switch data.Params.SignatureBits { - case 256: - return x509.SHA256WithRSA - case 384: - return x509.SHA384WithRSA - case 512: - return x509.SHA512WithRSA - default: - return x509.SHA256WithRSA - } -} - -func createCertificate(data *CreationBundle, randReader io.Reader, privateKeyGenerator KeyGenerator) (*ParsedCertBundle, error) { - var err error - result := &ParsedCertBundle{} - - serialNumber, err := GenerateSerialNumber() - if err != nil { - return nil, err - } - - if err := privateKeyGenerator(data.Params.KeyType, - data.Params.KeyBits, - result, randReader); err != nil { - return nil, err - } - - subjKeyID, err := GetSubjKeyID(result.PrivateKey) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error getting subject key ID: %s", err)} - } - - certTemplate := &x509.Certificate{ - SerialNumber: serialNumber, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: data.Params.NotAfter, - IsCA: false, - SubjectKeyId: subjKeyID, - Subject: data.Params.Subject, - DNSNames: data.Params.DNSNames, - EmailAddresses: data.Params.EmailAddresses, - IPAddresses: data.Params.IPAddresses, - URIs: data.Params.URIs, - } - if data.Params.NotBeforeDuration > 0 { - certTemplate.NotBefore = time.Now().Add(-1 * data.Params.NotBeforeDuration) - } - - if err := HandleOtherSANs(certTemplate, data.Params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - // Add this before calling addKeyUsages - if data.SigningBundle == nil { - certTemplate.IsCA = true - } else if data.Params.BasicConstraintsValidForNonCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = false - } - - // This will only be filled in from the generation paths - if len(data.Params.PermittedDNSDomains) > 0 { - certTemplate.PermittedDNSDomains = data.Params.PermittedDNSDomains - certTemplate.PermittedDNSDomainsCritical = true - } - - AddPolicyIdentifiers(data, certTemplate) - - AddKeyUsages(data, certTemplate) - - AddExtKeyUsageOids(data, certTemplate) - - certTemplate.IssuingCertificateURL = data.Params.URLs.IssuingCertificates - certTemplate.CRLDistributionPoints = data.Params.URLs.CRLDistributionPoints - certTemplate.OCSPServer = data.Params.URLs.OCSPServers - - var certBytes []byte - if data.SigningBundle != nil { - privateKeyType := data.SigningBundle.PrivateKeyType - if privateKeyType == ManagedPrivateKey { - privateKeyType = GetPrivateKeyTypeFromSigner(data.SigningBundle.PrivateKey) - } - switch privateKeyType { - case RSAPrivateKey: - certTemplateSetSigAlgo(certTemplate, data) - case Ed25519PrivateKey: - certTemplate.SignatureAlgorithm = x509.PureEd25519 - case ECPrivateKey: - certTemplate.SignatureAlgorithm = selectSignatureAlgorithmForECDSA(data.SigningBundle.PrivateKey.Public(), data.Params.SignatureBits) - } - - caCert := data.SigningBundle.Certificate - certTemplate.AuthorityKeyId = caCert.SubjectKeyId - - certBytes, err = x509.CreateCertificate(randReader, certTemplate, caCert, result.PrivateKey.Public(), data.SigningBundle.PrivateKey) - } else { - // Creating a self-signed root - if data.Params.MaxPathLength == 0 { - certTemplate.MaxPathLen = 0 - certTemplate.MaxPathLenZero = true - } else { - certTemplate.MaxPathLen = data.Params.MaxPathLength - } - - switch data.Params.KeyType { - case "rsa": - certTemplateSetSigAlgo(certTemplate, data) - case "ed25519": - certTemplate.SignatureAlgorithm = x509.PureEd25519 - case "ec": - certTemplate.SignatureAlgorithm = selectSignatureAlgorithmForECDSA(result.PrivateKey.Public(), data.Params.SignatureBits) - } - - certTemplate.AuthorityKeyId = subjKeyID - certTemplate.BasicConstraintsValid = true - certBytes, err = x509.CreateCertificate(randReader, certTemplate, certTemplate, result.PrivateKey.Public(), result.PrivateKey) - } - - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CertificateBytes = certBytes - result.Certificate, err = x509.ParseCertificate(certBytes) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)} - } - - if data.SigningBundle != nil { - if (len(data.SigningBundle.Certificate.AuthorityKeyId) > 0 && - !bytes.Equal(data.SigningBundle.Certificate.AuthorityKeyId, data.SigningBundle.Certificate.SubjectKeyId)) || - data.Params.ForceAppendCaChain { - var chain []*CertBlock - - signingChain := data.SigningBundle.CAChain - // Some bundles already include the root included in the chain, so don't include it twice. - if len(signingChain) == 0 || !bytes.Equal(signingChain[0].Bytes, data.SigningBundle.CertificateBytes) { - chain = append(chain, &CertBlock{ - Certificate: data.SigningBundle.Certificate, - Bytes: data.SigningBundle.CertificateBytes, - }) - } - - if len(signingChain) > 0 { - chain = append(chain, signingChain...) - } - - result.CAChain = chain - } - } - - return result, nil -} - -func selectSignatureAlgorithmForECDSA(pub crypto.PublicKey, signatureBits int) x509.SignatureAlgorithm { - // Previously we preferred the user-specified signature bits for ECDSA - // keys. However, this could result in using a longer hash function than - // the underlying NIST P-curve will encode (e.g., a SHA-512 hash with a - // P-256 key). This isn't ideal: the hash is implicitly truncated - // (effectively turning it into SHA-512/256) and we then need to rely - // on the prefix security of the hash. Since both NIST and Mozilla guidance - // suggest instead using the correct hash function, we should prefer that - // over the operator-specified signatureBits. - // - // Lastly, note that pub above needs to be the _signer's_ public key; - // the issue with DefaultOrValueHashBits is that it is called at role - // configuration time, which might _precede_ issuer generation. Thus - // it only has access to the desired key type and not the actual issuer. - // The reference from that function is reproduced below: - // - // > To comply with BSI recommendations Section 4.2 and Mozilla root - // > store policy section 5.1.2, enforce that NIST P-curves use a hash - // > length corresponding to curve length. Note that ed25519 does not - // > implement the "ec" key type. - key, ok := pub.(*ecdsa.PublicKey) - if !ok { - return x509.ECDSAWithSHA256 - } - switch key.Curve { - case elliptic.P224(), elliptic.P256(): - return x509.ECDSAWithSHA256 - case elliptic.P384(): - return x509.ECDSAWithSHA384 - case elliptic.P521(): - return x509.ECDSAWithSHA512 - default: - return x509.ECDSAWithSHA256 - } -} - -var ( - oidExtensionBasicConstraints = []int{2, 5, 29, 19} - oidExtensionSubjectAltName = []int{2, 5, 29, 17} -) - -// CreateCSR creates a CSR with the default rand.Reader to -// generate a cert/keypair. This is currently only meant -// for use when generating an intermediate certificate. -func CreateCSR(data *CreationBundle, addBasicConstraints bool) (*ParsedCSRBundle, error) { - return createCSR(data, addBasicConstraints, rand.Reader, generatePrivateKey) -} - -// CreateCSRWithRandomSource creates a CSR with a custom io.Reader -// for randomness to generate a cert/keypair. -func CreateCSRWithRandomSource(data *CreationBundle, addBasicConstraints bool, randReader io.Reader) (*ParsedCSRBundle, error) { - return createCSR(data, addBasicConstraints, randReader, generatePrivateKey) -} - -// CreateCSRWithKeyGenerator creates a CSR with a custom io.Reader -// for randomness to generate a cert/keypair with the provided private key generator. -func CreateCSRWithKeyGenerator(data *CreationBundle, addBasicConstraints bool, randReader io.Reader, keyGenerator KeyGenerator) (*ParsedCSRBundle, error) { - return createCSR(data, addBasicConstraints, randReader, keyGenerator) -} - -func createCSR(data *CreationBundle, addBasicConstraints bool, randReader io.Reader, keyGenerator KeyGenerator) (*ParsedCSRBundle, error) { - var err error - result := &ParsedCSRBundle{} - - if err := keyGenerator(data.Params.KeyType, - data.Params.KeyBits, - result, randReader); err != nil { - return nil, err - } - - // Like many root CAs, other information is ignored - csrTemplate := &x509.CertificateRequest{ - Subject: data.Params.Subject, - DNSNames: data.Params.DNSNames, - EmailAddresses: data.Params.EmailAddresses, - IPAddresses: data.Params.IPAddresses, - URIs: data.Params.URIs, - } - - if err := HandleOtherCSRSANs(csrTemplate, data.Params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - if addBasicConstraints { - type basicConstraints struct { - IsCA bool `asn1:"optional"` - MaxPathLen int `asn1:"optional,default:-1"` - } - val, err := asn1.Marshal(basicConstraints{IsCA: true, MaxPathLen: -1}) - if err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling basic constraints: {{err}}", err).Error()} - } - ext := pkix.Extension{ - Id: oidExtensionBasicConstraints, - Value: val, - Critical: true, - } - csrTemplate.ExtraExtensions = append(csrTemplate.ExtraExtensions, ext) - } - - switch data.Params.KeyType { - case "rsa": - // use specified RSA algorithm defaulting to the appropriate SHA256 RSA signature type - csrTemplate.SignatureAlgorithm = selectSignatureAlgorithmForRSA(data) - case "ec": - csrTemplate.SignatureAlgorithm = selectSignatureAlgorithmForECDSA(result.PrivateKey.Public(), data.Params.SignatureBits) - case "ed25519": - csrTemplate.SignatureAlgorithm = x509.PureEd25519 - } - - csr, err := x509.CreateCertificateRequest(randReader, csrTemplate, result.PrivateKey) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CSRBytes = csr - result.CSR, err = x509.ParseCertificateRequest(csr) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %v", err)} - } - - if err = result.CSR.CheckSignature(); err != nil { - return nil, errors.New("failed signature validation for CSR") - } - - return result, nil -} - -// SignCertificate performs the heavy lifting -// of generating a certificate from a CSR. -// Returns a ParsedCertBundle sans private keys. -func SignCertificate(data *CreationBundle) (*ParsedCertBundle, error) { - return signCertificate(data, rand.Reader) -} - -// SignCertificateWithRandomSource generates a certificate -// from a CSR, using custom randomness from the randReader. -// Returns a ParsedCertBundle sans private keys. -func SignCertificateWithRandomSource(data *CreationBundle, randReader io.Reader) (*ParsedCertBundle, error) { - return signCertificate(data, randReader) -} - -func signCertificate(data *CreationBundle, randReader io.Reader) (*ParsedCertBundle, error) { - switch { - case data == nil: - return nil, errutil.UserError{Err: "nil data bundle given to signCertificate"} - case data.Params == nil: - return nil, errutil.UserError{Err: "nil parameters given to signCertificate"} - case data.SigningBundle == nil: - return nil, errutil.UserError{Err: "nil signing bundle given to signCertificate"} - case data.CSR == nil: - return nil, errutil.UserError{Err: "nil csr given to signCertificate"} - } - - err := data.CSR.CheckSignature() - if err != nil { - return nil, errutil.UserError{Err: "request signature invalid"} - } - - result := &ParsedCertBundle{} - - serialNumber, err := GenerateSerialNumber() - if err != nil { - return nil, err - } - - subjKeyID, err := getSubjectKeyIDFromBundle(data) - if err != nil { - return nil, err - } - - caCert := data.SigningBundle.Certificate - - certTemplate := &x509.Certificate{ - SerialNumber: serialNumber, - Subject: data.Params.Subject, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: data.Params.NotAfter, - SubjectKeyId: subjKeyID[:], - AuthorityKeyId: caCert.SubjectKeyId, - } - if data.Params.NotBeforeDuration > 0 { - certTemplate.NotBefore = time.Now().Add(-1 * data.Params.NotBeforeDuration) - } - - privateKeyType := data.SigningBundle.PrivateKeyType - if privateKeyType == ManagedPrivateKey { - privateKeyType = GetPrivateKeyTypeFromSigner(data.SigningBundle.PrivateKey) - } - - switch privateKeyType { - case RSAPrivateKey: - certTemplateSetSigAlgo(certTemplate, data) - case ECPrivateKey: - switch data.Params.SignatureBits { - case 256: - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256 - case 384: - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA384 - case 512: - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA512 - } - } - - if data.Params.UseCSRValues { - certTemplate.Subject = data.CSR.Subject - certTemplate.Subject.ExtraNames = certTemplate.Subject.Names - - certTemplate.DNSNames = data.CSR.DNSNames - certTemplate.EmailAddresses = data.CSR.EmailAddresses - certTemplate.IPAddresses = data.CSR.IPAddresses - certTemplate.URIs = data.CSR.URIs - - for _, name := range data.CSR.Extensions { - if !name.Id.Equal(oidExtensionBasicConstraints) && !(len(data.Params.OtherSANs) > 0 && name.Id.Equal(oidExtensionSubjectAltName)) { - certTemplate.ExtraExtensions = append(certTemplate.ExtraExtensions, name) - } - } - - } else { - certTemplate.DNSNames = data.Params.DNSNames - certTemplate.EmailAddresses = data.Params.EmailAddresses - certTemplate.IPAddresses = data.Params.IPAddresses - certTemplate.URIs = data.Params.URIs - } - - if err := HandleOtherSANs(certTemplate, data.Params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - AddPolicyIdentifiers(data, certTemplate) - - AddKeyUsages(data, certTemplate) - - AddExtKeyUsageOids(data, certTemplate) - - var certBytes []byte - - certTemplate.IssuingCertificateURL = data.Params.URLs.IssuingCertificates - certTemplate.CRLDistributionPoints = data.Params.URLs.CRLDistributionPoints - certTemplate.OCSPServer = data.SigningBundle.URLs.OCSPServers - - if data.Params.IsCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = true - - if data.SigningBundle.Certificate.MaxPathLen == 0 && - data.SigningBundle.Certificate.MaxPathLenZero { - return nil, errutil.UserError{Err: "signing certificate has a max path length of zero, and cannot issue further CA certificates"} - } - - certTemplate.MaxPathLen = data.Params.MaxPathLength - if certTemplate.MaxPathLen == 0 { - certTemplate.MaxPathLenZero = true - } - } else if data.Params.BasicConstraintsValidForNonCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = false - } - - if len(data.Params.PermittedDNSDomains) > 0 { - certTemplate.PermittedDNSDomains = data.Params.PermittedDNSDomains - certTemplate.PermittedDNSDomainsCritical = true - } - - certBytes, err = x509.CreateCertificate(randReader, certTemplate, caCert, data.CSR.PublicKey, data.SigningBundle.PrivateKey) - - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CertificateBytes = certBytes - result.Certificate, err = x509.ParseCertificate(certBytes) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)} - } - - result.CAChain = data.SigningBundle.GetFullChain() - - return result, nil -} - -func NewCertPool(reader io.Reader) (*x509.CertPool, error) { - pemBlock, err := ioutil.ReadAll(reader) - if err != nil { - return nil, err - } - certs, err := parseCertsPEM(pemBlock) - if err != nil { - return nil, fmt.Errorf("error reading certs: %s", err) - } - pool := x509.NewCertPool() - for _, cert := range certs { - pool.AddCert(cert) - } - return pool, nil -} - -// parseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array -// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates -func parseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) { - ok := false - certs := []*x509.Certificate{} - for len(pemCerts) > 0 { - var block *pem.Block - block, pemCerts = pem.Decode(pemCerts) - if block == nil { - break - } - // Only use PEM "CERTIFICATE" blocks without extra headers - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - continue - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return certs, err - } - - certs = append(certs, cert) - ok = true - } - - if !ok { - return certs, errors.New("data does not contain any valid RSA or ECDSA certificates") - } - return certs, nil -} - -// GetPublicKeySize returns the key size in bits for a given arbitrary crypto.PublicKey -// Returns -1 for an unsupported key type. -func GetPublicKeySize(key crypto.PublicKey) int { - if key, ok := key.(*rsa.PublicKey); ok { - return key.Size() * 8 - } - if key, ok := key.(*ecdsa.PublicKey); ok { - return key.Params().BitSize - } - if key, ok := key.(ed25519.PublicKey); ok { - return len(key) * 8 - } - if key, ok := key.(dsa.PublicKey); ok { - return key.Y.BitLen() - } - - return -1 -} - -// CreateKeyBundle create a KeyBundle struct object which includes a generated key -// of keyType with keyBits leveraging the randomness from randReader. -func CreateKeyBundle(keyType string, keyBits int, randReader io.Reader) (KeyBundle, error) { - return CreateKeyBundleWithKeyGenerator(keyType, keyBits, randReader, generatePrivateKey) -} - -// CreateKeyBundleWithKeyGenerator create a KeyBundle struct object which includes -// a generated key of keyType with keyBits leveraging the randomness from randReader and -// delegates the actual key generation to keyGenerator -func CreateKeyBundleWithKeyGenerator(keyType string, keyBits int, randReader io.Reader, keyGenerator KeyGenerator) (KeyBundle, error) { - result := KeyBundle{} - if err := keyGenerator(keyType, keyBits, &result, randReader); err != nil { - return result, err - } - return result, nil -} - -// CreateDeltaCRLIndicatorExt allows creating correctly formed delta CRLs -// that point back to the last complete CRL that they're based on. -func CreateDeltaCRLIndicatorExt(completeCRLNumber int64) (pkix.Extension, error) { - bigNum := big.NewInt(completeCRLNumber) - bigNumValue, err := asn1.Marshal(bigNum) - if err != nil { - return pkix.Extension{}, fmt.Errorf("unable to marshal complete CRL number (%v): %v", completeCRLNumber, err) - } - return pkix.Extension{ - Id: DeltaCRLIndicatorOID, - // > When a conforming CRL issuer generates a delta CRL, the delta - // > CRL MUST include a critical delta CRL indicator extension. - Critical: true, - // This extension only includes the complete CRL number: - // - // > BaseCRLNumber ::= CRLNumber - // - // But, this needs to be encoded as a big number for encoding/asn1 - // to work properly. - Value: bigNumValue, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/certutil/types.go b/vendor/github.com/hashicorp/vault/sdk/helper/certutil/types.go deleted file mode 100644 index 15b816f0c..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/certutil/types.go +++ /dev/null @@ -1,1015 +0,0 @@ -// Package certutil contains helper functions that are mostly used -// with the PKI backend but can be generally useful. Functionality -// includes helpers for converting a certificate/private key bundle -// between DER and PEM, printing certificate serial numbers, and more. -// -// Functionality specific to the PKI backend includes some types -// and helper methods to make requesting certificates from the -// backend easy. -package certutil - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "math/big" - "net" - "net/url" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/sdk/helper/errutil" -) - -const ( - PrivateKeyTypeP521 = "p521" -) - -// This can be one of a few key types so the different params may or may not be filled -type ClusterKeyParams struct { - Type string `json:"type" structs:"type" mapstructure:"type"` - X *big.Int `json:"x" structs:"x" mapstructure:"x"` - Y *big.Int `json:"y" structs:"y" mapstructure:"y"` - D *big.Int `json:"d" structs:"d" mapstructure:"d"` -} - -// Secret is used to attempt to unmarshal a Vault secret -// JSON response, as a convenience -type Secret struct { - Data map[string]interface{} `json:"data"` -} - -// PrivateKeyType holds a string representation of the type of private key (ec -// or rsa) referenced in CertBundle and ParsedCertBundle. This uses colloquial -// names rather than official names, to eliminate confusion -type PrivateKeyType string - -// Well-known PrivateKeyTypes -const ( - UnknownPrivateKey PrivateKeyType = "" - RSAPrivateKey PrivateKeyType = "rsa" - ECPrivateKey PrivateKeyType = "ec" - Ed25519PrivateKey PrivateKeyType = "ed25519" - ManagedPrivateKey PrivateKeyType = "ManagedPrivateKey" -) - -// TLSUsage controls whether the intended usage of a *tls.Config -// returned from ParsedCertBundle.getTLSConfig is for server use, -// client use, or both, which affects which values are set -type TLSUsage int - -// Well-known TLSUsage types -const ( - TLSUnknown TLSUsage = 0 - TLSServer TLSUsage = 1 << iota - TLSClient -) - -// BlockType indicates the serialization format of the key -type BlockType string - -// Well-known formats -const ( - UnknownBlock BlockType = "" - PKCS1Block BlockType = "RSA PRIVATE KEY" - PKCS8Block BlockType = "PRIVATE KEY" - ECBlock BlockType = "EC PRIVATE KEY" -) - -// ParsedPrivateKeyContainer allows common key setting for certs and CSRs -type ParsedPrivateKeyContainer interface { - SetParsedPrivateKey(crypto.Signer, PrivateKeyType, []byte) -} - -// CertBlock contains the DER-encoded certificate and the PEM -// block's byte array -type CertBlock struct { - Certificate *x509.Certificate - Bytes []byte -} - -// CertBundle contains a key type, a PEM-encoded private key, -// a PEM-encoded certificate, and a string-encoded serial number, -// returned from a successful Issue request -type CertBundle struct { - PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"` - Certificate string `json:"certificate" structs:"certificate" mapstructure:"certificate"` - IssuingCA string `json:"issuing_ca" structs:"issuing_ca" mapstructure:"issuing_ca"` - CAChain []string `json:"ca_chain" structs:"ca_chain" mapstructure:"ca_chain"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` - SerialNumber string `json:"serial_number" structs:"serial_number" mapstructure:"serial_number"` -} - -// ParsedCertBundle contains a key type, a DER-encoded private key, -// and a DER-encoded certificate -type ParsedCertBundle struct { - PrivateKeyType PrivateKeyType - PrivateKeyFormat BlockType - PrivateKeyBytes []byte - PrivateKey crypto.Signer - CertificateBytes []byte - Certificate *x509.Certificate - CAChain []*CertBlock -} - -// CSRBundle contains a key type, a PEM-encoded private key, -// and a PEM-encoded CSR -type CSRBundle struct { - PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"` - CSR string `json:"csr" structs:"csr" mapstructure:"csr"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` -} - -// ParsedCSRBundle contains a key type, a DER-encoded private key, -// and a DER-encoded certificate request -type ParsedCSRBundle struct { - PrivateKeyType PrivateKeyType - PrivateKeyBytes []byte - PrivateKey crypto.Signer - CSRBytes []byte - CSR *x509.CertificateRequest -} - -type KeyBundle struct { - PrivateKeyType PrivateKeyType - PrivateKeyBytes []byte - PrivateKey crypto.Signer -} - -func GetPrivateKeyTypeFromSigner(signer crypto.Signer) PrivateKeyType { - // We look at the public key types to work-around limitations/typing of managed keys. - switch signer.Public().(type) { - case *rsa.PublicKey: - return RSAPrivateKey - case *ecdsa.PublicKey: - return ECPrivateKey - case ed25519.PublicKey: - return Ed25519PrivateKey - } - return UnknownPrivateKey -} - -// ToPEMBundle converts a string-based certificate bundle -// to a PEM-based string certificate bundle in trust path -// order, leaf certificate first -func (c *CertBundle) ToPEMBundle() string { - var result []string - - if len(c.PrivateKey) > 0 { - result = append(result, c.PrivateKey) - } - if len(c.Certificate) > 0 { - result = append(result, c.Certificate) - } - if len(c.CAChain) > 0 { - result = append(result, c.CAChain...) - } - - return strings.Join(result, "\n") -} - -// ToParsedCertBundle converts a string-based certificate bundle -// to a byte-based raw certificate bundle -func (c *CertBundle) ToParsedCertBundle() (*ParsedCertBundle, error) { - return c.ToParsedCertBundleWithExtractor(extractAndSetPrivateKey) -} - -// PrivateKeyExtractor extract out a private key from the passed in -// CertBundle and set the appropriate bits within the ParsedCertBundle. -type PrivateKeyExtractor func(c *CertBundle, parsedBundle *ParsedCertBundle) error - -func (c *CertBundle) ToParsedCertBundleWithExtractor(privateKeyExtractor PrivateKeyExtractor) (*ParsedCertBundle, error) { - var err error - var pemBlock *pem.Block - result := &ParsedCertBundle{} - - err = privateKeyExtractor(c, result) - if err != nil { - return nil, err - } - - if len(c.Certificate) > 0 { - pemBlock, _ = pem.Decode([]byte(c.Certificate)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - result.CertificateBytes = pemBlock.Bytes - result.Certificate, err = x509.ParseCertificate(result.CertificateBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle: %v", err)} - } - } - switch { - case len(c.CAChain) > 0: - for _, cert := range c.CAChain { - pemBlock, _ := pem.Decode([]byte(cert)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - - parsedCert, err := x509.ParseCertificate(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via CA chain: %v", err)} - } - - certBlock := &CertBlock{ - Bytes: pemBlock.Bytes, - Certificate: parsedCert, - } - result.CAChain = append(result.CAChain, certBlock) - } - - // For backwards compatibility - case len(c.IssuingCA) > 0: - pemBlock, _ = pem.Decode([]byte(c.IssuingCA)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding ca certificate from cert bundle"} - } - - parsedCert, err := x509.ParseCertificate(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via issuing CA: %v", err)} - } - - certBlock := &CertBlock{ - Bytes: pemBlock.Bytes, - Certificate: parsedCert, - } - result.CAChain = append(result.CAChain, certBlock) - } - - // Populate if it isn't there already - if len(c.SerialNumber) == 0 && len(c.Certificate) > 0 { - c.SerialNumber = GetHexFormatted(result.Certificate.SerialNumber.Bytes(), ":") - } - - return result, nil -} - -func extractAndSetPrivateKey(c *CertBundle, parsedBundle *ParsedCertBundle) error { - if len(c.PrivateKey) == 0 { - return nil - } - - pemBlock, _ := pem.Decode([]byte(c.PrivateKey)) - if pemBlock == nil { - return errutil.UserError{Err: "Error decoding private key from cert bundle"} - } - - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKeyFormat = BlockType(strings.TrimSpace(pemBlock.Type)) - - switch parsedBundle.PrivateKeyFormat { - case ECBlock: - parsedBundle.PrivateKeyType, c.PrivateKeyType = ECPrivateKey, ECPrivateKey - case PKCS1Block: - c.PrivateKeyType, parsedBundle.PrivateKeyType = RSAPrivateKey, RSAPrivateKey - case PKCS8Block: - t, err := getPKCS8Type(pemBlock.Bytes) - if err != nil { - return errutil.UserError{Err: fmt.Sprintf("Error getting key type from pkcs#8: %v", err)} - } - parsedBundle.PrivateKeyType = t - switch t { - case ECPrivateKey: - c.PrivateKeyType = ECPrivateKey - case RSAPrivateKey: - c.PrivateKeyType = RSAPrivateKey - case Ed25519PrivateKey: - c.PrivateKeyType = Ed25519PrivateKey - case ManagedPrivateKey: - c.PrivateKeyType = ManagedPrivateKey - } - default: - return errutil.UserError{Err: fmt.Sprintf("Unsupported key block type: %s", pemBlock.Type)} - } - - var err error - parsedBundle.PrivateKey, err = parsedBundle.getSigner() - if err != nil { - return errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", err)} - } - return nil -} - -// ToCertBundle converts a byte-based raw DER certificate bundle -// to a PEM-based string certificate bundle -func (p *ParsedCertBundle) ToCertBundle() (*CertBundle, error) { - result := &CertBundle{} - block := pem.Block{ - Type: "CERTIFICATE", - } - - if p.Certificate != nil { - result.SerialNumber = strings.TrimSpace(GetHexFormatted(p.Certificate.SerialNumber.Bytes(), ":")) - } - - if p.CertificateBytes != nil && len(p.CertificateBytes) > 0 { - block.Bytes = p.CertificateBytes - result.Certificate = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - for _, caCert := range p.CAChain { - block.Bytes = caCert.Bytes - certificate := strings.TrimSpace(string(pem.EncodeToMemory(&block))) - - result.CAChain = append(result.CAChain, certificate) - } - - if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 { - block.Type = string(p.PrivateKeyFormat) - block.Bytes = p.PrivateKeyBytes - result.PrivateKeyType = p.PrivateKeyType - - // Handle bundle not parsed by us - if block.Type == "" { - switch p.PrivateKeyType { - case ECPrivateKey: - block.Type = string(ECBlock) - case RSAPrivateKey: - block.Type = string(PKCS1Block) - case Ed25519PrivateKey: - block.Type = string(PKCS8Block) - } - } - - result.PrivateKey = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - return result, nil -} - -// Verify checks if the parsed bundle is valid. It validates the public -// key of the certificate to the private key and checks the certificate trust -// chain for path issues. -func (p *ParsedCertBundle) Verify() error { - // If private key exists, check if it matches the public key of cert - if p.PrivateKey != nil && p.Certificate != nil { - equal, err := ComparePublicKeys(p.Certificate.PublicKey, p.PrivateKey.Public()) - if err != nil { - return errwrap.Wrapf("could not compare public and private keys: {{err}}", err) - } - if !equal { - return fmt.Errorf("public key of certificate does not match private key") - } - } - - certPath := p.GetCertificatePath() - if len(certPath) > 1 { - for i, caCert := range certPath[1:] { - if !caCert.Certificate.IsCA { - return fmt.Errorf("certificate %d of certificate chain is not a certificate authority", i+1) - } - if !bytes.Equal(certPath[i].Certificate.AuthorityKeyId, caCert.Certificate.SubjectKeyId) { - return fmt.Errorf("certificate %d of certificate chain ca trust path is incorrect (%q/%q) (%X/%X)", - i+1, - certPath[i].Certificate.Subject.CommonName, caCert.Certificate.Subject.CommonName, - certPath[i].Certificate.AuthorityKeyId, caCert.Certificate.SubjectKeyId) - } - } - } - - return nil -} - -// GetCertificatePath returns a slice of certificates making up a path, pulled -// from the parsed cert bundle -func (p *ParsedCertBundle) GetCertificatePath() []*CertBlock { - var certPath []*CertBlock - - certPath = append(certPath, &CertBlock{ - Certificate: p.Certificate, - Bytes: p.CertificateBytes, - }) - - if len(p.CAChain) > 0 { - // Root CA puts itself in the chain - if p.CAChain[0].Certificate.SerialNumber != p.Certificate.SerialNumber { - certPath = append(certPath, p.CAChain...) - } - } - - return certPath -} - -// GetSigner returns a crypto.Signer corresponding to the private key -// contained in this ParsedCertBundle. The Signer contains a Public() function -// for getting the corresponding public. The Signer can also be -// type-converted to private keys -func (p *ParsedCertBundle) getSigner() (crypto.Signer, error) { - var signer crypto.Signer - var err error - - if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 { - return nil, errutil.UserError{Err: "Given parsed cert bundle does not have private key information"} - } - - switch p.PrivateKeyFormat { - case ECBlock: - signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private EC key: %s", err)} - } - - case PKCS1Block: - signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)} - } - - case PKCS8Block: - if k, err := x509.ParsePKCS8PrivateKey(p.PrivateKeyBytes); err == nil { - switch k := k.(type) { - case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey: - return k.(crypto.Signer), nil - default: - return nil, errutil.UserError{Err: "Found unknown private key type in pkcs#8 wrapping"} - } - } - return nil, errutil.UserError{Err: fmt.Sprintf("Failed to parse pkcs#8 key: %v", err)} - default: - return nil, errutil.UserError{Err: "Unable to determine type of private key; only RSA and EC are supported"} - } - return signer, nil -} - -// SetParsedPrivateKey sets the private key parameters on the bundle -func (p *ParsedCertBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte) { - p.PrivateKey = privateKey - p.PrivateKeyType = privateKeyType - p.PrivateKeyBytes = privateKeyBytes -} - -func getPKCS8Type(bs []byte) (PrivateKeyType, error) { - k, err := x509.ParsePKCS8PrivateKey(bs) - if err != nil { - return UnknownPrivateKey, errutil.UserError{Err: fmt.Sprintf("Failed to parse pkcs#8 key: %v", err)} - } - - switch k.(type) { - case *ecdsa.PrivateKey: - return ECPrivateKey, nil - case *rsa.PrivateKey: - return RSAPrivateKey, nil - case ed25519.PrivateKey: - return Ed25519PrivateKey, nil - default: - return UnknownPrivateKey, errutil.UserError{Err: "Found unknown private key type in pkcs#8 wrapping"} - } -} - -// ToParsedCSRBundle converts a string-based CSR bundle -// to a byte-based raw CSR bundle -func (c *CSRBundle) ToParsedCSRBundle() (*ParsedCSRBundle, error) { - result := &ParsedCSRBundle{} - var err error - var pemBlock *pem.Block - - if len(c.PrivateKey) > 0 { - pemBlock, _ = pem.Decode([]byte(c.PrivateKey)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding private key from cert bundle"} - } - result.PrivateKeyBytes = pemBlock.Bytes - - switch BlockType(pemBlock.Type) { - case ECBlock: - result.PrivateKeyType = ECPrivateKey - case PKCS1Block: - result.PrivateKeyType = RSAPrivateKey - default: - // Try to figure it out and correct - if _, err := x509.ParseECPrivateKey(pemBlock.Bytes); err == nil { - result.PrivateKeyType = ECPrivateKey - c.PrivateKeyType = "ec" - } else if _, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes); err == nil { - result.PrivateKeyType = RSAPrivateKey - c.PrivateKeyType = "rsa" - } else if _, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes); err == nil { - result.PrivateKeyType = Ed25519PrivateKey - c.PrivateKeyType = "ed25519" - } else { - return nil, errutil.UserError{Err: fmt.Sprintf("Unknown private key type in bundle: %s", c.PrivateKeyType)} - } - } - - result.PrivateKey, err = result.getSigner() - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", err)} - } - } - - if len(c.CSR) > 0 { - pemBlock, _ = pem.Decode([]byte(c.CSR)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - result.CSRBytes = pemBlock.Bytes - result.CSR, err = x509.ParseCertificateRequest(result.CSRBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via CSR: %v", err)} - } - } - - return result, nil -} - -// ToCSRBundle converts a byte-based raw DER certificate bundle -// to a PEM-based string certificate bundle -func (p *ParsedCSRBundle) ToCSRBundle() (*CSRBundle, error) { - result := &CSRBundle{} - block := pem.Block{ - Type: "CERTIFICATE REQUEST", - } - - if p.CSRBytes != nil && len(p.CSRBytes) > 0 { - block.Bytes = p.CSRBytes - result.CSR = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 { - block.Bytes = p.PrivateKeyBytes - switch p.PrivateKeyType { - case RSAPrivateKey: - result.PrivateKeyType = "rsa" - block.Type = "RSA PRIVATE KEY" - case ECPrivateKey: - result.PrivateKeyType = "ec" - block.Type = "EC PRIVATE KEY" - case Ed25519PrivateKey: - result.PrivateKeyType = "ed25519" - block.Type = "PRIVATE KEY" - case ManagedPrivateKey: - result.PrivateKeyType = ManagedPrivateKey - block.Type = "PRIVATE KEY" - default: - return nil, errutil.InternalError{Err: "Could not determine private key type when creating block"} - } - result.PrivateKey = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - return result, nil -} - -// GetSigner returns a crypto.Signer corresponding to the private key -// contained in this ParsedCSRBundle. The Signer contains a Public() function -// for getting the corresponding public. The Signer can also be -// type-converted to private keys -func (p *ParsedCSRBundle) getSigner() (crypto.Signer, error) { - var signer crypto.Signer - var err error - - if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 { - return nil, errutil.UserError{Err: "Given parsed cert bundle does not have private key information"} - } - - switch p.PrivateKeyType { - case ECPrivateKey: - signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private EC key: %s", err)} - } - - case RSAPrivateKey: - signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)} - } - - case Ed25519PrivateKey: - signerd, err := x509.ParsePKCS8PrivateKey(p.PrivateKeyBytes) - signer = signerd.(ed25519.PrivateKey) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private Ed25519 key: %s", err)} - } - - default: - return nil, errutil.UserError{Err: "Unable to determine type of private key; only RSA, Ed25519 and EC are supported"} - } - return signer, nil -} - -// SetParsedPrivateKey sets the private key parameters on the bundle -func (p *ParsedCSRBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte) { - p.PrivateKey = privateKey - p.PrivateKeyType = privateKeyType - p.PrivateKeyBytes = privateKeyBytes -} - -// getTLSConfig returns a TLS config generally suitable for client -// authentication. The returned TLS config can be modified slightly -// to be made suitable for a server requiring client authentication; -// specifically, you should set the value of ClientAuth in the returned -// config to match your needs. -func (p *ParsedCertBundle) GetTLSConfig(usage TLSUsage) (*tls.Config, error) { - tlsCert := tls.Certificate{ - Certificate: [][]byte{}, - } - - tlsConfig := &tls.Config{ - MinVersion: tls.VersionTLS12, - } - - if p.Certificate != nil { - tlsCert.Leaf = p.Certificate - } - - if p.PrivateKey != nil { - tlsCert.PrivateKey = p.PrivateKey - } - - if p.CertificateBytes != nil && len(p.CertificateBytes) > 0 { - tlsCert.Certificate = append(tlsCert.Certificate, p.CertificateBytes) - } - - if len(p.CAChain) > 0 { - for _, cert := range p.CAChain { - tlsCert.Certificate = append(tlsCert.Certificate, cert.Bytes) - } - - // Technically we only need one cert, but this doesn't duplicate code - certBundle, err := p.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting parsed bundle to string bundle when getting TLS config: {{err}}", err) - } - - caPool := x509.NewCertPool() - ok := caPool.AppendCertsFromPEM([]byte(certBundle.CAChain[0])) - if !ok { - return nil, fmt.Errorf("could not append CA certificate") - } - - if usage&TLSServer > 0 { - tlsConfig.ClientCAs = caPool - tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven - } - if usage&TLSClient > 0 { - tlsConfig.RootCAs = caPool - } - } - - if tlsCert.Certificate != nil && len(tlsCert.Certificate) > 0 { - tlsConfig.Certificates = []tls.Certificate{tlsCert} - } - - return tlsConfig, nil -} - -// IssueData is a structure that is suitable for marshaling into a request; -// either via JSON, or into a map[string]interface{} via the structs package -type IssueData struct { - TTL string `json:"ttl" structs:"ttl" mapstructure:"ttl"` - CommonName string `json:"common_name" structs:"common_name" mapstructure:"common_name"` - OU string `json:"ou" structs:"ou" mapstructure:"ou"` - AltNames string `json:"alt_names" structs:"alt_names" mapstructure:"alt_names"` - IPSANs string `json:"ip_sans" structs:"ip_sans" mapstructure:"ip_sans"` - CSR string `json:"csr" structs:"csr" mapstructure:"csr"` - OtherSANs string `json:"other_sans" structs:"other_sans" mapstructure:"other_sans"` -} - -type URLEntries struct { - IssuingCertificates []string `json:"issuing_certificates" structs:"issuing_certificates" mapstructure:"issuing_certificates"` - CRLDistributionPoints []string `json:"crl_distribution_points" structs:"crl_distribution_points" mapstructure:"crl_distribution_points"` - OCSPServers []string `json:"ocsp_servers" structs:"ocsp_servers" mapstructure:"ocsp_servers"` -} - -type NotAfterBehavior int - -const ( - ErrNotAfterBehavior NotAfterBehavior = iota - TruncateNotAfterBehavior - PermitNotAfterBehavior -) - -var notAfterBehaviorNames = map[NotAfterBehavior]string{ - ErrNotAfterBehavior: "err", - TruncateNotAfterBehavior: "truncate", - PermitNotAfterBehavior: "permit", -} - -func (n NotAfterBehavior) String() string { - if name, ok := notAfterBehaviorNames[n]; ok && len(name) > 0 { - return name - } - - return "unknown" -} - -type CAInfoBundle struct { - ParsedCertBundle - URLs *URLEntries - LeafNotAfterBehavior NotAfterBehavior - RevocationSigAlg x509.SignatureAlgorithm -} - -func (b *CAInfoBundle) GetCAChain() []*CertBlock { - chain := []*CertBlock{} - - // Include issuing CA in Chain, not including Root Authority - if (len(b.Certificate.AuthorityKeyId) > 0 && - !bytes.Equal(b.Certificate.AuthorityKeyId, b.Certificate.SubjectKeyId)) || - (len(b.Certificate.AuthorityKeyId) == 0 && - !bytes.Equal(b.Certificate.RawIssuer, b.Certificate.RawSubject)) { - - chain = b.GetFullChain() - } - - return chain -} - -func (b *CAInfoBundle) GetFullChain() []*CertBlock { - var chain []*CertBlock - - // Some bundles already include the root included in the chain, - // so don't include it twice. - if len(b.CAChain) == 0 || !bytes.Equal(b.CAChain[0].Bytes, b.CertificateBytes) { - chain = append(chain, &CertBlock{ - Certificate: b.Certificate, - Bytes: b.CertificateBytes, - }) - } - - if len(b.CAChain) > 0 { - chain = append(chain, b.CAChain...) - } - - return chain -} - -type CertExtKeyUsage int - -const ( - AnyExtKeyUsage CertExtKeyUsage = 1 << iota - ServerAuthExtKeyUsage - ClientAuthExtKeyUsage - CodeSigningExtKeyUsage - EmailProtectionExtKeyUsage - IpsecEndSystemExtKeyUsage - IpsecTunnelExtKeyUsage - IpsecUserExtKeyUsage - TimeStampingExtKeyUsage - OcspSigningExtKeyUsage - MicrosoftServerGatedCryptoExtKeyUsage - NetscapeServerGatedCryptoExtKeyUsage - MicrosoftCommercialCodeSigningExtKeyUsage - MicrosoftKernelCodeSigningExtKeyUsage -) - -type CreationParameters struct { - Subject pkix.Name - DNSNames []string - EmailAddresses []string - IPAddresses []net.IP - URIs []*url.URL - OtherSANs map[string][]string - IsCA bool - KeyType string - KeyBits int - NotAfter time.Time - KeyUsage x509.KeyUsage - ExtKeyUsage CertExtKeyUsage - ExtKeyUsageOIDs []string - PolicyIdentifiers []string - BasicConstraintsValidForNonCA bool - SignatureBits int - UsePSS bool - ForceAppendCaChain bool - - // Only used when signing a CA cert - UseCSRValues bool - PermittedDNSDomains []string - - // URLs to encode into the certificate - URLs *URLEntries - - // The maximum path length to encode - MaxPathLength int - - // The duration the certificate will use NotBefore - NotBeforeDuration time.Duration - - // The explicit SKID to use; especially useful for cross-signing. - SKID []byte -} - -type CreationBundle struct { - Params *CreationParameters - SigningBundle *CAInfoBundle - CSR *x509.CertificateRequest -} - -// addKeyUsages adds appropriate key usages to the template given the creation -// information -func AddKeyUsages(data *CreationBundle, certTemplate *x509.Certificate) { - if data.Params.IsCA { - certTemplate.KeyUsage = x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign) - return - } - - certTemplate.KeyUsage = data.Params.KeyUsage - - if data.Params.ExtKeyUsage&AnyExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageAny) - } - - if data.Params.ExtKeyUsage&ServerAuthExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageServerAuth) - } - - if data.Params.ExtKeyUsage&ClientAuthExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageClientAuth) - } - - if data.Params.ExtKeyUsage&CodeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageCodeSigning) - } - - if data.Params.ExtKeyUsage&EmailProtectionExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageEmailProtection) - } - - if data.Params.ExtKeyUsage&IpsecEndSystemExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECEndSystem) - } - - if data.Params.ExtKeyUsage&IpsecTunnelExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECTunnel) - } - - if data.Params.ExtKeyUsage&IpsecUserExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECUser) - } - - if data.Params.ExtKeyUsage&TimeStampingExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageTimeStamping) - } - - if data.Params.ExtKeyUsage&OcspSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageOCSPSigning) - } - - if data.Params.ExtKeyUsage&MicrosoftServerGatedCryptoExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftServerGatedCrypto) - } - - if data.Params.ExtKeyUsage&NetscapeServerGatedCryptoExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageNetscapeServerGatedCrypto) - } - - if data.Params.ExtKeyUsage&MicrosoftCommercialCodeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftCommercialCodeSigning) - } - - if data.Params.ExtKeyUsage&MicrosoftKernelCodeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftKernelCodeSigning) - } -} - -// SetParsedPrivateKey sets the private key parameters on the bundle -func (p *KeyBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte) { - p.PrivateKey = privateKey - p.PrivateKeyType = privateKeyType - p.PrivateKeyBytes = privateKeyBytes -} - -func (p *KeyBundle) ToPrivateKeyPemString() (string, error) { - block := pem.Block{} - - if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 { - block.Bytes = p.PrivateKeyBytes - switch p.PrivateKeyType { - case RSAPrivateKey: - block.Type = "RSA PRIVATE KEY" - case ECPrivateKey: - block.Type = "EC PRIVATE KEY" - default: - block.Type = "PRIVATE KEY" - } - privateKeyPemString := strings.TrimSpace(string(pem.EncodeToMemory(&block))) - return privateKeyPemString, nil - } - - return "", errutil.InternalError{Err: "No Private Key Bytes to Wrap"} -} - -// PolicyIdentifierWithQualifierEntry Structure for Internal Storage -type PolicyIdentifierWithQualifierEntry struct { - PolicyIdentifierOid string `json:"oid",mapstructure:"oid"` - CPS string `json:"cps,omitempty",mapstructure:"cps"` - Notice string `json:"notice,omitempty",mapstructure:"notice"` -} - -// GetPolicyIdentifierFromString parses out the internal structure of a Policy Identifier -func GetPolicyIdentifierFromString(policyIdentifier string) (*PolicyIdentifierWithQualifierEntry, error) { - if policyIdentifier == "" { - return nil, nil - } - entry := &PolicyIdentifierWithQualifierEntry{} - // Either a OID, or a JSON Entry: First check OID: - _, err := StringToOid(policyIdentifier) - if err == nil { - entry.PolicyIdentifierOid = policyIdentifier - return entry, nil - } - // Now Check If JSON Entry - jsonErr := json.Unmarshal([]byte(policyIdentifier), &entry) - if jsonErr != nil { // Neither, if we got here - return entry, errors.New(fmt.Sprintf("Policy Identifier %q is neither a valid OID: %s, Nor JSON Policy Identifier: %s", policyIdentifier, err.Error(), jsonErr.Error())) - } - return entry, nil -} - -// Policy Identifier with Qualifier Structure for ASN Marshalling: - -var policyInformationOid = asn1.ObjectIdentifier{2, 5, 29, 32} - -type policyInformation struct { - PolicyIdentifier asn1.ObjectIdentifier - Qualifiers []interface{} `asn1:"tag:optional,omitempty"` -} - -var cpsPolicyQualifierID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 1} - -type cpsUrlPolicyQualifier struct { - PolicyQualifierID asn1.ObjectIdentifier - Qualifier string `asn1:"tag:optional,ia5"` -} - -var userNoticePolicyQualifierID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2} - -type userNoticePolicyQualifier struct { - PolicyQualifierID asn1.ObjectIdentifier - Qualifier userNotice -} - -type userNotice struct { - ExplicitText string `asn1:"tag:optional,utf8"` -} - -func createPolicyIdentifierWithQualifier(entry PolicyIdentifierWithQualifierEntry) (*policyInformation, error) { - // Each Policy is Identified by a Unique ID, as designated here: - policyOid, err := StringToOid(entry.PolicyIdentifierOid) - if err != nil { - return nil, err - } - pi := policyInformation{ - PolicyIdentifier: policyOid, - } - if entry.CPS != "" { - qualifier := cpsUrlPolicyQualifier{ - PolicyQualifierID: cpsPolicyQualifierID, - Qualifier: entry.CPS, - } - pi.Qualifiers = append(pi.Qualifiers, qualifier) - } - if entry.Notice != "" { - qualifier := userNoticePolicyQualifier{ - PolicyQualifierID: userNoticePolicyQualifierID, - Qualifier: userNotice{ - ExplicitText: entry.Notice, - }, - } - pi.Qualifiers = append(pi.Qualifiers, qualifier) - } - return &pi, nil -} - -// CreatePolicyInformationExtensionFromStorageStrings parses the stored policyIdentifiers, which might be JSON Policy -// Identifier with Qualifier Entries or String OIDs, and returns an extension if everything parsed correctly, and an -// error if constructing -func CreatePolicyInformationExtensionFromStorageStrings(policyIdentifiers []string) (*pkix.Extension, error) { - var policyInformationList []policyInformation - for _, policyIdentifierStr := range policyIdentifiers { - policyIdentifierEntry, err := GetPolicyIdentifierFromString(policyIdentifierStr) - if err != nil { - return nil, err - } - if policyIdentifierEntry != nil { // Okay to skip empty entries if there is no error - policyInformationStruct, err := createPolicyIdentifierWithQualifier(*policyIdentifierEntry) - if err != nil { - return nil, err - } - policyInformationList = append(policyInformationList, *policyInformationStruct) - } - } - asn1Bytes, err := asn1.Marshal(policyInformationList) - if err != nil { - return nil, err - } - return &pkix.Extension{ - Id: policyInformationOid, - Critical: false, - Value: asn1Bytes, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/compressutil/compress.go b/vendor/github.com/hashicorp/vault/sdk/helper/compressutil/compress.go deleted file mode 100644 index 924f82a2a..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/compressutil/compress.go +++ /dev/null @@ -1,222 +0,0 @@ -package compressutil - -import ( - "bytes" - "compress/gzip" - "compress/lzw" - "fmt" - "io" - - "github.com/golang/snappy" - "github.com/hashicorp/errwrap" - "github.com/pierrec/lz4" -) - -const ( - // A byte value used as a canary prefix for the compressed information - // which is used to distinguish if a JSON input is compressed or not. - // The value of this constant should not be a first character of any - // valid JSON string. - - CompressionTypeGzip = "gzip" - CompressionCanaryGzip byte = 'G' - - CompressionTypeLZW = "lzw" - CompressionCanaryLZW byte = 'L' - - CompressionTypeSnappy = "snappy" - CompressionCanarySnappy byte = 'S' - - CompressionTypeLZ4 = "lz4" - CompressionCanaryLZ4 byte = '4' -) - -// SnappyReadCloser embeds the snappy reader which implements the io.Reader -// interface. The decompress procedure in this utility expects an -// io.ReadCloser. This type implements the io.Closer interface to retain the -// generic way of decompression. -type CompressUtilReadCloser struct { - io.Reader -} - -// Close is a noop method implemented only to satisfy the io.Closer interface -func (c *CompressUtilReadCloser) Close() error { - return nil -} - -// CompressionConfig is used to select a compression type to be performed by -// Compress and Decompress utilities. -// Supported types are: -// * CompressionTypeLZW -// * CompressionTypeGzip -// * CompressionTypeSnappy -// * CompressionTypeLZ4 -// -// When using CompressionTypeGzip, the compression levels can also be chosen: -// * gzip.DefaultCompression -// * gzip.BestSpeed -// * gzip.BestCompression -type CompressionConfig struct { - // Type of the compression algorithm to be used - Type string - - // When using Gzip format, the compression level to employ - GzipCompressionLevel int -} - -// Compress places the canary byte in a buffer and uses the same buffer to fill -// in the compressed information of the given input. The configuration supports -// two type of compression: LZW and Gzip. When using Gzip compression format, -// if GzipCompressionLevel is not specified, the 'gzip.DefaultCompression' will -// be assumed. -func Compress(data []byte, config *CompressionConfig) ([]byte, error) { - var buf bytes.Buffer - var writer io.WriteCloser - var err error - - if config == nil { - return nil, fmt.Errorf("config is nil") - } - - // Write the canary into the buffer and create writer to compress the - // input data based on the configured type - switch config.Type { - case CompressionTypeLZW: - buf.Write([]byte{CompressionCanaryLZW}) - writer = lzw.NewWriter(&buf, lzw.LSB, 8) - - case CompressionTypeGzip: - buf.Write([]byte{CompressionCanaryGzip}) - - switch { - case config.GzipCompressionLevel == gzip.BestCompression, - config.GzipCompressionLevel == gzip.BestSpeed, - config.GzipCompressionLevel == gzip.DefaultCompression: - // These are valid compression levels - default: - // If compression level is set to NoCompression or to - // any invalid value, fallback to Defaultcompression - config.GzipCompressionLevel = gzip.DefaultCompression - } - writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) - - case CompressionTypeSnappy: - buf.Write([]byte{CompressionCanarySnappy}) - writer = snappy.NewBufferedWriter(&buf) - - case CompressionTypeLZ4: - buf.Write([]byte{CompressionCanaryLZ4}) - writer = lz4.NewWriter(&buf) - - default: - return nil, fmt.Errorf("unsupported compression type") - } - - if err != nil { - return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) - } - - if writer == nil { - return nil, fmt.Errorf("failed to create a compression writer") - } - - // Compress the input and place it in the same buffer containing the - // canary byte. - if _, err = writer.Write(data); err != nil { - return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) - } - - // Close the io.WriteCloser - if err = writer.Close(); err != nil { - return nil, err - } - - // Return the compressed bytes with canary byte at the start - return buf.Bytes(), nil -} - -// Decompress checks if the first byte in the input matches the canary byte. -// If the first byte is a canary byte, then the input past the canary byte -// will be decompressed using the method specified in the given configuration. -// If the first byte isn't a canary byte, then the utility returns a boolean -// value indicating that the input was not compressed. -func Decompress(data []byte) ([]byte, bool, error) { - bytes, _, notCompressed, err := DecompressWithCanary(data) - return bytes, notCompressed, err -} - -// DecompressWithCanary checks if the first byte in the input matches the canary byte. -// If the first byte is a canary byte, then the input past the canary byte -// will be decompressed using the method specified in the given configuration. The type of compression used is also -// returned. If the first byte isn't a canary byte, then the utility returns a boolean -// value indicating that the input was not compressed. -func DecompressWithCanary(data []byte) ([]byte, string, bool, error) { - var err error - var reader io.ReadCloser - var compressionType string - if data == nil || len(data) == 0 { - return nil, "", false, fmt.Errorf("'data' being decompressed is empty") - } - - canary := data[0] - cData := data[1:] - - switch canary { - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. - case CompressionCanaryGzip: - if len(data) < 2 { - return nil, "", false, fmt.Errorf("invalid 'data' after the canary") - } - reader, err = gzip.NewReader(bytes.NewReader(cData)) - compressionType = CompressionTypeGzip - - case CompressionCanaryLZW: - if len(data) < 2 { - return nil, "", false, fmt.Errorf("invalid 'data' after the canary") - } - reader = lzw.NewReader(bytes.NewReader(cData), lzw.LSB, 8) - compressionType = CompressionTypeLZW - - case CompressionCanarySnappy: - if len(data) < 2 { - return nil, "", false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: snappy.NewReader(bytes.NewReader(cData)), - } - compressionType = CompressionTypeSnappy - - case CompressionCanaryLZ4: - if len(data) < 2 { - return nil, "", false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: lz4.NewReader(bytes.NewReader(cData)), - } - compressionType = CompressionTypeLZ4 - - default: - // If the first byte doesn't match the canary byte, it means - // that the content was not compressed at all. Indicate the - // caller that the input was not compressed. - return nil, "", true, nil - } - if err != nil { - return nil, "", false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) - } - if reader == nil { - return nil, "", false, fmt.Errorf("failed to create a compression reader") - } - - // Close the io.ReadCloser - defer reader.Close() - - // Read all the compressed data into a buffer - var buf bytes.Buffer - if _, err = io.Copy(&buf, reader); err != nil { - return nil, "", false, err - } - - return buf.Bytes(), compressionType, false, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/agent.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/agent.go deleted file mode 100644 index 92207e3d8..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/agent.go +++ /dev/null @@ -1,12 +0,0 @@ -package consts - -// AgentPathCacheClear is the path that the agent will use as its cache-clear -// endpoint. -const AgentPathCacheClear = "/agent/v1/cache-clear" - -// AgentPathMetrics is the path the agent will use to expose its internal -// metrics. -const AgentPathMetrics = "/agent/v1/metrics" - -// AgentPathQuit is the path that the agent will use to trigger stopping it. -const AgentPathQuit = "/agent/v1/quit" diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/consts.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/consts.go deleted file mode 100644 index a4b7c5040..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/consts.go +++ /dev/null @@ -1,39 +0,0 @@ -package consts - -const ( - // ExpirationRestoreWorkerCount specifies the number of workers to use while - // restoring leases into the expiration manager - ExpirationRestoreWorkerCount = 64 - - // NamespaceHeaderName is the header set to specify which namespace the - // request is indented for. - NamespaceHeaderName = "X-Vault-Namespace" - - // AuthHeaderName is the name of the header containing the token. - AuthHeaderName = "X-Vault-Token" - - // RequestHeaderName is the name of the header used by the Agent for - // SSRF protection. - RequestHeaderName = "X-Vault-Request" - - // PerformanceReplicationALPN is the negotiated protocol used for - // performance replication. - PerformanceReplicationALPN = "replication_v1" - - // DRReplicationALPN is the negotiated protocol used for dr replication. - DRReplicationALPN = "replication_dr_v1" - - PerfStandbyALPN = "perf_standby_v1" - - RequestForwardingALPN = "req_fw_sb-act_v1" - - RaftStorageALPN = "raft_storage_v1" - - // ReplicationResolverALPN is the negotiated protocol used for - // resolving replicaiton addresses - ReplicationResolverALPN = "replication_resolver_v1" - - VaultEnableFilePermissionsCheckEnv = "VAULT_ENABLE_FILE_PERMISSIONS_CHECK" - - VaultDisableUserLockout = "VAULT_DISABLE_USER_LOCKOUT" -) diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/deprecation_status.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/deprecation_status.go deleted file mode 100644 index 656d6cc99..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/deprecation_status.go +++ /dev/null @@ -1,34 +0,0 @@ -package consts - -// EnvVaultAllowPendingRemovalMounts allows Pending Removal builtins to be -// mounted as if they are Deprecated to facilitate migration to supported -// builtin plugins. -const EnvVaultAllowPendingRemovalMounts = "VAULT_ALLOW_PENDING_REMOVAL_MOUNTS" - -// DeprecationStatus represents the current deprecation state for builtins -type DeprecationStatus uint32 - -// These are the states of deprecation for builtin plugins -const ( - Supported = iota - Deprecated - PendingRemoval - Removed - Unknown -) - -// String returns the string representation of a builtin deprecation status -func (s DeprecationStatus) String() string { - switch s { - case Supported: - return "supported" - case Deprecated: - return "deprecated" - case PendingRemoval: - return "pending removal" - case Removed: - return "removed" - default: - return "" - } -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/error.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/error.go deleted file mode 100644 index 1a9175c63..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/error.go +++ /dev/null @@ -1,25 +0,0 @@ -package consts - -import "errors" - -var ( - // ErrSealed is returned if an operation is performed on a sealed barrier. - // No operation is expected to succeed before unsealing - ErrSealed = errors.New("Vault is sealed") - - // ErrAPILocked is returned if an operation is performed when the API is - // locked for the request namespace. - ErrAPILocked = errors.New("API access to this namespace has been locked by an administrator") - - // ErrStandby is returned if an operation is performed on a standby Vault. - // No operation is expected to succeed until active. - ErrStandby = errors.New("Vault is in standby mode") - - // ErrPathContainsParentReferences is returned when a path contains parent - // references. - ErrPathContainsParentReferences = errors.New("path cannot contain parent references") - - // ErrInvalidWrappingToken is returned when checking for the validity of - // a wrapping token that turns out to be invalid. - ErrInvalidWrappingToken = errors.New("wrapping token is not valid or does not exist") -) diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/replication.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/replication.go deleted file mode 100644 index f72c2f47a..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/replication.go +++ /dev/null @@ -1,159 +0,0 @@ -package consts - -const ( - // N.B. This needs to be excluded from replication despite the name; it's - // merely saying that this is cluster information for the replicated - // cluster. - CoreReplicatedClusterPrefix = "core/cluster/replicated/" - CoreReplicatedClusterPrefixDR = "core/cluster/replicated-dr/" - - CoreReplicatedClusterInfoPath = CoreReplicatedClusterPrefix + "info" - CoreReplicatedClusterSecondariesPrefix = CoreReplicatedClusterPrefix + "secondaries/" - CoreReplicatedClusterInfoPathDR = CoreReplicatedClusterPrefixDR + "info" - CoreReplicatedClusterSecondariesPrefixDR = CoreReplicatedClusterPrefixDR + "secondaries/" - - // This is an identifier for the current secondary in the replicated paths - // manager. It should contain a character that is not allowed in secondary - // ids to ensure it doesn't collide. - CurrentReplicatedSecondaryIdentifier = ".current" - CoreFeatureFlagPath = "core/cluster/feature-flags" -) - -type ReplicationState uint32 - -const ( - _ ReplicationState = iota - OldReplicationPrimary - OldReplicationSecondary - OldReplicationBootstrapping - // Don't add anything here. Adding anything to this Old block would cause - // the rest of the values to change below. This was done originally to - // ensure no overlap between old and new values. - - ReplicationUnknown ReplicationState = 0 - ReplicationPerformancePrimary ReplicationState = 1 << iota // Note -- iota is 5 here! - ReplicationPerformanceSecondary - OldSplitReplicationBootstrapping - ReplicationDRPrimary - ReplicationDRSecondary - ReplicationPerformanceBootstrapping - ReplicationDRBootstrapping - ReplicationPerformanceDisabled - ReplicationDRDisabled - ReplicationPerformanceStandby -) - -// We verify no change to the above values are made -func init() { - if OldReplicationBootstrapping != 3 { - panic("Replication Constants have changed") - } - - if ReplicationPerformancePrimary != 1<<5 { - panic("Replication Constants have changed") - } -} - -func (r ReplicationState) string() string { - switch r { - case ReplicationPerformanceSecondary: - return "secondary" - case ReplicationPerformancePrimary: - return "primary" - case ReplicationPerformanceBootstrapping: - return "bootstrapping" - case ReplicationPerformanceDisabled: - return "disabled" - case ReplicationDRPrimary: - return "primary" - case ReplicationDRSecondary: - return "secondary" - case ReplicationDRBootstrapping: - return "bootstrapping" - case ReplicationDRDisabled: - return "disabled" - } - - return "unknown" -} - -func (r ReplicationState) StateStrings() []string { - var ret []string - if r.HasState(ReplicationPerformanceSecondary) { - ret = append(ret, "perf-secondary") - } - if r.HasState(ReplicationPerformancePrimary) { - ret = append(ret, "perf-primary") - } - if r.HasState(ReplicationPerformanceBootstrapping) { - ret = append(ret, "perf-bootstrapping") - } - if r.HasState(ReplicationPerformanceDisabled) { - ret = append(ret, "perf-disabled") - } - if r.HasState(ReplicationDRPrimary) { - ret = append(ret, "dr-primary") - } - if r.HasState(ReplicationDRSecondary) { - ret = append(ret, "dr-secondary") - } - if r.HasState(ReplicationDRBootstrapping) { - ret = append(ret, "dr-bootstrapping") - } - if r.HasState(ReplicationDRDisabled) { - ret = append(ret, "dr-disabled") - } - if r.HasState(ReplicationPerformanceStandby) { - ret = append(ret, "perfstandby") - } - - return ret -} - -func (r ReplicationState) GetDRString() string { - switch { - case r.HasState(ReplicationDRBootstrapping): - return ReplicationDRBootstrapping.string() - case r.HasState(ReplicationDRPrimary): - return ReplicationDRPrimary.string() - case r.HasState(ReplicationDRSecondary): - return ReplicationDRSecondary.string() - case r.HasState(ReplicationDRDisabled): - return ReplicationDRDisabled.string() - default: - return "unknown" - } -} - -func (r ReplicationState) GetPerformanceString() string { - switch { - case r.HasState(ReplicationPerformanceBootstrapping): - return ReplicationPerformanceBootstrapping.string() - case r.HasState(ReplicationPerformancePrimary): - return ReplicationPerformancePrimary.string() - case r.HasState(ReplicationPerformanceSecondary): - return ReplicationPerformanceSecondary.string() - case r.HasState(ReplicationPerformanceDisabled): - return ReplicationPerformanceDisabled.string() - default: - return "unknown" - } -} - -func (r ReplicationState) IsPrimaryState() bool { - return r.HasState(ReplicationPerformancePrimary | ReplicationDRPrimary) -} - -func (r ReplicationState) HasState(flag ReplicationState) bool { return r&flag != 0 } -func (r *ReplicationState) AddState(flag ReplicationState) { *r |= flag } -func (r *ReplicationState) ClearState(flag ReplicationState) { *r &= ^flag } -func (r *ReplicationState) ToggleState(flag ReplicationState) { *r ^= flag } - -type HAState uint32 - -const ( - _ HAState = iota - Standby - PerfStandby - Active -) diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/consts/token_consts.go b/vendor/github.com/hashicorp/vault/sdk/helper/consts/token_consts.go deleted file mode 100644 index 2b4e0278b..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/consts/token_consts.go +++ /dev/null @@ -1,10 +0,0 @@ -package consts - -const ( - ServiceTokenPrefix = "hvs." - BatchTokenPrefix = "hvb." - RecoveryTokenPrefix = "hvr." - LegacyServiceTokenPrefix = "s." - LegacyBatchTokenPrefix = "b." - LegacyRecoveryTokenPrefix = "r." -) diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/cryptoutil/cryptoutil.go b/vendor/github.com/hashicorp/vault/sdk/helper/cryptoutil/cryptoutil.go deleted file mode 100644 index a37086c64..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/cryptoutil/cryptoutil.go +++ /dev/null @@ -1,11 +0,0 @@ -package cryptoutil - -import "golang.org/x/crypto/blake2b" - -func Blake2b256Hash(key string) []byte { - hf, _ := blake2b.New256(nil) - - hf.Write([]byte(key)) - - return hf.Sum(nil) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/errutil/error.go b/vendor/github.com/hashicorp/vault/sdk/helper/errutil/error.go deleted file mode 100644 index 0b95efb40..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/errutil/error.go +++ /dev/null @@ -1,20 +0,0 @@ -package errutil - -// UserError represents an error generated due to invalid user input -type UserError struct { - Err string -} - -func (e UserError) Error() string { - return e.Err -} - -// InternalError represents an error generated internally, -// presumably not due to invalid user input -type InternalError struct { - Err string -} - -func (e InternalError) Error() string { - return e.Err -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/hclutil/hcl.go b/vendor/github.com/hashicorp/vault/sdk/helper/hclutil/hcl.go deleted file mode 100644 index 0b120367d..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/hclutil/hcl.go +++ /dev/null @@ -1,36 +0,0 @@ -package hclutil - -import ( - "fmt" - - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl/hcl/ast" -) - -// CheckHCLKeys checks whether the keys in the AST list contains any of the valid keys provided. -func CheckHCLKeys(node ast.Node, valid []string) error { - var list *ast.ObjectList - switch n := node.(type) { - case *ast.ObjectList: - list = n - case *ast.ObjectType: - list = n.List - default: - return fmt.Errorf("cannot check HCL keys of type %T", n) - } - - validMap := make(map[string]struct{}, len(valid)) - for _, v := range valid { - validMap[v] = struct{}{} - } - - var result error - for _, item := range list.Items { - key := item.Keys[0].Token.Value().(string) - if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) - } - } - - return result -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/jsonutil/json.go b/vendor/github.com/hashicorp/vault/sdk/helper/jsonutil/json.go deleted file mode 100644 index c03a4f8c8..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/jsonutil/json.go +++ /dev/null @@ -1,100 +0,0 @@ -package jsonutil - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/sdk/helper/compressutil" -) - -// Encodes/Marshals the given object into JSON -func EncodeJSON(in interface{}) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - if err := enc.Encode(in); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// EncodeJSONAndCompress encodes the given input into JSON and compresses the -// encoded value (using Gzip format BestCompression level, by default). A -// canary byte is placed at the beginning of the returned bytes for the logic -// in decompression method to identify compressed input. -func EncodeJSONAndCompress(in interface{}, config *compressutil.CompressionConfig) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - - // First JSON encode the given input - encodedBytes, err := EncodeJSON(in) - if err != nil { - return nil, err - } - - if config == nil { - config = &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeGzip, - GzipCompressionLevel: gzip.BestCompression, - } - } - - return compressutil.Compress(encodedBytes, config) -} - -// DecodeJSON tries to decompress the given data. The call to decompress, fails -// if the content was not compressed in the first place, which is identified by -// a canary byte before the compressed data. If the data is not compressed, it -// is JSON decoded directly. Otherwise the decompressed data will be JSON -// decoded. -func DecodeJSON(data []byte, out interface{}) error { - if data == nil || len(data) == 0 { - return fmt.Errorf("'data' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - // Decompress the data if it was compressed in the first place - decompressedBytes, uncompressed, err := compressutil.Decompress(data) - if err != nil { - return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) - } - if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { - return fmt.Errorf("decompressed data being decoded is invalid") - } - - // If the input supplied failed to contain the compression canary, it - // will be notified by the compression utility. Decode the decompressed - // input. - if !uncompressed { - data = decompressedBytes - } - - return DecodeJSONFromReader(bytes.NewReader(data), out) -} - -// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object -func DecodeJSONFromReader(r io.Reader, out interface{}) error { - if r == nil { - return fmt.Errorf("'io.Reader' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - dec := json.NewDecoder(r) - - // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. - dec.UseNumber() - - // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' - return dec.Decode(out) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/license/feature.go b/vendor/github.com/hashicorp/vault/sdk/helper/license/feature.go deleted file mode 100644 index c7c000a58..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/license/feature.go +++ /dev/null @@ -1,10 +0,0 @@ -package license - -// Features is a bitmask of feature flags -type Features uint - -const FeatureNone Features = 0 - -func (f Features) HasFeature(flag Features) bool { - return false -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/locksutil/locks.go b/vendor/github.com/hashicorp/vault/sdk/helper/locksutil/locks.go deleted file mode 100644 index 35ffcf739..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/locksutil/locks.go +++ /dev/null @@ -1,58 +0,0 @@ -package locksutil - -import ( - "sync" - - "github.com/hashicorp/vault/sdk/helper/cryptoutil" -) - -const ( - LockCount = 256 -) - -type LockEntry struct { - sync.RWMutex -} - -// CreateLocks returns an array so that the locks can be iterated over in -// order. -// -// This is only threadsafe if a process is using a single lock, or iterating -// over the entire lock slice in order. Using a consistent order avoids -// deadlocks because you can never have the following: -// -// Lock A, Lock B -// Lock B, Lock A -// -// Where process 1 is now deadlocked trying to lock B, and process 2 deadlocked trying to lock A -func CreateLocks() []*LockEntry { - ret := make([]*LockEntry, LockCount) - for i := range ret { - ret[i] = new(LockEntry) - } - return ret -} - -func LockIndexForKey(key string) uint8 { - return uint8(cryptoutil.Blake2b256Hash(key)[0]) -} - -func LockForKey(locks []*LockEntry, key string) *LockEntry { - return locks[LockIndexForKey(key)] -} - -func LocksForKeys(locks []*LockEntry, keys []string) []*LockEntry { - lockIndexes := make(map[uint8]struct{}, len(keys)) - for _, k := range keys { - lockIndexes[LockIndexForKey(k)] = struct{}{} - } - - locksToReturn := make([]*LockEntry, 0, len(keys)) - for i, l := range locks { - if _, ok := lockIndexes[uint8(i)]; ok { - locksToReturn = append(locksToReturn, l) - } - } - - return locksToReturn -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/logging/logging.go b/vendor/github.com/hashicorp/vault/sdk/helper/logging/logging.go deleted file mode 100644 index 25de5a781..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/logging/logging.go +++ /dev/null @@ -1,78 +0,0 @@ -package logging - -import ( - "fmt" - "io" - "os" - "strings" - - log "github.com/hashicorp/go-hclog" -) - -type LogFormat int - -const ( - UnspecifiedFormat LogFormat = iota - StandardFormat - JSONFormat -) - -// Stringer implementation -func (l LogFormat) String() string { - switch l { - case UnspecifiedFormat: - return "unspecified" - case StandardFormat: - return "standard" - case JSONFormat: - return "json" - } - - // unreachable - return "unknown" -} - -// NewVaultLogger creates a new logger with the specified level and a Vault -// formatter -func NewVaultLogger(level log.Level) log.Logger { - return NewVaultLoggerWithWriter(log.DefaultOutput, level) -} - -// NewVaultLoggerWithWriter creates a new logger with the specified level and -// writer and a Vault formatter -func NewVaultLoggerWithWriter(w io.Writer, level log.Level) log.Logger { - opts := &log.LoggerOptions{ - Level: level, - IndependentLevels: true, - Output: w, - JSONFormat: ParseEnvLogFormat() == JSONFormat, - } - return log.New(opts) -} - -// ParseLogFormat parses the log format from the provided string. -func ParseLogFormat(format string) (LogFormat, error) { - switch strings.ToLower(strings.TrimSpace(format)) { - case "": - return UnspecifiedFormat, nil - case "standard": - return StandardFormat, nil - case "json": - return JSONFormat, nil - default: - return UnspecifiedFormat, fmt.Errorf("unknown log format: %s", format) - } -} - -// ParseEnvLogFormat parses the log format from an environment variable. -func ParseEnvLogFormat() LogFormat { - logFormat := os.Getenv("VAULT_LOG_FORMAT") - switch strings.ToLower(logFormat) { - case "json", "vault_json", "vault-json", "vaultjson": - return JSONFormat - case "standard": - return StandardFormat - default: - return UnspecifiedFormat - } -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pathmanager/pathmanager.go b/vendor/github.com/hashicorp/vault/sdk/helper/pathmanager/pathmanager.go deleted file mode 100644 index e0e39445b..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pathmanager/pathmanager.go +++ /dev/null @@ -1,136 +0,0 @@ -package pathmanager - -import ( - "strings" - "sync" - - iradix "github.com/hashicorp/go-immutable-radix" -) - -// PathManager is a prefix searchable index of paths -type PathManager struct { - l sync.RWMutex - paths *iradix.Tree -} - -// New creates a new path manager -func New() *PathManager { - return &PathManager{ - paths: iradix.New(), - } -} - -// AddPaths adds path to the paths list -func (p *PathManager) AddPaths(paths []string) { - p.l.Lock() - defer p.l.Unlock() - - txn := p.paths.Txn() - for _, prefix := range paths { - if len(prefix) == 0 { - continue - } - - var exception bool - if strings.HasPrefix(prefix, "!") { - prefix = strings.TrimPrefix(prefix, "!") - exception = true - } - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - txn.Insert([]byte(strings.TrimSuffix(prefix, "*")), exception) - } - p.paths = txn.Commit() -} - -// RemovePaths removes paths from the paths list -func (p *PathManager) RemovePaths(paths []string) { - p.l.Lock() - defer p.l.Unlock() - - txn := p.paths.Txn() - for _, prefix := range paths { - if len(prefix) == 0 { - continue - } - - // Exceptions aren't stored with the leading ! so strip it - if strings.HasPrefix(prefix, "!") { - prefix = strings.TrimPrefix(prefix, "!") - } - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - txn.Delete([]byte(strings.TrimSuffix(prefix, "*"))) - } - p.paths = txn.Commit() -} - -// RemovePathPrefix removes all paths with the given prefix -func (p *PathManager) RemovePathPrefix(prefix string) { - p.l.Lock() - defer p.l.Unlock() - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - p.paths, _ = p.paths.DeletePrefix([]byte(strings.TrimSuffix(prefix, "*"))) -} - -// Len returns the number of paths -func (p *PathManager) Len() int { - return p.paths.Len() -} - -// Paths returns the path list -func (p *PathManager) Paths() []string { - p.l.RLock() - defer p.l.RUnlock() - - paths := make([]string, 0, p.paths.Len()) - walkFn := func(k []byte, v interface{}) bool { - paths = append(paths, string(k)) - return false - } - p.paths.Root().Walk(walkFn) - return paths -} - -// HasPath returns if the prefix for the path exists regardless if it is a path -// (ending with /) or a prefix for a leaf node -func (p *PathManager) HasPath(path string) bool { - p.l.RLock() - defer p.l.RUnlock() - - if _, exceptionRaw, ok := p.paths.Root().LongestPrefix([]byte(path)); ok { - var exception bool - if exceptionRaw != nil { - exception = exceptionRaw.(bool) - } - return !exception - } - return false -} - -// HasExactPath returns if the longest match is an exact match for the -// full path -func (p *PathManager) HasExactPath(path string) bool { - p.l.RLock() - defer p.l.RUnlock() - - if val, exceptionRaw, ok := p.paths.Root().LongestPrefix([]byte(path)); ok { - var exception bool - if exceptionRaw != nil { - exception = exceptionRaw.(bool) - } - - strVal := string(val) - if strings.HasSuffix(strVal, "/") || strVal == path { - return !exception - } - } - return false -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/env.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/env.go deleted file mode 100644 index df1fdbeed..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/env.go +++ /dev/null @@ -1,77 +0,0 @@ -package pluginutil - -import ( - "os" - - "github.com/hashicorp/go-secure-stdlib/mlock" - version "github.com/hashicorp/go-version" -) - -const ( - // PluginAutoMTLSEnv is used to ensure AutoMTLS is used. This will override - // setting a TLSProviderFunc for a plugin. - PluginAutoMTLSEnv = "VAULT_PLUGIN_AUTOMTLS_ENABLED" - - // PluginMlockEnabled is the ENV name used to pass the configuration for - // enabling mlock - PluginMlockEnabled = "VAULT_PLUGIN_MLOCK_ENABLED" - - // PluginVaultVersionEnv is the ENV name used to pass the version of the - // vault server to the plugin - PluginVaultVersionEnv = "VAULT_VERSION" - - // PluginMetadataModeEnv is an ENV name used to disable TLS communication - // to bootstrap mounting plugins. - PluginMetadataModeEnv = "VAULT_PLUGIN_METADATA_MODE" - - // PluginUnwrapTokenEnv is the ENV name used to pass unwrap tokens to the - // plugin. - PluginUnwrapTokenEnv = "VAULT_UNWRAP_TOKEN" - - // PluginCACertPEMEnv is an ENV name used for holding a CA PEM-encoded - // string. Used for testing. - PluginCACertPEMEnv = "VAULT_TESTING_PLUGIN_CA_PEM" - - // PluginMultiplexingOptOut is an ENV name used to define a comma separated list of plugin names - // opted-out of the multiplexing feature; for emergencies if multiplexing ever causes issues - PluginMultiplexingOptOut = "VAULT_PLUGIN_MULTIPLEXING_OPT_OUT" -) - -// OptionallyEnableMlock determines if mlock should be called, and if so enables -// mlock. -func OptionallyEnableMlock() error { - if os.Getenv(PluginMlockEnabled) == "true" { - return mlock.LockMemory() - } - - return nil -} - -// GRPCSupport defaults to returning true, unless VAULT_VERSION is missing or -// it fails to meet the version constraint. -func GRPCSupport() bool { - verString := os.Getenv(PluginVaultVersionEnv) - // If the env var is empty, we fall back to netrpc for backward compatibility. - if verString == "" { - return false - } - if verString != "unknown" { - ver, err := version.NewVersion(verString) - if err != nil { - return true - } - // Due to some regressions on 0.9.2 & 0.9.3 we now require version 0.9.4 - // to allow the plugin framework to default to gRPC. - constraint, err := version.NewConstraint(">= 0.9.4") - if err != nil { - return true - } - return constraint.Check(ver) - } - return true -} - -// InMetadataMode returns true if the plugin calling this function is running in metadata mode. -func InMetadataMode() bool { - return os.Getenv(PluginMetadataModeEnv) == "true" -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.go deleted file mode 100644 index 41316ec49..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.go +++ /dev/null @@ -1,80 +0,0 @@ -package pluginutil - -import ( - "context" - "errors" - "fmt" - "os" - "strings" - - "github.com/hashicorp/go-secure-stdlib/strutil" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -var ErrNoMultiplexingIDFound = errors.New("no multiplexing ID found") - -type PluginMultiplexingServerImpl struct { - UnimplementedPluginMultiplexingServer - - Supported bool -} - -func (pm PluginMultiplexingServerImpl) MultiplexingSupport(_ context.Context, _ *MultiplexingSupportRequest) (*MultiplexingSupportResponse, error) { - return &MultiplexingSupportResponse{ - Supported: pm.Supported, - }, nil -} - -func MultiplexingSupported(ctx context.Context, cc grpc.ClientConnInterface, name string) (bool, error) { - if cc == nil { - return false, fmt.Errorf("client connection is nil") - } - - out := strings.Split(os.Getenv(PluginMultiplexingOptOut), ",") - if strutil.StrListContains(out, name) { - return false, nil - } - - req := new(MultiplexingSupportRequest) - resp, err := NewPluginMultiplexingClient(cc).MultiplexingSupport(ctx, req) - if err != nil { - - // If the server does not implement the multiplexing server then we can - // assume it is not multiplexed - if status.Code(err) == codes.Unimplemented { - return false, nil - } - - return false, err - } - if resp == nil { - // Somehow got a nil response, assume not multiplexed - return false, nil - } - - return resp.Supported, nil -} - -func GetMultiplexIDFromContext(ctx context.Context) (string, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return "", fmt.Errorf("missing plugin multiplexing metadata") - } - - multiplexIDs := md[MultiplexingCtxKey] - if len(multiplexIDs) == 0 { - return "", ErrNoMultiplexingIDFound - } else if len(multiplexIDs) != 1 { - return "", fmt.Errorf("unexpected number of IDs in metadata: (%d)", len(multiplexIDs)) - } - - multiplexID := multiplexIDs[0] - if multiplexID == "" { - return "", fmt.Errorf("empty multiplex ID in metadata") - } - - return multiplexID, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.pb.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.pb.go deleted file mode 100644 index cfd463d6a..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.pb.go +++ /dev/null @@ -1,213 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.9 -// source: sdk/helper/pluginutil/multiplexing.proto - -package pluginutil - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type MultiplexingSupportRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *MultiplexingSupportRequest) Reset() { - *x = MultiplexingSupportRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *MultiplexingSupportRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*MultiplexingSupportRequest) ProtoMessage() {} - -func (x *MultiplexingSupportRequest) ProtoReflect() protoreflect.Message { - mi := &file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use MultiplexingSupportRequest.ProtoReflect.Descriptor instead. -func (*MultiplexingSupportRequest) Descriptor() ([]byte, []int) { - return file_sdk_helper_pluginutil_multiplexing_proto_rawDescGZIP(), []int{0} -} - -type MultiplexingSupportResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Supported bool `protobuf:"varint,1,opt,name=supported,proto3" json:"supported,omitempty"` -} - -func (x *MultiplexingSupportResponse) Reset() { - *x = MultiplexingSupportResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *MultiplexingSupportResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*MultiplexingSupportResponse) ProtoMessage() {} - -func (x *MultiplexingSupportResponse) ProtoReflect() protoreflect.Message { - mi := &file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use MultiplexingSupportResponse.ProtoReflect.Descriptor instead. -func (*MultiplexingSupportResponse) Descriptor() ([]byte, []int) { - return file_sdk_helper_pluginutil_multiplexing_proto_rawDescGZIP(), []int{1} -} - -func (x *MultiplexingSupportResponse) GetSupported() bool { - if x != nil { - return x.Supported - } - return false -} - -var File_sdk_helper_pluginutil_multiplexing_proto protoreflect.FileDescriptor - -var file_sdk_helper_pluginutil_multiplexing_proto_rawDesc = []byte{ - 0x0a, 0x28, 0x73, 0x64, 0x6b, 0x2f, 0x68, 0x65, 0x6c, 0x70, 0x65, 0x72, 0x2f, 0x70, 0x6c, 0x75, - 0x67, 0x69, 0x6e, 0x75, 0x74, 0x69, 0x6c, 0x2f, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, - 0x78, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x17, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x75, 0x74, 0x69, 0x6c, 0x2e, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x78, - 0x69, 0x6e, 0x67, 0x22, 0x1c, 0x0a, 0x1a, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x78, - 0x69, 0x6e, 0x67, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x22, 0x3b, 0x0a, 0x1b, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x78, 0x69, 0x6e, - 0x67, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x09, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x32, 0x97, - 0x01, 0x0a, 0x12, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, - 0x65, 0x78, 0x69, 0x6e, 0x67, 0x12, 0x80, 0x01, 0x0a, 0x13, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, - 0x6c, 0x65, 0x78, 0x69, 0x6e, 0x67, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x33, 0x2e, - 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x75, 0x74, 0x69, 0x6c, 0x2e, 0x6d, 0x75, 0x6c, 0x74, 0x69, - 0x70, 0x6c, 0x65, 0x78, 0x69, 0x6e, 0x67, 0x2e, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, - 0x78, 0x69, 0x6e, 0x67, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x34, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x75, 0x74, 0x69, 0x6c, 0x2e, - 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x78, 0x69, 0x6e, 0x67, 0x2e, 0x4d, 0x75, 0x6c, - 0x74, 0x69, 0x70, 0x6c, 0x65, 0x78, 0x69, 0x6e, 0x67, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x32, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, - 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, - 0x2f, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x2f, 0x73, 0x64, 0x6b, 0x2f, 0x68, 0x65, 0x6c, 0x70, 0x65, - 0x72, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x75, 0x74, 0x69, 0x6c, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_sdk_helper_pluginutil_multiplexing_proto_rawDescOnce sync.Once - file_sdk_helper_pluginutil_multiplexing_proto_rawDescData = file_sdk_helper_pluginutil_multiplexing_proto_rawDesc -) - -func file_sdk_helper_pluginutil_multiplexing_proto_rawDescGZIP() []byte { - file_sdk_helper_pluginutil_multiplexing_proto_rawDescOnce.Do(func() { - file_sdk_helper_pluginutil_multiplexing_proto_rawDescData = protoimpl.X.CompressGZIP(file_sdk_helper_pluginutil_multiplexing_proto_rawDescData) - }) - return file_sdk_helper_pluginutil_multiplexing_proto_rawDescData -} - -var file_sdk_helper_pluginutil_multiplexing_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_sdk_helper_pluginutil_multiplexing_proto_goTypes = []interface{}{ - (*MultiplexingSupportRequest)(nil), // 0: pluginutil.multiplexing.MultiplexingSupportRequest - (*MultiplexingSupportResponse)(nil), // 1: pluginutil.multiplexing.MultiplexingSupportResponse -} -var file_sdk_helper_pluginutil_multiplexing_proto_depIdxs = []int32{ - 0, // 0: pluginutil.multiplexing.PluginMultiplexing.MultiplexingSupport:input_type -> pluginutil.multiplexing.MultiplexingSupportRequest - 1, // 1: pluginutil.multiplexing.PluginMultiplexing.MultiplexingSupport:output_type -> pluginutil.multiplexing.MultiplexingSupportResponse - 1, // [1:2] is the sub-list for method output_type - 0, // [0:1] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_sdk_helper_pluginutil_multiplexing_proto_init() } -func file_sdk_helper_pluginutil_multiplexing_proto_init() { - if File_sdk_helper_pluginutil_multiplexing_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MultiplexingSupportRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_helper_pluginutil_multiplexing_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MultiplexingSupportResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_sdk_helper_pluginutil_multiplexing_proto_rawDesc, - NumEnums: 0, - NumMessages: 2, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_sdk_helper_pluginutil_multiplexing_proto_goTypes, - DependencyIndexes: file_sdk_helper_pluginutil_multiplexing_proto_depIdxs, - MessageInfos: file_sdk_helper_pluginutil_multiplexing_proto_msgTypes, - }.Build() - File_sdk_helper_pluginutil_multiplexing_proto = out.File - file_sdk_helper_pluginutil_multiplexing_proto_rawDesc = nil - file_sdk_helper_pluginutil_multiplexing_proto_goTypes = nil - file_sdk_helper_pluginutil_multiplexing_proto_depIdxs = nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.proto b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.proto deleted file mode 100644 index aa2438b07..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; -package pluginutil.multiplexing; - -option go_package = "github.com/hashicorp/vault/sdk/helper/pluginutil"; - -message MultiplexingSupportRequest {} -message MultiplexingSupportResponse { - bool supported = 1; -} - -service PluginMultiplexing { - rpc MultiplexingSupport(MultiplexingSupportRequest) returns (MultiplexingSupportResponse); -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing_grpc.pb.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing_grpc.pb.go deleted file mode 100644 index aa8d0e47b..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/multiplexing_grpc.pb.go +++ /dev/null @@ -1,101 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. - -package pluginutil - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -// PluginMultiplexingClient is the client API for PluginMultiplexing service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type PluginMultiplexingClient interface { - MultiplexingSupport(ctx context.Context, in *MultiplexingSupportRequest, opts ...grpc.CallOption) (*MultiplexingSupportResponse, error) -} - -type pluginMultiplexingClient struct { - cc grpc.ClientConnInterface -} - -func NewPluginMultiplexingClient(cc grpc.ClientConnInterface) PluginMultiplexingClient { - return &pluginMultiplexingClient{cc} -} - -func (c *pluginMultiplexingClient) MultiplexingSupport(ctx context.Context, in *MultiplexingSupportRequest, opts ...grpc.CallOption) (*MultiplexingSupportResponse, error) { - out := new(MultiplexingSupportResponse) - err := c.cc.Invoke(ctx, "/pluginutil.multiplexing.PluginMultiplexing/MultiplexingSupport", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// PluginMultiplexingServer is the server API for PluginMultiplexing service. -// All implementations must embed UnimplementedPluginMultiplexingServer -// for forward compatibility -type PluginMultiplexingServer interface { - MultiplexingSupport(context.Context, *MultiplexingSupportRequest) (*MultiplexingSupportResponse, error) - mustEmbedUnimplementedPluginMultiplexingServer() -} - -// UnimplementedPluginMultiplexingServer must be embedded to have forward compatible implementations. -type UnimplementedPluginMultiplexingServer struct { -} - -func (UnimplementedPluginMultiplexingServer) MultiplexingSupport(context.Context, *MultiplexingSupportRequest) (*MultiplexingSupportResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MultiplexingSupport not implemented") -} -func (UnimplementedPluginMultiplexingServer) mustEmbedUnimplementedPluginMultiplexingServer() {} - -// UnsafePluginMultiplexingServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to PluginMultiplexingServer will -// result in compilation errors. -type UnsafePluginMultiplexingServer interface { - mustEmbedUnimplementedPluginMultiplexingServer() -} - -func RegisterPluginMultiplexingServer(s grpc.ServiceRegistrar, srv PluginMultiplexingServer) { - s.RegisterService(&PluginMultiplexing_ServiceDesc, srv) -} - -func _PluginMultiplexing_MultiplexingSupport_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MultiplexingSupportRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PluginMultiplexingServer).MultiplexingSupport(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pluginutil.multiplexing.PluginMultiplexing/MultiplexingSupport", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PluginMultiplexingServer).MultiplexingSupport(ctx, req.(*MultiplexingSupportRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// PluginMultiplexing_ServiceDesc is the grpc.ServiceDesc for PluginMultiplexing service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var PluginMultiplexing_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "pluginutil.multiplexing.PluginMultiplexing", - HandlerType: (*PluginMultiplexingServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "MultiplexingSupport", - Handler: _PluginMultiplexing_MultiplexingSupport_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "sdk/helper/pluginutil/multiplexing.proto", -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/run_config.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/run_config.go deleted file mode 100644 index f344ca979..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/run_config.go +++ /dev/null @@ -1,182 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/sha256" - "crypto/tls" - "fmt" - "os/exec" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/sdk/helper/consts" -) - -type PluginClientConfig struct { - Name string - PluginType consts.PluginType - Version string - PluginSets map[int]plugin.PluginSet - HandshakeConfig plugin.HandshakeConfig - Logger log.Logger - IsMetadataMode bool - AutoMTLS bool - MLock bool - Wrapper RunnerUtil -} - -type runConfig struct { - // Provided by PluginRunner - command string - args []string - sha256 []byte - - // Initialized with what's in PluginRunner.Env, but can be added to - env []string - - PluginClientConfig -} - -func (rc runConfig) makeConfig(ctx context.Context) (*plugin.ClientConfig, error) { - cmd := exec.Command(rc.command, rc.args...) - cmd.Env = append(cmd.Env, rc.env...) - - // Add the mlock setting to the ENV of the plugin - if rc.MLock || (rc.Wrapper != nil && rc.Wrapper.MlockEnabled()) { - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMlockEnabled, "true")) - } - version, err := rc.Wrapper.VaultVersion(ctx) - if err != nil { - return nil, err - } - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginVaultVersionEnv, version)) - - if rc.IsMetadataMode { - rc.Logger = rc.Logger.With("metadata", "true") - } - metadataEnv := fmt.Sprintf("%s=%t", PluginMetadataModeEnv, rc.IsMetadataMode) - cmd.Env = append(cmd.Env, metadataEnv) - - automtlsEnv := fmt.Sprintf("%s=%t", PluginAutoMTLSEnv, rc.AutoMTLS) - cmd.Env = append(cmd.Env, automtlsEnv) - - var clientTLSConfig *tls.Config - if !rc.AutoMTLS && !rc.IsMetadataMode { - // Get a CA TLS Certificate - certBytes, key, err := generateCert() - if err != nil { - return nil, err - } - - // Use CA to sign a client cert and return a configured TLS config - clientTLSConfig, err = createClientTLSConfig(certBytes, key) - if err != nil { - return nil, err - } - - // Use CA to sign a server cert and wrap the values in a response wrapped - // token. - wrapToken, err := wrapServerConfig(ctx, rc.Wrapper, certBytes, key) - if err != nil { - return nil, err - } - - // Add the response wrap token to the ENV of the plugin - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginUnwrapTokenEnv, wrapToken)) - } - - secureConfig := &plugin.SecureConfig{ - Checksum: rc.sha256, - Hash: sha256.New(), - } - - clientConfig := &plugin.ClientConfig{ - HandshakeConfig: rc.HandshakeConfig, - VersionedPlugins: rc.PluginSets, - Cmd: cmd, - SecureConfig: secureConfig, - TLSConfig: clientTLSConfig, - Logger: rc.Logger, - AllowedProtocols: []plugin.Protocol{ - plugin.ProtocolNetRPC, - plugin.ProtocolGRPC, - }, - AutoMTLS: rc.AutoMTLS, - } - return clientConfig, nil -} - -func (rc runConfig) run(ctx context.Context) (*plugin.Client, error) { - clientConfig, err := rc.makeConfig(ctx) - if err != nil { - return nil, err - } - - client := plugin.NewClient(clientConfig) - return client, nil -} - -type RunOpt func(*runConfig) - -func Env(env ...string) RunOpt { - return func(rc *runConfig) { - rc.env = append(rc.env, env...) - } -} - -func Runner(wrapper RunnerUtil) RunOpt { - return func(rc *runConfig) { - rc.Wrapper = wrapper - } -} - -func PluginSets(pluginSets map[int]plugin.PluginSet) RunOpt { - return func(rc *runConfig) { - rc.PluginSets = pluginSets - } -} - -func HandshakeConfig(hs plugin.HandshakeConfig) RunOpt { - return func(rc *runConfig) { - rc.HandshakeConfig = hs - } -} - -func Logger(logger log.Logger) RunOpt { - return func(rc *runConfig) { - rc.Logger = logger - } -} - -func MetadataMode(isMetadataMode bool) RunOpt { - return func(rc *runConfig) { - rc.IsMetadataMode = isMetadataMode - } -} - -func AutoMTLS(autoMTLS bool) RunOpt { - return func(rc *runConfig) { - rc.AutoMTLS = autoMTLS - } -} - -func MLock(mlock bool) RunOpt { - return func(rc *runConfig) { - rc.MLock = mlock - } -} - -func (r *PluginRunner) RunConfig(ctx context.Context, opts ...RunOpt) (*plugin.Client, error) { - rc := runConfig{ - command: r.Command, - args: r.Args, - sha256: r.Sha256, - env: r.Env, - } - - for _, opt := range opts { - opt(&rc) - } - - return rc.run(ctx) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/runner.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/runner.go deleted file mode 100644 index 886efe21f..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/runner.go +++ /dev/null @@ -1,116 +0,0 @@ -package pluginutil - -import ( - "context" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/go-version" - "github.com/hashicorp/vault/sdk/helper/consts" - "github.com/hashicorp/vault/sdk/helper/wrapping" - "google.golang.org/grpc" -) - -// Looker defines the plugin Lookup function that looks into the plugin catalog -// for available plugins and returns a PluginRunner -type Looker interface { - LookupPlugin(ctx context.Context, pluginName string, pluginType consts.PluginType) (*PluginRunner, error) - LookupPluginVersion(ctx context.Context, pluginName string, pluginType consts.PluginType, version string) (*PluginRunner, error) -} - -// RunnerUtil interface defines the functions needed by the runner to wrap the -// metadata needed to run a plugin process. This includes looking up Mlock -// configuration and wrapping data in a response wrapped token. -// logical.SystemView implementations satisfy this interface. -type RunnerUtil interface { - NewPluginClient(ctx context.Context, config PluginClientConfig) (PluginClient, error) - ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) - MlockEnabled() bool - VaultVersion(ctx context.Context) (string, error) -} - -// LookRunnerUtil defines the functions for both Looker and Wrapper -type LookRunnerUtil interface { - Looker - RunnerUtil -} - -type PluginClient interface { - Conn() grpc.ClientConnInterface - Reload() error - plugin.ClientProtocol -} - -const MultiplexingCtxKey string = "multiplex_id" - -// PluginRunner defines the metadata needed to run a plugin securely with -// go-plugin. -type PluginRunner struct { - Name string `json:"name" structs:"name"` - Type consts.PluginType `json:"type" structs:"type"` - Version string `json:"version" structs:"version"` - Command string `json:"command" structs:"command"` - Args []string `json:"args" structs:"args"` - Env []string `json:"env" structs:"env"` - Sha256 []byte `json:"sha256" structs:"sha256"` - Builtin bool `json:"builtin" structs:"builtin"` - BuiltinFactory func() (interface{}, error) `json:"-" structs:"-"` -} - -// Run takes a wrapper RunnerUtil instance along with the go-plugin parameters and -// returns a configured plugin.Client with TLS Configured and a wrapping token set -// on PluginUnwrapTokenEnv for plugin process consumption. -func (r *PluginRunner) Run(ctx context.Context, wrapper RunnerUtil, pluginSets map[int]plugin.PluginSet, hs plugin.HandshakeConfig, env []string, logger log.Logger) (*plugin.Client, error) { - return r.RunConfig(ctx, - Runner(wrapper), - PluginSets(pluginSets), - HandshakeConfig(hs), - Env(env...), - Logger(logger), - MetadataMode(false), - ) -} - -// RunMetadataMode returns a configured plugin.Client that will dispense a plugin -// in metadata mode. The PluginMetadataModeEnv is passed in as part of the Cmd to -// plugin.Client, and consumed by the plugin process on api.VaultPluginTLSProvider. -func (r *PluginRunner) RunMetadataMode(ctx context.Context, wrapper RunnerUtil, pluginSets map[int]plugin.PluginSet, hs plugin.HandshakeConfig, env []string, logger log.Logger) (*plugin.Client, error) { - return r.RunConfig(ctx, - Runner(wrapper), - PluginSets(pluginSets), - HandshakeConfig(hs), - Env(env...), - Logger(logger), - MetadataMode(true), - ) -} - -// VersionedPlugin holds any versioning information stored about a plugin in the -// plugin catalog. -type VersionedPlugin struct { - Type string `json:"type"` // string instead of consts.PluginType so that we get the string form in API responses. - Name string `json:"name"` - Version string `json:"version"` - SHA256 string `json:"sha256,omitempty"` - Builtin bool `json:"builtin"` - DeprecationStatus string `json:"deprecation_status,omitempty"` - - // Pre-parsed semver struct of the Version field - SemanticVersion *version.Version `json:"-"` -} - -// CtxCancelIfCanceled takes a context cancel func and a context. If the context is -// shutdown the cancelfunc is called. This is useful for merging two cancel -// functions. -func CtxCancelIfCanceled(f context.CancelFunc, ctxCanceler context.Context) chan struct{} { - quitCh := make(chan struct{}) - go func() { - select { - case <-quitCh: - case <-ctxCanceler.Done(): - f() - } - }() - return quitCh -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/tls.go b/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/tls.go deleted file mode 100644 index c5fff6d70..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/pluginutil/tls.go +++ /dev/null @@ -1,106 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/sdk/helper/certutil" -) - -// generateCert is used internally to create certificates for the plugin -// client and server. -func generateCert() ([]byte, *ecdsa.PrivateKey, error) { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - return nil, nil, err - } - - host, err := uuid.GenerateUUID() - if err != nil { - return nil, nil, err - } - - sn, err := certutil.GenerateSerialNumber() - if err != nil { - return nil, nil, err - } - - template := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: host, - }, - DNSNames: []string{host}, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageClientAuth, - x509.ExtKeyUsageServerAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement, - SerialNumber: sn, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - IsCA: true, - } - - certBytes, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) - if err != nil { - return nil, nil, errwrap.Wrapf("unable to generate client certificate: {{err}}", err) - } - - return certBytes, key, nil -} - -// createClientTLSConfig creates a signed certificate and returns a configured -// TLS config. -func createClientTLSConfig(certBytes []byte, key *ecdsa.PrivateKey) (*tls.Config, error) { - clientCert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, errwrap.Wrapf("error parsing generated plugin certificate: {{err}}", err) - } - - cert := tls.Certificate{ - Certificate: [][]byte{certBytes}, - PrivateKey: key, - Leaf: clientCert, - } - - clientCertPool := x509.NewCertPool() - clientCertPool.AddCert(clientCert) - - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: clientCertPool, - ClientCAs: clientCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - ServerName: clientCert.Subject.CommonName, - MinVersion: tls.VersionTLS12, - } - - return tlsConfig, nil -} - -// wrapServerConfig is used to create a server certificate and private key, then -// wrap them in an unwrap token for later retrieval by the plugin. -func wrapServerConfig(ctx context.Context, sys RunnerUtil, certBytes []byte, key *ecdsa.PrivateKey) (string, error) { - rawKey, err := x509.MarshalECPrivateKey(key) - if err != nil { - return "", err - } - - wrapInfo, err := sys.ResponseWrapData(ctx, map[string]interface{}{ - "ServerCert": certBytes, - "ServerKey": rawKey, - }, time.Second*60, true) - if err != nil { - return "", err - } - - return wrapInfo.Token, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/strutil/strutil.go b/vendor/github.com/hashicorp/vault/sdk/helper/strutil/strutil.go deleted file mode 100644 index 09cc9425c..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/strutil/strutil.go +++ /dev/null @@ -1,94 +0,0 @@ -// DEPRECATED: this has been moved to go-secure-stdlib and will be removed -package strutil - -import ( - extstrutil "github.com/hashicorp/go-secure-stdlib/strutil" -) - -func StrListContainsGlob(haystack []string, needle string) bool { - return extstrutil.StrListContainsGlob(haystack, needle) -} - -func StrListContains(haystack []string, needle string) bool { - return extstrutil.StrListContains(haystack, needle) -} - -func StrListContainsCaseInsensitive(haystack []string, needle string) bool { - return extstrutil.StrListContainsCaseInsensitive(haystack, needle) -} - -func StrListSubset(super, sub []string) bool { - return extstrutil.StrListSubset(super, sub) -} - -func ParseDedupAndSortStrings(input string, sep string) []string { - return extstrutil.ParseDedupAndSortStrings(input, sep) -} - -func ParseDedupLowercaseAndSortStrings(input string, sep string) []string { - return extstrutil.ParseDedupLowercaseAndSortStrings(input, sep) -} - -func ParseKeyValues(input string, out map[string]string, sep string) error { - return extstrutil.ParseKeyValues(input, out, sep) -} - -func ParseArbitraryKeyValues(input string, out map[string]string, sep string) error { - return extstrutil.ParseArbitraryKeyValues(input, out, sep) -} - -func ParseStringSlice(input string, sep string) []string { - return extstrutil.ParseStringSlice(input, sep) -} - -func ParseArbitraryStringSlice(input string, sep string) []string { - return extstrutil.ParseArbitraryStringSlice(input, sep) -} - -func TrimStrings(items []string) []string { - return extstrutil.TrimStrings(items) -} - -func RemoveDuplicates(items []string, lowercase bool) []string { - return extstrutil.RemoveDuplicates(items, lowercase) -} - -func RemoveDuplicatesStable(items []string, caseInsensitive bool) []string { - return extstrutil.RemoveDuplicatesStable(items, caseInsensitive) -} - -func RemoveEmpty(items []string) []string { - return extstrutil.RemoveEmpty(items) -} - -func EquivalentSlices(a, b []string) bool { - return extstrutil.EquivalentSlices(a, b) -} - -func EqualStringMaps(a, b map[string]string) bool { - return extstrutil.EqualStringMaps(a, b) -} - -func StrListDelete(s []string, d string) []string { - return extstrutil.StrListDelete(s, d) -} - -func GlobbedStringsMatch(item, val string) bool { - return extstrutil.GlobbedStringsMatch(item, val) -} - -func AppendIfMissing(slice []string, i string) []string { - return extstrutil.AppendIfMissing(slice, i) -} - -func MergeSlices(args ...[]string) []string { - return extstrutil.MergeSlices(args...) -} - -func Difference(a, b []string, lowercase bool) []string { - return extstrutil.Difference(a, b, lowercase) -} - -func GetString(m map[string]interface{}, key string) (string, error) { - return extstrutil.GetString(m, key) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/helper/wrapping/wrapinfo.go b/vendor/github.com/hashicorp/vault/sdk/helper/wrapping/wrapinfo.go deleted file mode 100644 index 8d8e63340..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/helper/wrapping/wrapinfo.go +++ /dev/null @@ -1,37 +0,0 @@ -package wrapping - -import "time" - -type ResponseWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl" sentinel:""` - - // The token containing the wrapped response - Token string `json:"token" structs:"token" mapstructure:"token" sentinel:""` - - // The token accessor for the wrapped response token - Accessor string `json:"accessor" structs:"accessor" mapstructure:"accessor"` - - // The creation time. This can be used with the TTL to figure out an - // expected expiration. - CreationTime time.Time `json:"creation_time" structs:"creation_time" mapstructure:"creation_time" sentinel:""` - - // If the contained response is the output of a token or approle secret-id creation call, the - // created token's/secret-id's accessor will be accessible here - WrappedAccessor string `json:"wrapped_accessor" structs:"wrapped_accessor" mapstructure:"wrapped_accessor" sentinel:""` - - // WrappedEntityID is the entity identifier of the caller who initiated the - // wrapping request - WrappedEntityID string `json:"wrapped_entity_id" structs:"wrapped_entity_id" mapstructure:"wrapped_entity_id" sentinel:""` - - // The format to use. This doesn't get returned, it's only internal. - Format string `json:"format" structs:"format" mapstructure:"format" sentinel:""` - - // CreationPath is the original request path that was used to create - // the wrapped response. - CreationPath string `json:"creation_path" structs:"creation_path" mapstructure:"creation_path" sentinel:""` - - // Controls seal wrapping behavior downstream for specific use cases - SealWrap bool `json:"seal_wrap" structs:"seal_wrap" mapstructure:"seal_wrap" sentinel:""` -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/audit.go b/vendor/github.com/hashicorp/vault/sdk/logical/audit.go deleted file mode 100644 index 8ba70f37e..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/audit.go +++ /dev/null @@ -1,19 +0,0 @@ -package logical - -type LogInput struct { - Type string - Auth *Auth - Request *Request - Response *Response - OuterErr error - NonHMACReqDataKeys []string - NonHMACRespDataKeys []string -} - -type MarshalOptions struct { - ValueHasher func(string) string -} - -type OptMarshaler interface { - MarshalJSONWithOptions(*MarshalOptions) ([]byte, error) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/auth.go b/vendor/github.com/hashicorp/vault/sdk/logical/auth.go deleted file mode 100644 index 62707e819..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/auth.go +++ /dev/null @@ -1,129 +0,0 @@ -package logical - -import ( - "fmt" - "time" - - sockaddr "github.com/hashicorp/go-sockaddr" -) - -// Auth is the resulting authentication information that is part of -// Response for credential backends. It's also attached to Request objects and -// defines the authentication used for the request. This value is audit logged. -type Auth struct { - LeaseOptions - - // InternalData is JSON-encodable data that is stored with the auth struct. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - InternalData map[string]interface{} `json:"internal_data" mapstructure:"internal_data" structs:"internal_data"` - - // DisplayName is a non-security sensitive identifier that is - // applicable to this Auth. It is used for logging and prefixing - // of dynamic secrets. For example, DisplayName may be "armon" for - // the github credential backend. If the client token is used to - // generate a SQL credential, the user may be "github-armon-uuid". - // This is to help identify the source without using audit tables. - DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"` - - // Policies is the list of policies that the authenticated user - // is associated with. - Policies []string `json:"policies" mapstructure:"policies" structs:"policies"` - - // TokenPolicies and IdentityPolicies break down the list in Policies to - // help determine where a policy was sourced - TokenPolicies []string `json:"token_policies" mapstructure:"token_policies" structs:"token_policies"` - IdentityPolicies []string `json:"identity_policies" mapstructure:"identity_policies" structs:"identity_policies"` - - // ExternalNamespacePolicies represent the policies authorized from - // different namespaces indexed by respective namespace identifiers - ExternalNamespacePolicies map[string][]string `json:"external_namespace_policies" mapstructure:"external_namespace_policies" structs:"external_namespace_policies"` - - // Indicates that the default policy should not be added by core when - // creating a token. The default policy will still be added if it's - // explicitly defined. - NoDefaultPolicy bool `json:"no_default_policy" mapstructure:"no_default_policy" structs:"no_default_policy"` - - // Metadata is used to attach arbitrary string-type metadata to - // an authenticated user. This metadata will be outputted into the - // audit log. - Metadata map[string]string `json:"metadata" mapstructure:"metadata" structs:"metadata"` - - // ClientToken is the token that is generated for the authentication. - // This will be filled in by Vault core when an auth structure is - // returned. Setting this manually will have no effect. - ClientToken string `json:"client_token" mapstructure:"client_token" structs:"client_token"` - - // Accessor is the identifier for the ClientToken. This can be used - // to perform management functionalities (especially revocation) when - // ClientToken in the audit logs are obfuscated. Accessor can be used - // to revoke a ClientToken and to lookup the capabilities of the ClientToken, - // both without actually knowing the ClientToken. - Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor"` - - // Period indicates that the token generated using this Auth object - // should never expire. The token should be renewed within the duration - // specified by this period. - Period time.Duration `json:"period" mapstructure:"period" structs:"period"` - - // ExplicitMaxTTL is the max TTL that constrains periodic tokens. For normal - // tokens, this value is constrained by the configured max ttl. - ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl"` - - // Number of allowed uses of the issued token - NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` - - // EntityID is the identifier of the entity in identity store to which the - // identity of the authenticating client belongs to. - EntityID string `json:"entity_id" mapstructure:"entity_id" structs:"entity_id"` - - // Alias is the information about the authenticated client returned by - // the auth backend - Alias *Alias `json:"alias" mapstructure:"alias" structs:"alias"` - - // GroupAliases are the informational mappings of external groups which an - // authenticated user belongs to. This is used to check if there are - // mappings groups for the group aliases in identity store. For all the - // matching groups, the entity ID of the user will be added. - GroupAliases []*Alias `json:"group_aliases" mapstructure:"group_aliases" structs:"group_aliases"` - - // The set of CIDRs that this token can be used with - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` - - // CreationPath is a path that the backend can return to use in the lease. - // This is currently only supported for the token store where roles may - // change the perceived path of the lease, even though they don't change - // the request path itself. - CreationPath string `json:"creation_path"` - - // TokenType is the type of token being requested - TokenType TokenType `json:"token_type"` - - // Orphan is set if the token does not have a parent - Orphan bool `json:"orphan"` - - // PolicyResults is the set of policies that grant the token access to the - // requesting path. - PolicyResults *PolicyResults `json:"policy_results"` - - // MFARequirement - MFARequirement *MFARequirement `json:"mfa_requirement"` - - // EntityCreated is set to true if an entity is created as part of a login request - EntityCreated bool `json:"entity_created"` -} - -func (a *Auth) GoString() string { - return fmt.Sprintf("*%#v", *a) -} - -type PolicyResults struct { - Allowed bool `json:"allowed"` - GrantingPolicies []PolicyInfo `json:"granting_policies"` -} - -type PolicyInfo struct { - Name string `json:"name"` - NamespaceId string `json:"namespace_id"` - Type string `json:"type"` -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/connection.go b/vendor/github.com/hashicorp/vault/sdk/logical/connection.go deleted file mode 100644 index 5be863077..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/connection.go +++ /dev/null @@ -1,18 +0,0 @@ -package logical - -import ( - "crypto/tls" -) - -// Connection represents the connection information for a request. This -// is present on the Request structure for credential backends. -type Connection struct { - // RemoteAddr is the network address that sent the request. - RemoteAddr string `json:"remote_addr"` - - // RemotePort is the network port that sent the request. - RemotePort int `json:"remote_port"` - - // ConnState is the TLS connection state if applicable. - ConnState *tls.ConnectionState `sentinel:""` -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/controlgroup.go b/vendor/github.com/hashicorp/vault/sdk/logical/controlgroup.go deleted file mode 100644 index 2ed1b0768..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/controlgroup.go +++ /dev/null @@ -1,17 +0,0 @@ -package logical - -import ( - "time" -) - -type ControlGroup struct { - Authorizations []*Authz `json:"authorizations"` - RequestTime time.Time `json:"request_time"` - Approved bool `json:"approved"` - NamespaceID string `json:"namespace_id"` -} - -type Authz struct { - Token string `json:"token"` - AuthorizationTime time.Time `json:"authorization_time"` -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/error.go b/vendor/github.com/hashicorp/vault/sdk/logical/error.go deleted file mode 100644 index 68c8e1373..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/error.go +++ /dev/null @@ -1,122 +0,0 @@ -package logical - -import "errors" - -var ( - // ErrUnsupportedOperation is returned if the operation is not supported - // by the logical backend. - ErrUnsupportedOperation = errors.New("unsupported operation") - - // ErrUnsupportedPath is returned if the path is not supported - // by the logical backend. - ErrUnsupportedPath = errors.New("unsupported path") - - // ErrInvalidRequest is returned if the request is invalid - ErrInvalidRequest = errors.New("invalid request") - - // ErrPermissionDenied is returned if the client is not authorized - ErrPermissionDenied = errors.New("permission denied") - - // ErrInvalidCredentials is returned when the provided credentials are incorrect - // This is used internally for user lockout purposes. This is not seen externally. - // The status code returned does not change because of this error - ErrInvalidCredentials = errors.New("invalid credentials") - - // ErrMultiAuthzPending is returned if the the request needs more - // authorizations - ErrMultiAuthzPending = errors.New("request needs further approval") - - // ErrUpstreamRateLimited is returned when Vault receives a rate limited - // response from an upstream - ErrUpstreamRateLimited = errors.New("upstream rate limited") - - // ErrPerfStandbyForward is returned when Vault is in a state such that a - // perf standby cannot satisfy a request - ErrPerfStandbyPleaseForward = errors.New("please forward to the active node") - - // ErrLeaseCountQuotaExceeded is returned when a request is rejected due to a lease - // count quota being exceeded. - ErrLeaseCountQuotaExceeded = errors.New("lease count quota exceeded") - - // ErrRateLimitQuotaExceeded is returned when a request is rejected due to a - // rate limit quota being exceeded. - ErrRateLimitQuotaExceeded = errors.New("rate limit quota exceeded") - - // ErrUnrecoverable is returned when a request fails due to something that - // is likely to require manual intervention. This is a generic form of an - // unrecoverable error. - // e.g.: misconfigured or disconnected storage backend. - ErrUnrecoverable = errors.New("unrecoverable error") - - // ErrMissingRequiredState is returned when a request can't be satisfied - // with the data in the local node's storage, based on the provided - // X-Vault-Index request header. - ErrMissingRequiredState = errors.New("required index state not present") - - // Error indicating that the requested path used to serve a purpose in older - // versions, but the functionality has now been removed - ErrPathFunctionalityRemoved = errors.New("functionality on this path has been removed") -) - -type HTTPCodedError interface { - Error() string - Code() int -} - -func CodedError(status int, msg string) HTTPCodedError { - return &codedError{ - Status: status, - Message: msg, - } -} - -var _ HTTPCodedError = (*codedError)(nil) - -type codedError struct { - Status int - Message string -} - -func (e *codedError) Error() string { - return e.Message -} - -func (e *codedError) Code() int { - return e.Status -} - -// Struct to identify user input errors. This is helpful in responding the -// appropriate status codes to clients from the HTTP endpoints. -type StatusBadRequest struct { - Err string -} - -// Implementing error interface -func (s *StatusBadRequest) Error() string { - return s.Err -} - -// This is a new type declared to not cause potential compatibility problems if -// the logic around the CodedError changes; in particular for logical request -// paths it is basically ignored, and changing that behavior might cause -// unforeseen issues. -type ReplicationCodedError struct { - Msg string - Code int -} - -func (r *ReplicationCodedError) Error() string { - return r.Msg -} - -type KeyNotFoundError struct { - Err error -} - -func (e *KeyNotFoundError) WrappedErrors() []error { - return []error{e.Err} -} - -func (e *KeyNotFoundError) Error() string { - return e.Err.Error() -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/identity.pb.go b/vendor/github.com/hashicorp/vault/sdk/logical/identity.pb.go deleted file mode 100644 index 42c722afe..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/identity.pb.go +++ /dev/null @@ -1,709 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.9 -// source: sdk/logical/identity.proto - -package logical - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type Entity struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // ID is the unique identifier for the entity - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - // Name is the human-friendly unique identifier for the entity - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Aliases contains thhe alias mappings for the given entity - Aliases []*Alias `protobuf:"bytes,3,rep,name=aliases,proto3" json:"aliases,omitempty"` - // Metadata represents the custom data tied to this entity - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Disabled is true if the entity is disabled. - Disabled bool `protobuf:"varint,5,opt,name=disabled,proto3" json:"disabled,omitempty"` - // NamespaceID is the identifier of the namespace to which this entity - // belongs to. - NamespaceID string `protobuf:"bytes,6,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` -} - -func (x *Entity) Reset() { - *x = Entity{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Entity) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Entity) ProtoMessage() {} - -func (x *Entity) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Entity.ProtoReflect.Descriptor instead. -func (*Entity) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{0} -} - -func (x *Entity) GetID() string { - if x != nil { - return x.ID - } - return "" -} - -func (x *Entity) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Entity) GetAliases() []*Alias { - if x != nil { - return x.Aliases - } - return nil -} - -func (x *Entity) GetMetadata() map[string]string { - if x != nil { - return x.Metadata - } - return nil -} - -func (x *Entity) GetDisabled() bool { - if x != nil { - return x.Disabled - } - return false -} - -func (x *Entity) GetNamespaceID() string { - if x != nil { - return x.NamespaceID - } - return "" -} - -type Alias struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // MountType is the backend mount's type to which this identity belongs - MountType string `protobuf:"bytes,1,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - // MountAccessor is the identifier of the mount entry to which this - // identity belongs - MountAccessor string `protobuf:"bytes,2,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - // Name is the identifier of this identity in its authentication source - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the custom data tied to this alias. Fields added - // to it should have a low rate of change (or no change) because each - // change incurs a storage write, so quickly-changing fields can have - // a significant performance impact at scale. See the SDK's - // "aliasmetadata" package for a helper that eases and standardizes - // using this safely. - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // ID is the unique identifier for the alias - ID string `protobuf:"bytes,5,opt,name=ID,proto3" json:"ID,omitempty"` - // NamespaceID is the identifier of the namespace to which this alias - // belongs. - NamespaceID string `protobuf:"bytes,6,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` - // Custom Metadata represents the custom data tied to this alias - CustomMetadata map[string]string `protobuf:"bytes,7,rep,name=custom_metadata,json=customMetadata,proto3" json:"custom_metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Local indicates if the alias only belongs to the cluster where it was - // created. If true, the alias will be stored in a location that are ignored - // by the performance replication subsystem. - Local bool `protobuf:"varint,8,opt,name=local,proto3" json:"local,omitempty"` -} - -func (x *Alias) Reset() { - *x = Alias{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Alias) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Alias) ProtoMessage() {} - -func (x *Alias) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Alias.ProtoReflect.Descriptor instead. -func (*Alias) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{1} -} - -func (x *Alias) GetMountType() string { - if x != nil { - return x.MountType - } - return "" -} - -func (x *Alias) GetMountAccessor() string { - if x != nil { - return x.MountAccessor - } - return "" -} - -func (x *Alias) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Alias) GetMetadata() map[string]string { - if x != nil { - return x.Metadata - } - return nil -} - -func (x *Alias) GetID() string { - if x != nil { - return x.ID - } - return "" -} - -func (x *Alias) GetNamespaceID() string { - if x != nil { - return x.NamespaceID - } - return "" -} - -func (x *Alias) GetCustomMetadata() map[string]string { - if x != nil { - return x.CustomMetadata - } - return nil -} - -func (x *Alias) GetLocal() bool { - if x != nil { - return x.Local - } - return false -} - -type Group struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // ID is the unique identifier for the group - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - // Name is the human-friendly unique identifier for the group - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the custom data tied to this group - Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // NamespaceID is the identifier of the namespace to which this group - // belongs to. - NamespaceID string `protobuf:"bytes,4,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` -} - -func (x *Group) Reset() { - *x = Group{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Group) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Group) ProtoMessage() {} - -func (x *Group) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Group.ProtoReflect.Descriptor instead. -func (*Group) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{2} -} - -func (x *Group) GetID() string { - if x != nil { - return x.ID - } - return "" -} - -func (x *Group) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Group) GetMetadata() map[string]string { - if x != nil { - return x.Metadata - } - return nil -} - -func (x *Group) GetNamespaceID() string { - if x != nil { - return x.NamespaceID - } - return "" -} - -type MFAMethodID struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - ID string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - UsesPasscode bool `protobuf:"varint,3,opt,name=uses_passcode,json=usesPasscode,proto3" json:"uses_passcode,omitempty"` -} - -func (x *MFAMethodID) Reset() { - *x = MFAMethodID{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *MFAMethodID) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*MFAMethodID) ProtoMessage() {} - -func (x *MFAMethodID) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use MFAMethodID.ProtoReflect.Descriptor instead. -func (*MFAMethodID) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{3} -} - -func (x *MFAMethodID) GetType() string { - if x != nil { - return x.Type - } - return "" -} - -func (x *MFAMethodID) GetID() string { - if x != nil { - return x.ID - } - return "" -} - -func (x *MFAMethodID) GetUsesPasscode() bool { - if x != nil { - return x.UsesPasscode - } - return false -} - -type MFAConstraintAny struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Any []*MFAMethodID `protobuf:"bytes,1,rep,name=any,proto3" json:"any,omitempty"` -} - -func (x *MFAConstraintAny) Reset() { - *x = MFAConstraintAny{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *MFAConstraintAny) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*MFAConstraintAny) ProtoMessage() {} - -func (x *MFAConstraintAny) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use MFAConstraintAny.ProtoReflect.Descriptor instead. -func (*MFAConstraintAny) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{4} -} - -func (x *MFAConstraintAny) GetAny() []*MFAMethodID { - if x != nil { - return x.Any - } - return nil -} - -type MFARequirement struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - MFARequestID string `protobuf:"bytes,1,opt,name=mfa_request_id,json=mfaRequestId,proto3" json:"mfa_request_id,omitempty"` - MFAConstraints map[string]*MFAConstraintAny `protobuf:"bytes,2,rep,name=mfa_constraints,json=mfaConstraints,proto3" json:"mfa_constraints,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` -} - -func (x *MFARequirement) Reset() { - *x = MFARequirement{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_identity_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *MFARequirement) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*MFARequirement) ProtoMessage() {} - -func (x *MFARequirement) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_identity_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use MFARequirement.ProtoReflect.Descriptor instead. -func (*MFARequirement) Descriptor() ([]byte, []int) { - return file_sdk_logical_identity_proto_rawDescGZIP(), []int{5} -} - -func (x *MFARequirement) GetMFARequestID() string { - if x != nil { - return x.MFARequestID - } - return "" -} - -func (x *MFARequirement) GetMFAConstraints() map[string]*MFAConstraintAny { - if x != nil { - return x.MFAConstraints - } - return nil -} - -var File_sdk_logical_identity_proto protoreflect.FileDescriptor - -var file_sdk_logical_identity_proto_rawDesc = []byte{ - 0x0a, 0x1a, 0x73, 0x64, 0x6b, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2f, 0x69, 0x64, - 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x6c, 0x6f, - 0x67, 0x69, 0x63, 0x61, 0x6c, 0x22, 0x8d, 0x02, 0x0a, 0x06, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, - 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x49, 0x44, - 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, - 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x07, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x18, - 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, - 0x41, 0x6c, 0x69, 0x61, 0x73, 0x52, 0x07, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x12, 0x39, - 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x1d, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x45, 0x6e, 0x74, 0x69, 0x74, - 0x79, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, - 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x69, 0x73, - 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x64, 0x69, 0x73, - 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6e, 0x61, 0x6d, - 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x49, 0x64, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x61, - 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xb1, 0x03, 0x0a, 0x05, 0x41, 0x6c, 0x69, 0x61, 0x73, 0x12, - 0x1d, 0x0a, 0x0a, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x09, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x25, - 0x0a, 0x0e, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x41, 0x63, 0x63, - 0x65, 0x73, 0x73, 0x6f, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x38, 0x0a, 0x08, 0x6d, 0x65, 0x74, - 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x6c, 0x6f, - 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x41, 0x6c, 0x69, 0x61, 0x73, 0x2e, 0x4d, 0x65, 0x74, 0x61, - 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, - 0x61, 0x74, 0x61, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x02, 0x49, 0x44, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, - 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6e, 0x61, 0x6d, 0x65, 0x73, - 0x70, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x4b, 0x0a, 0x0f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, - 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, - 0x22, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x41, 0x6c, 0x69, 0x61, 0x73, 0x2e, - 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, - 0x74, 0x72, 0x79, 0x52, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x4d, 0x65, 0x74, 0x61, 0x64, - 0x61, 0x74, 0x61, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x18, 0x08, 0x20, 0x01, - 0x28, 0x08, 0x52, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, 0x65, 0x74, - 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, - 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x41, 0x0a, 0x13, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, - 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, - 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, - 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xc5, 0x01, 0x0a, 0x05, 0x47, 0x72, - 0x6f, 0x75, 0x70, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x02, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x38, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, - 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x6c, 0x6f, 0x67, 0x69, - 0x63, 0x61, 0x6c, 0x2e, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, - 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, - 0x61, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x5f, 0x69, - 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x49, 0x64, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, - 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, - 0x01, 0x22, 0x56, 0x0a, 0x0b, 0x4d, 0x46, 0x41, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x49, 0x44, - 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, - 0x74, 0x79, 0x70, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x02, 0x69, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x75, 0x73, 0x65, 0x73, 0x5f, 0x70, 0x61, 0x73, - 0x73, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x75, 0x73, 0x65, - 0x73, 0x50, 0x61, 0x73, 0x73, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x0a, 0x10, 0x4d, 0x46, 0x41, - 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x74, 0x41, 0x6e, 0x79, 0x12, 0x26, 0x0a, - 0x03, 0x61, 0x6e, 0x79, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x6c, 0x6f, 0x67, - 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x4d, 0x46, 0x41, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x49, 0x44, - 0x52, 0x03, 0x61, 0x6e, 0x79, 0x22, 0xea, 0x01, 0x0a, 0x0e, 0x4d, 0x46, 0x41, 0x52, 0x65, 0x71, - 0x75, 0x69, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x66, 0x61, 0x5f, - 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0c, 0x6d, 0x66, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x54, - 0x0a, 0x0f, 0x6d, 0x66, 0x61, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x74, - 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, - 0x6c, 0x2e, 0x4d, 0x46, 0x41, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, - 0x2e, 0x4d, 0x66, 0x61, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x74, 0x73, 0x45, - 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0e, 0x6d, 0x66, 0x61, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, - 0x69, 0x6e, 0x74, 0x73, 0x1a, 0x5c, 0x0a, 0x13, 0x4d, 0x66, 0x61, 0x43, 0x6f, 0x6e, 0x73, 0x74, - 0x72, 0x61, 0x69, 0x6e, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, - 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x2f, 0x0a, - 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x6c, - 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x4d, 0x46, 0x41, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, - 0x61, 0x69, 0x6e, 0x74, 0x41, 0x6e, 0x79, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, - 0x38, 0x01, 0x42, 0x28, 0x5a, 0x26, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, - 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x76, 0x61, 0x75, 0x6c, 0x74, - 0x2f, 0x73, 0x64, 0x6b, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_sdk_logical_identity_proto_rawDescOnce sync.Once - file_sdk_logical_identity_proto_rawDescData = file_sdk_logical_identity_proto_rawDesc -) - -func file_sdk_logical_identity_proto_rawDescGZIP() []byte { - file_sdk_logical_identity_proto_rawDescOnce.Do(func() { - file_sdk_logical_identity_proto_rawDescData = protoimpl.X.CompressGZIP(file_sdk_logical_identity_proto_rawDescData) - }) - return file_sdk_logical_identity_proto_rawDescData -} - -var file_sdk_logical_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 11) -var file_sdk_logical_identity_proto_goTypes = []interface{}{ - (*Entity)(nil), // 0: logical.Entity - (*Alias)(nil), // 1: logical.Alias - (*Group)(nil), // 2: logical.Group - (*MFAMethodID)(nil), // 3: logical.MFAMethodID - (*MFAConstraintAny)(nil), // 4: logical.MFAConstraintAny - (*MFARequirement)(nil), // 5: logical.MFARequirement - nil, // 6: logical.Entity.MetadataEntry - nil, // 7: logical.Alias.MetadataEntry - nil, // 8: logical.Alias.CustomMetadataEntry - nil, // 9: logical.Group.MetadataEntry - nil, // 10: logical.MFARequirement.MFAConstraintsEntry -} -var file_sdk_logical_identity_proto_depIDxs = []int32{ - 1, // 0: logical.Entity.aliases:type_name -> logical.Alias - 6, // 1: logical.Entity.metadata:type_name -> logical.Entity.MetadataEntry - 7, // 2: logical.Alias.metadata:type_name -> logical.Alias.MetadataEntry - 8, // 3: logical.Alias.custom_metadata:type_name -> logical.Alias.CustomMetadataEntry - 9, // 4: logical.Group.metadata:type_name -> logical.Group.MetadataEntry - 3, // 5: logical.MFAConstraintAny.any:type_name -> logical.MFAMethodID - 10, // 6: logical.MFARequirement.mfa_constraints:type_name -> logical.MFARequirement.MFAConstraintsEntry - 4, // 7: logical.MFARequirement.MFAConstraintsEntry.value:type_name -> logical.MFAConstraintAny - 8, // [8:8] is the sub-list for method output_type - 8, // [8:8] is the sub-list for method input_type - 8, // [8:8] is the sub-list for extension type_name - 8, // [8:8] is the sub-list for extension extendee - 0, // [0:8] is the sub-list for field type_name -} - -func init() { file_sdk_logical_identity_proto_init() } -func file_sdk_logical_identity_proto_init() { - if File_sdk_logical_identity_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_sdk_logical_identity_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Entity); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_identity_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Alias); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_identity_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Group); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_identity_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MFAMethodID); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_identity_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MFAConstraintAny); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_identity_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MFARequirement); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_sdk_logical_identity_proto_rawDesc, - NumEnums: 0, - NumMessages: 11, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_sdk_logical_identity_proto_goTypes, - DependencyIndexes: file_sdk_logical_identity_proto_depIDxs, - MessageInfos: file_sdk_logical_identity_proto_msgTypes, - }.Build() - File_sdk_logical_identity_proto = out.File - file_sdk_logical_identity_proto_rawDesc = nil - file_sdk_logical_identity_proto_goTypes = nil - file_sdk_logical_identity_proto_depIDxs = nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/identity.proto b/vendor/github.com/hashicorp/vault/sdk/logical/identity.proto deleted file mode 100644 index ea2e373b1..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/identity.proto +++ /dev/null @@ -1,91 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/sdk/logical"; - -package logical; - -message Entity { - // ID is the unique identifier for the entity - string ID = 1; - - // Name is the human-friendly unique identifier for the entity - string name = 2; - - // Aliases contains thhe alias mappings for the given entity - repeated Alias aliases = 3; - - // Metadata represents the custom data tied to this entity - map metadata = 4; - - // Disabled is true if the entity is disabled. - bool disabled = 5; - - // NamespaceID is the identifier of the namespace to which this entity - // belongs to. - string namespace_id = 6; -} - -message Alias { - // MountType is the backend mount's type to which this identity belongs - string mount_type = 1; - - // MountAccessor is the identifier of the mount entry to which this - // identity belongs - string mount_accessor = 2; - - // Name is the identifier of this identity in its authentication source - string name = 3; - - // Metadata represents the custom data tied to this alias. Fields added - // to it should have a low rate of change (or no change) because each - // change incurs a storage write, so quickly-changing fields can have - // a significant performance impact at scale. See the SDK's - // "aliasmetadata" package for a helper that eases and standardizes - // using this safely. - map metadata = 4; - - // ID is the unique identifier for the alias - string ID = 5; - - // NamespaceID is the identifier of the namespace to which this alias - // belongs. - string namespace_id = 6; - - // Custom Metadata represents the custom data tied to this alias - map custom_metadata = 7; - - // Local indicates if the alias only belongs to the cluster where it was - // created. If true, the alias will be stored in a location that are ignored - // by the performance replication subsystem. - bool local = 8; -} - -message Group { - // ID is the unique identifier for the group - string ID = 1; - - // Name is the human-friendly unique identifier for the group - string name = 2; - - // Metadata represents the custom data tied to this group - map metadata = 3; - - // NamespaceID is the identifier of the namespace to which this group - // belongs to. - string namespace_id = 4; -} - -message MFAMethodID { - string type = 1; - string id = 2; - bool uses_passcode = 3; -} - -message MFAConstraintAny { - repeated MFAMethodID any = 1; -} - -message MFARequirement { - string mfa_request_id = 1; - map mfa_constraints = 2; -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/lease.go b/vendor/github.com/hashicorp/vault/sdk/logical/lease.go deleted file mode 100644 index 97bbe4f65..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/lease.go +++ /dev/null @@ -1,53 +0,0 @@ -package logical - -import ( - "time" -) - -// LeaseOptions is an embeddable struct to capture common lease -// settings between a Secret and Auth -type LeaseOptions struct { - // TTL is the duration that this secret is valid for. Vault - // will automatically revoke it after the duration. - TTL time.Duration `json:"lease"` - - // MaxTTL is the maximum duration that this secret is valid for. - MaxTTL time.Duration `json:"max_ttl"` - - // Renewable, if true, means that this secret can be renewed. - Renewable bool `json:"renewable"` - - // Increment will be the lease increment that the user requested. - // This is only available on a Renew operation and has no effect - // when returning a response. - Increment time.Duration `json:"-"` - - // IssueTime is the time of issue for the original lease. This is - // only available on Renew and Revoke operations and has no effect when returning - // a response. It can be used to enforce maximum lease periods by - // a logical backend. - IssueTime time.Time `json:"-"` -} - -// LeaseEnabled checks if leasing is enabled -func (l *LeaseOptions) LeaseEnabled() bool { - return l.TTL > 0 -} - -// LeaseTotal is the lease duration with a guard against a negative TTL -func (l *LeaseOptions) LeaseTotal() time.Duration { - if l.TTL <= 0 { - return 0 - } - - return l.TTL -} - -// ExpirationTime computes the time until expiration including the grace period -func (l *LeaseOptions) ExpirationTime() time.Time { - var expireTime time.Time - if l.LeaseEnabled() { - expireTime = time.Now().Add(l.LeaseTotal()) - } - return expireTime -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/logical.go b/vendor/github.com/hashicorp/vault/sdk/logical/logical.go deleted file mode 100644 index 601148952..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/logical.go +++ /dev/null @@ -1,156 +0,0 @@ -package logical - -import ( - "context" - - log "github.com/hashicorp/go-hclog" -) - -// BackendType is the type of backend that is being implemented -type BackendType uint32 - -// The these are the types of backends that can be derived from -// logical.Backend -const ( - TypeUnknown BackendType = 0 // This is also the zero-value for BackendType - TypeLogical BackendType = 1 - TypeCredential BackendType = 2 -) - -// Stringer implementation -func (b BackendType) String() string { - switch b { - case TypeLogical: - return "secret" - case TypeCredential: - return "auth" - } - - return "unknown" -} - -// Backend interface must be implemented to be "mountable" at -// a given path. Requests flow through a router which has various mount -// points that flow to a logical backend. The logic of each backend is flexible, -// and this is what allows materialized keys to function. There can be specialized -// logical backends for various upstreams (Consul, PostgreSQL, MySQL, etc) that can -// interact with remote APIs to generate keys dynamically. This interface also -// allows for a "procfs" like interaction, as internal state can be exposed by -// acting like a logical backend and being mounted. -type Backend interface { - // Initialize is used to initialize a plugin after it has been mounted. - Initialize(context.Context, *InitializationRequest) error - - // HandleRequest is used to handle a request and generate a response. - // The backends must check the operation type and handle appropriately. - HandleRequest(context.Context, *Request) (*Response, error) - - // SpecialPaths is a list of paths that are special in some way. - // See PathType for the types of special paths. The key is the type - // of the special path, and the value is a list of paths for this type. - // This is not a regular expression but is an exact match. If the path - // ends in '*' then it is a prefix-based match. The '*' can only appear - // at the end. - SpecialPaths() *Paths - - // System provides an interface to access certain system configuration - // information, such as globally configured default and max lease TTLs. - System() SystemView - - // Logger provides an interface to access the underlying logger. This - // is useful when a struct embeds a Backend-implemented struct that - // contains a private instance of logger. - Logger() log.Logger - - // HandleExistenceCheck is used to handle a request and generate a response - // indicating whether the given path exists or not; this is used to - // understand whether the request must have a Create or Update capability - // ACL applied. The first bool indicates whether an existence check - // function was found for the backend; the second indicates whether, if an - // existence check function was found, the item exists or not. - HandleExistenceCheck(context.Context, *Request) (bool, bool, error) - - // Cleanup is invoked during an unmount of a backend to allow it to - // handle any cleanup like connection closing or releasing of file handles. - Cleanup(context.Context) - - // InvalidateKey may be invoked when an object is modified that belongs - // to the backend. The backend can use this to clear any caches or reset - // internal state as needed. - InvalidateKey(context.Context, string) - - // Setup is used to set up the backend based on the provided backend - // configuration. - Setup(context.Context, *BackendConfig) error - - // Type returns the BackendType for the particular backend - Type() BackendType -} - -// BackendConfig is provided to the factory to initialize the backend -type BackendConfig struct { - // View should not be stored, and should only be used for initialization - StorageView Storage - - // The backend should use this logger. The log should not contain any secrets. - Logger log.Logger - - // System provides a view into a subset of safe system information that - // is useful for backends, such as the default/max lease TTLs - System SystemView - - // BackendUUID is a unique identifier provided to this backend. It's useful - // when a backend needs a consistent and unique string without using storage. - BackendUUID string - - // Config is the opaque user configuration provided when mounting - Config map[string]string -} - -// Factory is the factory function to create a logical backend. -type Factory func(context.Context, *BackendConfig) (Backend, error) - -// Paths is the structure of special paths that is used for SpecialPaths. -type Paths struct { - // Root are the API paths that require a root token to access - Root []string - - // Unauthenticated are the API paths that can be accessed without any auth. - // These can't be regular expressions, it is either exact match, a prefix - // match and/or a wildcard match. For prefix match, append '*' as a suffix. - // For a wildcard match, use '+' in the segment to match any identifier - // (e.g. 'foo/+/bar'). Note that '+' can't be adjacent to a non-slash. - Unauthenticated []string - - // LocalStorage are storage paths (prefixes) that are local to this cluster; - // this indicates that these paths should not be replicated across performance clusters - // (DR replication is unaffected). - LocalStorage []string - - // SealWrapStorage are storage paths that, when using a capable seal, - // should be seal wrapped with extra encryption. It is exact matching - // unless it ends with '/' in which case it will be treated as a prefix. - SealWrapStorage []string -} - -type Auditor interface { - AuditRequest(ctx context.Context, input *LogInput) error - AuditResponse(ctx context.Context, input *LogInput) error -} - -// Externaler allows us to check if a backend is running externally (i.e., over GRPC) -type Externaler interface { - IsExternal() bool -} - -type PluginVersion struct { - Version string -} - -// PluginVersioner is an optional interface to return version info. -type PluginVersioner interface { - // PluginVersion returns the version for the backend - PluginVersion() PluginVersion -} - -var EmptyPluginVersion = PluginVersion{""} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/logical_storage.go b/vendor/github.com/hashicorp/vault/sdk/logical/logical_storage.go deleted file mode 100644 index 16b85cd79..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/logical_storage.go +++ /dev/null @@ -1,52 +0,0 @@ -package logical - -import ( - "context" - - "github.com/hashicorp/vault/sdk/physical" -) - -type LogicalStorage struct { - underlying physical.Backend -} - -func (s *LogicalStorage) Get(ctx context.Context, key string) (*StorageEntry, error) { - entry, err := s.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - return &StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -func (s *LogicalStorage) Put(ctx context.Context, entry *StorageEntry) error { - return s.underlying.Put(ctx, &physical.Entry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }) -} - -func (s *LogicalStorage) Delete(ctx context.Context, key string) error { - return s.underlying.Delete(ctx, key) -} - -func (s *LogicalStorage) List(ctx context.Context, prefix string) ([]string, error) { - return s.underlying.List(ctx, prefix) -} - -func (s *LogicalStorage) Underlying() physical.Backend { - return s.underlying -} - -func NewLogicalStorage(underlying physical.Backend) *LogicalStorage { - return &LogicalStorage{ - underlying: underlying, - } -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/managed_key.go b/vendor/github.com/hashicorp/vault/sdk/logical/managed_key.go deleted file mode 100644 index 6f642ad57..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/managed_key.go +++ /dev/null @@ -1,119 +0,0 @@ -package logical - -import ( - "context" - "crypto" - "crypto/cipher" - "io" -) - -type KeyUsage int - -const ( - KeyUsageEncrypt KeyUsage = 1 + iota - KeyUsageDecrypt - KeyUsageSign - KeyUsageVerify - KeyUsageWrap - KeyUsageUnwrap -) - -type ManagedKey interface { - // Name is a human-readable identifier for a managed key that may change/renamed. Use Uuid if a - // long term consistent identifier is needed. - Name() string - // UUID is a unique identifier for a managed key that is guaranteed to remain - // consistent even if a key is migrated or renamed. - UUID() string - // Present returns true if the key is established in the KMS. This may return false if for example - // an HSM library is not configured on all cluster nodes. - Present(ctx context.Context) (bool, error) - - // AllowsAll returns true if all the requested usages are supported by the managed key. - AllowsAll(usages []KeyUsage) bool -} - -type ( - ManagedKeyConsumer func(context.Context, ManagedKey) error - ManagedSigningKeyConsumer func(context.Context, ManagedSigningKey) error - ManagedEncryptingKeyConsumer func(context.Context, ManagedEncryptingKey) error - ManagedMACKeyConsumer func(context.Context, ManagedMACKey) error - ManagedKeyRandomSourceConsumer func(context.Context, ManagedKeyRandomSource) error -) - -type ManagedKeySystemView interface { - // WithManagedKeyByName retrieves an instantiated managed key for consumption by the given function. The - // provided key can only be used within the scope of that function call - WithManagedKeyByName(ctx context.Context, keyName, backendUUID string, f ManagedKeyConsumer) error - // WithManagedKeyByUUID retrieves an instantiated managed key for consumption by the given function. The - // provided key can only be used within the scope of that function call - WithManagedKeyByUUID(ctx context.Context, keyUuid, backendUUID string, f ManagedKeyConsumer) error - - // WithManagedSigningKeyByName retrieves an instantiated managed signing key for consumption by the given function, - // with the same semantics as WithManagedKeyByName - WithManagedSigningKeyByName(ctx context.Context, keyName, backendUUID string, f ManagedSigningKeyConsumer) error - // WithManagedSigningKeyByUUID retrieves an instantiated managed signing key for consumption by the given function, - // with the same semantics as WithManagedKeyByUUID - WithManagedSigningKeyByUUID(ctx context.Context, keyUuid, backendUUID string, f ManagedSigningKeyConsumer) error - // WithManagedSigningKeyByName retrieves an instantiated managed signing key for consumption by the given function, - // with the same semantics as WithManagedKeyByName - WithManagedEncryptingKeyByName(ctx context.Context, keyName, backendUUID string, f ManagedEncryptingKeyConsumer) error - // WithManagedSigningKeyByUUID retrieves an instantiated managed signing key for consumption by the given function, - // with the same semantics as WithManagedKeyByUUID - WithManagedEncryptingKeyByUUID(ctx context.Context, keyUuid, backendUUID string, f ManagedEncryptingKeyConsumer) error - // WithManagedMACKeyByName retrieves an instantiated managed MAC key by name for consumption by the given function, - // with the same semantics as WithManagedKeyByName. - WithManagedMACKeyByName(ctx context.Context, keyName, backendUUID string, f ManagedMACKeyConsumer) error - // WithManagedMACKeyByUUID retrieves an instantiated managed MAC key by UUID for consumption by the given function, - // with the same semantics as WithManagedKeyByUUID. - WithManagedMACKeyByUUID(ctx context.Context, keyUUID, backendUUID string, f ManagedMACKeyConsumer) error -} - -type ManagedAsymmetricKey interface { - ManagedKey - GetPublicKey(ctx context.Context) (crypto.PublicKey, error) -} - -type ManagedKeyLifecycle interface { - // GenerateKey generates a key in the KMS if it didn't yet exist, returning the id. - // If it already existed, returns the existing id. KMSKey's key material is ignored if present. - GenerateKey(ctx context.Context) (string, error) -} - -type ManagedSigningKey interface { - ManagedAsymmetricKey - - // Sign returns a digital signature of the provided value. The SignerOpts param must provide the hash function - // that generated the value (if any). - // The optional randomSource specifies the source of random values and may be ignored by the implementation - // (such as on HSMs with their own internal RNG) - Sign(ctx context.Context, value []byte, randomSource io.Reader, opts crypto.SignerOpts) ([]byte, error) - - // Verify verifies the provided signature against the value. The SignerOpts param must provide the hash function - // that generated the value (if any). - // If true is returned the signature is correct, false otherwise. - Verify(ctx context.Context, signature, value []byte, opts crypto.SignerOpts) (bool, error) - - // GetSigner returns an implementation of crypto.Signer backed by the managed key. This should be called - // as needed so as to use per request contexts. - GetSigner(context.Context) (crypto.Signer, error) -} - -type ManagedEncryptingKey interface { - ManagedKey - GetAEAD(iv []byte) (cipher.AEAD, error) -} - -type ManagedMACKey interface { - ManagedKey - - // MAC generates a MAC tag using the provided algorithm for the provided value. - MAC(ctx context.Context, algorithm string, data []byte) ([]byte, error) -} - -type ManagedKeyRandomSource interface { - ManagedKey - - // GetRandomBytes returns a number (specified by the count parameter) of random bytes sourced from the target managed key. - GetRandomBytes(ctx context.Context, count int) ([]byte, error) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/plugin.pb.go b/vendor/github.com/hashicorp/vault/sdk/logical/plugin.pb.go deleted file mode 100644 index f3a9ec52c..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/plugin.pb.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.9 -// source: sdk/logical/plugin.proto - -package logical - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type PluginEnvironment struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // VaultVersion is the version of the Vault server - VaultVersion string `protobuf:"bytes,1,opt,name=vault_version,json=vaultVersion,proto3" json:"vault_version,omitempty"` - // VaultVersionPrerelease is the prerelease information of the Vault server - VaultVersionPrerelease string `protobuf:"bytes,2,opt,name=vault_version_prerelease,json=vaultVersionPrerelease,proto3" json:"vault_version_prerelease,omitempty"` - // VaultVersionMetadata is the version metadata of the Vault server - VaultVersionMetadata string `protobuf:"bytes,3,opt,name=vault_version_metadata,json=vaultVersionMetadata,proto3" json:"vault_version_metadata,omitempty"` -} - -func (x *PluginEnvironment) Reset() { - *x = PluginEnvironment{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_plugin_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *PluginEnvironment) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*PluginEnvironment) ProtoMessage() {} - -func (x *PluginEnvironment) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_plugin_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use PluginEnvironment.ProtoReflect.Descriptor instead. -func (*PluginEnvironment) Descriptor() ([]byte, []int) { - return file_sdk_logical_plugin_proto_rawDescGZIP(), []int{0} -} - -func (x *PluginEnvironment) GetVaultVersion() string { - if x != nil { - return x.VaultVersion - } - return "" -} - -func (x *PluginEnvironment) GetVaultVersionPrerelease() string { - if x != nil { - return x.VaultVersionPrerelease - } - return "" -} - -func (x *PluginEnvironment) GetVaultVersionMetadata() string { - if x != nil { - return x.VaultVersionMetadata - } - return "" -} - -var File_sdk_logical_plugin_proto protoreflect.FileDescriptor - -var file_sdk_logical_plugin_proto_rawDesc = []byte{ - 0x0a, 0x18, 0x73, 0x64, 0x6b, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2f, 0x70, 0x6c, - 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x6c, 0x6f, 0x67, 0x69, - 0x63, 0x61, 0x6c, 0x22, 0xa8, 0x01, 0x0a, 0x11, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x45, 0x6e, - 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x76, 0x61, 0x75, - 0x6c, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0c, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x38, - 0x0a, 0x18, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x5f, - 0x70, 0x72, 0x65, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x16, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x50, 0x72, - 0x65, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x16, 0x76, 0x61, 0x75, 0x6c, - 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, - 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x14, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x56, - 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x42, 0x28, - 0x5a, 0x26, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, - 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x2f, 0x73, 0x64, 0x6b, - 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_sdk_logical_plugin_proto_rawDescOnce sync.Once - file_sdk_logical_plugin_proto_rawDescData = file_sdk_logical_plugin_proto_rawDesc -) - -func file_sdk_logical_plugin_proto_rawDescGZIP() []byte { - file_sdk_logical_plugin_proto_rawDescOnce.Do(func() { - file_sdk_logical_plugin_proto_rawDescData = protoimpl.X.CompressGZIP(file_sdk_logical_plugin_proto_rawDescData) - }) - return file_sdk_logical_plugin_proto_rawDescData -} - -var file_sdk_logical_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_sdk_logical_plugin_proto_goTypes = []interface{}{ - (*PluginEnvironment)(nil), // 0: logical.PluginEnvironment -} -var file_sdk_logical_plugin_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_sdk_logical_plugin_proto_init() } -func file_sdk_logical_plugin_proto_init() { - if File_sdk_logical_plugin_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_sdk_logical_plugin_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*PluginEnvironment); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_sdk_logical_plugin_proto_rawDesc, - NumEnums: 0, - NumMessages: 1, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_sdk_logical_plugin_proto_goTypes, - DependencyIndexes: file_sdk_logical_plugin_proto_depIdxs, - MessageInfos: file_sdk_logical_plugin_proto_msgTypes, - }.Build() - File_sdk_logical_plugin_proto = out.File - file_sdk_logical_plugin_proto_rawDesc = nil - file_sdk_logical_plugin_proto_goTypes = nil - file_sdk_logical_plugin_proto_depIdxs = nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/plugin.proto b/vendor/github.com/hashicorp/vault/sdk/logical/plugin.proto deleted file mode 100644 index f2df6c75d..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/plugin.proto +++ /dev/null @@ -1,16 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/sdk/logical"; - -package logical; - -message PluginEnvironment { - // VaultVersion is the version of the Vault server - string vault_version = 1; - - // VaultVersionPrerelease is the prerelease information of the Vault server - string vault_version_prerelease = 2; - - // VaultVersionMetadata is the version metadata of the Vault server - string vault_version_metadata = 3; -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/request.go b/vendor/github.com/hashicorp/vault/sdk/logical/request.go deleted file mode 100644 index d774fd176..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/request.go +++ /dev/null @@ -1,394 +0,0 @@ -package logical - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/mitchellh/copystructure" -) - -// RequestWrapInfo is a struct that stores information about desired response -// and seal wrapping behavior -type RequestWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl" sentinel:""` - - // The format to use for the wrapped response; if not specified it's a bare - // token - Format string `json:"format" structs:"format" mapstructure:"format" sentinel:""` - - // A flag to conforming backends that data for a given request should be - // seal wrapped - SealWrap bool `json:"seal_wrap" structs:"seal_wrap" mapstructure:"seal_wrap" sentinel:""` -} - -func (r *RequestWrapInfo) SentinelGet(key string) (interface{}, error) { - if r == nil { - return nil, nil - } - switch key { - case "ttl": - return r.TTL, nil - case "ttl_seconds": - return int64(r.TTL.Seconds()), nil - } - - return nil, nil -} - -func (r *RequestWrapInfo) SentinelKeys() []string { - return []string{ - "ttl", - "ttl_seconds", - } -} - -type ClientTokenSource uint32 - -const ( - NoClientToken ClientTokenSource = iota - ClientTokenFromVaultHeader - ClientTokenFromAuthzHeader -) - -type WALState struct { - ClusterID string - LocalIndex uint64 - ReplicatedIndex uint64 -} - -const indexStateCtxKey = "index_state" - -// IndexStateContext returns a context with an added value holding the index -// state that should be populated on writes. -func IndexStateContext(ctx context.Context, state *WALState) context.Context { - return context.WithValue(ctx, indexStateCtxKey, state) -} - -// IndexStateFromContext is a helper to look up if the provided context contains -// an index state pointer. -func IndexStateFromContext(ctx context.Context) *WALState { - s, ok := ctx.Value(indexStateCtxKey).(*WALState) - if !ok { - return nil - } - return s -} - -// Request is a struct that stores the parameters and context of a request -// being made to Vault. It is used to abstract the details of the higher level -// request protocol from the handlers. -// -// Note: Many of these have Sentinel disabled because they are values populated -// by the router after policy checks; the token namespace would be the right -// place to access them via Sentinel -type Request struct { - // Id is the uuid associated with each request - ID string `json:"id" structs:"id" mapstructure:"id" sentinel:""` - - // If set, the name given to the replication secondary where this request - // originated - ReplicationCluster string `json:"replication_cluster" structs:"replication_cluster" mapstructure:"replication_cluster" sentinel:""` - - // Operation is the requested operation type - Operation Operation `json:"operation" structs:"operation" mapstructure:"operation"` - - // Path is the full path of the request - Path string `json:"path" structs:"path" mapstructure:"path" sentinel:""` - - // Request data is an opaque map that must have string keys. - Data map[string]interface{} `json:"map" structs:"data" mapstructure:"data"` - - // Storage can be used to durably store and retrieve state. - Storage Storage `json:"-" sentinel:""` - - // Secret will be non-nil only for Revoke and Renew operations - // to represent the secret that was returned prior. - Secret *Secret `json:"secret" structs:"secret" mapstructure:"secret" sentinel:""` - - // Auth will be non-nil only for Renew operations - // to represent the auth that was returned prior. - Auth *Auth `json:"auth" structs:"auth" mapstructure:"auth" sentinel:""` - - // Headers will contain the http headers from the request. This value will - // be used in the audit broker to ensure we are auditing only the allowed - // headers. - Headers map[string][]string `json:"headers" structs:"headers" mapstructure:"headers" sentinel:""` - - // Connection will be non-nil only for credential providers to - // inspect the connection information and potentially use it for - // authentication/protection. - Connection *Connection `json:"connection" structs:"connection" mapstructure:"connection"` - - // ClientToken is provided to the core so that the identity - // can be verified and ACLs applied. This value is passed - // through to the logical backends but after being salted and - // hashed. - ClientToken string `json:"client_token" structs:"client_token" mapstructure:"client_token" sentinel:""` - - // ClientTokenAccessor is provided to the core so that the it can get - // logged as part of request audit logging. - ClientTokenAccessor string `json:"client_token_accessor" structs:"client_token_accessor" mapstructure:"client_token_accessor" sentinel:""` - - // DisplayName is provided to the logical backend to help associate - // dynamic secrets with the source entity. This is not a sensitive - // name, but is useful for operators. - DisplayName string `json:"display_name" structs:"display_name" mapstructure:"display_name" sentinel:""` - - // MountPoint is provided so that a logical backend can generate - // paths relative to itself. The `Path` is effectively the client - // request path with the MountPoint trimmed off. - MountPoint string `json:"mount_point" structs:"mount_point" mapstructure:"mount_point" sentinel:""` - - // MountType is provided so that a logical backend can make decisions - // based on the specific mount type (e.g., if a mount type has different - // aliases, generating different defaults depending on the alias) - MountType string `json:"mount_type" structs:"mount_type" mapstructure:"mount_type" sentinel:""` - - // MountAccessor is provided so that identities returned by the authentication - // backends can be tied to the mount it belongs to. - MountAccessor string `json:"mount_accessor" structs:"mount_accessor" mapstructure:"mount_accessor" sentinel:""` - - // WrapInfo contains requested response wrapping parameters - WrapInfo *RequestWrapInfo `json:"wrap_info" structs:"wrap_info" mapstructure:"wrap_info" sentinel:""` - - // ClientTokenRemainingUses represents the allowed number of uses left on the - // token supplied - ClientTokenRemainingUses int `json:"client_token_remaining_uses" structs:"client_token_remaining_uses" mapstructure:"client_token_remaining_uses"` - - // EntityID is the identity of the caller extracted out of the token used - // to make this request - EntityID string `json:"entity_id" structs:"entity_id" mapstructure:"entity_id" sentinel:""` - - // PolicyOverride indicates that the requestor wishes to override - // soft-mandatory Sentinel policies - PolicyOverride bool `json:"policy_override" structs:"policy_override" mapstructure:"policy_override"` - - // Whether the request is unauthenticated, as in, had no client token - // attached. Useful in some situations where the client token is not made - // accessible. - Unauthenticated bool `json:"unauthenticated" structs:"unauthenticated" mapstructure:"unauthenticated"` - - // MFACreds holds the parsed MFA information supplied over the API as part of - // X-Vault-MFA header - MFACreds MFACreds `json:"mfa_creds" structs:"mfa_creds" mapstructure:"mfa_creds" sentinel:""` - - // Cached token entry. This avoids another lookup in request handling when - // we've already looked it up at http handling time. Note that this token - // has not been "used", as in it will not properly take into account use - // count limitations. As a result this field should only ever be used for - // transport to a function that would otherwise do a lookup and then - // properly use the token. - tokenEntry *TokenEntry - - // For replication, contains the last WAL on the remote side after handling - // the request, used for best-effort avoidance of stale read-after-write - lastRemoteWAL uint64 - - // ControlGroup holds the authorizations that have happened on this - // request - ControlGroup *ControlGroup `json:"control_group" structs:"control_group" mapstructure:"control_group" sentinel:""` - - // ClientTokenSource tells us where the client token was sourced from, so - // we can delete it before sending off to plugins - ClientTokenSource ClientTokenSource - - // HTTPRequest, if set, can be used to access fields from the HTTP request - // that generated this logical.Request object, such as the request body. - HTTPRequest *http.Request `json:"-" sentinel:""` - - // ResponseWriter if set can be used to stream a response value to the http - // request that generated this logical.Request object. - ResponseWriter *HTTPResponseWriter `json:"-" sentinel:""` - - // requiredState is used internally to propagate the X-Vault-Index request - // header to later levels of request processing that operate only on - // logical.Request. - requiredState []string - - // responseState is used internally to propagate the state that should appear - // in response headers; it's attached to the request rather than the response - // because not all requests yields non-nil responses. - responseState *WALState - - // ClientID is the identity of the caller. If the token is associated with an - // entity, it will be the same as the EntityID . If the token has no entity, - // this will be the sha256(sorted policies + namespace) associated with the - // client token. - ClientID string `json:"client_id" structs:"client_id" mapstructure:"client_id" sentinel:""` - - // InboundSSCToken is the token that arrives on an inbound request, supplied - // by the vault user. - InboundSSCToken string -} - -// Clone returns a deep copy of the request by using copystructure -func (r *Request) Clone() (*Request, error) { - cpy, err := copystructure.Copy(r) - if err != nil { - return nil, err - } - return cpy.(*Request), nil -} - -// Get returns a data field and guards for nil Data -func (r *Request) Get(key string) interface{} { - if r.Data == nil { - return nil - } - return r.Data[key] -} - -// GetString returns a data field as a string -func (r *Request) GetString(key string) string { - raw := r.Get(key) - s, _ := raw.(string) - return s -} - -func (r *Request) GoString() string { - return fmt.Sprintf("*%#v", *r) -} - -func (r *Request) SentinelGet(key string) (interface{}, error) { - switch key { - case "path": - // Sanitize it here so that it's consistent in policies - return strings.TrimPrefix(r.Path, "/"), nil - - case "wrapping", "wrap_info": - // If the pointer is nil accessing the wrap info is considered - // "undefined" so this allows us to instead discover a TTL of zero - if r.WrapInfo == nil { - return &RequestWrapInfo{}, nil - } - return r.WrapInfo, nil - } - - return nil, nil -} - -func (r *Request) SentinelKeys() []string { - return []string{ - "path", - "wrapping", - "wrap_info", - } -} - -func (r *Request) LastRemoteWAL() uint64 { - return r.lastRemoteWAL -} - -func (r *Request) SetLastRemoteWAL(last uint64) { - r.lastRemoteWAL = last -} - -func (r *Request) RequiredState() []string { - return r.requiredState -} - -func (r *Request) SetRequiredState(state []string) { - r.requiredState = state -} - -func (r *Request) ResponseState() *WALState { - return r.responseState -} - -func (r *Request) SetResponseState(w *WALState) { - r.responseState = w -} - -func (r *Request) TokenEntry() *TokenEntry { - return r.tokenEntry -} - -func (r *Request) SetTokenEntry(te *TokenEntry) { - r.tokenEntry = te -} - -// RenewRequest creates the structure of the renew request. -func RenewRequest(path string, secret *Secret, data map[string]interface{}) *Request { - return &Request{ - Operation: RenewOperation, - Path: path, - Data: data, - Secret: secret, - } -} - -// RenewAuthRequest creates the structure of the renew request for an auth. -func RenewAuthRequest(path string, auth *Auth, data map[string]interface{}) *Request { - return &Request{ - Operation: RenewOperation, - Path: path, - Data: data, - Auth: auth, - } -} - -// RevokeRequest creates the structure of the revoke request. -func RevokeRequest(path string, secret *Secret, data map[string]interface{}) *Request { - return &Request{ - Operation: RevokeOperation, - Path: path, - Data: data, - Secret: secret, - } -} - -// RollbackRequest creates the structure of the revoke request. -func RollbackRequest(path string) *Request { - return &Request{ - Operation: RollbackOperation, - Path: path, - Data: make(map[string]interface{}), - } -} - -// Operation is an enum that is used to specify the type -// of request being made -type Operation string - -const ( - // The operations below are called per path - CreateOperation Operation = "create" - ReadOperation = "read" - UpdateOperation = "update" - PatchOperation = "patch" - DeleteOperation = "delete" - ListOperation = "list" - HelpOperation = "help" - AliasLookaheadOperation = "alias-lookahead" - ResolveRoleOperation = "resolve-role" - - // The operations below are called globally, the path is less relevant. - RevokeOperation Operation = "revoke" - RenewOperation = "renew" - RollbackOperation = "rollback" -) - -type MFACreds map[string][]string - -// InitializationRequest stores the parameters and context of an Initialize() -// call being made to a logical.Backend. -type InitializationRequest struct { - // Storage can be used to durably store and retrieve state. - Storage Storage -} - -type CustomHeader struct { - Name string - Value string -} - -type CtxKeyInFlightRequestID struct{} - -func (c CtxKeyInFlightRequestID) String() string { - return "in-flight-request-ID" -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/response.go b/vendor/github.com/hashicorp/vault/sdk/logical/response.go deleted file mode 100644 index 0f8a2210e..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/response.go +++ /dev/null @@ -1,322 +0,0 @@ -package logical - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "sync/atomic" - - "github.com/hashicorp/vault/sdk/helper/wrapping" -) - -const ( - // HTTPContentType can be specified in the Data field of a Response - // so that the HTTP front end can specify a custom Content-Type associated - // with the HTTPRawBody. This can only be used for non-secrets, and should - // be avoided unless absolutely necessary, such as implementing a specification. - // The value must be a string. - HTTPContentType = "http_content_type" - - // HTTPRawBody is the raw content of the HTTP body that goes with the HTTPContentType. - // This can only be specified for non-secrets, and should should be similarly - // avoided like the HTTPContentType. The value must be a byte slice. - HTTPRawBody = "http_raw_body" - - // HTTPStatusCode is the response code of the HTTP body that goes with the HTTPContentType. - // This can only be specified for non-secrets, and should should be similarly - // avoided like the HTTPContentType. The value must be an integer. - HTTPStatusCode = "http_status_code" - - // For unwrapping we may need to know whether the value contained in the - // raw body is already JSON-unmarshaled. The presence of this key indicates - // that it has already been unmarshaled. That way we don't need to simply - // ignore errors. - HTTPRawBodyAlreadyJSONDecoded = "http_raw_body_already_json_decoded" - - // If set, HTTPCacheControlHeader will replace the default Cache-Control=no-store header - // set by the generic wrapping handler. The value must be a string. - HTTPCacheControlHeader = "http_raw_cache_control" - - // If set, HTTPPragmaHeader will set the Pragma response header. - // The value must be a string. - HTTPPragmaHeader = "http_raw_pragma" - - // If set, HTTPWWWAuthenticateHeader will set the WWW-Authenticate response header. - // The value must be a string. - HTTPWWWAuthenticateHeader = "http_www_authenticate" -) - -// Response is a struct that stores the response of a request. -// It is used to abstract the details of the higher level request protocol. -type Response struct { - // Secret, if not nil, denotes that this response represents a secret. - Secret *Secret `json:"secret" structs:"secret" mapstructure:"secret"` - - // Auth, if not nil, contains the authentication information for - // this response. This is only checked and means something for - // credential backends. - Auth *Auth `json:"auth" structs:"auth" mapstructure:"auth"` - - // Response data is an opaque map that must have string keys. For - // secrets, this data is sent down to the user as-is. To store internal - // data that you don't want the user to see, store it in - // Secret.InternalData. - Data map[string]interface{} `json:"data" structs:"data" mapstructure:"data"` - - // Redirect is an HTTP URL to redirect to for further authentication. - // This is only valid for credential backends. This will be blanked - // for any logical backend and ignored. - Redirect string `json:"redirect" structs:"redirect" mapstructure:"redirect"` - - // Warnings allow operations or backends to return warnings in response - // to user actions without failing the action outright. - Warnings []string `json:"warnings" structs:"warnings" mapstructure:"warnings"` - - // Information for wrapping the response in a cubbyhole - WrapInfo *wrapping.ResponseWrapInfo `json:"wrap_info" structs:"wrap_info" mapstructure:"wrap_info"` - - // Headers will contain the http headers from the plugin that it wishes to - // have as part of the output - Headers map[string][]string `json:"headers" structs:"headers" mapstructure:"headers"` -} - -// AddWarning adds a warning into the response's warning list -func (r *Response) AddWarning(warning string) { - if r.Warnings == nil { - r.Warnings = make([]string, 0, 1) - } - r.Warnings = append(r.Warnings, warning) -} - -// IsError returns true if this response seems to indicate an error. -func (r *Response) IsError() bool { - // If the response data contains only an 'error' element, or an 'error' and a 'data' element only - return r != nil && r.Data != nil && r.Data["error"] != nil && (len(r.Data) == 1 || (r.Data["data"] != nil && len(r.Data) == 2)) -} - -func (r *Response) Error() error { - if !r.IsError() { - return nil - } - switch r.Data["error"].(type) { - case string: - return errors.New(r.Data["error"].(string)) - case error: - return r.Data["error"].(error) - } - return nil -} - -// HelpResponse is used to format a help response -func HelpResponse(text string, seeAlso []string, oapiDoc interface{}) *Response { - return &Response{ - Data: map[string]interface{}{ - "help": text, - "see_also": seeAlso, - "openapi": oapiDoc, - }, - } -} - -// ErrorResponse is used to format an error response -func ErrorResponse(text string, vargs ...interface{}) *Response { - if len(vargs) > 0 { - text = fmt.Sprintf(text, vargs...) - } - return &Response{ - Data: map[string]interface{}{ - "error": text, - }, - } -} - -// ListResponse is used to format a response to a list operation. -func ListResponse(keys []string) *Response { - resp := &Response{ - Data: map[string]interface{}{}, - } - if len(keys) != 0 { - resp.Data["keys"] = keys - } - return resp -} - -// ListResponseWithInfo is used to format a response to a list operation and -// return the keys as well as a map with corresponding key info. -func ListResponseWithInfo(keys []string, keyInfo map[string]interface{}) *Response { - resp := ListResponse(keys) - - keyInfoData := make(map[string]interface{}) - for _, key := range keys { - val, ok := keyInfo[key] - if ok { - keyInfoData[key] = val - } - } - - if len(keyInfoData) > 0 { - resp.Data["key_info"] = keyInfoData - } - - return resp -} - -// RespondWithStatusCode takes a response and converts it to a raw response with -// the provided Status Code. -func RespondWithStatusCode(resp *Response, req *Request, code int) (*Response, error) { - ret := &Response{ - Data: map[string]interface{}{ - HTTPContentType: "application/json", - HTTPStatusCode: code, - }, - } - - if resp != nil { - httpResp := LogicalResponseToHTTPResponse(resp) - - if req != nil { - httpResp.RequestID = req.ID - } - - body, err := json.Marshal(httpResp) - if err != nil { - return nil, err - } - - // We default to string here so that the value is HMAC'd via audit. - // Since this function is always marshaling to JSON, this is - // appropriate. - ret.Data[HTTPRawBody] = string(body) - } - - return ret, nil -} - -// HTTPResponseWriter is optionally added to a request object and can be used to -// write directly to the HTTP response writer. -type HTTPResponseWriter struct { - http.ResponseWriter - written *uint32 -} - -// NewHTTPResponseWriter creates a new HTTPResponseWriter object that wraps the -// provided io.Writer. -func NewHTTPResponseWriter(w http.ResponseWriter) *HTTPResponseWriter { - return &HTTPResponseWriter{ - ResponseWriter: w, - written: new(uint32), - } -} - -// Write will write the bytes to the underlying io.Writer. -func (w *HTTPResponseWriter) Write(bytes []byte) (int, error) { - atomic.StoreUint32(w.written, 1) - return w.ResponseWriter.Write(bytes) -} - -// Written tells us if the writer has been written to yet. -func (w *HTTPResponseWriter) Written() bool { - return atomic.LoadUint32(w.written) == 1 -} - -type WrappingResponseWriter interface { - http.ResponseWriter - Wrapped() http.ResponseWriter -} - -type StatusHeaderResponseWriter struct { - wrapped http.ResponseWriter - wroteHeader bool - StatusCode int - headers map[string][]*CustomHeader -} - -func NewStatusHeaderResponseWriter(w http.ResponseWriter, h map[string][]*CustomHeader) *StatusHeaderResponseWriter { - return &StatusHeaderResponseWriter{ - wrapped: w, - wroteHeader: false, - StatusCode: 200, - headers: h, - } -} - -func (w *StatusHeaderResponseWriter) Wrapped() http.ResponseWriter { - return w.wrapped -} - -func (w *StatusHeaderResponseWriter) Header() http.Header { - return w.wrapped.Header() -} - -func (w *StatusHeaderResponseWriter) Write(buf []byte) (int, error) { - // It is allowed to only call ResponseWriter.Write and skip - // ResponseWriter.WriteHeader. An example of such a situation is - // "handleUIStub". The Write function will internally set the status code - // 200 for the response for which that call might invoke other - // implementations of the WriteHeader function. So, we still need to set - // the custom headers. In cases where both WriteHeader and Write of - // statusHeaderResponseWriter struct are called the internal call to the - // WriterHeader invoked from inside Write method won't change the headers. - if !w.wroteHeader { - w.setCustomResponseHeaders(w.StatusCode) - } - - return w.wrapped.Write(buf) -} - -func (w *StatusHeaderResponseWriter) WriteHeader(statusCode int) { - w.setCustomResponseHeaders(statusCode) - w.wrapped.WriteHeader(statusCode) - w.StatusCode = statusCode - // in cases where Write is called after WriteHeader, let's prevent setting - // ResponseWriter headers twice - w.wroteHeader = true -} - -func (w *StatusHeaderResponseWriter) setCustomResponseHeaders(status int) { - sch := w.headers - if sch == nil { - return - } - - // Checking the validity of the status code - if status >= 600 || status < 100 { - return - } - - // setter function to set the headers - setter := func(hvl []*CustomHeader) { - for _, hv := range hvl { - w.Header().Set(hv.Name, hv.Value) - } - } - - // Setting the default headers first - setter(sch["default"]) - - // setting the Xyy pattern first - d := fmt.Sprintf("%vxx", status/100) - if val, ok := sch[d]; ok { - setter(val) - } - - // Setting the specific headers - if val, ok := sch[strconv.Itoa(status)]; ok { - setter(val) - } - - return -} - -var _ WrappingResponseWriter = &StatusHeaderResponseWriter{} - -// ResolveRoleResponse returns a standard response to be returned by functions handling a ResolveRoleOperation -func ResolveRoleResponse(roleName string) (*Response, error) { - return &Response{ - Data: map[string]interface{}{ - "role": roleName, - }, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/response_util.go b/vendor/github.com/hashicorp/vault/sdk/logical/response_util.go deleted file mode 100644 index 4a9f61d56..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/response_util.go +++ /dev/null @@ -1,204 +0,0 @@ -package logical - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/sdk/helper/consts" -) - -// RespondErrorCommon pulls most of the functionality from http's -// respondErrorCommon and some of http's handleLogical and makes it available -// to both the http package and elsewhere. -func RespondErrorCommon(req *Request, resp *Response, err error) (int, error) { - if err == nil && (resp == nil || !resp.IsError()) { - switch { - case req.Operation == ReadOperation: - if resp == nil { - return http.StatusNotFound, nil - } - - // Basically: if we have empty "keys" or no keys at all, 404. This - // provides consistency with GET. - case req.Operation == ListOperation && (resp == nil || resp.WrapInfo == nil): - if resp == nil { - return http.StatusNotFound, nil - } - if len(resp.Data) == 0 { - if len(resp.Warnings) > 0 { - return 0, nil - } - return http.StatusNotFound, nil - } - keysRaw, ok := resp.Data["keys"] - if !ok || keysRaw == nil { - // If we don't have keys but have other data, return as-is - if len(resp.Data) > 0 || len(resp.Warnings) > 0 { - return 0, nil - } - return http.StatusNotFound, nil - } - - var keys []string - switch keysRaw.(type) { - case []interface{}: - keys = make([]string, len(keysRaw.([]interface{}))) - for i, el := range keysRaw.([]interface{}) { - s, ok := el.(string) - if !ok { - return http.StatusInternalServerError, nil - } - keys[i] = s - } - - case []string: - keys = keysRaw.([]string) - default: - return http.StatusInternalServerError, nil - } - - if len(keys) == 0 { - return http.StatusNotFound, nil - } - } - - return 0, nil - } - - if errwrap.ContainsType(err, new(ReplicationCodedError)) { - var allErrors error - var codedErr *ReplicationCodedError - errwrap.Walk(err, func(inErr error) { - newErr, ok := inErr.(*ReplicationCodedError) - if ok { - codedErr = newErr - } else { - allErrors = multierror.Append(allErrors, inErr) - } - }) - if allErrors != nil { - return codedErr.Code, multierror.Append(fmt.Errorf("errors from both primary and secondary; primary error was %v; secondary errors follow", codedErr.Msg), allErrors) - } - return codedErr.Code, errors.New(codedErr.Msg) - } - - // Start out with internal server error since in most of these cases there - // won't be a response so this won't be overridden - statusCode := http.StatusInternalServerError - // If we actually have a response, start out with bad request - if resp != nil { - statusCode = http.StatusBadRequest - } - - // Now, check the error itself; if it has a specific logical error, set the - // appropriate code - if err != nil { - switch { - case errwrap.ContainsType(err, new(StatusBadRequest)): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrPermissionDenied.Error()): - statusCode = http.StatusForbidden - case errwrap.Contains(err, consts.ErrInvalidWrappingToken.Error()): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrUnsupportedOperation.Error()): - statusCode = http.StatusMethodNotAllowed - case errwrap.Contains(err, ErrUnsupportedPath.Error()): - statusCode = http.StatusNotFound - case errwrap.Contains(err, ErrInvalidRequest.Error()): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrUpstreamRateLimited.Error()): - statusCode = http.StatusBadGateway - case errwrap.Contains(err, ErrRateLimitQuotaExceeded.Error()): - statusCode = http.StatusTooManyRequests - case errwrap.Contains(err, ErrLeaseCountQuotaExceeded.Error()): - statusCode = http.StatusTooManyRequests - case errwrap.Contains(err, ErrMissingRequiredState.Error()): - statusCode = http.StatusPreconditionFailed - case errwrap.Contains(err, ErrPathFunctionalityRemoved.Error()): - statusCode = http.StatusNotFound - case errwrap.Contains(err, ErrRelativePath.Error()): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrInvalidCredentials.Error()): - statusCode = http.StatusBadRequest - } - } - - if resp != nil && resp.IsError() { - err = fmt.Errorf("%s", resp.Data["error"].(string)) - } - - return statusCode, err -} - -// AdjustErrorStatusCode adjusts the status that will be sent in error -// conditions in a way that can be shared across http's respondError and other -// locations. -func AdjustErrorStatusCode(status *int, err error) { - // Handle nested errors - if t, ok := err.(*multierror.Error); ok { - for _, e := range t.Errors { - AdjustErrorStatusCode(status, e) - } - } - - // Adjust status code when sealed - if errwrap.Contains(err, consts.ErrSealed.Error()) { - *status = http.StatusServiceUnavailable - } - - if errwrap.Contains(err, consts.ErrAPILocked.Error()) { - *status = http.StatusServiceUnavailable - } - - // Adjust status code on - if errwrap.Contains(err, "http: request body too large") { - *status = http.StatusRequestEntityTooLarge - } - - // Allow HTTPCoded error passthrough to specify a code - if t, ok := err.(HTTPCodedError); ok { - *status = t.Code() - } -} - -func RespondError(w http.ResponseWriter, status int, err error) { - AdjustErrorStatusCode(&status, err) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - - type ErrorResponse struct { - Errors []string `json:"errors"` - } - resp := &ErrorResponse{Errors: make([]string, 0, 1)} - if err != nil { - resp.Errors = append(resp.Errors, err.Error()) - } - - enc := json.NewEncoder(w) - enc.Encode(resp) -} - -func RespondErrorAndData(w http.ResponseWriter, status int, data interface{}, err error) { - AdjustErrorStatusCode(&status, err) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - - type ErrorAndDataResponse struct { - Errors []string `json:"errors"` - Data interface{} `json:"data""` - } - resp := &ErrorAndDataResponse{Errors: make([]string, 0, 1)} - if err != nil { - resp.Errors = append(resp.Errors, err.Error()) - } - resp.Data = data - - enc := json.NewEncoder(w) - enc.Encode(resp) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/secret.go b/vendor/github.com/hashicorp/vault/sdk/logical/secret.go deleted file mode 100644 index a2128d868..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/secret.go +++ /dev/null @@ -1,30 +0,0 @@ -package logical - -import "fmt" - -// Secret represents the secret part of a response. -type Secret struct { - LeaseOptions - - // InternalData is JSON-encodable data that is stored with the secret. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - InternalData map[string]interface{} `json:"internal_data" sentinel:""` - - // LeaseID is the ID returned to the user to manage this secret. - // This is generated by Vault core. Any set value will be ignored. - // For requests, this will always be blank. - LeaseID string `sentinel:""` -} - -func (s *Secret) Validate() error { - if s.TTL < 0 { - return fmt.Errorf("ttl duration must not be less than zero") - } - - return nil -} - -func (s *Secret) GoString() string { - return fmt.Sprintf("*%#v", *s) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/storage.go b/vendor/github.com/hashicorp/vault/sdk/logical/storage.go deleted file mode 100644 index 0802ad01a..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/storage.go +++ /dev/null @@ -1,158 +0,0 @@ -package logical - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/sdk/helper/jsonutil" -) - -// ErrReadOnly is returned when a backend does not support -// writing. This can be caused by a read-only replica or secondary -// cluster operation. -var ErrReadOnly = errors.New("cannot write to readonly storage") - -// ErrSetupReadOnly is returned when a write operation is attempted on a -// storage while the backend is still being setup. -var ErrSetupReadOnly = errors.New("cannot write to storage during setup") - -// Storage is the way that logical backends are able read/write data. -type Storage interface { - List(context.Context, string) ([]string, error) - Get(context.Context, string) (*StorageEntry, error) - Put(context.Context, *StorageEntry) error - Delete(context.Context, string) error -} - -// StorageEntry is the entry for an item in a Storage implementation. -type StorageEntry struct { - Key string - Value []byte - SealWrap bool -} - -// DecodeJSON decodes the 'Value' present in StorageEntry. -func (e *StorageEntry) DecodeJSON(out interface{}) error { - return jsonutil.DecodeJSON(e.Value, out) -} - -// StorageEntryJSON creates a StorageEntry with a JSON-encoded value. -func StorageEntryJSON(k string, v interface{}) (*StorageEntry, error) { - encodedBytes, err := jsonutil.EncodeJSON(v) - if err != nil { - return nil, errwrap.Wrapf("failed to encode storage entry: {{err}}", err) - } - - return &StorageEntry{ - Key: k, - Value: encodedBytes, - }, nil -} - -type ClearableView interface { - List(context.Context, string) ([]string, error) - Delete(context.Context, string) error -} - -// ScanView is used to scan all the keys in a view iteratively -func ScanView(ctx context.Context, view ClearableView, cb func(path string)) error { - frontier := []string{""} - for len(frontier) > 0 { - n := len(frontier) - current := frontier[n-1] - frontier = frontier[:n-1] - - // List the contents - contents, err := view.List(ctx, current) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("list failed at path %q: {{err}}", current), err) - } - - // Handle the contents in the directory - for _, c := range contents { - // Exit if the context has been canceled - if ctx.Err() != nil { - return ctx.Err() - } - fullPath := current + c - if strings.HasSuffix(c, "/") { - frontier = append(frontier, fullPath) - } else { - cb(fullPath) - } - } - } - return nil -} - -// CollectKeys is used to collect all the keys in a view -func CollectKeys(ctx context.Context, view ClearableView) ([]string, error) { - return CollectKeysWithPrefix(ctx, view, "") -} - -// CollectKeysWithPrefix is used to collect all the keys in a view with a given prefix string -func CollectKeysWithPrefix(ctx context.Context, view ClearableView, prefix string) ([]string, error) { - var keys []string - - cb := func(path string) { - if strings.HasPrefix(path, prefix) { - keys = append(keys, path) - } - } - - // Scan for all the keys - if err := ScanView(ctx, view, cb); err != nil { - return nil, err - } - return keys, nil -} - -// ClearView is used to delete all the keys in a view -func ClearView(ctx context.Context, view ClearableView) error { - return ClearViewWithLogging(ctx, view, nil) -} - -func ClearViewWithLogging(ctx context.Context, view ClearableView, logger hclog.Logger) error { - if view == nil { - return nil - } - - if logger == nil { - logger = hclog.NewNullLogger() - } - - // Collect all the keys - keys, err := CollectKeys(ctx, view) - if err != nil { - return err - } - - logger.Debug("clearing view", "total_keys", len(keys)) - - // Delete all the keys - var pctDone int - for idx, key := range keys { - // Rather than keep trying to do stuff with a canceled context, bail; - // storage will fail anyways - if ctx.Err() != nil { - return ctx.Err() - } - if err := view.Delete(ctx, key); err != nil { - return err - } - - newPctDone := idx * 100.0 / len(keys) - if int(newPctDone) > pctDone { - pctDone = int(newPctDone) - logger.Trace("view deletion progress", "percent", pctDone, "keys_deleted", idx) - } - } - - logger.Debug("view cleared") - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/storage_inmem.go b/vendor/github.com/hashicorp/vault/sdk/logical/storage_inmem.go deleted file mode 100644 index 65368a070..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/storage_inmem.go +++ /dev/null @@ -1,87 +0,0 @@ -package logical - -import ( - "context" - "sync" - - "github.com/hashicorp/vault/sdk/physical" - "github.com/hashicorp/vault/sdk/physical/inmem" -) - -// InmemStorage implements Storage and stores all data in memory. It is -// basically a straight copy of physical.Inmem, but it prevents backends from -// having to load all of physical's dependencies (which are legion) just to -// have some testing storage. -type InmemStorage struct { - underlying physical.Backend - once sync.Once -} - -func (s *InmemStorage) Get(ctx context.Context, key string) (*StorageEntry, error) { - s.once.Do(s.init) - - entry, err := s.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - return &StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -func (s *InmemStorage) Put(ctx context.Context, entry *StorageEntry) error { - s.once.Do(s.init) - - return s.underlying.Put(ctx, &physical.Entry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }) -} - -func (s *InmemStorage) Delete(ctx context.Context, key string) error { - s.once.Do(s.init) - - return s.underlying.Delete(ctx, key) -} - -func (s *InmemStorage) List(ctx context.Context, prefix string) ([]string, error) { - s.once.Do(s.init) - - return s.underlying.List(ctx, prefix) -} - -func (s *InmemStorage) Underlying() *inmem.InmemBackend { - s.once.Do(s.init) - - return s.underlying.(*inmem.InmemBackend) -} - -func (s *InmemStorage) FailPut(fail bool) *InmemStorage { - s.Underlying().FailPut(fail) - return s -} - -func (s *InmemStorage) FailGet(fail bool) *InmemStorage { - s.Underlying().FailGet(fail) - return s -} - -func (s *InmemStorage) FailDelete(fail bool) *InmemStorage { - s.Underlying().FailDelete(fail) - return s -} - -func (s *InmemStorage) FailList(fail bool) *InmemStorage { - s.Underlying().FailList(fail) - return s -} - -func (s *InmemStorage) init() { - s.underlying, _ = inmem.NewInmem(nil, nil) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/storage_view.go b/vendor/github.com/hashicorp/vault/sdk/logical/storage_view.go deleted file mode 100644 index 2cd07715c..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/storage_view.go +++ /dev/null @@ -1,110 +0,0 @@ -package logical - -import ( - "context" - "errors" - "strings" -) - -type StorageView struct { - storage Storage - prefix string -} - -var ErrRelativePath = errors.New("relative paths not supported") - -func NewStorageView(storage Storage, prefix string) *StorageView { - return &StorageView{ - storage: storage, - prefix: prefix, - } -} - -// logical.Storage impl. -func (s *StorageView) List(ctx context.Context, prefix string) ([]string, error) { - if err := s.SanityCheck(prefix); err != nil { - return nil, err - } - return s.storage.List(ctx, s.ExpandKey(prefix)) -} - -// logical.Storage impl. -func (s *StorageView) Get(ctx context.Context, key string) (*StorageEntry, error) { - if err := s.SanityCheck(key); err != nil { - return nil, err - } - entry, err := s.storage.Get(ctx, s.ExpandKey(key)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - entry.Key = s.TruncateKey(entry.Key) - - return &StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -// logical.Storage impl. -func (s *StorageView) Put(ctx context.Context, entry *StorageEntry) error { - if entry == nil { - return errors.New("cannot write nil entry") - } - - if err := s.SanityCheck(entry.Key); err != nil { - return err - } - - expandedKey := s.ExpandKey(entry.Key) - - nested := &StorageEntry{ - Key: expandedKey, - Value: entry.Value, - SealWrap: entry.SealWrap, - } - - return s.storage.Put(ctx, nested) -} - -// logical.Storage impl. -func (s *StorageView) Delete(ctx context.Context, key string) error { - if err := s.SanityCheck(key); err != nil { - return err - } - - expandedKey := s.ExpandKey(key) - - return s.storage.Delete(ctx, expandedKey) -} - -func (s *StorageView) Prefix() string { - return s.prefix -} - -// SubView constructs a nested sub-view using the given prefix -func (s *StorageView) SubView(prefix string) *StorageView { - sub := s.ExpandKey(prefix) - return &StorageView{storage: s.storage, prefix: sub} -} - -// SanityCheck is used to perform a sanity check on a key -func (s *StorageView) SanityCheck(key string) error { - if strings.Contains(key, "..") { - return ErrRelativePath - } - return nil -} - -// ExpandKey is used to expand to the full key path with the prefix -func (s *StorageView) ExpandKey(suffix string) string { - return s.prefix + suffix -} - -// TruncateKey is used to remove the prefix of the key -func (s *StorageView) TruncateKey(full string) string { - return strings.TrimPrefix(full, s.prefix) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/system_view.go b/vendor/github.com/hashicorp/vault/sdk/logical/system_view.go deleted file mode 100644 index fc7f30a7f..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/system_view.go +++ /dev/null @@ -1,242 +0,0 @@ -package logical - -import ( - "context" - "errors" - "fmt" - "io" - "time" - - "github.com/hashicorp/vault/sdk/helper/consts" - "github.com/hashicorp/vault/sdk/helper/license" - "github.com/hashicorp/vault/sdk/helper/pluginutil" - "github.com/hashicorp/vault/sdk/helper/wrapping" -) - -// SystemView exposes system configuration information in a safe way -// for logical backends to consume -type SystemView interface { - // DefaultLeaseTTL returns the default lease TTL set in Vault configuration - DefaultLeaseTTL() time.Duration - - // MaxLeaseTTL returns the max lease TTL set in Vault configuration; backend - // authors should take care not to issue credentials that last longer than - // this value, as Vault will revoke them - MaxLeaseTTL() time.Duration - - // Returns true if the mount is tainted. A mount is tainted if it is in the - // process of being unmounted. This should only be used in special - // circumstances; a primary use-case is as a guard in revocation functions. - // If revocation of a backend's leases fails it can keep the unmounting - // process from being successful. If the reason for this failure is not - // relevant when the mount is tainted (for instance, saving a CRL to disk - // when the stored CRL will be removed during the unmounting process - // anyways), we can ignore the errors to allow unmounting to complete. - Tainted() bool - - // Returns true if caching is disabled. If true, no caches should be used, - // despite known slowdowns. - CachingDisabled() bool - - // When run from a system view attached to a request, indicates whether the - // request is affecting a local mount or not - LocalMount() bool - - // ReplicationState indicates the state of cluster replication - ReplicationState() consts.ReplicationState - - // HasFeature returns true if the feature is currently enabled - HasFeature(feature license.Features) bool - - // ResponseWrapData wraps the given data in a cubbyhole and returns the - // token used to unwrap. - ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) - - // LookupPlugin looks into the plugin catalog for a plugin with the given - // name. Returns a PluginRunner or an error if a plugin can not be found. - LookupPlugin(ctx context.Context, pluginName string, pluginType consts.PluginType) (*pluginutil.PluginRunner, error) - - // LookupPluginVersion looks into the plugin catalog for a plugin with the given - // name and version. Returns a PluginRunner or an error if a plugin can not be found. - LookupPluginVersion(ctx context.Context, pluginName string, pluginType consts.PluginType, version string) (*pluginutil.PluginRunner, error) - - // ListVersionedPlugins returns information about all plugins of a certain - // type in the catalog, including any versioning information stored for them. - ListVersionedPlugins(ctx context.Context, pluginType consts.PluginType) ([]pluginutil.VersionedPlugin, error) - - // NewPluginClient returns a client for managing the lifecycle of plugin - // processes - NewPluginClient(ctx context.Context, config pluginutil.PluginClientConfig) (pluginutil.PluginClient, error) - - // MlockEnabled returns the configuration setting for enabling mlock on - // plugins. - MlockEnabled() bool - - // EntityInfo returns a subset of information related to the identity entity - // for the given entity id - EntityInfo(entityID string) (*Entity, error) - - // GroupsForEntity returns the group membership information for the provided - // entity id - GroupsForEntity(entityID string) ([]*Group, error) - - // PluginEnv returns Vault environment information used by plugins - PluginEnv(context.Context) (*PluginEnvironment, error) - - // VaultVersion returns the version string for the currently running Vault. - VaultVersion(context.Context) (string, error) - - // GeneratePasswordFromPolicy generates a password from the policy referenced. - // If the policy does not exist, this will return an error. - GeneratePasswordFromPolicy(ctx context.Context, policyName string) (password string, err error) -} - -type PasswordPolicy interface { - // Generate a random password - Generate(context.Context, io.Reader) (string, error) -} - -type ExtendedSystemView interface { - Auditor() Auditor - ForwardGenericRequest(context.Context, *Request) (*Response, error) -} - -type PasswordGenerator func() (password string, err error) - -type StaticSystemView struct { - DefaultLeaseTTLVal time.Duration - MaxLeaseTTLVal time.Duration - SudoPrivilegeVal bool - TaintedVal bool - CachingDisabledVal bool - Primary bool - EnableMlock bool - LocalMountVal bool - ReplicationStateVal consts.ReplicationState - EntityVal *Entity - GroupsVal []*Group - Features license.Features - PluginEnvironment *PluginEnvironment - PasswordPolicies map[string]PasswordGenerator - VersionString string -} - -type noopAuditor struct{} - -func (a noopAuditor) AuditRequest(ctx context.Context, input *LogInput) error { - return nil -} - -func (a noopAuditor) AuditResponse(ctx context.Context, input *LogInput) error { - return nil -} - -func (d StaticSystemView) Auditor() Auditor { - return noopAuditor{} -} - -func (d StaticSystemView) ForwardGenericRequest(ctx context.Context, req *Request) (*Response, error) { - return nil, errors.New("ForwardGenericRequest is not implemented in StaticSystemView") -} - -func (d StaticSystemView) DefaultLeaseTTL() time.Duration { - return d.DefaultLeaseTTLVal -} - -func (d StaticSystemView) MaxLeaseTTL() time.Duration { - return d.MaxLeaseTTLVal -} - -func (d StaticSystemView) SudoPrivilege(_ context.Context, path string, token string) bool { - return d.SudoPrivilegeVal -} - -func (d StaticSystemView) Tainted() bool { - return d.TaintedVal -} - -func (d StaticSystemView) CachingDisabled() bool { - return d.CachingDisabledVal -} - -func (d StaticSystemView) LocalMount() bool { - return d.LocalMountVal -} - -func (d StaticSystemView) ReplicationState() consts.ReplicationState { - return d.ReplicationStateVal -} - -func (d StaticSystemView) NewPluginClient(ctx context.Context, config pluginutil.PluginClientConfig) (pluginutil.PluginClient, error) { - return nil, errors.New("NewPluginClient is not implemented in StaticSystemView") -} - -func (d StaticSystemView) ResponseWrapData(_ context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - return nil, errors.New("ResponseWrapData is not implemented in StaticSystemView") -} - -func (d StaticSystemView) LookupPlugin(_ context.Context, _ string, _ consts.PluginType) (*pluginutil.PluginRunner, error) { - return nil, errors.New("LookupPlugin is not implemented in StaticSystemView") -} - -func (d StaticSystemView) LookupPluginVersion(_ context.Context, _ string, _ consts.PluginType, _ string) (*pluginutil.PluginRunner, error) { - return nil, errors.New("LookupPluginVersion is not implemented in StaticSystemView") -} - -func (d StaticSystemView) ListVersionedPlugins(_ context.Context, _ consts.PluginType) ([]pluginutil.VersionedPlugin, error) { - return nil, errors.New("ListVersionedPlugins is not implemented in StaticSystemView") -} - -func (d StaticSystemView) MlockEnabled() bool { - return d.EnableMlock -} - -func (d StaticSystemView) EntityInfo(entityID string) (*Entity, error) { - return d.EntityVal, nil -} - -func (d StaticSystemView) GroupsForEntity(entityID string) ([]*Group, error) { - return d.GroupsVal, nil -} - -func (d StaticSystemView) HasFeature(feature license.Features) bool { - return d.Features.HasFeature(feature) -} - -func (d StaticSystemView) PluginEnv(_ context.Context) (*PluginEnvironment, error) { - return d.PluginEnvironment, nil -} - -func (d StaticSystemView) VaultVersion(_ context.Context) (string, error) { - return d.VersionString, nil -} - -func (d StaticSystemView) GeneratePasswordFromPolicy(ctx context.Context, policyName string) (password string, err error) { - select { - case <-ctx.Done(): - return "", fmt.Errorf("context timed out") - default: - } - - if d.PasswordPolicies == nil { - return "", fmt.Errorf("password policy not found") - } - policy, exists := d.PasswordPolicies[policyName] - if !exists { - return "", fmt.Errorf("password policy not found") - } - return policy() -} - -func (d *StaticSystemView) SetPasswordPolicy(name string, generator PasswordGenerator) { - if d.PasswordPolicies == nil { - d.PasswordPolicies = map[string]PasswordGenerator{} - } - d.PasswordPolicies[name] = generator -} - -func (d *StaticSystemView) DeletePasswordPolicy(name string) (existed bool) { - _, existed = d.PasswordPolicies[name] - delete(d.PasswordPolicies, name) - return existed -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/testing.go b/vendor/github.com/hashicorp/vault/sdk/logical/testing.go deleted file mode 100644 index 8cb41e2e7..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/testing.go +++ /dev/null @@ -1,88 +0,0 @@ -package logical - -import ( - "context" - "reflect" - "time" - - testing "github.com/mitchellh/go-testing-interface" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/sdk/helper/logging" -) - -// TestRequest is a helper to create a purely in-memory Request struct. -func TestRequest(t testing.T, op Operation, path string) *Request { - return &Request{ - Operation: op, - Path: path, - Data: make(map[string]interface{}), - Storage: new(InmemStorage), - Connection: &Connection{}, - } -} - -// TestStorage is a helper that can be used from unit tests to verify -// the behavior of a Storage impl. -func TestStorage(t testing.T, s Storage) { - keys, err := s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if len(keys) > 0 { - t.Fatalf("should have no keys to start: %#v", keys) - } - - entry := &StorageEntry{Key: "foo", Value: []byte("bar")} - if err := s.Put(context.Background(), entry); err != nil { - t.Fatalf("put error: %s", err) - } - - actual, err := s.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get error: %s", err) - } - if !reflect.DeepEqual(actual, entry) { - t.Fatalf("wrong value. Expected: %#v\nGot: %#v", entry, actual) - } - - keys, err = s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if !reflect.DeepEqual(keys, []string{"foo"}) { - t.Fatalf("bad keys: %#v", keys) - } - - if err := s.Delete(context.Background(), "foo"); err != nil { - t.Fatalf("put error: %s", err) - } - - keys, err = s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if len(keys) > 0 { - t.Fatalf("should have no keys to start: %#v", keys) - } -} - -func TestSystemView() *StaticSystemView { - defaultLeaseTTLVal := time.Hour * 24 - maxLeaseTTLVal := time.Hour * 24 * 2 - return &StaticSystemView{ - DefaultLeaseTTLVal: defaultLeaseTTLVal, - MaxLeaseTTLVal: maxLeaseTTLVal, - VersionString: "testVersionString", - } -} - -func TestBackendConfig() *BackendConfig { - bc := &BackendConfig{ - Logger: logging.NewVaultLogger(log.Trace), - System: TestSystemView(), - Config: make(map[string]string), - } - - return bc -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/token.go b/vendor/github.com/hashicorp/vault/sdk/logical/token.go deleted file mode 100644 index ebebd4ad9..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/token.go +++ /dev/null @@ -1,304 +0,0 @@ -package logical - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - "sort" - "strings" - "time" - - sockaddr "github.com/hashicorp/go-sockaddr" -) - -type TokenType uint8 - -const ( - // TokenTypeDefault means "use the default, if any, that is currently set - // on the mount". If not set, results in a Service token. - TokenTypeDefault TokenType = iota - - // TokenTypeService is a "normal" Vault token for long-lived services - TokenTypeService - - // TokenTypeBatch is a batch token - TokenTypeBatch - - // TokenTypeDefaultService configured on a mount, means that if - // TokenTypeDefault is sent back by the mount, create Service tokens - TokenTypeDefaultService - - // TokenTypeDefaultBatch configured on a mount, means that if - // TokenTypeDefault is sent back by the mount, create Batch tokens - TokenTypeDefaultBatch - - // ClientIDTWEDelimiter Delimiter between the string fields used to generate a client - // ID for tokens without entities. This is the 0 character, which - // is a non-printable string. Please see unicode.IsPrint for details. - ClientIDTWEDelimiter = rune('\x00') - - // SortedPoliciesTWEDelimiter Delimiter between each policy in the sorted policies used to - // generate a client ID for tokens without entities. This is the 127 - // character, which is a non-printable string. Please see unicode.IsPrint - // for details. - SortedPoliciesTWEDelimiter = rune('\x7F') -) - -func (t *TokenType) UnmarshalJSON(b []byte) error { - if len(b) == 1 { - *t = TokenType(b[0] - '0') - return nil - } - - // Handle upgrade from pre-1.2 where we were serialized as string: - s := string(b) - switch s { - case `"default"`, `""`: - *t = TokenTypeDefault - case `"service"`: - *t = TokenTypeService - case `"batch"`: - *t = TokenTypeBatch - case `"default-service"`: - *t = TokenTypeDefaultService - case `"default-batch"`: - *t = TokenTypeDefaultBatch - default: - return fmt.Errorf("unknown token type %q", s) - } - return nil -} - -func (t TokenType) String() string { - switch t { - case TokenTypeDefault: - return "default" - case TokenTypeService: - return "service" - case TokenTypeBatch: - return "batch" - case TokenTypeDefaultService: - return "default-service" - case TokenTypeDefaultBatch: - return "default-batch" - default: - panic("unreachable") - } -} - -// TokenEntry is used to represent a given token -type TokenEntry struct { - Type TokenType `json:"type" mapstructure:"type" structs:"type" sentinel:""` - - // ID of this entry, generally a random UUID - ID string `json:"id" mapstructure:"id" structs:"id" sentinel:""` - - // ExternalID is the ID of a newly created service - // token that will be returned to a user - ExternalID string `json:"-"` - - // Accessor for this token, a random UUID - Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor" sentinel:""` - - // Parent token, used for revocation trees - Parent string `json:"parent" mapstructure:"parent" structs:"parent" sentinel:""` - - // Which named policies should be used - Policies []string `json:"policies" mapstructure:"policies" structs:"policies"` - - // InlinePolicy specifies ACL rules to be applied to this token entry. - InlinePolicy string `json:"inline_policy" mapstructure:"inline_policy" structs:"inline_policy"` - - // Used for audit trails, this is something like "auth/user/login" - Path string `json:"path" mapstructure:"path" structs:"path"` - - // Used for auditing. This could include things like "source", "user", "ip" - Meta map[string]string `json:"meta" mapstructure:"meta" structs:"meta" sentinel:"meta"` - - // InternalMeta is used to store internal metadata. This metadata will not be audit logged or returned from lookup APIs. - InternalMeta map[string]string `json:"internal_meta" mapstructure:"internal_meta" structs:"internal_meta"` - - // Used for operators to be able to associate with the source - DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"` - - // Used to restrict the number of uses (zero is unlimited). This is to - // support one-time-tokens (generalized). There are a few special values: - // if it's -1 it has run through its use counts and is executing its final - // use; if it's -2 it is tainted, which means revocation is currently - // running on it; and if it's -3 it's also tainted but revocation - // previously ran and failed, so this hints the tidy function to try it - // again. - NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` - - // Time of token creation - CreationTime int64 `json:"creation_time" mapstructure:"creation_time" structs:"creation_time" sentinel:""` - - // Duration set when token was created - TTL time.Duration `json:"ttl" mapstructure:"ttl" structs:"ttl" sentinel:""` - - // Explicit maximum TTL on the token - ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl" sentinel:""` - - // If set, the role that was used for parameters at creation time - Role string `json:"role" mapstructure:"role" structs:"role"` - - // If set, the period of the token. This is only used when created directly - // through the create endpoint; periods managed by roles or other auth - // backends are subject to those renewal rules. - Period time.Duration `json:"period" mapstructure:"period" structs:"period" sentinel:""` - - // These are the deprecated fields - DisplayNameDeprecated string `json:"DisplayName" mapstructure:"DisplayName" structs:"DisplayName" sentinel:""` - NumUsesDeprecated int `json:"NumUses" mapstructure:"NumUses" structs:"NumUses" sentinel:""` - CreationTimeDeprecated int64 `json:"CreationTime" mapstructure:"CreationTime" structs:"CreationTime" sentinel:""` - ExplicitMaxTTLDeprecated time.Duration `json:"ExplicitMaxTTL" mapstructure:"ExplicitMaxTTL" structs:"ExplicitMaxTTL" sentinel:""` - - // EntityID is the ID of the entity associated with this token. - EntityID string `json:"entity_id" mapstructure:"entity_id" structs:"entity_id"` - - // If NoIdentityPolicies is true, the token will not inherit - // identity policies from the associated EntityID. - NoIdentityPolicies bool `json:"no_identity_policies" mapstructure:"no_identity_policies" structs:"no_identity_policies"` - - // The set of CIDRs that this token can be used with - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs" sentinel:""` - - // NamespaceID is the identifier of the namespace to which this token is - // confined to. Do not return this value over the API when the token is - // being looked up. - NamespaceID string `json:"namespace_id" mapstructure:"namespace_id" structs:"namespace_id" sentinel:""` - - // CubbyholeID is the identifier of the cubbyhole storage belonging to this - // token - CubbyholeID string `json:"cubbyhole_id" mapstructure:"cubbyhole_id" structs:"cubbyhole_id" sentinel:""` -} - -// CreateClientID returns the client ID, and a boolean which is false if the clientID -// has an entity, and true otherwise -func (te *TokenEntry) CreateClientID() (string, bool) { - var clientIDInputBuilder strings.Builder - - // if entry has an associated entity ID, return it - if te.EntityID != "" { - return te.EntityID, false - } - - // The entry is associated with a TWE (token without entity). In this case - // we must create a client ID by calculating the following formula: - // clientID = SHA256(sorted policies + namespace) - - // Step 1: Copy entry policies to a new struct - sortedPolicies := make([]string, len(te.Policies)) - copy(sortedPolicies, te.Policies) - - // Step 2: Sort and join copied policies - sort.Strings(sortedPolicies) - for _, pol := range sortedPolicies { - clientIDInputBuilder.WriteRune(SortedPoliciesTWEDelimiter) - clientIDInputBuilder.WriteString(pol) - } - - // Step 3: Add namespace ID - clientIDInputBuilder.WriteRune(ClientIDTWEDelimiter) - clientIDInputBuilder.WriteString(te.NamespaceID) - - if clientIDInputBuilder.Len() == 0 { - return "", true - } - // Step 4: Remove the first character in the string, as it's an unnecessary delimiter - clientIDInput := clientIDInputBuilder.String()[1:] - - // Step 5: Hash the sum - hashed := sha256.Sum256([]byte(clientIDInput)) - return base64.StdEncoding.EncodeToString(hashed[:]), true -} - -func (te *TokenEntry) SentinelGet(key string) (interface{}, error) { - if te == nil { - return nil, nil - } - switch key { - case "policies": - return te.Policies, nil - - case "path": - return te.Path, nil - - case "display_name": - return te.DisplayName, nil - - case "num_uses": - return te.NumUses, nil - - case "role": - return te.Role, nil - - case "entity_id": - return te.EntityID, nil - - case "period": - return te.Period, nil - - case "period_seconds": - return int64(te.Period.Seconds()), nil - - case "explicit_max_ttl": - return te.ExplicitMaxTTL, nil - - case "explicit_max_ttl_seconds": - return int64(te.ExplicitMaxTTL.Seconds()), nil - - case "creation_ttl": - return te.TTL, nil - - case "creation_ttl_seconds": - return int64(te.TTL.Seconds()), nil - - case "creation_time": - return time.Unix(te.CreationTime, 0).Format(time.RFC3339Nano), nil - - case "creation_time_unix": - return time.Unix(te.CreationTime, 0), nil - - case "meta", "metadata": - return te.Meta, nil - - case "type": - teType := te.Type - switch teType { - case TokenTypeBatch, TokenTypeService: - case TokenTypeDefault: - teType = TokenTypeService - default: - return "unknown", nil - } - return teType.String(), nil - } - - return nil, nil -} - -func (te *TokenEntry) SentinelKeys() []string { - return []string{ - "period", - "period_seconds", - "explicit_max_ttl", - "explicit_max_ttl_seconds", - "creation_ttl", - "creation_ttl_seconds", - "creation_time", - "creation_time_unix", - "meta", - "metadata", - "type", - } -} - -// IsRoot returns false if the token is not root (or doesn't exist) -func (te *TokenEntry) IsRoot() bool { - if te == nil { - return false - } - - return len(te.Policies) == 1 && te.Policies[0] == "root" -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/translate_response.go b/vendor/github.com/hashicorp/vault/sdk/logical/translate_response.go deleted file mode 100644 index de5ea8fdb..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/translate_response.go +++ /dev/null @@ -1,161 +0,0 @@ -package logical - -import ( - "bytes" - "encoding/json" - "fmt" - "time" -) - -// This logic was pulled from the http package so that it can be used for -// encoding wrapped responses as well. It simply translates the logical -// response to an http response, with the values we want and omitting the -// values we don't. -func LogicalResponseToHTTPResponse(input *Response) *HTTPResponse { - httpResp := &HTTPResponse{ - Data: input.Data, - Warnings: input.Warnings, - Headers: input.Headers, - } - - if input.Secret != nil { - httpResp.LeaseID = input.Secret.LeaseID - httpResp.Renewable = input.Secret.Renewable - httpResp.LeaseDuration = int(input.Secret.TTL.Seconds()) - } - - // If we have authentication information, then - // set up the result structure. - if input.Auth != nil { - httpResp.Auth = &HTTPAuth{ - ClientToken: input.Auth.ClientToken, - Accessor: input.Auth.Accessor, - Policies: input.Auth.Policies, - TokenPolicies: input.Auth.TokenPolicies, - IdentityPolicies: input.Auth.IdentityPolicies, - Metadata: input.Auth.Metadata, - LeaseDuration: int(input.Auth.TTL.Seconds()), - Renewable: input.Auth.Renewable, - EntityID: input.Auth.EntityID, - TokenType: input.Auth.TokenType.String(), - Orphan: input.Auth.Orphan, - MFARequirement: input.Auth.MFARequirement, - NumUses: input.Auth.NumUses, - } - } - - return httpResp -} - -func HTTPResponseToLogicalResponse(input *HTTPResponse) *Response { - logicalResp := &Response{ - Data: input.Data, - Warnings: input.Warnings, - Headers: input.Headers, - } - - if input.LeaseID != "" { - logicalResp.Secret = &Secret{ - LeaseID: input.LeaseID, - } - logicalResp.Secret.Renewable = input.Renewable - logicalResp.Secret.TTL = time.Second * time.Duration(input.LeaseDuration) - } - - if input.Auth != nil { - logicalResp.Auth = &Auth{ - ClientToken: input.Auth.ClientToken, - Accessor: input.Auth.Accessor, - Policies: input.Auth.Policies, - TokenPolicies: input.Auth.TokenPolicies, - IdentityPolicies: input.Auth.IdentityPolicies, - Metadata: input.Auth.Metadata, - EntityID: input.Auth.EntityID, - Orphan: input.Auth.Orphan, - } - logicalResp.Auth.Renewable = input.Auth.Renewable - logicalResp.Auth.TTL = time.Second * time.Duration(input.Auth.LeaseDuration) - switch input.Auth.TokenType { - case "service": - logicalResp.Auth.TokenType = TokenTypeService - case "batch": - logicalResp.Auth.TokenType = TokenTypeBatch - } - } - - return logicalResp -} - -type HTTPResponse struct { - RequestID string `json:"request_id"` - LeaseID string `json:"lease_id"` - Renewable bool `json:"renewable"` - LeaseDuration int `json:"lease_duration"` - Data map[string]interface{} `json:"data"` - WrapInfo *HTTPWrapInfo `json:"wrap_info"` - Warnings []string `json:"warnings"` - Headers map[string][]string `json:"-"` - Auth *HTTPAuth `json:"auth"` -} - -type HTTPAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies,omitempty"` - IdentityPolicies []string `json:"identity_policies,omitempty"` - Metadata map[string]string `json:"metadata"` - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` - EntityID string `json:"entity_id"` - TokenType string `json:"token_type"` - Orphan bool `json:"orphan"` - MFARequirement *MFARequirement `json:"mfa_requirement"` - NumUses int `json:"num_uses"` -} - -type HTTPWrapInfo struct { - Token string `json:"token"` - Accessor string `json:"accessor"` - TTL int `json:"ttl"` - CreationTime string `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor,omitempty"` -} - -type HTTPSysInjector struct { - Response *HTTPResponse -} - -func (h HTTPSysInjector) MarshalJSON() ([]byte, error) { - j, err := json.Marshal(h.Response) - if err != nil { - return nil, err - } - // Fast path no data or empty data - if h.Response.Data == nil || len(h.Response.Data) == 0 { - return j, nil - } - // Marshaling a response will always be a JSON object, meaning it will - // always start with '{', so we hijack this to prepend necessary values - - var buf bytes.Buffer - buf.WriteRune('{') - for k, v := range h.Response.Data { - // Marshal each key/value individually - mk, err := json.Marshal(k) - if err != nil { - return nil, err - } - mv, err := json.Marshal(v) - if err != nil { - return nil, err - } - // Write into the final buffer. We'll never have a valid response - // without any fields so we can unconditionally add a comma after each. - buf.WriteString(fmt.Sprintf("%s: %s, ", mk, mv)) - } - // Add the rest, without the first '{' - buf.Write(j[1:]) - return buf.Bytes(), nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/version.pb.go b/vendor/github.com/hashicorp/vault/sdk/logical/version.pb.go deleted file mode 100644 index fb3ce8121..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/version.pb.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.9 -// source: sdk/logical/version.proto - -package logical - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type Empty struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *Empty) Reset() { - *x = Empty{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_version_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Empty) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Empty) ProtoMessage() {} - -func (x *Empty) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_version_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Empty.ProtoReflect.Descriptor instead. -func (*Empty) Descriptor() ([]byte, []int) { - return file_sdk_logical_version_proto_rawDescGZIP(), []int{0} -} - -// VersionReply is the reply for the Version method. -type VersionReply struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - PluginVersion string `protobuf:"bytes,1,opt,name=plugin_version,json=pluginVersion,proto3" json:"plugin_version,omitempty"` -} - -func (x *VersionReply) Reset() { - *x = VersionReply{} - if protoimpl.UnsafeEnabled { - mi := &file_sdk_logical_version_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *VersionReply) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VersionReply) ProtoMessage() {} - -func (x *VersionReply) ProtoReflect() protoreflect.Message { - mi := &file_sdk_logical_version_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VersionReply.ProtoReflect.Descriptor instead. -func (*VersionReply) Descriptor() ([]byte, []int) { - return file_sdk_logical_version_proto_rawDescGZIP(), []int{1} -} - -func (x *VersionReply) GetPluginVersion() string { - if x != nil { - return x.PluginVersion - } - return "" -} - -var File_sdk_logical_version_proto protoreflect.FileDescriptor - -var file_sdk_logical_version_proto_rawDesc = []byte{ - 0x0a, 0x19, 0x73, 0x64, 0x6b, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2f, 0x76, 0x65, - 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x6c, 0x6f, 0x67, - 0x69, 0x63, 0x61, 0x6c, 0x22, 0x07, 0x0a, 0x05, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x22, 0x35, 0x0a, - 0x0c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x25, 0x0a, - 0x0e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x56, 0x65, 0x72, - 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x41, 0x0a, 0x0d, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x56, 0x65, - 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x30, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, - 0x12, 0x0e, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x1a, 0x15, 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, 0x6c, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, - 0x6f, 0x6e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x42, 0x28, 0x5a, 0x26, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, - 0x76, 0x61, 0x75, 0x6c, 0x74, 0x2f, 0x73, 0x64, 0x6b, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x63, 0x61, - 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_sdk_logical_version_proto_rawDescOnce sync.Once - file_sdk_logical_version_proto_rawDescData = file_sdk_logical_version_proto_rawDesc -) - -func file_sdk_logical_version_proto_rawDescGZIP() []byte { - file_sdk_logical_version_proto_rawDescOnce.Do(func() { - file_sdk_logical_version_proto_rawDescData = protoimpl.X.CompressGZIP(file_sdk_logical_version_proto_rawDescData) - }) - return file_sdk_logical_version_proto_rawDescData -} - -var file_sdk_logical_version_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_sdk_logical_version_proto_goTypes = []interface{}{ - (*Empty)(nil), // 0: logical.Empty - (*VersionReply)(nil), // 1: logical.VersionReply -} -var file_sdk_logical_version_proto_depIdxs = []int32{ - 0, // 0: logical.PluginVersion.Version:input_type -> logical.Empty - 1, // 1: logical.PluginVersion.Version:output_type -> logical.VersionReply - 1, // [1:2] is the sub-list for method output_type - 0, // [0:1] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_sdk_logical_version_proto_init() } -func file_sdk_logical_version_proto_init() { - if File_sdk_logical_version_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_sdk_logical_version_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Empty); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sdk_logical_version_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*VersionReply); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_sdk_logical_version_proto_rawDesc, - NumEnums: 0, - NumMessages: 2, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_sdk_logical_version_proto_goTypes, - DependencyIndexes: file_sdk_logical_version_proto_depIdxs, - MessageInfos: file_sdk_logical_version_proto_msgTypes, - }.Build() - File_sdk_logical_version_proto = out.File - file_sdk_logical_version_proto_rawDesc = nil - file_sdk_logical_version_proto_goTypes = nil - file_sdk_logical_version_proto_depIdxs = nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/version.proto b/vendor/github.com/hashicorp/vault/sdk/logical/version.proto deleted file mode 100644 index 345051ae9..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/version.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; -package logical; - -option go_package = "github.com/hashicorp/vault/sdk/logical"; - -message Empty {} - -// VersionReply is the reply for the Version method. -message VersionReply { - string plugin_version = 1; -} - -// PluginVersion is an optional RPC service implemented by plugins. -service PluginVersion { - // Version returns version information for the plugin. - rpc Version(Empty) returns (VersionReply); -} \ No newline at end of file diff --git a/vendor/github.com/hashicorp/vault/sdk/logical/version_grpc.pb.go b/vendor/github.com/hashicorp/vault/sdk/logical/version_grpc.pb.go deleted file mode 100644 index a69e97059..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/logical/version_grpc.pb.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. - -package logical - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -// PluginVersionClient is the client API for PluginVersion service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type PluginVersionClient interface { - // Version returns version information for the plugin. - Version(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*VersionReply, error) -} - -type pluginVersionClient struct { - cc grpc.ClientConnInterface -} - -func NewPluginVersionClient(cc grpc.ClientConnInterface) PluginVersionClient { - return &pluginVersionClient{cc} -} - -func (c *pluginVersionClient) Version(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*VersionReply, error) { - out := new(VersionReply) - err := c.cc.Invoke(ctx, "/logical.PluginVersion/Version", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// PluginVersionServer is the server API for PluginVersion service. -// All implementations must embed UnimplementedPluginVersionServer -// for forward compatibility -type PluginVersionServer interface { - // Version returns version information for the plugin. - Version(context.Context, *Empty) (*VersionReply, error) - mustEmbedUnimplementedPluginVersionServer() -} - -// UnimplementedPluginVersionServer must be embedded to have forward compatible implementations. -type UnimplementedPluginVersionServer struct { -} - -func (UnimplementedPluginVersionServer) Version(context.Context, *Empty) (*VersionReply, error) { - return nil, status.Errorf(codes.Unimplemented, "method Version not implemented") -} -func (UnimplementedPluginVersionServer) mustEmbedUnimplementedPluginVersionServer() {} - -// UnsafePluginVersionServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to PluginVersionServer will -// result in compilation errors. -type UnsafePluginVersionServer interface { - mustEmbedUnimplementedPluginVersionServer() -} - -func RegisterPluginVersionServer(s grpc.ServiceRegistrar, srv PluginVersionServer) { - s.RegisterService(&PluginVersion_ServiceDesc, srv) -} - -func _PluginVersion_Version_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PluginVersionServer).Version(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/logical.PluginVersion/Version", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PluginVersionServer).Version(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -// PluginVersion_ServiceDesc is the grpc.ServiceDesc for PluginVersion service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var PluginVersion_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "logical.PluginVersion", - HandlerType: (*PluginVersionServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Version", - Handler: _PluginVersion_Version_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "sdk/logical/version.proto", -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/cache.go b/vendor/github.com/hashicorp/vault/sdk/physical/cache.go deleted file mode 100644 index af40f5385..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/cache.go +++ /dev/null @@ -1,260 +0,0 @@ -package physical - -import ( - "context" - "sync/atomic" - - metrics "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - lru "github.com/hashicorp/golang-lru" - "github.com/hashicorp/vault/sdk/helper/locksutil" - "github.com/hashicorp/vault/sdk/helper/pathmanager" -) - -const ( - // DefaultCacheSize is used if no cache size is specified for NewCache - DefaultCacheSize = 128 * 1024 - - // refreshCacheCtxKey is a ctx value that denotes the cache should be - // refreshed during a Get call. - refreshCacheCtxKey = "refresh_cache" -) - -// These paths don't need to be cached by the LRU cache. This should -// particularly help memory pressure when unsealing. -var cacheExceptionsPaths = []string{ - "wal/logs/", - "index/pages/", - "index-dr/pages/", - "sys/expire/", - "core/poison-pill", - "core/raft/tls", -} - -// CacheRefreshContext returns a context with an added value denoting if the -// cache should attempt a refresh. -func CacheRefreshContext(ctx context.Context, r bool) context.Context { - return context.WithValue(ctx, refreshCacheCtxKey, r) -} - -// cacheRefreshFromContext is a helper to look up if the provided context is -// requesting a cache refresh. -func cacheRefreshFromContext(ctx context.Context) bool { - r, ok := ctx.Value(refreshCacheCtxKey).(bool) - if !ok { - return false - } - return r -} - -// Cache is used to wrap an underlying physical backend -// and provide an LRU cache layer on top. Most of the reads done by -// Vault are for policy objects so there is a large read reduction -// by using a simple write-through cache. -type Cache struct { - backend Backend - lru *lru.TwoQueueCache - locks []*locksutil.LockEntry - logger log.Logger - enabled *uint32 - cacheExceptions *pathmanager.PathManager - metricSink metrics.MetricSink -} - -// TransactionalCache is a Cache that wraps the physical that is transactional -type TransactionalCache struct { - *Cache - Transactional -} - -// Verify Cache satisfies the correct interfaces -var ( - _ ToggleablePurgemonster = (*Cache)(nil) - _ ToggleablePurgemonster = (*TransactionalCache)(nil) - _ Backend = (*Cache)(nil) - _ Transactional = (*TransactionalCache)(nil) -) - -// NewCache returns a physical cache of the given size. -// If no size is provided, the default size is used. -func NewCache(b Backend, size int, logger log.Logger, metricSink metrics.MetricSink) *Cache { - if logger.IsDebug() { - logger.Debug("creating LRU cache", "size", size) - } - if size <= 0 { - size = DefaultCacheSize - } - - pm := pathmanager.New() - pm.AddPaths(cacheExceptionsPaths) - - cache, _ := lru.New2Q(size) - c := &Cache{ - backend: b, - lru: cache, - locks: locksutil.CreateLocks(), - logger: logger, - // This fails safe. - enabled: new(uint32), - cacheExceptions: pm, - metricSink: metricSink, - } - return c -} - -func NewTransactionalCache(b Backend, size int, logger log.Logger, metricSink metrics.MetricSink) *TransactionalCache { - c := &TransactionalCache{ - Cache: NewCache(b, size, logger, metricSink), - Transactional: b.(Transactional), - } - return c -} - -func (c *Cache) ShouldCache(key string) bool { - if atomic.LoadUint32(c.enabled) == 0 { - return false - } - - return !c.cacheExceptions.HasPath(key) -} - -// SetEnabled is used to toggle whether the cache is on or off. It must be -// called with true to actually activate the cache after creation. -func (c *Cache) SetEnabled(enabled bool) { - if enabled { - atomic.StoreUint32(c.enabled, 1) - return - } - atomic.StoreUint32(c.enabled, 0) -} - -// Purge is used to clear the cache -func (c *Cache) Purge(ctx context.Context) { - // Lock the world - for _, lock := range c.locks { - lock.Lock() - defer lock.Unlock() - } - - c.lru.Purge() -} - -func (c *Cache) Put(ctx context.Context, entry *Entry) error { - if entry != nil && !c.ShouldCache(entry.Key) { - return c.backend.Put(ctx, entry) - } - - lock := locksutil.LockForKey(c.locks, entry.Key) - lock.Lock() - defer lock.Unlock() - - err := c.backend.Put(ctx, entry) - if err == nil { - c.lru.Add(entry.Key, entry) - c.metricSink.IncrCounter([]string{"cache", "write"}, 1) - } - return err -} - -func (c *Cache) Get(ctx context.Context, key string) (*Entry, error) { - if !c.ShouldCache(key) { - return c.backend.Get(ctx, key) - } - - lock := locksutil.LockForKey(c.locks, key) - lock.RLock() - defer lock.RUnlock() - - // Check the LRU first - if !cacheRefreshFromContext(ctx) { - if raw, ok := c.lru.Get(key); ok { - if raw == nil { - return nil, nil - } - c.metricSink.IncrCounter([]string{"cache", "hit"}, 1) - return raw.(*Entry), nil - } - } - - c.metricSink.IncrCounter([]string{"cache", "miss"}, 1) - // Read from the underlying backend - ent, err := c.backend.Get(ctx, key) - if err != nil { - return nil, err - } - - // Cache the result, even if nil - c.lru.Add(key, ent) - - return ent, nil -} - -func (c *Cache) Delete(ctx context.Context, key string) error { - if !c.ShouldCache(key) { - return c.backend.Delete(ctx, key) - } - - lock := locksutil.LockForKey(c.locks, key) - lock.Lock() - defer lock.Unlock() - - err := c.backend.Delete(ctx, key) - if err == nil { - c.lru.Remove(key) - } - return err -} - -func (c *Cache) List(ctx context.Context, prefix string) ([]string, error) { - // Always pass-through as this would be difficult to cache. For the same - // reason we don't lock as we can't reasonably know which locks to readlock - // ahead of time. - return c.backend.List(ctx, prefix) -} - -func (c *TransactionalCache) Locks() []*locksutil.LockEntry { - return c.locks -} - -func (c *TransactionalCache) LRU() *lru.TwoQueueCache { - return c.lru -} - -func (c *TransactionalCache) Transaction(ctx context.Context, txns []*TxnEntry) error { - // Bypass the locking below - if atomic.LoadUint32(c.enabled) == 0 { - return c.Transactional.Transaction(ctx, txns) - } - - // Collect keys that need to be locked - var keys []string - for _, curr := range txns { - keys = append(keys, curr.Entry.Key) - } - // Lock the keys - for _, l := range locksutil.LocksForKeys(c.locks, keys) { - l.Lock() - defer l.Unlock() - } - - if err := c.Transactional.Transaction(ctx, txns); err != nil { - return err - } - - for _, txn := range txns { - if !c.ShouldCache(txn.Entry.Key) { - continue - } - - switch txn.Operation { - case PutOperation: - c.lru.Add(txn.Entry.Key, txn.Entry) - c.metricSink.IncrCounter([]string{"cache", "write"}, 1) - case DeleteOperation: - c.lru.Remove(txn.Entry.Key) - c.metricSink.IncrCounter([]string{"cache", "delete"}, 1) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/encoding.go b/vendor/github.com/hashicorp/vault/sdk/physical/encoding.go deleted file mode 100644 index dbde84cc6..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/encoding.go +++ /dev/null @@ -1,108 +0,0 @@ -package physical - -import ( - "context" - "errors" - "strings" - "unicode" - "unicode/utf8" -) - -var ( - ErrNonUTF8 = errors.New("key contains invalid UTF-8 characters") - ErrNonPrintable = errors.New("key contains non-printable characters") -) - -// StorageEncoding is used to add errors into underlying physical requests -type StorageEncoding struct { - Backend -} - -// TransactionalStorageEncoding is the transactional version of the error -// injector -type TransactionalStorageEncoding struct { - *StorageEncoding - Transactional -} - -// Verify StorageEncoding satisfies the correct interfaces -var ( - _ Backend = (*StorageEncoding)(nil) - _ Transactional = (*TransactionalStorageEncoding)(nil) -) - -// NewStorageEncoding returns a wrapped physical backend and verifies the key -// encoding -func NewStorageEncoding(b Backend) Backend { - enc := &StorageEncoding{ - Backend: b, - } - - if bTxn, ok := b.(Transactional); ok { - return &TransactionalStorageEncoding{ - StorageEncoding: enc, - Transactional: bTxn, - } - } - - return enc -} - -func (e *StorageEncoding) containsNonPrintableChars(key string) bool { - idx := strings.IndexFunc(key, func(c rune) bool { - return !unicode.IsPrint(c) - }) - - return idx != -1 -} - -func (e *StorageEncoding) Put(ctx context.Context, entry *Entry) error { - if !utf8.ValidString(entry.Key) { - return ErrNonUTF8 - } - - if e.containsNonPrintableChars(entry.Key) { - return ErrNonPrintable - } - - return e.Backend.Put(ctx, entry) -} - -func (e *StorageEncoding) Delete(ctx context.Context, key string) error { - if !utf8.ValidString(key) { - return ErrNonUTF8 - } - - if e.containsNonPrintableChars(key) { - return ErrNonPrintable - } - - return e.Backend.Delete(ctx, key) -} - -func (e *TransactionalStorageEncoding) Transaction(ctx context.Context, txns []*TxnEntry) error { - for _, txn := range txns { - if !utf8.ValidString(txn.Entry.Key) { - return ErrNonUTF8 - } - - if e.containsNonPrintableChars(txn.Entry.Key) { - return ErrNonPrintable - } - - } - - return e.Transactional.Transaction(ctx, txns) -} - -func (e *StorageEncoding) Purge(ctx context.Context) { - if purgeable, ok := e.Backend.(ToggleablePurgemonster); ok { - purgeable.Purge(ctx) - } -} - -func (e *StorageEncoding) SetEnabled(enabled bool) { - if purgeable, ok := e.Backend.(ToggleablePurgemonster); ok { - purgeable.SetEnabled(enabled) - } -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/entry.go b/vendor/github.com/hashicorp/vault/sdk/physical/entry.go deleted file mode 100644 index 389fe6c81..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/entry.go +++ /dev/null @@ -1,20 +0,0 @@ -package physical - -import ( - "encoding/hex" - "fmt" -) - -// Entry is used to represent data stored by the physical backend -type Entry struct { - Key string - Value []byte - SealWrap bool `json:"seal_wrap,omitempty"` - - // Only used in replication - ValueHash []byte -} - -func (e *Entry) String() string { - return fmt.Sprintf("Key: %s. SealWrap: %t. Value: %s. ValueHash: %s", e.Key, e.SealWrap, hex.EncodeToString(e.Value), hex.EncodeToString(e.ValueHash)) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/error.go b/vendor/github.com/hashicorp/vault/sdk/physical/error.go deleted file mode 100644 index b547e4e42..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/error.go +++ /dev/null @@ -1,110 +0,0 @@ -package physical - -import ( - "context" - "errors" - "math/rand" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" -) - -const ( - // DefaultErrorPercent is used to determin how often we error - DefaultErrorPercent = 20 -) - -// ErrorInjector is used to add errors into underlying physical requests -type ErrorInjector struct { - backend Backend - errorPercent int - randomLock *sync.Mutex - random *rand.Rand -} - -// TransactionalErrorInjector is the transactional version of the error -// injector -type TransactionalErrorInjector struct { - *ErrorInjector - Transactional -} - -// Verify ErrorInjector satisfies the correct interfaces -var ( - _ Backend = (*ErrorInjector)(nil) - _ Transactional = (*TransactionalErrorInjector)(nil) -) - -// NewErrorInjector returns a wrapped physical backend to inject error -func NewErrorInjector(b Backend, errorPercent int, logger log.Logger) *ErrorInjector { - if errorPercent < 0 || errorPercent > 100 { - errorPercent = DefaultErrorPercent - } - logger.Info("creating error injector") - - return &ErrorInjector{ - backend: b, - errorPercent: errorPercent, - randomLock: new(sync.Mutex), - random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))), - } -} - -// NewTransactionalErrorInjector creates a new transactional ErrorInjector -func NewTransactionalErrorInjector(b Backend, errorPercent int, logger log.Logger) *TransactionalErrorInjector { - return &TransactionalErrorInjector{ - ErrorInjector: NewErrorInjector(b, errorPercent, logger), - Transactional: b.(Transactional), - } -} - -func (e *ErrorInjector) SetErrorPercentage(p int) { - e.errorPercent = p -} - -func (e *ErrorInjector) addError() error { - e.randomLock.Lock() - roll := e.random.Intn(100) - e.randomLock.Unlock() - if roll < e.errorPercent { - return errors.New("random error") - } - - return nil -} - -func (e *ErrorInjector) Put(ctx context.Context, entry *Entry) error { - if err := e.addError(); err != nil { - return err - } - return e.backend.Put(ctx, entry) -} - -func (e *ErrorInjector) Get(ctx context.Context, key string) (*Entry, error) { - if err := e.addError(); err != nil { - return nil, err - } - return e.backend.Get(ctx, key) -} - -func (e *ErrorInjector) Delete(ctx context.Context, key string) error { - if err := e.addError(); err != nil { - return err - } - return e.backend.Delete(ctx, key) -} - -func (e *ErrorInjector) List(ctx context.Context, prefix string) ([]string, error) { - if err := e.addError(); err != nil { - return nil, err - } - return e.backend.List(ctx, prefix) -} - -func (e *TransactionalErrorInjector) Transaction(ctx context.Context, txns []*TxnEntry) error { - if err := e.addError(); err != nil { - return err - } - return e.Transactional.Transaction(ctx, txns) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem.go b/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem.go deleted file mode 100644 index be16b4caa..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem.go +++ /dev/null @@ -1,310 +0,0 @@ -package inmem - -import ( - "context" - "errors" - "fmt" - "os" - "strconv" - "strings" - "sync" - "sync/atomic" - - "github.com/armon/go-radix" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/sdk/physical" -) - -// Verify interfaces are satisfied -var ( - _ physical.Backend = (*InmemBackend)(nil) - _ physical.HABackend = (*InmemHABackend)(nil) - _ physical.HABackend = (*TransactionalInmemHABackend)(nil) - _ physical.Lock = (*InmemLock)(nil) - _ physical.Transactional = (*TransactionalInmemBackend)(nil) - _ physical.Transactional = (*TransactionalInmemHABackend)(nil) -) - -var ( - PutDisabledError = errors.New("put operations disabled in inmem backend") - GetDisabledError = errors.New("get operations disabled in inmem backend") - DeleteDisabledError = errors.New("delete operations disabled in inmem backend") - ListDisabledError = errors.New("list operations disabled in inmem backend") - GetInTxnDisabledError = errors.New("get operations inside transactions are disabled in inmem backend") -) - -// InmemBackend is an in-memory only physical backend. It is useful -// for testing and development situations where the data is not -// expected to be durable. -type InmemBackend struct { - sync.RWMutex - root *radix.Tree - permitPool *physical.PermitPool - logger log.Logger - failGet *uint32 - failPut *uint32 - failDelete *uint32 - failList *uint32 - failGetInTxn *uint32 - logOps bool - maxValueSize int -} - -type TransactionalInmemBackend struct { - InmemBackend -} - -// NewInmem constructs a new in-memory backend -func NewInmem(conf map[string]string, logger log.Logger) (physical.Backend, error) { - maxValueSize := 0 - maxValueSizeStr, ok := conf["max_value_size"] - if ok { - var err error - maxValueSize, err = strconv.Atoi(maxValueSizeStr) - if err != nil { - return nil, err - } - } - - return &InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - failGetInTxn: new(uint32), - logOps: os.Getenv("VAULT_INMEM_LOG_ALL_OPS") != "", - maxValueSize: maxValueSize, - }, nil -} - -// Basically for now just creates a permit pool of size 1 so only one operation -// can run at a time -func NewTransactionalInmem(conf map[string]string, logger log.Logger) (physical.Backend, error) { - maxValueSize := 0 - maxValueSizeStr, ok := conf["max_value_size"] - if ok { - var err error - maxValueSize, err = strconv.Atoi(maxValueSizeStr) - if err != nil { - return nil, err - } - } - - return &TransactionalInmemBackend{ - InmemBackend: InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(1), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - failGetInTxn: new(uint32), - logOps: os.Getenv("VAULT_INMEM_LOG_ALL_OPS") != "", - maxValueSize: maxValueSize, - }, - }, nil -} - -// Put is used to insert or update an entry -func (i *InmemBackend) Put(ctx context.Context, entry *physical.Entry) error { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.Lock() - defer i.Unlock() - - return i.PutInternal(ctx, entry) -} - -func (i *InmemBackend) PutInternal(ctx context.Context, entry *physical.Entry) error { - if i.logOps { - i.logger.Trace("put", "key", entry.Key) - } - if atomic.LoadUint32(i.failPut) != 0 { - return PutDisabledError - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - if i.maxValueSize > 0 && len(entry.Value) > i.maxValueSize { - return fmt.Errorf("%s", physical.ErrValueTooLarge) - } - - i.root.Insert(entry.Key, entry.Value) - return nil -} - -func (i *InmemBackend) FailPut(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failPut, val) -} - -// Get is used to fetch an entry -func (i *InmemBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.RLock() - defer i.RUnlock() - - return i.GetInternal(ctx, key) -} - -func (i *InmemBackend) GetInternal(ctx context.Context, key string) (*physical.Entry, error) { - if i.logOps { - i.logger.Trace("get", "key", key) - } - if atomic.LoadUint32(i.failGet) != 0 { - return nil, GetDisabledError - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - if raw, ok := i.root.Get(key); ok { - return &physical.Entry{ - Key: key, - Value: raw.([]byte), - }, nil - } - return nil, nil -} - -func (i *InmemBackend) FailGet(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failGet, val) -} - -func (i *InmemBackend) FailGetInTxn(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failGetInTxn, val) -} - -// Delete is used to permanently delete an entry -func (i *InmemBackend) Delete(ctx context.Context, key string) error { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.Lock() - defer i.Unlock() - - return i.DeleteInternal(ctx, key) -} - -func (i *InmemBackend) DeleteInternal(ctx context.Context, key string) error { - if i.logOps { - i.logger.Trace("delete", "key", key) - } - if atomic.LoadUint32(i.failDelete) != 0 { - return DeleteDisabledError - } - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - i.root.Delete(key) - return nil -} - -func (i *InmemBackend) FailDelete(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failDelete, val) -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (i *InmemBackend) List(ctx context.Context, prefix string) ([]string, error) { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.RLock() - defer i.RUnlock() - - return i.ListInternal(ctx, prefix) -} - -func (i *InmemBackend) ListInternal(ctx context.Context, prefix string) ([]string, error) { - if i.logOps { - i.logger.Trace("list", "prefix", prefix) - } - if atomic.LoadUint32(i.failList) != 0 { - return nil, ListDisabledError - } - - var out []string - seen := make(map[string]interface{}) - walkFn := func(s string, v interface{}) bool { - trimmed := strings.TrimPrefix(s, prefix) - sep := strings.Index(trimmed, "/") - if sep == -1 { - out = append(out, trimmed) - } else { - trimmed = trimmed[:sep+1] - if _, ok := seen[trimmed]; !ok { - out = append(out, trimmed) - seen[trimmed] = struct{}{} - } - } - return false - } - i.root.WalkPrefix(prefix, walkFn) - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - return out, nil -} - -func (i *InmemBackend) FailList(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failList, val) -} - -// Transaction implements the transaction interface -func (t *TransactionalInmemBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - t.permitPool.Acquire() - defer t.permitPool.Release() - - t.Lock() - defer t.Unlock() - - failGetInTxn := atomic.LoadUint32(t.failGetInTxn) - for _, t := range txns { - if t.Operation == physical.GetOperation && failGetInTxn != 0 { - return GetInTxnDisabledError - } - } - - return physical.GenericTransactionHandler(ctx, t, txns) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem_ha.go b/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem_ha.go deleted file mode 100644 index 64fcb3a66..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/inmem/inmem_ha.go +++ /dev/null @@ -1,167 +0,0 @@ -package inmem - -import ( - "fmt" - "sync" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/sdk/physical" -) - -type InmemHABackend struct { - physical.Backend - locks map[string]string - l *sync.Mutex - cond *sync.Cond - logger log.Logger -} - -type TransactionalInmemHABackend struct { - physical.Transactional - InmemHABackend -} - -// NewInmemHA constructs a new in-memory HA backend. This is only for testing. -func NewInmemHA(_ map[string]string, logger log.Logger) (physical.Backend, error) { - be, err := NewInmem(nil, logger) - if err != nil { - return nil, err - } - - in := &InmemHABackend{ - Backend: be, - locks: make(map[string]string), - logger: logger, - l: new(sync.Mutex), - } - in.cond = sync.NewCond(in.l) - return in, nil -} - -func NewTransactionalInmemHA(_ map[string]string, logger log.Logger) (physical.Backend, error) { - transInmem, err := NewTransactionalInmem(nil, logger) - if err != nil { - return nil, err - } - inmemHA := InmemHABackend{ - Backend: transInmem, - locks: make(map[string]string), - logger: logger, - l: new(sync.Mutex), - } - - in := &TransactionalInmemHABackend{ - InmemHABackend: inmemHA, - Transactional: transInmem.(physical.Transactional), - } - in.cond = sync.NewCond(in.l) - return in, nil -} - -// LockWith is used for mutual exclusion based on the given key. -func (i *InmemHABackend) LockWith(key, value string) (physical.Lock, error) { - l := &InmemLock{ - in: i, - key: key, - value: value, - } - return l, nil -} - -// LockMapSize is used in some tests to determine whether this backend has ever -// been used for HA purposes rather than simply for storage -func (i *InmemHABackend) LockMapSize() int { - return len(i.locks) -} - -// HAEnabled indicates whether the HA functionality should be exposed. -// Currently always returns true. -func (i *InmemHABackend) HAEnabled() bool { - return true -} - -// InmemLock is an in-memory Lock implementation for the HABackend -type InmemLock struct { - in *InmemHABackend - key string - value string - - held bool - leaderCh chan struct{} - l sync.Mutex -} - -func (i *InmemLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - i.l.Lock() - defer i.l.Unlock() - if i.held { - return nil, fmt.Errorf("lock already held") - } - - // Attempt an async acquisition - didLock := make(chan struct{}) - releaseCh := make(chan bool, 1) - go func() { - // Wait to acquire the lock - i.in.l.Lock() - _, ok := i.in.locks[i.key] - for ok { - i.in.cond.Wait() - _, ok = i.in.locks[i.key] - } - i.in.locks[i.key] = i.value - i.in.l.Unlock() - - // Signal that lock is held - close(didLock) - - // Handle an early abort - release := <-releaseCh - if release { - i.in.l.Lock() - delete(i.in.locks, i.key) - i.in.l.Unlock() - i.in.cond.Broadcast() - } - }() - - // Wait for lock acquisition or shutdown - select { - case <-didLock: - releaseCh <- false - case <-stopCh: - releaseCh <- true - return nil, nil - } - - // Create the leader channel - i.held = true - i.leaderCh = make(chan struct{}) - return i.leaderCh, nil -} - -func (i *InmemLock) Unlock() error { - i.l.Lock() - defer i.l.Unlock() - - if !i.held { - return nil - } - - close(i.leaderCh) - i.leaderCh = nil - i.held = false - - i.in.l.Lock() - delete(i.in.locks, i.key) - i.in.l.Unlock() - i.in.cond.Broadcast() - return nil -} - -func (i *InmemLock) Value() (bool, string, error) { - i.in.l.Lock() - val, ok := i.in.locks[i.key] - i.in.l.Unlock() - return ok, val, nil -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/latency.go b/vendor/github.com/hashicorp/vault/sdk/physical/latency.go deleted file mode 100644 index 18b2c4c14..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/latency.go +++ /dev/null @@ -1,113 +0,0 @@ -package physical - -import ( - "context" - "math/rand" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - uberAtomic "go.uber.org/atomic" -) - -const ( - // DefaultJitterPercent is used if no cache size is specified for NewCache - DefaultJitterPercent = 20 -) - -// LatencyInjector is used to add latency into underlying physical requests -type LatencyInjector struct { - logger log.Logger - backend Backend - latency *uberAtomic.Duration - jitterPercent int - randomLock *sync.Mutex - random *rand.Rand -} - -// TransactionalLatencyInjector is the transactional version of the latency -// injector -type TransactionalLatencyInjector struct { - *LatencyInjector - Transactional -} - -// Verify LatencyInjector satisfies the correct interfaces -var ( - _ Backend = (*LatencyInjector)(nil) - _ Transactional = (*TransactionalLatencyInjector)(nil) -) - -// NewLatencyInjector returns a wrapped physical backend to simulate latency -func NewLatencyInjector(b Backend, latency time.Duration, jitter int, logger log.Logger) *LatencyInjector { - if jitter < 0 || jitter > 100 { - jitter = DefaultJitterPercent - } - logger.Info("creating latency injector") - - return &LatencyInjector{ - logger: logger, - backend: b, - latency: uberAtomic.NewDuration(latency), - jitterPercent: jitter, - randomLock: new(sync.Mutex), - random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))), - } -} - -// NewTransactionalLatencyInjector creates a new transactional LatencyInjector -func NewTransactionalLatencyInjector(b Backend, latency time.Duration, jitter int, logger log.Logger) *TransactionalLatencyInjector { - return &TransactionalLatencyInjector{ - LatencyInjector: NewLatencyInjector(b, latency, jitter, logger), - Transactional: b.(Transactional), - } -} - -func (l *LatencyInjector) SetLatency(latency time.Duration) { - l.logger.Info("Changing backend latency", "latency", latency) - l.latency.Store(latency) -} - -func (l *LatencyInjector) addLatency() { - // Calculate a value between 1 +- jitter% - percent := 100 - if l.jitterPercent > 0 { - min := 100 - l.jitterPercent - max := 100 + l.jitterPercent - l.randomLock.Lock() - percent = l.random.Intn(max-min) + min - l.randomLock.Unlock() - } - latencyDuration := time.Duration(int(l.latency.Load()) * percent / 100) - time.Sleep(latencyDuration) -} - -// Put is a latent put request -func (l *LatencyInjector) Put(ctx context.Context, entry *Entry) error { - l.addLatency() - return l.backend.Put(ctx, entry) -} - -// Get is a latent get request -func (l *LatencyInjector) Get(ctx context.Context, key string) (*Entry, error) { - l.addLatency() - return l.backend.Get(ctx, key) -} - -// Delete is a latent delete request -func (l *LatencyInjector) Delete(ctx context.Context, key string) error { - l.addLatency() - return l.backend.Delete(ctx, key) -} - -// List is a latent list request -func (l *LatencyInjector) List(ctx context.Context, prefix string) ([]string, error) { - l.addLatency() - return l.backend.List(ctx, prefix) -} - -// Transaction is a latent transaction request -func (l *TransactionalLatencyInjector) Transaction(ctx context.Context, txns []*TxnEntry) error { - l.addLatency() - return l.Transactional.Transaction(ctx, txns) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/physical.go b/vendor/github.com/hashicorp/vault/sdk/physical/physical.go deleted file mode 100644 index 808abd50f..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/physical.go +++ /dev/null @@ -1,134 +0,0 @@ -package physical - -import ( - "context" - "strings" - - log "github.com/hashicorp/go-hclog" -) - -const DefaultParallelOperations = 128 - -// The operation type -type Operation string - -const ( - DeleteOperation Operation = "delete" - GetOperation = "get" - ListOperation = "list" - PutOperation = "put" -) - -const ( - ErrValueTooLarge = "put failed due to value being too large" - ErrKeyTooLarge = "put failed due to key being too large" -) - -// Backend is the interface required for a physical -// backend. A physical backend is used to durably store -// data outside of Vault. As such, it is completely untrusted, -// and is only accessed via a security barrier. The backends -// must represent keys in a hierarchical manner. All methods -// are expected to be thread safe. -type Backend interface { - // Put is used to insert or update an entry - Put(ctx context.Context, entry *Entry) error - - // Get is used to fetch an entry - Get(ctx context.Context, key string) (*Entry, error) - - // Delete is used to permanently delete an entry - Delete(ctx context.Context, key string) error - - // List is used to list all the keys under a given - // prefix, up to the next prefix. - List(ctx context.Context, prefix string) ([]string, error) -} - -// HABackend is an extensions to the standard physical -// backend to support high-availability. Vault only expects to -// use mutual exclusion to allow multiple instances to act as a -// hot standby for a leader that services all requests. -type HABackend interface { - // LockWith is used for mutual exclusion based on the given key. - LockWith(key, value string) (Lock, error) - - // Whether or not HA functionality is enabled - HAEnabled() bool -} - -// ToggleablePurgemonster is an interface for backends that can toggle on or -// off special functionality and/or support purging. This is only used for the -// cache, don't use it for other things. -type ToggleablePurgemonster interface { - Purge(ctx context.Context) - SetEnabled(bool) -} - -// RedirectDetect is an optional interface that an HABackend -// can implement. If they do, a redirect address can be automatically -// detected. -type RedirectDetect interface { - // DetectHostAddr is used to detect the host address - DetectHostAddr() (string, error) -} - -type Lock interface { - // Lock is used to acquire the given lock - // The stopCh is optional and if closed should interrupt the lock - // acquisition attempt. The return struct should be closed when - // leadership is lost. - Lock(stopCh <-chan struct{}) (<-chan struct{}, error) - - // Unlock is used to release the lock - Unlock() error - - // Returns the value of the lock and if it is held - Value() (bool, string, error) -} - -// Factory is the factory function to create a physical backend. -type Factory func(config map[string]string, logger log.Logger) (Backend, error) - -// PermitPool is used to limit maximum outstanding requests -type PermitPool struct { - sem chan int -} - -// NewPermitPool returns a new permit pool with the provided -// number of permits -func NewPermitPool(permits int) *PermitPool { - if permits < 1 { - permits = DefaultParallelOperations - } - return &PermitPool{ - sem: make(chan int, permits), - } -} - -// Acquire returns when a permit has been acquired -func (c *PermitPool) Acquire() { - c.sem <- 1 -} - -// Release returns a permit to the pool -func (c *PermitPool) Release() { - <-c.sem -} - -// Get number of requests in the permit pool -func (c *PermitPool) CurrentPermits() int { - return len(c.sem) -} - -// Prefixes is a shared helper function returns all parent 'folders' for a -// given vault key. -// e.g. for 'foo/bar/baz', it returns ['foo', 'foo/bar'] -func Prefixes(s string) []string { - components := strings.Split(s, "/") - result := []string{} - for i := 1; i < len(components); i++ { - result = append(result, strings.Join(components[:i], "/")) - } - return result -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/physical_access.go b/vendor/github.com/hashicorp/vault/sdk/physical/physical_access.go deleted file mode 100644 index 7497313af..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/physical_access.go +++ /dev/null @@ -1,40 +0,0 @@ -package physical - -import ( - "context" -) - -// PhysicalAccess is a wrapper around physical.Backend that allows Core to -// expose its physical storage operations through PhysicalAccess() while -// restricting the ability to modify Core.physical itself. -type PhysicalAccess struct { - physical Backend -} - -var _ Backend = (*PhysicalAccess)(nil) - -func NewPhysicalAccess(physical Backend) *PhysicalAccess { - return &PhysicalAccess{physical: physical} -} - -func (p *PhysicalAccess) Put(ctx context.Context, entry *Entry) error { - return p.physical.Put(ctx, entry) -} - -func (p *PhysicalAccess) Get(ctx context.Context, key string) (*Entry, error) { - return p.physical.Get(ctx, key) -} - -func (p *PhysicalAccess) Delete(ctx context.Context, key string) error { - return p.physical.Delete(ctx, key) -} - -func (p *PhysicalAccess) List(ctx context.Context, prefix string) ([]string, error) { - return p.physical.List(ctx, prefix) -} - -func (p *PhysicalAccess) Purge(ctx context.Context) { - if purgeable, ok := p.physical.(ToggleablePurgemonster); ok { - purgeable.Purge(ctx) - } -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/physical_view.go b/vendor/github.com/hashicorp/vault/sdk/physical/physical_view.go deleted file mode 100644 index 189ac9317..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/physical_view.go +++ /dev/null @@ -1,94 +0,0 @@ -package physical - -import ( - "context" - "errors" - "strings" -) - -var ErrRelativePath = errors.New("relative paths not supported") - -// View represents a prefixed view of a physical backend -type View struct { - backend Backend - prefix string -} - -// Verify View satisfies the correct interfaces -var _ Backend = (*View)(nil) - -// NewView takes an underlying physical backend and returns -// a view of it that can only operate with the given prefix. -func NewView(backend Backend, prefix string) *View { - return &View{ - backend: backend, - prefix: prefix, - } -} - -// List the contents of the prefixed view -func (v *View) List(ctx context.Context, prefix string) ([]string, error) { - if err := v.sanityCheck(prefix); err != nil { - return nil, err - } - return v.backend.List(ctx, v.expandKey(prefix)) -} - -// Get the key of the prefixed view -func (v *View) Get(ctx context.Context, key string) (*Entry, error) { - if err := v.sanityCheck(key); err != nil { - return nil, err - } - entry, err := v.backend.Get(ctx, v.expandKey(key)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - entry.Key = v.truncateKey(entry.Key) - - return &Entry{ - Key: entry.Key, - Value: entry.Value, - }, nil -} - -// Put the entry into the prefix view -func (v *View) Put(ctx context.Context, entry *Entry) error { - if err := v.sanityCheck(entry.Key); err != nil { - return err - } - - nested := &Entry{ - Key: v.expandKey(entry.Key), - Value: entry.Value, - } - return v.backend.Put(ctx, nested) -} - -// Delete the entry from the prefix view -func (v *View) Delete(ctx context.Context, key string) error { - if err := v.sanityCheck(key); err != nil { - return err - } - return v.backend.Delete(ctx, v.expandKey(key)) -} - -// sanityCheck is used to perform a sanity check on a key -func (v *View) sanityCheck(key string) error { - if strings.Contains(key, "..") { - return ErrRelativePath - } - return nil -} - -// expandKey is used to expand to the full key path with the prefix -func (v *View) expandKey(suffix string) string { - return v.prefix + suffix -} - -// truncateKey is used to remove the prefix of the key -func (v *View) truncateKey(full string) string { - return strings.TrimPrefix(full, v.prefix) -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/testing.go b/vendor/github.com/hashicorp/vault/sdk/physical/testing.go deleted file mode 100644 index 6e0ddfcc0..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/testing.go +++ /dev/null @@ -1,497 +0,0 @@ -package physical - -import ( - "context" - "reflect" - "sort" - "testing" - "time" -) - -func ExerciseBackend(t testing.TB, b Backend) { - t.Helper() - - // Should be empty - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatalf("initial list failed: %v", err) - } - if len(keys) != 0 { - t.Errorf("initial not empty: %v", keys) - } - - // Delete should work if it does not exist - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("idempotent delete: %v", err) - } - - // Get should not fail, but be nil - out, err := b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("initial get failed: %v", err) - } - if out != nil { - t.Errorf("initial get was not nil: %v", out) - } - - // Make an entry - e := &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("put failed: %v", err) - } - - // Get should work - out, err = b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get failed: %v", err) - } - if !reflect.DeepEqual(out, e) { - t.Errorf("bad: %v expected: %v", out, e) - } - - // List should not be empty - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list failed: %v", err) - } - if len(keys) != 1 || keys[0] != "foo" { - t.Errorf("keys[0] did not equal foo: %v", keys) - } - - // Delete should work - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("delete: %v", err) - } - - // Should be empty - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list after delete: %v", err) - } - if len(keys) != 0 { - t.Errorf("list after delete not empty: %v", keys) - } - - // Get should fail - out, err = b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get after delete: %v", err) - } - if out != nil { - t.Errorf("get after delete not nil: %v", out) - } - - // Multiple Puts should work; GH-189 - e = &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("multi put 1 failed: %v", err) - } - e = &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("multi put 2 failed: %v", err) - } - - // Make a nested entry - e = &Entry{Key: "foo/bar", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("nested put failed: %v", err) - } - - // Get should work - out, err = b.Get(context.Background(), "foo/bar") - if err != nil { - t.Fatalf("get failed: %v", err) - } - if !reflect.DeepEqual(out, e) { - t.Errorf("bad: %v expected: %v", out, e) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list multi failed: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "foo" || keys[1] != "foo/" { - t.Errorf("expected 2 keys [foo, foo/]: %v", keys) - } - - // Delete with children should work - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("delete after multi: %v", err) - } - - // Get should return the child - out, err = b.Get(context.Background(), "foo/bar") - if err != nil { - t.Fatalf("get after multi delete: %v", err) - } - if out == nil { - t.Errorf("get after multi delete not nil: %v", out) - } - - // Removal of nested secret should not leave artifacts - e = &Entry{Key: "foo/nested1/nested2/nested3", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - err = b.Delete(context.Background(), "foo/nested1/nested2/nested3") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "foo/") - if err != nil { - t.Fatalf("err: %v", err) - } - if len(keys) != 1 || keys[0] != "bar" { - t.Errorf("should be exactly 1 key == bar: %v", keys) - } - - // Make a second nested entry to test prefix removal - e = &Entry{Key: "foo/zip", Value: []byte("zap")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("failed to create second nested: %v", err) - } - - // Delete should not remove the prefix - err = b.Delete(context.Background(), "foo/bar") - if err != nil { - t.Fatalf("failed to delete nested prefix: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list nested prefix: %v", err) - } - if len(keys) != 1 || keys[0] != "foo/" { - t.Errorf("should be exactly 1 key == foo/: %v", keys) - } - - // Delete should remove the prefix - err = b.Delete(context.Background(), "foo/zip") - if err != nil { - t.Fatalf("failed to delete second prefix: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing after second delete failed: %v", err) - } - if len(keys) != 0 { - t.Errorf("should be empty at end: %v", keys) - } - - // When the root path is empty, adding and removing deep nested values should not break listing - e = &Entry{Key: "foo/nested1/nested2/value1", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - e = &Entry{Key: "foo/nested1/nested2/value2", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - err = b.Delete(context.Background(), "foo/nested1/nested2/value2") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing of root failed after deletion: %v", err) - } - if len(keys) == 0 { - t.Errorf("root is returning empty after deleting a single nested value, expected nested1/: %v", keys) - keys, err = b.List(context.Background(), "foo/nested1") - if err != nil { - t.Fatalf("listing of expected nested path 'foo/nested1' failed: %v", err) - } - // prove that the root should not be empty and that foo/nested1 exists - if len(keys) != 0 { - t.Logf(" keys can still be listed from nested1/ so it's not empty, expected nested2/: %v", keys) - } - } - - // cleanup left over listing bug test value - err = b.Delete(context.Background(), "foo/nested1/nested2/value1") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing of root failed after delete of deep nest: %v", err) - } - if len(keys) != 0 { - t.Errorf("should be empty at end: %v", keys) - } -} - -func ExerciseBackend_ListPrefix(t testing.TB, b Backend) { - t.Helper() - - e1 := &Entry{Key: "foo", Value: []byte("test")} - e2 := &Entry{Key: "foo/bar", Value: []byte("test")} - e3 := &Entry{Key: "foo/bar/baz", Value: []byte("test")} - - defer func() { - b.Delete(context.Background(), "foo") - b.Delete(context.Background(), "foo/bar") - b.Delete(context.Background(), "foo/bar/baz") - }() - - err := b.Put(context.Background(), e1) - if err != nil { - t.Fatalf("failed to put entry 1: %v", err) - } - err = b.Put(context.Background(), e2) - if err != nil { - t.Fatalf("failed to put entry 2: %v", err) - } - err = b.Put(context.Background(), e3) - if err != nil { - t.Fatalf("failed to put entry 3: %v", err) - } - - // Scan the root - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatalf("list root: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "foo" || keys[1] != "foo/" { - t.Errorf("root expected [foo foo/]: %v", keys) - } - - // Scan foo/ - keys, err = b.List(context.Background(), "foo/") - if err != nil { - t.Fatalf("list level 1: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "bar" || keys[1] != "bar/" { - t.Errorf("level 1 expected [bar bar/]: %v", keys) - } - - // Scan foo/bar/ - keys, err = b.List(context.Background(), "foo/bar/") - if err != nil { - t.Fatalf("list level 2: %v", err) - } - sort.Strings(keys) - if len(keys) != 1 || keys[0] != "baz" { - t.Errorf("level 1 expected [baz]: %v", keys) - } -} - -func ExerciseHABackend(t testing.TB, b HABackend, b2 HABackend) { - t.Helper() - - // Get the lock - lock, err := b.LockWith("foo", "bar") - if err != nil { - t.Fatalf("initial lock: %v", err) - } - - // Attempt to lock - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("lock attempt 1: %v", err) - } - if leaderCh == nil { - t.Fatalf("missing leaderCh") - } - - // Check the value - held, val, err := lock.Value() - if err != nil { - t.Fatalf("err: %v", err) - } - if !held { - t.Errorf("should be held") - } - if val != "bar" { - t.Errorf("expected value bar: %v", err) - } - - // Second acquisition should fail - lock2, err := b2.LockWith("foo", "baz") - if err != nil { - t.Fatalf("lock 2: %v", err) - } - - // Cancel attempt in 50 msec - stopCh := make(chan struct{}) - time.AfterFunc(50*time.Millisecond, func() { - close(stopCh) - }) - - // Attempt to lock - leaderCh2, err := lock2.Lock(stopCh) - if err != nil { - t.Fatalf("stop lock 2: %v", err) - } - if leaderCh2 != nil { - t.Errorf("should not have gotten leaderCh: %v", leaderCh2) - } - - // Release the first lock - lock.Unlock() - - // Attempt to lock should work - leaderCh2, err = lock2.Lock(nil) - if err != nil { - t.Fatalf("lock 2 lock: %v", err) - } - if leaderCh2 == nil { - t.Errorf("should get leaderCh") - } - - // Check the value - held, val, err = lock2.Value() - if err != nil { - t.Fatalf("value: %v", err) - } - if !held { - t.Errorf("should still be held") - } - if val != "baz" { - t.Errorf("expected: baz, got: %v", val) - } - - // Cleanup - lock2.Unlock() -} - -func ExerciseTransactionalBackend(t testing.TB, b Backend) { - t.Helper() - tb, ok := b.(Transactional) - if !ok { - t.Fatal("Not a transactional backend") - } - - txns := SetupTestingTransactions(t, b) - - if err := tb.Transaction(context.Background(), txns); err != nil { - t.Fatal(err) - } - - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatal(err) - } - - expected := []string{"foo", "zip"} - - sort.Strings(keys) - sort.Strings(expected) - if !reflect.DeepEqual(keys, expected) { - t.Fatalf("mismatch: expected\n%#v\ngot\n%#v\n", expected, keys) - } - - entry, err := b.Get(context.Background(), "foo") - if err != nil { - t.Fatal(err) - } - if entry == nil { - t.Fatal("got nil entry") - } - if entry.Value == nil { - t.Fatal("got nil value") - } - if string(entry.Value) != "bar3" { - t.Fatal("updates did not apply correctly") - } - - entry, err = b.Get(context.Background(), "zip") - if err != nil { - t.Fatal(err) - } - if entry == nil { - t.Fatal("got nil entry") - } - if entry.Value == nil { - t.Fatal("got nil value") - } - if string(entry.Value) != "zap3" { - t.Fatal("updates did not apply correctly") - } -} - -func SetupTestingTransactions(t testing.TB, b Backend) []*TxnEntry { - t.Helper() - // Add a few keys so that we test rollback with deletion - if err := b.Put(context.Background(), &Entry{ - Key: "foo", - Value: []byte("bar"), - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "zip", - Value: []byte("zap"), - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "deleteme", - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "deleteme2", - }); err != nil { - t.Fatal(err) - } - - txns := []*TxnEntry{ - { - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar2"), - }, - }, - { - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme", - }, - }, - { - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar3"), - }, - }, - { - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme2", - }, - }, - { - Operation: PutOperation, - Entry: &Entry{ - Key: "zip", - Value: []byte("zap3"), - }, - }, - } - - return txns -} diff --git a/vendor/github.com/hashicorp/vault/sdk/physical/transactions.go b/vendor/github.com/hashicorp/vault/sdk/physical/transactions.go deleted file mode 100644 index a943c6bd9..000000000 --- a/vendor/github.com/hashicorp/vault/sdk/physical/transactions.go +++ /dev/null @@ -1,150 +0,0 @@ -package physical - -import ( - "context" - "fmt" - - "github.com/hashicorp/go-multierror" -) - -// TxnEntry is an operation that takes atomically as part of -// a transactional update. Only supported by Transactional backends. -type TxnEntry struct { - Operation Operation - Entry *Entry -} - -func (t *TxnEntry) String() string { - return fmt.Sprintf("Operation: %s. Entry: %s", t.Operation, t.Entry) -} - -// Transactional is an optional interface for backends that -// support doing transactional updates of multiple keys. This is -// required for some features such as replication. -type Transactional interface { - // The function to run a transaction - Transaction(context.Context, []*TxnEntry) error -} - -type TransactionalBackend interface { - Backend - Transactional -} - -type PseudoTransactional interface { - // An internal function should do no locking or permit pool acquisition. - // Depending on the backend and if it natively supports transactions, these - // may simply chain to the normal backend functions. - GetInternal(context.Context, string) (*Entry, error) - PutInternal(context.Context, *Entry) error - DeleteInternal(context.Context, string) error -} - -// Implements the transaction interface -func GenericTransactionHandler(ctx context.Context, t PseudoTransactional, txns []*TxnEntry) (retErr error) { - rollbackStack := make([]*TxnEntry, 0, len(txns)) - var dirty bool - - // Update all of our GET transaction entries, so we can populate existing values back at the wal layer. - for _, txn := range txns { - if txn.Operation == GetOperation { - entry, err := t.GetInternal(ctx, txn.Entry.Key) - if err != nil { - return err - } - if entry != nil { - txn.Entry.Value = entry.Value - } - } - } - - // We walk the transactions in order; each successful operation goes into a - // LIFO for rollback if we hit an error along the way -TxnWalk: - for _, txn := range txns { - switch txn.Operation { - case DeleteOperation: - entry, err := t.GetInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - if entry == nil { - // Nothing to delete or roll back - continue - } - rollbackEntry := &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: entry.Key, - Value: entry.Value, - }, - } - err = t.DeleteInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...) - - case PutOperation: - entry, err := t.GetInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - - // Nothing existed so in fact rolling back requires a delete - var rollbackEntry *TxnEntry - if entry == nil { - rollbackEntry = &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: txn.Entry.Key, - }, - } - } else { - rollbackEntry = &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: entry.Key, - Value: entry.Value, - }, - } - } - - err = t.PutInternal(ctx, txn.Entry) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...) - } - } - - // Need to roll back because we hit an error along the way - if dirty { - // While traversing this, if we get an error, we continue anyways in - // best-effort fashion - for _, txn := range rollbackStack { - switch txn.Operation { - case DeleteOperation: - err := t.DeleteInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - } - case PutOperation: - err := t.PutInternal(ctx, txn.Entry) - if err != nil { - retErr = multierror.Append(retErr, err) - } - } - } - } - - return -} diff --git a/vendor/github.com/hashicorp/yamux/.gitignore b/vendor/github.com/hashicorp/yamux/.gitignore deleted file mode 100644 index 836562412..000000000 --- a/vendor/github.com/hashicorp/yamux/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test diff --git a/vendor/github.com/hashicorp/yamux/LICENSE b/vendor/github.com/hashicorp/yamux/LICENSE deleted file mode 100644 index f0e5c79e1..000000000 --- a/vendor/github.com/hashicorp/yamux/LICENSE +++ /dev/null @@ -1,362 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/vendor/github.com/hashicorp/yamux/README.md b/vendor/github.com/hashicorp/yamux/README.md deleted file mode 100644 index d4db7fc99..000000000 --- a/vendor/github.com/hashicorp/yamux/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# Yamux - -Yamux (Yet another Multiplexer) is a multiplexing library for Golang. -It relies on an underlying connection to provide reliability -and ordering, such as TCP or Unix domain sockets, and provides -stream-oriented multiplexing. It is inspired by SPDY but is not -interoperable with it. - -Yamux features include: - -* Bi-directional streams - * Streams can be opened by either client or server - * Useful for NAT traversal - * Server-side push support -* Flow control - * Avoid starvation - * Back-pressure to prevent overwhelming a receiver -* Keep Alives - * Enables persistent connections over a load balancer -* Efficient - * Enables thousands of logical streams with low overhead - -## Documentation - -For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/yamux). - -## Specification - -The full specification for Yamux is provided in the `spec.md` file. -It can be used as a guide to implementors of interoperable libraries. - -## Usage - -Using Yamux is remarkably simple: - -```go - -func client() { - // Get a TCP connection - conn, err := net.Dial(...) - if err != nil { - panic(err) - } - - // Setup client side of yamux - session, err := yamux.Client(conn, nil) - if err != nil { - panic(err) - } - - // Open a new stream - stream, err := session.Open() - if err != nil { - panic(err) - } - - // Stream implements net.Conn - stream.Write([]byte("ping")) -} - -func server() { - // Accept a TCP connection - conn, err := listener.Accept() - if err != nil { - panic(err) - } - - // Setup server side of yamux - session, err := yamux.Server(conn, nil) - if err != nil { - panic(err) - } - - // Accept a stream - stream, err := session.Accept() - if err != nil { - panic(err) - } - - // Listen for a message - buf := make([]byte, 4) - stream.Read(buf) -} - -``` - diff --git a/vendor/github.com/hashicorp/yamux/addr.go b/vendor/github.com/hashicorp/yamux/addr.go deleted file mode 100644 index f6a00199c..000000000 --- a/vendor/github.com/hashicorp/yamux/addr.go +++ /dev/null @@ -1,60 +0,0 @@ -package yamux - -import ( - "fmt" - "net" -) - -// hasAddr is used to get the address from the underlying connection -type hasAddr interface { - LocalAddr() net.Addr - RemoteAddr() net.Addr -} - -// yamuxAddr is used when we cannot get the underlying address -type yamuxAddr struct { - Addr string -} - -func (*yamuxAddr) Network() string { - return "yamux" -} - -func (y *yamuxAddr) String() string { - return fmt.Sprintf("yamux:%s", y.Addr) -} - -// Addr is used to get the address of the listener. -func (s *Session) Addr() net.Addr { - return s.LocalAddr() -} - -// LocalAddr is used to get the local address of the -// underlying connection. -func (s *Session) LocalAddr() net.Addr { - addr, ok := s.conn.(hasAddr) - if !ok { - return &yamuxAddr{"local"} - } - return addr.LocalAddr() -} - -// RemoteAddr is used to get the address of remote end -// of the underlying connection -func (s *Session) RemoteAddr() net.Addr { - addr, ok := s.conn.(hasAddr) - if !ok { - return &yamuxAddr{"remote"} - } - return addr.RemoteAddr() -} - -// LocalAddr returns the local address -func (s *Stream) LocalAddr() net.Addr { - return s.session.LocalAddr() -} - -// RemoteAddr returns the remote address -func (s *Stream) RemoteAddr() net.Addr { - return s.session.RemoteAddr() -} diff --git a/vendor/github.com/hashicorp/yamux/const.go b/vendor/github.com/hashicorp/yamux/const.go deleted file mode 100644 index 2fdbf844a..000000000 --- a/vendor/github.com/hashicorp/yamux/const.go +++ /dev/null @@ -1,182 +0,0 @@ -package yamux - -import ( - "encoding/binary" - "fmt" -) - -// NetError implements net.Error -type NetError struct { - err error - timeout bool - temporary bool -} - -func (e *NetError) Error() string { - return e.err.Error() -} - -func (e *NetError) Timeout() bool { - return e.timeout -} - -func (e *NetError) Temporary() bool { - return e.temporary -} - -var ( - // ErrInvalidVersion means we received a frame with an - // invalid version - ErrInvalidVersion = fmt.Errorf("invalid protocol version") - - // ErrInvalidMsgType means we received a frame with an - // invalid message type - ErrInvalidMsgType = fmt.Errorf("invalid msg type") - - // ErrSessionShutdown is used if there is a shutdown during - // an operation - ErrSessionShutdown = fmt.Errorf("session shutdown") - - // ErrStreamsExhausted is returned if we have no more - // stream ids to issue - ErrStreamsExhausted = fmt.Errorf("streams exhausted") - - // ErrDuplicateStream is used if a duplicate stream is - // opened inbound - ErrDuplicateStream = fmt.Errorf("duplicate stream initiated") - - // ErrReceiveWindowExceeded indicates the window was exceeded - ErrRecvWindowExceeded = fmt.Errorf("recv window exceeded") - - // ErrTimeout is used when we reach an IO deadline - ErrTimeout = &NetError{ - err: fmt.Errorf("i/o deadline reached"), - - // Error should meet net.Error interface for timeouts for compatability - // with standard library expectations, such as http servers. - timeout: true, - } - - // ErrStreamClosed is returned when using a closed stream - ErrStreamClosed = fmt.Errorf("stream closed") - - // ErrUnexpectedFlag is set when we get an unexpected flag - ErrUnexpectedFlag = fmt.Errorf("unexpected flag") - - // ErrRemoteGoAway is used when we get a go away from the other side - ErrRemoteGoAway = fmt.Errorf("remote end is not accepting connections") - - // ErrConnectionReset is sent if a stream is reset. This can happen - // if the backlog is exceeded, or if there was a remote GoAway. - ErrConnectionReset = fmt.Errorf("connection reset") - - // ErrConnectionWriteTimeout indicates that we hit the "safety valve" - // timeout writing to the underlying stream connection. - ErrConnectionWriteTimeout = fmt.Errorf("connection write timeout") - - // ErrKeepAliveTimeout is sent if a missed keepalive caused the stream close - ErrKeepAliveTimeout = fmt.Errorf("keepalive timeout") -) - -const ( - // protoVersion is the only version we support - protoVersion uint8 = 0 -) - -const ( - // Data is used for data frames. They are followed - // by length bytes worth of payload. - typeData uint8 = iota - - // WindowUpdate is used to change the window of - // a given stream. The length indicates the delta - // update to the window. - typeWindowUpdate - - // Ping is sent as a keep-alive or to measure - // the RTT. The StreamID and Length value are echoed - // back in the response. - typePing - - // GoAway is sent to terminate a session. The StreamID - // should be 0 and the length is an error code. - typeGoAway -) - -const ( - // SYN is sent to signal a new stream. May - // be sent with a data payload - flagSYN uint16 = 1 << iota - - // ACK is sent to acknowledge a new stream. May - // be sent with a data payload - flagACK - - // FIN is sent to half-close the given stream. - // May be sent with a data payload. - flagFIN - - // RST is used to hard close a given stream. - flagRST -) - -const ( - // initialStreamWindow is the initial stream window size - initialStreamWindow uint32 = 256 * 1024 -) - -const ( - // goAwayNormal is sent on a normal termination - goAwayNormal uint32 = iota - - // goAwayProtoErr sent on a protocol error - goAwayProtoErr - - // goAwayInternalErr sent on an internal error - goAwayInternalErr -) - -const ( - sizeOfVersion = 1 - sizeOfType = 1 - sizeOfFlags = 2 - sizeOfStreamID = 4 - sizeOfLength = 4 - headerSize = sizeOfVersion + sizeOfType + sizeOfFlags + - sizeOfStreamID + sizeOfLength -) - -type header []byte - -func (h header) Version() uint8 { - return h[0] -} - -func (h header) MsgType() uint8 { - return h[1] -} - -func (h header) Flags() uint16 { - return binary.BigEndian.Uint16(h[2:4]) -} - -func (h header) StreamID() uint32 { - return binary.BigEndian.Uint32(h[4:8]) -} - -func (h header) Length() uint32 { - return binary.BigEndian.Uint32(h[8:12]) -} - -func (h header) String() string { - return fmt.Sprintf("Vsn:%d Type:%d Flags:%d StreamID:%d Length:%d", - h.Version(), h.MsgType(), h.Flags(), h.StreamID(), h.Length()) -} - -func (h header) encode(msgType uint8, flags uint16, streamID uint32, length uint32) { - h[0] = protoVersion - h[1] = msgType - binary.BigEndian.PutUint16(h[2:4], flags) - binary.BigEndian.PutUint32(h[4:8], streamID) - binary.BigEndian.PutUint32(h[8:12], length) -} diff --git a/vendor/github.com/hashicorp/yamux/mux.go b/vendor/github.com/hashicorp/yamux/mux.go deleted file mode 100644 index 0c3e67b02..000000000 --- a/vendor/github.com/hashicorp/yamux/mux.go +++ /dev/null @@ -1,114 +0,0 @@ -package yamux - -import ( - "fmt" - "io" - "log" - "os" - "time" -) - -// Config is used to tune the Yamux session -type Config struct { - // AcceptBacklog is used to limit how many streams may be - // waiting an accept. - AcceptBacklog int - - // EnableKeepalive is used to do a period keep alive - // messages using a ping. - EnableKeepAlive bool - - // KeepAliveInterval is how often to perform the keep alive - KeepAliveInterval time.Duration - - // ConnectionWriteTimeout is meant to be a "safety valve" timeout after - // we which will suspect a problem with the underlying connection and - // close it. This is only applied to writes, where's there's generally - // an expectation that things will move along quickly. - ConnectionWriteTimeout time.Duration - - // MaxStreamWindowSize is used to control the maximum - // window size that we allow for a stream. - MaxStreamWindowSize uint32 - - // StreamOpenTimeout is the maximum amount of time that a stream will - // be allowed to remain in pending state while waiting for an ack from the peer. - // Once the timeout is reached the session will be gracefully closed. - // A zero value disables the StreamOpenTimeout allowing unbounded - // blocking on OpenStream calls. - StreamOpenTimeout time.Duration - - // StreamCloseTimeout is the maximum time that a stream will allowed to - // be in a half-closed state when `Close` is called before forcibly - // closing the connection. Forcibly closed connections will empty the - // receive buffer, drop any future packets received for that stream, - // and send a RST to the remote side. - StreamCloseTimeout time.Duration - - // LogOutput is used to control the log destination. Either Logger or - // LogOutput can be set, not both. - LogOutput io.Writer - - // Logger is used to pass in the logger to be used. Either Logger or - // LogOutput can be set, not both. - Logger *log.Logger -} - -// DefaultConfig is used to return a default configuration -func DefaultConfig() *Config { - return &Config{ - AcceptBacklog: 256, - EnableKeepAlive: true, - KeepAliveInterval: 30 * time.Second, - ConnectionWriteTimeout: 10 * time.Second, - MaxStreamWindowSize: initialStreamWindow, - StreamCloseTimeout: 5 * time.Minute, - StreamOpenTimeout: 75 * time.Second, - LogOutput: os.Stderr, - } -} - -// VerifyConfig is used to verify the sanity of configuration -func VerifyConfig(config *Config) error { - if config.AcceptBacklog <= 0 { - return fmt.Errorf("backlog must be positive") - } - if config.KeepAliveInterval == 0 { - return fmt.Errorf("keep-alive interval must be positive") - } - if config.MaxStreamWindowSize < initialStreamWindow { - return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow) - } - if config.LogOutput != nil && config.Logger != nil { - return fmt.Errorf("both Logger and LogOutput may not be set, select one") - } else if config.LogOutput == nil && config.Logger == nil { - return fmt.Errorf("one of Logger or LogOutput must be set, select one") - } - return nil -} - -// Server is used to initialize a new server-side connection. -// There must be at most one server-side connection. If a nil config is -// provided, the DefaultConfiguration will be used. -func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) { - if config == nil { - config = DefaultConfig() - } - if err := VerifyConfig(config); err != nil { - return nil, err - } - return newSession(config, conn, false), nil -} - -// Client is used to initialize a new client-side connection. -// There must be at most one client-side connection. -func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) { - if config == nil { - config = DefaultConfig() - } - - if err := VerifyConfig(config); err != nil { - return nil, err - } - return newSession(config, conn, true), nil -} diff --git a/vendor/github.com/hashicorp/yamux/session.go b/vendor/github.com/hashicorp/yamux/session.go deleted file mode 100644 index 38fe3ed1f..000000000 --- a/vendor/github.com/hashicorp/yamux/session.go +++ /dev/null @@ -1,732 +0,0 @@ -package yamux - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "math" - "net" - "strings" - "sync" - "sync/atomic" - "time" -) - -// Session is used to wrap a reliable ordered connection and to -// multiplex it into multiple streams. -type Session struct { - // remoteGoAway indicates the remote side does - // not want futher connections. Must be first for alignment. - remoteGoAway int32 - - // localGoAway indicates that we should stop - // accepting futher connections. Must be first for alignment. - localGoAway int32 - - // nextStreamID is the next stream we should - // send. This depends if we are a client/server. - nextStreamID uint32 - - // config holds our configuration - config *Config - - // logger is used for our logs - logger *log.Logger - - // conn is the underlying connection - conn io.ReadWriteCloser - - // bufRead is a buffered reader - bufRead *bufio.Reader - - // pings is used to track inflight pings - pings map[uint32]chan struct{} - pingID uint32 - pingLock sync.Mutex - - // streams maps a stream id to a stream, and inflight has an entry - // for any outgoing stream that has not yet been established. Both are - // protected by streamLock. - streams map[uint32]*Stream - inflight map[uint32]struct{} - streamLock sync.Mutex - - // synCh acts like a semaphore. It is sized to the AcceptBacklog which - // is assumed to be symmetric between the client and server. This allows - // the client to avoid exceeding the backlog and instead blocks the open. - synCh chan struct{} - - // acceptCh is used to pass ready streams to the client - acceptCh chan *Stream - - // sendCh is used to mark a stream as ready to send, - // or to send a header out directly. - sendCh chan *sendReady - - // recvDoneCh is closed when recv() exits to avoid a race - // between stream registration and stream shutdown - recvDoneCh chan struct{} - sendDoneCh chan struct{} - - // shutdown is used to safely close a session - shutdown bool - shutdownErr error - shutdownCh chan struct{} - shutdownLock sync.Mutex - shutdownErrLock sync.Mutex -} - -// sendReady is used to either mark a stream as ready -// or to directly send a header -type sendReady struct { - Hdr []byte - mu sync.Mutex // Protects Body from unsafe reads. - Body []byte - Err chan error -} - -// newSession is used to construct a new session -func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { - logger := config.Logger - if logger == nil { - logger = log.New(config.LogOutput, "", log.LstdFlags) - } - - s := &Session{ - config: config, - logger: logger, - conn: conn, - bufRead: bufio.NewReader(conn), - pings: make(map[uint32]chan struct{}), - streams: make(map[uint32]*Stream), - inflight: make(map[uint32]struct{}), - synCh: make(chan struct{}, config.AcceptBacklog), - acceptCh: make(chan *Stream, config.AcceptBacklog), - sendCh: make(chan *sendReady, 64), - recvDoneCh: make(chan struct{}), - sendDoneCh: make(chan struct{}), - shutdownCh: make(chan struct{}), - } - if client { - s.nextStreamID = 1 - } else { - s.nextStreamID = 2 - } - go s.recv() - go s.send() - if config.EnableKeepAlive { - go s.keepalive() - } - return s -} - -// IsClosed does a safe check to see if we have shutdown -func (s *Session) IsClosed() bool { - select { - case <-s.shutdownCh: - return true - default: - return false - } -} - -// CloseChan returns a read-only channel which is closed as -// soon as the session is closed. -func (s *Session) CloseChan() <-chan struct{} { - return s.shutdownCh -} - -// NumStreams returns the number of currently open streams -func (s *Session) NumStreams() int { - s.streamLock.Lock() - num := len(s.streams) - s.streamLock.Unlock() - return num -} - -// Open is used to create a new stream as a net.Conn -func (s *Session) Open() (net.Conn, error) { - conn, err := s.OpenStream() - if err != nil { - return nil, err - } - return conn, nil -} - -// OpenStream is used to create a new stream -func (s *Session) OpenStream() (*Stream, error) { - if s.IsClosed() { - return nil, ErrSessionShutdown - } - if atomic.LoadInt32(&s.remoteGoAway) == 1 { - return nil, ErrRemoteGoAway - } - - // Block if we have too many inflight SYNs - select { - case s.synCh <- struct{}{}: - case <-s.shutdownCh: - return nil, ErrSessionShutdown - } - -GET_ID: - // Get an ID, and check for stream exhaustion - id := atomic.LoadUint32(&s.nextStreamID) - if id >= math.MaxUint32-1 { - return nil, ErrStreamsExhausted - } - if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) { - goto GET_ID - } - - // Register the stream - stream := newStream(s, id, streamInit) - s.streamLock.Lock() - s.streams[id] = stream - s.inflight[id] = struct{}{} - s.streamLock.Unlock() - - if s.config.StreamOpenTimeout > 0 { - go s.setOpenTimeout(stream) - } - - // Send the window update to create - if err := stream.sendWindowUpdate(); err != nil { - select { - case <-s.synCh: - default: - s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore") - } - return nil, err - } - return stream, nil -} - -// setOpenTimeout implements a timeout for streams that are opened but not established. -// If the StreamOpenTimeout is exceeded we assume the peer is unable to ACK, -// and close the session. -// The number of running timers is bounded by the capacity of the synCh. -func (s *Session) setOpenTimeout(stream *Stream) { - timer := time.NewTimer(s.config.StreamOpenTimeout) - defer timer.Stop() - - select { - case <-stream.establishCh: - return - case <-s.shutdownCh: - return - case <-timer.C: - // Timeout reached while waiting for ACK. - // Close the session to force connection re-establishment. - s.logger.Printf("[ERR] yamux: aborted stream open (destination=%s): %v", s.RemoteAddr().String(), ErrTimeout.err) - s.Close() - } -} - -// Accept is used to block until the next available stream -// is ready to be accepted. -func (s *Session) Accept() (net.Conn, error) { - conn, err := s.AcceptStream() - if err != nil { - return nil, err - } - return conn, err -} - -// AcceptStream is used to block until the next available stream -// is ready to be accepted. -func (s *Session) AcceptStream() (*Stream, error) { - select { - case stream := <-s.acceptCh: - if err := stream.sendWindowUpdate(); err != nil { - return nil, err - } - return stream, nil - case <-s.shutdownCh: - return nil, s.shutdownErr - } -} - -// Close is used to close the session and all streams. -// Attempts to send a GoAway before closing the connection. -func (s *Session) Close() error { - s.shutdownLock.Lock() - defer s.shutdownLock.Unlock() - - if s.shutdown { - return nil - } - s.shutdown = true - - s.shutdownErrLock.Lock() - if s.shutdownErr == nil { - s.shutdownErr = ErrSessionShutdown - } - s.shutdownErrLock.Unlock() - - close(s.shutdownCh) - - s.conn.Close() - <-s.recvDoneCh - - s.streamLock.Lock() - defer s.streamLock.Unlock() - for _, stream := range s.streams { - stream.forceClose() - } - <-s.sendDoneCh - return nil -} - -// exitErr is used to handle an error that is causing the -// session to terminate. -func (s *Session) exitErr(err error) { - s.shutdownErrLock.Lock() - if s.shutdownErr == nil { - s.shutdownErr = err - } - s.shutdownErrLock.Unlock() - s.Close() -} - -// GoAway can be used to prevent accepting further -// connections. It does not close the underlying conn. -func (s *Session) GoAway() error { - return s.waitForSend(s.goAway(goAwayNormal), nil) -} - -// goAway is used to send a goAway message -func (s *Session) goAway(reason uint32) header { - atomic.SwapInt32(&s.localGoAway, 1) - hdr := header(make([]byte, headerSize)) - hdr.encode(typeGoAway, 0, 0, reason) - return hdr -} - -// Ping is used to measure the RTT response time -func (s *Session) Ping() (time.Duration, error) { - // Get a channel for the ping - ch := make(chan struct{}) - - // Get a new ping id, mark as pending - s.pingLock.Lock() - id := s.pingID - s.pingID++ - s.pings[id] = ch - s.pingLock.Unlock() - - // Send the ping request - hdr := header(make([]byte, headerSize)) - hdr.encode(typePing, flagSYN, 0, id) - if err := s.waitForSend(hdr, nil); err != nil { - return 0, err - } - - // Wait for a response - start := time.Now() - select { - case <-ch: - case <-time.After(s.config.ConnectionWriteTimeout): - s.pingLock.Lock() - delete(s.pings, id) // Ignore it if a response comes later. - s.pingLock.Unlock() - return 0, ErrTimeout - case <-s.shutdownCh: - return 0, ErrSessionShutdown - } - - // Compute the RTT - return time.Now().Sub(start), nil -} - -// keepalive is a long running goroutine that periodically does -// a ping to keep the connection alive. -func (s *Session) keepalive() { - for { - select { - case <-time.After(s.config.KeepAliveInterval): - _, err := s.Ping() - if err != nil { - if err != ErrSessionShutdown { - s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) - s.exitErr(ErrKeepAliveTimeout) - } - return - } - case <-s.shutdownCh: - return - } - } -} - -// waitForSendErr waits to send a header, checking for a potential shutdown -func (s *Session) waitForSend(hdr header, body []byte) error { - errCh := make(chan error, 1) - return s.waitForSendErr(hdr, body, errCh) -} - -// waitForSendErr waits to send a header with optional data, checking for a -// potential shutdown. Since there's the expectation that sends can happen -// in a timely manner, we enforce the connection write timeout here. -func (s *Session) waitForSendErr(hdr header, body []byte, errCh chan error) error { - t := timerPool.Get() - timer := t.(*time.Timer) - timer.Reset(s.config.ConnectionWriteTimeout) - defer func() { - timer.Stop() - select { - case <-timer.C: - default: - } - timerPool.Put(t) - }() - - ready := &sendReady{Hdr: hdr, Body: body, Err: errCh} - select { - case s.sendCh <- ready: - case <-s.shutdownCh: - return ErrSessionShutdown - case <-timer.C: - return ErrConnectionWriteTimeout - } - - bodyCopy := func() { - if body == nil { - return // A nil body is ignored. - } - - // In the event of session shutdown or connection write timeout, - // we need to prevent `send` from reading the body buffer after - // returning from this function since the caller may re-use the - // underlying array. - ready.mu.Lock() - defer ready.mu.Unlock() - - if ready.Body == nil { - return // Body was already copied in `send`. - } - newBody := make([]byte, len(body)) - copy(newBody, body) - ready.Body = newBody - } - - select { - case err := <-errCh: - return err - case <-s.shutdownCh: - bodyCopy() - return ErrSessionShutdown - case <-timer.C: - bodyCopy() - return ErrConnectionWriteTimeout - } -} - -// sendNoWait does a send without waiting. Since there's the expectation that -// the send happens right here, we enforce the connection write timeout if we -// can't queue the header to be sent. -func (s *Session) sendNoWait(hdr header) error { - t := timerPool.Get() - timer := t.(*time.Timer) - timer.Reset(s.config.ConnectionWriteTimeout) - defer func() { - timer.Stop() - select { - case <-timer.C: - default: - } - timerPool.Put(t) - }() - - select { - case s.sendCh <- &sendReady{Hdr: hdr}: - return nil - case <-s.shutdownCh: - return ErrSessionShutdown - case <-timer.C: - return ErrConnectionWriteTimeout - } -} - -// send is a long running goroutine that sends data -func (s *Session) send() { - if err := s.sendLoop(); err != nil { - s.exitErr(err) - } -} - -func (s *Session) sendLoop() error { - defer close(s.sendDoneCh) - var bodyBuf bytes.Buffer - for { - bodyBuf.Reset() - - select { - case ready := <-s.sendCh: - // Send a header if ready - if ready.Hdr != nil { - _, err := s.conn.Write(ready.Hdr) - if err != nil { - s.logger.Printf("[ERR] yamux: Failed to write header: %v", err) - asyncSendErr(ready.Err, err) - return err - } - } - - ready.mu.Lock() - if ready.Body != nil { - // Copy the body into the buffer to avoid - // holding a mutex lock during the write. - _, err := bodyBuf.Write(ready.Body) - if err != nil { - ready.Body = nil - ready.mu.Unlock() - s.logger.Printf("[ERR] yamux: Failed to copy body into buffer: %v", err) - asyncSendErr(ready.Err, err) - return err - } - ready.Body = nil - } - ready.mu.Unlock() - - if bodyBuf.Len() > 0 { - // Send data from a body if given - _, err := s.conn.Write(bodyBuf.Bytes()) - if err != nil { - s.logger.Printf("[ERR] yamux: Failed to write body: %v", err) - asyncSendErr(ready.Err, err) - return err - } - } - - // No error, successful send - asyncSendErr(ready.Err, nil) - case <-s.shutdownCh: - return nil - } - } -} - -// recv is a long running goroutine that accepts new data -func (s *Session) recv() { - if err := s.recvLoop(); err != nil { - s.exitErr(err) - } -} - -// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type -var ( - handlers = []func(*Session, header) error{ - typeData: (*Session).handleStreamMessage, - typeWindowUpdate: (*Session).handleStreamMessage, - typePing: (*Session).handlePing, - typeGoAway: (*Session).handleGoAway, - } -) - -// recvLoop continues to receive data until a fatal error is encountered -func (s *Session) recvLoop() error { - defer close(s.recvDoneCh) - hdr := header(make([]byte, headerSize)) - for { - // Read the header - if _, err := io.ReadFull(s.bufRead, hdr); err != nil { - if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") { - s.logger.Printf("[ERR] yamux: Failed to read header: %v", err) - } - return err - } - - // Verify the version - if hdr.Version() != protoVersion { - s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version()) - return ErrInvalidVersion - } - - mt := hdr.MsgType() - if mt < typeData || mt > typeGoAway { - return ErrInvalidMsgType - } - - if err := handlers[mt](s, hdr); err != nil { - return err - } - } -} - -// handleStreamMessage handles either a data or window update frame -func (s *Session) handleStreamMessage(hdr header) error { - // Check for a new stream creation - id := hdr.StreamID() - flags := hdr.Flags() - if flags&flagSYN == flagSYN { - if err := s.incomingStream(id); err != nil { - return err - } - } - - // Get the stream - s.streamLock.Lock() - stream := s.streams[id] - s.streamLock.Unlock() - - // If we do not have a stream, likely we sent a RST - if stream == nil { - // Drain any data on the wire - if hdr.MsgType() == typeData && hdr.Length() > 0 { - s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id) - if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil { - s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err) - return nil - } - } else { - s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr) - } - return nil - } - - // Check if this is a window update - if hdr.MsgType() == typeWindowUpdate { - if err := stream.incrSendWindow(hdr, flags); err != nil { - if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { - s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) - } - return err - } - return nil - } - - // Read the new data - if err := stream.readData(hdr, flags, s.bufRead); err != nil { - if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { - s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) - } - return err - } - return nil -} - -// handlePing is invokde for a typePing frame -func (s *Session) handlePing(hdr header) error { - flags := hdr.Flags() - pingID := hdr.Length() - - // Check if this is a query, respond back in a separate context so we - // don't interfere with the receiving thread blocking for the write. - if flags&flagSYN == flagSYN { - go func() { - hdr := header(make([]byte, headerSize)) - hdr.encode(typePing, flagACK, 0, pingID) - if err := s.sendNoWait(hdr); err != nil { - s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err) - } - }() - return nil - } - - // Handle a response - s.pingLock.Lock() - ch := s.pings[pingID] - if ch != nil { - delete(s.pings, pingID) - close(ch) - } - s.pingLock.Unlock() - return nil -} - -// handleGoAway is invokde for a typeGoAway frame -func (s *Session) handleGoAway(hdr header) error { - code := hdr.Length() - switch code { - case goAwayNormal: - atomic.SwapInt32(&s.remoteGoAway, 1) - case goAwayProtoErr: - s.logger.Printf("[ERR] yamux: received protocol error go away") - return fmt.Errorf("yamux protocol error") - case goAwayInternalErr: - s.logger.Printf("[ERR] yamux: received internal error go away") - return fmt.Errorf("remote yamux internal error") - default: - s.logger.Printf("[ERR] yamux: received unexpected go away") - return fmt.Errorf("unexpected go away received") - } - return nil -} - -// incomingStream is used to create a new incoming stream -func (s *Session) incomingStream(id uint32) error { - // Reject immediately if we are doing a go away - if atomic.LoadInt32(&s.localGoAway) == 1 { - hdr := header(make([]byte, headerSize)) - hdr.encode(typeWindowUpdate, flagRST, id, 0) - return s.sendNoWait(hdr) - } - - // Allocate a new stream - stream := newStream(s, id, streamSYNReceived) - - s.streamLock.Lock() - defer s.streamLock.Unlock() - - // Check if stream already exists - if _, ok := s.streams[id]; ok { - s.logger.Printf("[ERR] yamux: duplicate stream declared") - if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { - s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) - } - return ErrDuplicateStream - } - - // Register the stream - s.streams[id] = stream - - // Check if we've exceeded the backlog - select { - case s.acceptCh <- stream: - return nil - default: - // Backlog exceeded! RST the stream - s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset") - delete(s.streams, id) - hdr := header(make([]byte, headerSize)) - hdr.encode(typeWindowUpdate, flagRST, id, 0) - return s.sendNoWait(hdr) - } -} - -// closeStream is used to close a stream once both sides have -// issued a close. If there was an in-flight SYN and the stream -// was not yet established, then this will give the credit back. -func (s *Session) closeStream(id uint32) { - s.streamLock.Lock() - if _, ok := s.inflight[id]; ok { - select { - case <-s.synCh: - default: - s.logger.Printf("[ERR] yamux: SYN tracking out of sync") - } - } - delete(s.streams, id) - s.streamLock.Unlock() -} - -// establishStream is used to mark a stream that was in the -// SYN Sent state as established. -func (s *Session) establishStream(id uint32) { - s.streamLock.Lock() - if _, ok := s.inflight[id]; ok { - delete(s.inflight, id) - } else { - s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)") - } - select { - case <-s.synCh: - default: - s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)") - } - s.streamLock.Unlock() -} diff --git a/vendor/github.com/hashicorp/yamux/spec.md b/vendor/github.com/hashicorp/yamux/spec.md deleted file mode 100644 index 183d797bd..000000000 --- a/vendor/github.com/hashicorp/yamux/spec.md +++ /dev/null @@ -1,140 +0,0 @@ -# Specification - -We use this document to detail the internal specification of Yamux. -This is used both as a guide for implementing Yamux, but also for -alternative interoperable libraries to be built. - -# Framing - -Yamux uses a streaming connection underneath, but imposes a message -framing so that it can be shared between many logical streams. Each -frame contains a header like: - -* Version (8 bits) -* Type (8 bits) -* Flags (16 bits) -* StreamID (32 bits) -* Length (32 bits) - -This means that each header has a 12 byte overhead. -All fields are encoded in network order (big endian). -Each field is described below: - -## Version Field - -The version field is used for future backward compatibility. At the -current time, the field is always set to 0, to indicate the initial -version. - -## Type Field - -The type field is used to switch the frame message type. The following -message types are supported: - -* 0x0 Data - Used to transmit data. May transmit zero length payloads - depending on the flags. - -* 0x1 Window Update - Used to updated the senders receive window size. - This is used to implement per-session flow control. - -* 0x2 Ping - Used to measure RTT. It can also be used to heart-beat - and do keep-alives over TCP. - -* 0x3 Go Away - Used to close a session. - -## Flag Field - -The flags field is used to provide additional information related -to the message type. The following flags are supported: - -* 0x1 SYN - Signals the start of a new stream. May be sent with a data or - window update message. Also sent with a ping to indicate outbound. - -* 0x2 ACK - Acknowledges the start of a new stream. May be sent with a data - or window update message. Also sent with a ping to indicate response. - -* 0x4 FIN - Performs a half-close of a stream. May be sent with a data - message or window update. - -* 0x8 RST - Reset a stream immediately. May be sent with a data or - window update message. - -## StreamID Field - -The StreamID field is used to identify the logical stream the frame -is addressing. The client side should use odd ID's, and the server even. -This prevents any collisions. Additionally, the 0 ID is reserved to represent -the session. - -Both Ping and Go Away messages should always use the 0 StreamID. - -## Length Field - -The meaning of the length field depends on the message type: - -* Data - provides the length of bytes following the header -* Window update - provides a delta update to the window size -* Ping - Contains an opaque value, echoed back -* Go Away - Contains an error code - -# Message Flow - -There is no explicit connection setup, as Yamux relies on an underlying -transport to be provided. However, there is a distinction between client -and server side of the connection. - -## Opening a stream - -To open a stream, an initial data or window update frame is sent -with a new StreamID. The SYN flag should be set to signal a new stream. - -The receiver must then reply with either a data or window update frame -with the StreamID along with the ACK flag to accept the stream or with -the RST flag to reject the stream. - -Because we are relying on the reliable stream underneath, a connection -can begin sending data once the SYN flag is sent. The corresponding -ACK does not need to be received. This is particularly well suited -for an RPC system where a client wants to open a stream and immediately -fire a request without waiting for the RTT of the ACK. - -This does introduce the possibility of a connection being rejected -after data has been sent already. This is a slight semantic difference -from TCP, where the conection cannot be refused after it is opened. -Clients should be prepared to handle this by checking for an error -that indicates a RST was received. - -## Closing a stream - -To close a stream, either side sends a data or window update frame -along with the FIN flag. This does a half-close indicating the sender -will send no further data. - -Once both sides have closed the connection, the stream is closed. - -Alternatively, if an error occurs, the RST flag can be used to -hard close a stream immediately. - -## Flow Control - -When Yamux is initially starts each stream with a 256KB window size. -There is no window size for the session. - -To prevent the streams from stalling, window update frames should be -sent regularly. Yamux can be configured to provide a larger limit for -windows sizes. Both sides assume the initial 256KB window, but can -immediately send a window update as part of the SYN/ACK indicating a -larger window. - -Both sides should track the number of bytes sent in Data frames -only, as only they are tracked as part of the window size. - -## Session termination - -When a session is being terminated, the Go Away message should -be sent. The Length should be set to one of the following to -provide an error code: - -* 0x0 Normal termination -* 0x1 Protocol error -* 0x2 Internal error diff --git a/vendor/github.com/hashicorp/yamux/stream.go b/vendor/github.com/hashicorp/yamux/stream.go deleted file mode 100644 index 23d08fcc8..000000000 --- a/vendor/github.com/hashicorp/yamux/stream.go +++ /dev/null @@ -1,544 +0,0 @@ -package yamux - -import ( - "bytes" - "errors" - "io" - "sync" - "sync/atomic" - "time" -) - -type streamState int - -const ( - streamInit streamState = iota - streamSYNSent - streamSYNReceived - streamEstablished - streamLocalClose - streamRemoteClose - streamClosed - streamReset -) - -// Stream is used to represent a logical stream -// within a session. -type Stream struct { - recvWindow uint32 - sendWindow uint32 - - id uint32 - session *Session - - state streamState - stateLock sync.Mutex - - recvBuf *bytes.Buffer - recvLock sync.Mutex - - controlHdr header - controlErr chan error - controlHdrLock sync.Mutex - - sendHdr header - sendErr chan error - sendLock sync.Mutex - - recvNotifyCh chan struct{} - sendNotifyCh chan struct{} - - readDeadline atomic.Value // time.Time - writeDeadline atomic.Value // time.Time - - // establishCh is notified if the stream is established or being closed. - establishCh chan struct{} - - // closeTimer is set with stateLock held to honor the StreamCloseTimeout - // setting on Session. - closeTimer *time.Timer -} - -// newStream is used to construct a new stream within -// a given session for an ID -func newStream(session *Session, id uint32, state streamState) *Stream { - s := &Stream{ - id: id, - session: session, - state: state, - controlHdr: header(make([]byte, headerSize)), - controlErr: make(chan error, 1), - sendHdr: header(make([]byte, headerSize)), - sendErr: make(chan error, 1), - recvWindow: initialStreamWindow, - sendWindow: initialStreamWindow, - recvNotifyCh: make(chan struct{}, 1), - sendNotifyCh: make(chan struct{}, 1), - establishCh: make(chan struct{}, 1), - } - s.readDeadline.Store(time.Time{}) - s.writeDeadline.Store(time.Time{}) - return s -} - -// Session returns the associated stream session -func (s *Stream) Session() *Session { - return s.session -} - -// StreamID returns the ID of this stream -func (s *Stream) StreamID() uint32 { - return s.id -} - -// Read is used to read from the stream -func (s *Stream) Read(b []byte) (n int, err error) { - defer asyncNotify(s.recvNotifyCh) -START: - s.stateLock.Lock() - switch s.state { - case streamLocalClose: - fallthrough - case streamRemoteClose: - fallthrough - case streamClosed: - s.recvLock.Lock() - if s.recvBuf == nil || s.recvBuf.Len() == 0 { - s.recvLock.Unlock() - s.stateLock.Unlock() - return 0, io.EOF - } - s.recvLock.Unlock() - case streamReset: - s.stateLock.Unlock() - return 0, ErrConnectionReset - } - s.stateLock.Unlock() - - // If there is no data available, block - s.recvLock.Lock() - if s.recvBuf == nil || s.recvBuf.Len() == 0 { - s.recvLock.Unlock() - goto WAIT - } - - // Read any bytes - n, _ = s.recvBuf.Read(b) - s.recvLock.Unlock() - - // Send a window update potentially - err = s.sendWindowUpdate() - if err == ErrSessionShutdown { - err = nil - } - return n, err - -WAIT: - var timeout <-chan time.Time - var timer *time.Timer - readDeadline := s.readDeadline.Load().(time.Time) - if !readDeadline.IsZero() { - delay := readDeadline.Sub(time.Now()) - timer = time.NewTimer(delay) - timeout = timer.C - } - select { - case <-s.recvNotifyCh: - if timer != nil { - timer.Stop() - } - goto START - case <-timeout: - return 0, ErrTimeout - } -} - -// Write is used to write to the stream -func (s *Stream) Write(b []byte) (n int, err error) { - s.sendLock.Lock() - defer s.sendLock.Unlock() - total := 0 - for total < len(b) { - n, err := s.write(b[total:]) - total += n - if err != nil { - return total, err - } - } - return total, nil -} - -// write is used to write to the stream, may return on -// a short write. -func (s *Stream) write(b []byte) (n int, err error) { - var flags uint16 - var max uint32 - var body []byte -START: - s.stateLock.Lock() - switch s.state { - case streamLocalClose: - fallthrough - case streamClosed: - s.stateLock.Unlock() - return 0, ErrStreamClosed - case streamReset: - s.stateLock.Unlock() - return 0, ErrConnectionReset - } - s.stateLock.Unlock() - - // If there is no data available, block - window := atomic.LoadUint32(&s.sendWindow) - if window == 0 { - goto WAIT - } - - // Determine the flags if any - flags = s.sendFlags() - - // Send up to our send window - max = min(window, uint32(len(b))) - body = b[:max] - - // Send the header - s.sendHdr.encode(typeData, flags, s.id, max) - if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { - if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) { - // Message left in ready queue, header re-use is unsafe. - s.sendHdr = header(make([]byte, headerSize)) - } - return 0, err - } - - // Reduce our send window - atomic.AddUint32(&s.sendWindow, ^uint32(max-1)) - - // Unlock - return int(max), err - -WAIT: - var timeout <-chan time.Time - writeDeadline := s.writeDeadline.Load().(time.Time) - if !writeDeadline.IsZero() { - delay := writeDeadline.Sub(time.Now()) - timeout = time.After(delay) - } - select { - case <-s.sendNotifyCh: - goto START - case <-timeout: - return 0, ErrTimeout - } - return 0, nil -} - -// sendFlags determines any flags that are appropriate -// based on the current stream state -func (s *Stream) sendFlags() uint16 { - s.stateLock.Lock() - defer s.stateLock.Unlock() - var flags uint16 - switch s.state { - case streamInit: - flags |= flagSYN - s.state = streamSYNSent - case streamSYNReceived: - flags |= flagACK - s.state = streamEstablished - } - return flags -} - -// sendWindowUpdate potentially sends a window update enabling -// further writes to take place. Must be invoked with the lock. -func (s *Stream) sendWindowUpdate() error { - s.controlHdrLock.Lock() - defer s.controlHdrLock.Unlock() - - // Determine the delta update - max := s.session.config.MaxStreamWindowSize - var bufLen uint32 - s.recvLock.Lock() - if s.recvBuf != nil { - bufLen = uint32(s.recvBuf.Len()) - } - delta := (max - bufLen) - s.recvWindow - - // Determine the flags if any - flags := s.sendFlags() - - // Check if we can omit the update - if delta < (max/2) && flags == 0 { - s.recvLock.Unlock() - return nil - } - - // Update our window - s.recvWindow += delta - s.recvLock.Unlock() - - // Send the header - s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) - if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { - if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) { - // Message left in ready queue, header re-use is unsafe. - s.controlHdr = header(make([]byte, headerSize)) - } - return err - } - return nil -} - -// sendClose is used to send a FIN -func (s *Stream) sendClose() error { - s.controlHdrLock.Lock() - defer s.controlHdrLock.Unlock() - - flags := s.sendFlags() - flags |= flagFIN - s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0) - if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { - if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) { - // Message left in ready queue, header re-use is unsafe. - s.controlHdr = header(make([]byte, headerSize)) - } - return err - } - return nil -} - -// Close is used to close the stream -func (s *Stream) Close() error { - closeStream := false - s.stateLock.Lock() - switch s.state { - // Opened means we need to signal a close - case streamSYNSent: - fallthrough - case streamSYNReceived: - fallthrough - case streamEstablished: - s.state = streamLocalClose - goto SEND_CLOSE - - case streamLocalClose: - case streamRemoteClose: - s.state = streamClosed - closeStream = true - goto SEND_CLOSE - - case streamClosed: - case streamReset: - default: - panic("unhandled state") - } - s.stateLock.Unlock() - return nil -SEND_CLOSE: - // This shouldn't happen (the more realistic scenario to cancel the - // timer is via processFlags) but just in case this ever happens, we - // cancel the timer to prevent dangling timers. - if s.closeTimer != nil { - s.closeTimer.Stop() - s.closeTimer = nil - } - - // If we have a StreamCloseTimeout set we start the timeout timer. - // We do this only if we're not already closing the stream since that - // means this was a graceful close. - // - // This prevents memory leaks if one side (this side) closes and the - // remote side poorly behaves and never responds with a FIN to complete - // the close. After the specified timeout, we clean our resources up no - // matter what. - if !closeStream && s.session.config.StreamCloseTimeout > 0 { - s.closeTimer = time.AfterFunc( - s.session.config.StreamCloseTimeout, s.closeTimeout) - } - - s.stateLock.Unlock() - s.sendClose() - s.notifyWaiting() - if closeStream { - s.session.closeStream(s.id) - } - return nil -} - -// closeTimeout is called after StreamCloseTimeout during a close to -// close this stream. -func (s *Stream) closeTimeout() { - // Close our side forcibly - s.forceClose() - - // Free the stream from the session map - s.session.closeStream(s.id) - - // Send a RST so the remote side closes too. - s.sendLock.Lock() - defer s.sendLock.Unlock() - hdr := header(make([]byte, headerSize)) - hdr.encode(typeWindowUpdate, flagRST, s.id, 0) - s.session.sendNoWait(hdr) -} - -// forceClose is used for when the session is exiting -func (s *Stream) forceClose() { - s.stateLock.Lock() - s.state = streamClosed - s.stateLock.Unlock() - s.notifyWaiting() -} - -// processFlags is used to update the state of the stream -// based on set flags, if any. Lock must be held -func (s *Stream) processFlags(flags uint16) error { - s.stateLock.Lock() - defer s.stateLock.Unlock() - - // Close the stream without holding the state lock - closeStream := false - defer func() { - if closeStream { - if s.closeTimer != nil { - // Stop our close timeout timer since we gracefully closed - s.closeTimer.Stop() - } - - s.session.closeStream(s.id) - } - }() - - if flags&flagACK == flagACK { - if s.state == streamSYNSent { - s.state = streamEstablished - } - asyncNotify(s.establishCh) - s.session.establishStream(s.id) - } - if flags&flagFIN == flagFIN { - switch s.state { - case streamSYNSent: - fallthrough - case streamSYNReceived: - fallthrough - case streamEstablished: - s.state = streamRemoteClose - s.notifyWaiting() - case streamLocalClose: - s.state = streamClosed - closeStream = true - s.notifyWaiting() - default: - s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state) - return ErrUnexpectedFlag - } - } - if flags&flagRST == flagRST { - s.state = streamReset - closeStream = true - s.notifyWaiting() - } - return nil -} - -// notifyWaiting notifies all the waiting channels -func (s *Stream) notifyWaiting() { - asyncNotify(s.recvNotifyCh) - asyncNotify(s.sendNotifyCh) - asyncNotify(s.establishCh) -} - -// incrSendWindow updates the size of our send window -func (s *Stream) incrSendWindow(hdr header, flags uint16) error { - if err := s.processFlags(flags); err != nil { - return err - } - - // Increase window, unblock a sender - atomic.AddUint32(&s.sendWindow, hdr.Length()) - asyncNotify(s.sendNotifyCh) - return nil -} - -// readData is used to handle a data frame -func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { - if err := s.processFlags(flags); err != nil { - return err - } - - // Check that our recv window is not exceeded - length := hdr.Length() - if length == 0 { - return nil - } - - // Wrap in a limited reader - conn = &io.LimitedReader{R: conn, N: int64(length)} - - // Copy into buffer - s.recvLock.Lock() - - if length > s.recvWindow { - s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length) - s.recvLock.Unlock() - return ErrRecvWindowExceeded - } - - if s.recvBuf == nil { - // Allocate the receive buffer just-in-time to fit the full data frame. - // This way we can read in the whole packet without further allocations. - s.recvBuf = bytes.NewBuffer(make([]byte, 0, length)) - } - copiedLength, err := io.Copy(s.recvBuf, conn) - if err != nil { - s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err) - s.recvLock.Unlock() - return err - } - - // Decrement the receive window - s.recvWindow -= uint32(copiedLength) - s.recvLock.Unlock() - - // Unblock any readers - asyncNotify(s.recvNotifyCh) - return nil -} - -// SetDeadline sets the read and write deadlines -func (s *Stream) SetDeadline(t time.Time) error { - if err := s.SetReadDeadline(t); err != nil { - return err - } - if err := s.SetWriteDeadline(t); err != nil { - return err - } - return nil -} - -// SetReadDeadline sets the deadline for blocked and future Read calls. -func (s *Stream) SetReadDeadline(t time.Time) error { - s.readDeadline.Store(t) - asyncNotify(s.recvNotifyCh) - return nil -} - -// SetWriteDeadline sets the deadline for blocked and future Write calls -func (s *Stream) SetWriteDeadline(t time.Time) error { - s.writeDeadline.Store(t) - asyncNotify(s.sendNotifyCh) - return nil -} - -// Shrink is used to compact the amount of buffers utilized -// This is useful when using Yamux in a connection pool to reduce -// the idle memory utilization. -func (s *Stream) Shrink() { - s.recvLock.Lock() - if s.recvBuf != nil && s.recvBuf.Len() == 0 { - s.recvBuf = nil - } - s.recvLock.Unlock() -} diff --git a/vendor/github.com/hashicorp/yamux/util.go b/vendor/github.com/hashicorp/yamux/util.go deleted file mode 100644 index 8a73e9249..000000000 --- a/vendor/github.com/hashicorp/yamux/util.go +++ /dev/null @@ -1,43 +0,0 @@ -package yamux - -import ( - "sync" - "time" -) - -var ( - timerPool = &sync.Pool{ - New: func() interface{} { - timer := time.NewTimer(time.Hour * 1e6) - timer.Stop() - return timer - }, - } -) - -// asyncSendErr is used to try an async send of an error -func asyncSendErr(ch chan error, err error) { - if ch == nil { - return - } - select { - case ch <- err: - default: - } -} - -// asyncNotify is used to signal a waiting goroutine -func asyncNotify(ch chan struct{}) { - select { - case ch <- struct{}{}: - default: - } -} - -// min computes the minimum of two values -func min(a, b uint32) uint32 { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/mitchellh/copystructure/LICENSE b/vendor/github.com/mitchellh/copystructure/LICENSE deleted file mode 100644 index 229851590..000000000 --- a/vendor/github.com/mitchellh/copystructure/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/copystructure/README.md b/vendor/github.com/mitchellh/copystructure/README.md deleted file mode 100644 index f0fbd2e5c..000000000 --- a/vendor/github.com/mitchellh/copystructure/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# copystructure - -copystructure is a Go library for deep copying values in Go. - -This allows you to copy Go values that may contain reference values -such as maps, slices, or pointers, and copy their data as well instead -of just their references. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/copystructure -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/copystructure). - -The `Copy` function has examples associated with it there. diff --git a/vendor/github.com/mitchellh/copystructure/copier_time.go b/vendor/github.com/mitchellh/copystructure/copier_time.go deleted file mode 100644 index db6a6aa1a..000000000 --- a/vendor/github.com/mitchellh/copystructure/copier_time.go +++ /dev/null @@ -1,15 +0,0 @@ -package copystructure - -import ( - "reflect" - "time" -) - -func init() { - Copiers[reflect.TypeOf(time.Time{})] = timeCopier -} - -func timeCopier(v interface{}) (interface{}, error) { - // Just... copy it. - return v.(time.Time), nil -} diff --git a/vendor/github.com/mitchellh/copystructure/copystructure.go b/vendor/github.com/mitchellh/copystructure/copystructure.go deleted file mode 100644 index 8089e6670..000000000 --- a/vendor/github.com/mitchellh/copystructure/copystructure.go +++ /dev/null @@ -1,631 +0,0 @@ -package copystructure - -import ( - "errors" - "reflect" - "sync" - - "github.com/mitchellh/reflectwalk" -) - -const tagKey = "copy" - -// Copy returns a deep copy of v. -// -// Copy is unable to copy unexported fields in a struct (lowercase field names). -// Unexported fields can't be reflected by the Go runtime and therefore -// copystructure can't perform any data copies. -// -// For structs, copy behavior can be controlled with struct tags. For example: -// -// struct { -// Name string -// Data *bytes.Buffer `copy:"shallow"` -// } -// -// The available tag values are: -// -// * "ignore" - The field will be ignored, effectively resulting in it being -// assigned the zero value in the copy. -// -// * "shallow" - The field will be be shallow copied. This means that references -// values such as pointers, maps, slices, etc. will be directly assigned -// versus deep copied. -// -func Copy(v interface{}) (interface{}, error) { - return Config{}.Copy(v) -} - -// CopierFunc is a function that knows how to deep copy a specific type. -// Register these globally with the Copiers variable. -type CopierFunc func(interface{}) (interface{}, error) - -// Copiers is a map of types that behave specially when they are copied. -// If a type is found in this map while deep copying, this function -// will be called to copy it instead of attempting to copy all fields. -// -// The key should be the type, obtained using: reflect.TypeOf(value with type). -// -// It is unsafe to write to this map after Copies have started. If you -// are writing to this map while also copying, wrap all modifications to -// this map as well as to Copy in a mutex. -var Copiers map[reflect.Type]CopierFunc = make(map[reflect.Type]CopierFunc) - -// ShallowCopiers is a map of pointer types that behave specially -// when they are copied. If a type is found in this map while deep -// copying, the pointer value will be shallow copied and not walked -// into. -// -// The key should be the type, obtained using: reflect.TypeOf(value -// with type). -// -// It is unsafe to write to this map after Copies have started. If you -// are writing to this map while also copying, wrap all modifications to -// this map as well as to Copy in a mutex. -var ShallowCopiers map[reflect.Type]struct{} = make(map[reflect.Type]struct{}) - -// Must is a helper that wraps a call to a function returning -// (interface{}, error) and panics if the error is non-nil. It is intended -// for use in variable initializations and should only be used when a copy -// error should be a crashing case. -func Must(v interface{}, err error) interface{} { - if err != nil { - panic("copy error: " + err.Error()) - } - - return v -} - -var errPointerRequired = errors.New("Copy argument must be a pointer when Lock is true") - -type Config struct { - // Lock any types that are a sync.Locker and are not a mutex while copying. - // If there is an RLocker method, use that to get the sync.Locker. - Lock bool - - // Copiers is a map of types associated with a CopierFunc. Use the global - // Copiers map if this is nil. - Copiers map[reflect.Type]CopierFunc - - // ShallowCopiers is a map of pointer types that when they are - // shallow copied no matter where they are encountered. Use the - // global ShallowCopiers if this is nil. - ShallowCopiers map[reflect.Type]struct{} -} - -func (c Config) Copy(v interface{}) (interface{}, error) { - if c.Lock && reflect.ValueOf(v).Kind() != reflect.Ptr { - return nil, errPointerRequired - } - - w := new(walker) - if c.Lock { - w.useLocks = true - } - - if c.Copiers == nil { - c.Copiers = Copiers - } - w.copiers = c.Copiers - - if c.ShallowCopiers == nil { - c.ShallowCopiers = ShallowCopiers - } - w.shallowCopiers = c.ShallowCopiers - - err := reflectwalk.Walk(v, w) - if err != nil { - return nil, err - } - - // Get the result. If the result is nil, then we want to turn it - // into a typed nil if we can. - result := w.Result - if result == nil { - val := reflect.ValueOf(v) - result = reflect.Indirect(reflect.New(val.Type())).Interface() - } - - return result, nil -} - -// Return the key used to index interfaces types we've seen. Store the number -// of pointers in the upper 32bits, and the depth in the lower 32bits. This is -// easy to calculate, easy to match a key with our current depth, and we don't -// need to deal with initializing and cleaning up nested maps or slices. -func ifaceKey(pointers, depth int) uint64 { - return uint64(pointers)<<32 | uint64(depth) -} - -type walker struct { - Result interface{} - - copiers map[reflect.Type]CopierFunc - shallowCopiers map[reflect.Type]struct{} - depth int - ignoreDepth int - vals []reflect.Value - cs []reflect.Value - - // This stores the number of pointers we've walked over, indexed by depth. - ps []int - - // If an interface is indirected by a pointer, we need to know the type of - // interface to create when creating the new value. Store the interface - // types here, indexed by both the walk depth and the number of pointers - // already seen at that depth. Use ifaceKey to calculate the proper uint64 - // value. - ifaceTypes map[uint64]reflect.Type - - // any locks we've taken, indexed by depth - locks []sync.Locker - // take locks while walking the structure - useLocks bool -} - -func (w *walker) Enter(l reflectwalk.Location) error { - w.depth++ - - // ensure we have enough elements to index via w.depth - for w.depth >= len(w.locks) { - w.locks = append(w.locks, nil) - } - - for len(w.ps) < w.depth+1 { - w.ps = append(w.ps, 0) - } - - return nil -} - -func (w *walker) Exit(l reflectwalk.Location) error { - locker := w.locks[w.depth] - w.locks[w.depth] = nil - if locker != nil { - defer locker.Unlock() - } - - // clear out pointers and interfaces as we exit the stack - w.ps[w.depth] = 0 - - for k := range w.ifaceTypes { - mask := uint64(^uint32(0)) - if k&mask == uint64(w.depth) { - delete(w.ifaceTypes, k) - } - } - - w.depth-- - if w.ignoreDepth > w.depth { - w.ignoreDepth = 0 - } - - if w.ignoring() { - return nil - } - - switch l { - case reflectwalk.Array: - fallthrough - case reflectwalk.Map: - fallthrough - case reflectwalk.Slice: - w.replacePointerMaybe() - - // Pop map off our container - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.MapValue: - // Pop off the key and value - mv := w.valPop() - mk := w.valPop() - m := w.cs[len(w.cs)-1] - - // If mv is the zero value, SetMapIndex deletes the key form the map, - // or in this case never adds it. We need to create a properly typed - // zero value so that this key can be set. - if !mv.IsValid() { - mv = reflect.Zero(m.Elem().Type().Elem()) - } - m.Elem().SetMapIndex(mk, mv) - case reflectwalk.ArrayElem: - // Pop off the value and the index and set it on the array - v := w.valPop() - i := w.valPop().Interface().(int) - if v.IsValid() { - a := w.cs[len(w.cs)-1] - ae := a.Elem().Index(i) // storing array as pointer on stack - so need Elem() call - if ae.CanSet() { - ae.Set(v) - } - } - case reflectwalk.SliceElem: - // Pop off the value and the index and set it on the slice - v := w.valPop() - i := w.valPop().Interface().(int) - if v.IsValid() { - s := w.cs[len(w.cs)-1] - se := s.Elem().Index(i) - if se.CanSet() { - se.Set(v) - } - } - case reflectwalk.Struct: - w.replacePointerMaybe() - - // Remove the struct from the container stack - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.StructField: - // Pop off the value and the field - v := w.valPop() - f := w.valPop().Interface().(reflect.StructField) - if v.IsValid() { - s := w.cs[len(w.cs)-1] - sf := reflect.Indirect(s).FieldByName(f.Name) - - if sf.CanSet() { - sf.Set(v) - } - } - case reflectwalk.WalkLoc: - // Clear out the slices for GC - w.cs = nil - w.vals = nil - } - - return nil -} - -func (w *walker) Map(m reflect.Value) error { - if w.ignoring() { - return nil - } - w.lock(m) - - // Create the map. If the map itself is nil, then just make a nil map - var newMap reflect.Value - if m.IsNil() { - newMap = reflect.New(m.Type()) - } else { - newMap = wrapPtr(reflect.MakeMap(m.Type())) - } - - w.cs = append(w.cs, newMap) - w.valPush(newMap) - return nil -} - -func (w *walker) MapElem(m, k, v reflect.Value) error { - return nil -} - -func (w *walker) PointerEnter(v bool) error { - if v { - w.ps[w.depth]++ - } - return nil -} - -func (w *walker) PointerExit(v bool) error { - if v { - w.ps[w.depth]-- - } - return nil -} - -func (w *walker) Pointer(v reflect.Value) error { - if _, ok := w.shallowCopiers[v.Type()]; ok { - // Shallow copy this value. Use the same logic as primitive, then - // return skip. - if err := w.Primitive(v); err != nil { - return err - } - - return reflectwalk.SkipEntry - } - - return nil -} - -func (w *walker) Interface(v reflect.Value) error { - if !v.IsValid() { - return nil - } - if w.ifaceTypes == nil { - w.ifaceTypes = make(map[uint64]reflect.Type) - } - - w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)] = v.Type() - return nil -} - -func (w *walker) Primitive(v reflect.Value) error { - if w.ignoring() { - return nil - } - w.lock(v) - - // IsValid verifies the v is non-zero and CanInterface verifies - // that we're allowed to read this value (unexported fields). - var newV reflect.Value - if v.IsValid() && v.CanInterface() { - newV = reflect.New(v.Type()) - newV.Elem().Set(v) - } - - w.valPush(newV) - w.replacePointerMaybe() - return nil -} - -func (w *walker) Slice(s reflect.Value) error { - if w.ignoring() { - return nil - } - w.lock(s) - - var newS reflect.Value - if s.IsNil() { - newS = reflect.New(s.Type()) - } else { - newS = wrapPtr(reflect.MakeSlice(s.Type(), s.Len(), s.Cap())) - } - - w.cs = append(w.cs, newS) - w.valPush(newS) - return nil -} - -func (w *walker) SliceElem(i int, elem reflect.Value) error { - if w.ignoring() { - return nil - } - - // We don't write the slice here because elem might still be - // arbitrarily complex. Just record the index and continue on. - w.valPush(reflect.ValueOf(i)) - - return nil -} - -func (w *walker) Array(a reflect.Value) error { - if w.ignoring() { - return nil - } - w.lock(a) - - newA := reflect.New(a.Type()) - - w.cs = append(w.cs, newA) - w.valPush(newA) - return nil -} - -func (w *walker) ArrayElem(i int, elem reflect.Value) error { - if w.ignoring() { - return nil - } - - // We don't write the array here because elem might still be - // arbitrarily complex. Just record the index and continue on. - w.valPush(reflect.ValueOf(i)) - - return nil -} - -func (w *walker) Struct(s reflect.Value) error { - if w.ignoring() { - return nil - } - w.lock(s) - - var v reflect.Value - if c, ok := w.copiers[s.Type()]; ok { - // We have a Copier for this struct, so we use that copier to - // get the copy, and we ignore anything deeper than this. - w.ignoreDepth = w.depth - - dup, err := c(s.Interface()) - if err != nil { - return err - } - - // We need to put a pointer to the value on the value stack, - // so allocate a new pointer and set it. - v = reflect.New(s.Type()) - reflect.Indirect(v).Set(reflect.ValueOf(dup)) - } else { - // No copier, we copy ourselves and allow reflectwalk to guide - // us deeper into the structure for copying. - v = reflect.New(s.Type()) - } - - // Push the value onto the value stack for setting the struct field, - // and add the struct itself to the containers stack in case we walk - // deeper so that its own fields can be modified. - w.valPush(v) - w.cs = append(w.cs, v) - - return nil -} - -func (w *walker) StructField(f reflect.StructField, v reflect.Value) error { - if w.ignoring() { - return nil - } - - // If PkgPath is non-empty, this is a private (unexported) field. - // We do not set this unexported since the Go runtime doesn't allow us. - if f.PkgPath != "" { - return reflectwalk.SkipEntry - } - - switch f.Tag.Get(tagKey) { - case "shallow": - // If we're shallow copying then assign the value directly to the - // struct and skip the entry. - if v.IsValid() { - s := w.cs[len(w.cs)-1] - sf := reflect.Indirect(s).FieldByName(f.Name) - if sf.CanSet() { - sf.Set(v) - } - } - - return reflectwalk.SkipEntry - - case "ignore": - // Do nothing - return reflectwalk.SkipEntry - } - - // Push the field onto the stack, we'll handle it when we exit - // the struct field in Exit... - w.valPush(reflect.ValueOf(f)) - - return nil -} - -// ignore causes the walker to ignore any more values until we exit this on -func (w *walker) ignore() { - w.ignoreDepth = w.depth -} - -func (w *walker) ignoring() bool { - return w.ignoreDepth > 0 && w.depth >= w.ignoreDepth -} - -func (w *walker) pointerPeek() bool { - return w.ps[w.depth] > 0 -} - -func (w *walker) valPop() reflect.Value { - result := w.vals[len(w.vals)-1] - w.vals = w.vals[:len(w.vals)-1] - - // If we're out of values, that means we popped everything off. In - // this case, we reset the result so the next pushed value becomes - // the result. - if len(w.vals) == 0 { - w.Result = nil - } - - return result -} - -func (w *walker) valPush(v reflect.Value) { - w.vals = append(w.vals, v) - - // If we haven't set the result yet, then this is the result since - // it is the first (outermost) value we're seeing. - if w.Result == nil && v.IsValid() { - w.Result = v.Interface() - } -} - -func (w *walker) replacePointerMaybe() { - // Determine the last pointer value. If it is NOT a pointer, then - // we need to push that onto the stack. - if !w.pointerPeek() { - w.valPush(reflect.Indirect(w.valPop())) - return - } - - v := w.valPop() - - // If the expected type is a pointer to an interface of any depth, - // such as *interface{}, **interface{}, etc., then we need to convert - // the value "v" from *CONCRETE to *interface{} so types match for - // Set. - // - // Example if v is type *Foo where Foo is a struct, v would become - // *interface{} instead. This only happens if we have an interface expectation - // at this depth. - // - // For more info, see GH-16 - if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)]; ok && iType.Kind() == reflect.Interface { - y := reflect.New(iType) // Create *interface{} - y.Elem().Set(reflect.Indirect(v)) // Assign "Foo" to interface{} (dereferenced) - v = y // v is now typed *interface{} (where *v = Foo) - } - - for i := 1; i < w.ps[w.depth]; i++ { - if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth]-i, w.depth)]; ok { - iface := reflect.New(iType).Elem() - iface.Set(v) - v = iface - } - - p := reflect.New(v.Type()) - p.Elem().Set(v) - v = p - } - - w.valPush(v) -} - -// if this value is a Locker, lock it and add it to the locks slice -func (w *walker) lock(v reflect.Value) { - if !w.useLocks { - return - } - - if !v.IsValid() || !v.CanInterface() { - return - } - - type rlocker interface { - RLocker() sync.Locker - } - - var locker sync.Locker - - // We can't call Interface() on a value directly, since that requires - // a copy. This is OK, since the pointer to a value which is a sync.Locker - // is also a sync.Locker. - if v.Kind() == reflect.Ptr { - switch l := v.Interface().(type) { - case rlocker: - // don't lock a mutex directly - if _, ok := l.(*sync.RWMutex); !ok { - locker = l.RLocker() - } - case sync.Locker: - locker = l - } - } else if v.CanAddr() { - switch l := v.Addr().Interface().(type) { - case rlocker: - // don't lock a mutex directly - if _, ok := l.(*sync.RWMutex); !ok { - locker = l.RLocker() - } - case sync.Locker: - locker = l - } - } - - // still no callable locker - if locker == nil { - return - } - - // don't lock a mutex directly - switch locker.(type) { - case *sync.Mutex, *sync.RWMutex: - return - } - - locker.Lock() - w.locks[w.depth] = locker -} - -// wrapPtr is a helper that takes v and always make it *v. copystructure -// stores things internally as pointers until the last moment before unwrapping -func wrapPtr(v reflect.Value) reflect.Value { - if !v.IsValid() { - return v - } - vPtr := reflect.New(v.Type()) - vPtr.Elem().Set(v) - return vPtr -} diff --git a/vendor/github.com/mitchellh/go-testing-interface/.travis.yml b/vendor/github.com/mitchellh/go-testing-interface/.travis.yml deleted file mode 100644 index cca949103..000000000 --- a/vendor/github.com/mitchellh/go-testing-interface/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go - -go: - - 1.x - - tip - -script: - - go test - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/mitchellh/go-testing-interface/LICENSE b/vendor/github.com/mitchellh/go-testing-interface/LICENSE deleted file mode 100644 index a3866a291..000000000 --- a/vendor/github.com/mitchellh/go-testing-interface/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/go-testing-interface/README.md b/vendor/github.com/mitchellh/go-testing-interface/README.md deleted file mode 100644 index ee435adc5..000000000 --- a/vendor/github.com/mitchellh/go-testing-interface/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# go-testing-interface - -go-testing-interface is a Go library that exports an interface that -`*testing.T` implements as well as a runtime version you can use in its -place. - -The purpose of this library is so that you can export test helpers as a -public API without depending on the "testing" package, since you can't -create a `*testing.T` struct manually. This lets you, for example, use the -public testing APIs to generate mock data at runtime, rather than just at -test time. - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/go-testing-interface). - -Given a test helper written using `go-testing-interface` like this: - - import "github.com/mitchellh/go-testing-interface" - - func TestHelper(t testing.T) { - t.Fatal("I failed") - } - -You can call the test helper in a real test easily: - - import "testing" - - func TestThing(t *testing.T) { - TestHelper(t) - } - -You can also call the test helper at runtime if needed: - - import "github.com/mitchellh/go-testing-interface" - - func main() { - TestHelper(&testing.RuntimeT{}) - } - -## Versioning - -The tagged version matches the version of Go that the interface is -compatible with. For example, the version "1.14.0" is for Go 1.14 and -introduced the `Cleanup` function. The patch version (the ".0" in the -prior example) is used to fix any bugs found in this library and has no -correlation to the supported Go version. - -## Why?! - -**Why would I call a test helper that takes a *testing.T at runtime?** - -You probably shouldn't. The only use case I've seen (and I've had) for this -is to implement a "dev mode" for a service where the test helpers are used -to populate mock data, create a mock DB, perhaps run service dependencies -in-memory, etc. - -Outside of a "dev mode", I've never seen a use case for this and I think -there shouldn't be one since the point of the `testing.T` interface is that -you can fail immediately. diff --git a/vendor/github.com/mitchellh/go-testing-interface/testing.go b/vendor/github.com/mitchellh/go-testing-interface/testing.go deleted file mode 100644 index 86510322a..000000000 --- a/vendor/github.com/mitchellh/go-testing-interface/testing.go +++ /dev/null @@ -1,112 +0,0 @@ -package testing - -import ( - "fmt" - "log" -) - -// T is the interface that mimics the standard library *testing.T. -// -// In unit tests you can just pass a *testing.T struct. At runtime, outside -// of tests, you can pass in a RuntimeT struct from this package. -type T interface { - Cleanup(func()) - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - Fail() - FailNow() - Failed() bool - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Helper() - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Name() string - Parallel() - Skip(args ...interface{}) - SkipNow() - Skipf(format string, args ...interface{}) - Skipped() bool -} - -// RuntimeT implements T and can be instantiated and run at runtime to -// mimic *testing.T behavior. Unlike *testing.T, this will simply panic -// for calls to Fatal. For calls to Error, you'll have to check the errors -// list to determine whether to exit yourself. -// -// Cleanup does NOT work, so if you're using a helper that uses Cleanup, -// there may be dangling resources. -// -// Parallel does not do anything. -type RuntimeT struct { - skipped bool - failed bool -} - -func (t *RuntimeT) Error(args ...interface{}) { - log.Println(fmt.Sprintln(args...)) - t.Fail() -} - -func (t *RuntimeT) Errorf(format string, args ...interface{}) { - log.Printf(format, args...) - t.Fail() -} - -func (t *RuntimeT) Fail() { - t.failed = true -} - -func (t *RuntimeT) FailNow() { - panic("testing.T failed, see logs for output (if any)") -} - -func (t *RuntimeT) Failed() bool { - return t.failed -} - -func (t *RuntimeT) Fatal(args ...interface{}) { - log.Print(args...) - t.FailNow() -} - -func (t *RuntimeT) Fatalf(format string, args ...interface{}) { - log.Printf(format, args...) - t.FailNow() -} - -func (t *RuntimeT) Log(args ...interface{}) { - log.Println(fmt.Sprintln(args...)) -} - -func (t *RuntimeT) Logf(format string, args ...interface{}) { - log.Println(fmt.Sprintf(format, args...)) -} - -func (t *RuntimeT) Name() string { - return "" -} - -func (t *RuntimeT) Parallel() {} - -func (t *RuntimeT) Skip(args ...interface{}) { - log.Print(args...) - t.SkipNow() -} - -func (t *RuntimeT) SkipNow() { - t.skipped = true -} - -func (t *RuntimeT) Skipf(format string, args ...interface{}) { - log.Printf(format, args...) - t.SkipNow() -} - -func (t *RuntimeT) Skipped() bool { - return t.skipped -} - -func (t *RuntimeT) Helper() {} - -func (t *RuntimeT) Cleanup(func()) {} diff --git a/vendor/github.com/mitchellh/reflectwalk/.travis.yml b/vendor/github.com/mitchellh/reflectwalk/.travis.yml deleted file mode 100644 index 4f2ee4d97..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: go diff --git a/vendor/github.com/mitchellh/reflectwalk/LICENSE b/vendor/github.com/mitchellh/reflectwalk/LICENSE deleted file mode 100644 index f9c841a51..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/reflectwalk/README.md b/vendor/github.com/mitchellh/reflectwalk/README.md deleted file mode 100644 index ac82cd2e1..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# reflectwalk - -reflectwalk is a Go library for "walking" a value in Go using reflection, -in the same way a directory tree can be "walked" on the filesystem. Walking -a complex structure can allow you to do manipulations on unknown structures -such as those decoded from JSON. diff --git a/vendor/github.com/mitchellh/reflectwalk/location.go b/vendor/github.com/mitchellh/reflectwalk/location.go deleted file mode 100644 index 6a7f17611..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/location.go +++ /dev/null @@ -1,19 +0,0 @@ -package reflectwalk - -//go:generate stringer -type=Location location.go - -type Location uint - -const ( - None Location = iota - Map - MapKey - MapValue - Slice - SliceElem - Array - ArrayElem - Struct - StructField - WalkLoc -) diff --git a/vendor/github.com/mitchellh/reflectwalk/location_string.go b/vendor/github.com/mitchellh/reflectwalk/location_string.go deleted file mode 100644 index 70760cf4c..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/location_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type=Location location.go"; DO NOT EDIT. - -package reflectwalk - -import "fmt" - -const _Location_name = "NoneMapMapKeyMapValueSliceSliceElemArrayArrayElemStructStructFieldWalkLoc" - -var _Location_index = [...]uint8{0, 4, 7, 13, 21, 26, 35, 40, 49, 55, 66, 73} - -func (i Location) String() string { - if i >= Location(len(_Location_index)-1) { - return fmt.Sprintf("Location(%d)", i) - } - return _Location_name[_Location_index[i]:_Location_index[i+1]] -} diff --git a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go b/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go deleted file mode 100644 index 7fee7b050..000000000 --- a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go +++ /dev/null @@ -1,420 +0,0 @@ -// reflectwalk is a package that allows you to "walk" complex structures -// similar to how you may "walk" a filesystem: visiting every element one -// by one and calling callback functions allowing you to handle and manipulate -// those elements. -package reflectwalk - -import ( - "errors" - "reflect" -) - -// PrimitiveWalker implementations are able to handle primitive values -// within complex structures. Primitive values are numbers, strings, -// booleans, funcs, chans. -// -// These primitive values are often members of more complex -// structures (slices, maps, etc.) that are walkable by other interfaces. -type PrimitiveWalker interface { - Primitive(reflect.Value) error -} - -// InterfaceWalker implementations are able to handle interface values as they -// are encountered during the walk. -type InterfaceWalker interface { - Interface(reflect.Value) error -} - -// MapWalker implementations are able to handle individual elements -// found within a map structure. -type MapWalker interface { - Map(m reflect.Value) error - MapElem(m, k, v reflect.Value) error -} - -// SliceWalker implementations are able to handle slice elements found -// within complex structures. -type SliceWalker interface { - Slice(reflect.Value) error - SliceElem(int, reflect.Value) error -} - -// ArrayWalker implementations are able to handle array elements found -// within complex structures. -type ArrayWalker interface { - Array(reflect.Value) error - ArrayElem(int, reflect.Value) error -} - -// StructWalker is an interface that has methods that are called for -// structs when a Walk is done. -type StructWalker interface { - Struct(reflect.Value) error - StructField(reflect.StructField, reflect.Value) error -} - -// EnterExitWalker implementations are notified before and after -// they walk deeper into complex structures (into struct fields, -// into slice elements, etc.) -type EnterExitWalker interface { - Enter(Location) error - Exit(Location) error -} - -// PointerWalker implementations are notified when the value they're -// walking is a pointer or not. Pointer is called for _every_ value whether -// it is a pointer or not. -type PointerWalker interface { - PointerEnter(bool) error - PointerExit(bool) error -} - -// PointerValueWalker implementations are notified with the value of -// a particular pointer when a pointer is walked. Pointer is called -// right before PointerEnter. -type PointerValueWalker interface { - Pointer(reflect.Value) error -} - -// SkipEntry can be returned from walk functions to skip walking -// the value of this field. This is only valid in the following functions: -// -// - Struct: skips all fields from being walked -// - StructField: skips walking the struct value -// -var SkipEntry = errors.New("skip this entry") - -// Walk takes an arbitrary value and an interface and traverses the -// value, calling callbacks on the interface if they are supported. -// The interface should implement one or more of the walker interfaces -// in this package, such as PrimitiveWalker, StructWalker, etc. -func Walk(data, walker interface{}) (err error) { - v := reflect.ValueOf(data) - ew, ok := walker.(EnterExitWalker) - if ok { - err = ew.Enter(WalkLoc) - } - - if err == nil { - err = walk(v, walker) - } - - if ok && err == nil { - err = ew.Exit(WalkLoc) - } - - return -} - -func walk(v reflect.Value, w interface{}) (err error) { - // Determine if we're receiving a pointer and if so notify the walker. - // The logic here is convoluted but very important (tests will fail if - // almost any part is changed). I will try to explain here. - // - // First, we check if the value is an interface, if so, we really need - // to check the interface's VALUE to see whether it is a pointer. - // - // Check whether the value is then a pointer. If so, then set pointer - // to true to notify the user. - // - // If we still have a pointer or an interface after the indirections, then - // we unwrap another level - // - // At this time, we also set "v" to be the dereferenced value. This is - // because once we've unwrapped the pointer we want to use that value. - pointer := false - pointerV := v - - for { - if pointerV.Kind() == reflect.Interface { - if iw, ok := w.(InterfaceWalker); ok { - if err = iw.Interface(pointerV); err != nil { - return - } - } - - pointerV = pointerV.Elem() - } - - if pointerV.Kind() == reflect.Ptr { - if pw, ok := w.(PointerValueWalker); ok { - if err = pw.Pointer(pointerV); err != nil { - if err == SkipEntry { - // Skip the rest of this entry but clear the error - return nil - } - - return - } - } - - pointer = true - v = reflect.Indirect(pointerV) - } - if pw, ok := w.(PointerWalker); ok { - if err = pw.PointerEnter(pointer); err != nil { - return - } - - defer func(pointer bool) { - if err != nil { - return - } - - err = pw.PointerExit(pointer) - }(pointer) - } - - if pointer { - pointerV = v - } - pointer = false - - // If we still have a pointer or interface we have to indirect another level. - switch pointerV.Kind() { - case reflect.Ptr, reflect.Interface: - continue - } - break - } - - // We preserve the original value here because if it is an interface - // type, we want to pass that directly into the walkPrimitive, so that - // we can set it. - originalV := v - if v.Kind() == reflect.Interface { - v = v.Elem() - } - - k := v.Kind() - if k >= reflect.Int && k <= reflect.Complex128 { - k = reflect.Int - } - - switch k { - // Primitives - case reflect.Bool, reflect.Chan, reflect.Func, reflect.Int, reflect.String, reflect.Invalid: - err = walkPrimitive(originalV, w) - return - case reflect.Map: - err = walkMap(v, w) - return - case reflect.Slice: - err = walkSlice(v, w) - return - case reflect.Struct: - err = walkStruct(v, w) - return - case reflect.Array: - err = walkArray(v, w) - return - default: - panic("unsupported type: " + k.String()) - } -} - -func walkMap(v reflect.Value, w interface{}) error { - ew, ewok := w.(EnterExitWalker) - if ewok { - ew.Enter(Map) - } - - if mw, ok := w.(MapWalker); ok { - if err := mw.Map(v); err != nil { - return err - } - } - - for _, k := range v.MapKeys() { - kv := v.MapIndex(k) - - if mw, ok := w.(MapWalker); ok { - if err := mw.MapElem(v, k, kv); err != nil { - return err - } - } - - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(MapKey) - } - - if err := walk(k, w); err != nil { - return err - } - - if ok { - ew.Exit(MapKey) - ew.Enter(MapValue) - } - - // get the map value again as it may have changed in the MapElem call - if err := walk(v.MapIndex(k), w); err != nil { - return err - } - - if ok { - ew.Exit(MapValue) - } - } - - if ewok { - ew.Exit(Map) - } - - return nil -} - -func walkPrimitive(v reflect.Value, w interface{}) error { - if pw, ok := w.(PrimitiveWalker); ok { - return pw.Primitive(v) - } - - return nil -} - -func walkSlice(v reflect.Value, w interface{}) (err error) { - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(Slice) - } - - if sw, ok := w.(SliceWalker); ok { - if err := sw.Slice(v); err != nil { - return err - } - } - - for i := 0; i < v.Len(); i++ { - elem := v.Index(i) - - if sw, ok := w.(SliceWalker); ok { - if err := sw.SliceElem(i, elem); err != nil { - return err - } - } - - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(SliceElem) - } - - if err := walk(elem, w); err != nil { - return err - } - - if ok { - ew.Exit(SliceElem) - } - } - - ew, ok = w.(EnterExitWalker) - if ok { - ew.Exit(Slice) - } - - return nil -} - -func walkArray(v reflect.Value, w interface{}) (err error) { - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(Array) - } - - if aw, ok := w.(ArrayWalker); ok { - if err := aw.Array(v); err != nil { - return err - } - } - - for i := 0; i < v.Len(); i++ { - elem := v.Index(i) - - if aw, ok := w.(ArrayWalker); ok { - if err := aw.ArrayElem(i, elem); err != nil { - return err - } - } - - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(ArrayElem) - } - - if err := walk(elem, w); err != nil { - return err - } - - if ok { - ew.Exit(ArrayElem) - } - } - - ew, ok = w.(EnterExitWalker) - if ok { - ew.Exit(Array) - } - - return nil -} - -func walkStruct(v reflect.Value, w interface{}) (err error) { - ew, ewok := w.(EnterExitWalker) - if ewok { - ew.Enter(Struct) - } - - skip := false - if sw, ok := w.(StructWalker); ok { - err = sw.Struct(v) - if err == SkipEntry { - skip = true - err = nil - } - if err != nil { - return - } - } - - if !skip { - vt := v.Type() - for i := 0; i < vt.NumField(); i++ { - sf := vt.Field(i) - f := v.FieldByIndex([]int{i}) - - if sw, ok := w.(StructWalker); ok { - err = sw.StructField(sf, f) - - // SkipEntry just pretends this field doesn't even exist - if err == SkipEntry { - continue - } - - if err != nil { - return - } - } - - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(StructField) - } - - err = walk(f, w) - if err != nil { - return - } - - if ok { - ew.Exit(StructField) - } - } - } - - if ewok { - ew.Exit(Struct) - } - - return nil -} diff --git a/vendor/github.com/oklog/run/.gitignore b/vendor/github.com/oklog/run/.gitignore deleted file mode 100644 index a1338d685..000000000 --- a/vendor/github.com/oklog/run/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ diff --git a/vendor/github.com/oklog/run/LICENSE b/vendor/github.com/oklog/run/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/oklog/run/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/oklog/run/README.md b/vendor/github.com/oklog/run/README.md deleted file mode 100644 index eba7d11cf..000000000 --- a/vendor/github.com/oklog/run/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# run - -[![GoDoc](https://godoc.org/github.com/oklog/run?status.svg)](https://godoc.org/github.com/oklog/run) -[![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Foklog%2Frun%2Fbadge&style=flat-square&label=build)](https://github.com/oklog/run/actions?query=workflow%3ATest) -[![Go Report Card](https://goreportcard.com/badge/github.com/oklog/run)](https://goreportcard.com/report/github.com/oklog/run) -[![Apache 2 licensed](https://img.shields.io/badge/license-Apache2-blue.svg)](https://raw.githubusercontent.com/oklog/run/master/LICENSE) - -run.Group is a universal mechanism to manage goroutine lifecycles. - -Create a zero-value run.Group, and then add actors to it. Actors are defined as -a pair of functions: an **execute** function, which should run synchronously; -and an **interrupt** function, which, when invoked, should cause the execute -function to return. Finally, invoke Run, which concurrently runs all of the -actors, waits until the first actor exits, invokes the interrupt functions, and -finally returns control to the caller only once all actors have returned. This -general-purpose API allows callers to model pretty much any runnable task, and -achieve well-defined lifecycle semantics for the group. - -run.Group was written to manage component lifecycles in func main for -[OK Log](https://github.com/oklog/oklog). -But it's useful in any circumstance where you need to orchestrate multiple -goroutines as a unit whole. -[Click here](https://www.youtube.com/watch?v=LHe1Cb_Ud_M&t=15m45s) to see a -video of a talk where run.Group is described. - -## Examples - -### context.Context - -```go -ctx, cancel := context.WithCancel(context.Background()) -g.Add(func() error { - return myProcess(ctx, ...) -}, func(error) { - cancel() -}) -``` - -### net.Listener - -```go -ln, _ := net.Listen("tcp", ":8080") -g.Add(func() error { - return http.Serve(ln, nil) -}, func(error) { - ln.Close() -}) -``` - -### io.ReadCloser - -```go -var conn io.ReadCloser = ... -g.Add(func() error { - s := bufio.NewScanner(conn) - for s.Scan() { - println(s.Text()) - } - return s.Err() -}, func(error) { - conn.Close() -}) -``` - -## Comparisons - -Package run is somewhat similar to package -[errgroup](https://godoc.org/golang.org/x/sync/errgroup), -except it doesn't require actor goroutines to understand context semantics. - -It's somewhat similar to package -[tomb.v1](https://godoc.org/gopkg.in/tomb.v1) or -[tomb.v2](https://godoc.org/gopkg.in/tomb.v2), -except it has a much smaller API surface, delegating e.g. staged shutdown of -goroutines to the caller. diff --git a/vendor/github.com/oklog/run/actors.go b/vendor/github.com/oklog/run/actors.go deleted file mode 100644 index ef93495d3..000000000 --- a/vendor/github.com/oklog/run/actors.go +++ /dev/null @@ -1,38 +0,0 @@ -package run - -import ( - "context" - "fmt" - "os" - "os/signal" -) - -// SignalHandler returns an actor, i.e. an execute and interrupt func, that -// terminates with SignalError when the process receives one of the provided -// signals, or the parent context is canceled. -func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) { - ctx, cancel := context.WithCancel(ctx) - return func() error { - c := make(chan os.Signal, 1) - signal.Notify(c, signals...) - select { - case sig := <-c: - return SignalError{Signal: sig} - case <-ctx.Done(): - return ctx.Err() - } - }, func(error) { - cancel() - } -} - -// SignalError is returned by the signal handler's execute function -// when it terminates due to a received signal. -type SignalError struct { - Signal os.Signal -} - -// Error implements the error interface. -func (e SignalError) Error() string { - return fmt.Sprintf("received signal %s", e.Signal) -} diff --git a/vendor/github.com/oklog/run/group.go b/vendor/github.com/oklog/run/group.go deleted file mode 100644 index 832d47dd1..000000000 --- a/vendor/github.com/oklog/run/group.go +++ /dev/null @@ -1,62 +0,0 @@ -// Package run implements an actor-runner with deterministic teardown. It is -// somewhat similar to package errgroup, except it does not require actor -// goroutines to understand context semantics. This makes it suitable for use in -// more circumstances; for example, goroutines which are handling connections -// from net.Listeners, or scanning input from a closable io.Reader. -package run - -// Group collects actors (functions) and runs them concurrently. -// When one actor (function) returns, all actors are interrupted. -// The zero value of a Group is useful. -type Group struct { - actors []actor -} - -// Add an actor (function) to the group. Each actor must be pre-emptable by an -// interrupt function. That is, if interrupt is invoked, execute should return. -// Also, it must be safe to call interrupt even after execute has returned. -// -// The first actor (function) to return interrupts all running actors. -// The error is passed to the interrupt functions, and is returned by Run. -func (g *Group) Add(execute func() error, interrupt func(error)) { - g.actors = append(g.actors, actor{execute, interrupt}) -} - -// Run all actors (functions) concurrently. -// When the first actor returns, all others are interrupted. -// Run only returns when all actors have exited. -// Run returns the error returned by the first exiting actor. -func (g *Group) Run() error { - if len(g.actors) == 0 { - return nil - } - - // Run each actor. - errors := make(chan error, len(g.actors)) - for _, a := range g.actors { - go func(a actor) { - errors <- a.execute() - }(a) - } - - // Wait for the first actor to stop. - err := <-errors - - // Signal all actors to stop. - for _, a := range g.actors { - a.interrupt(err) - } - - // Wait for all actors to stop. - for i := 1; i < cap(errors); i++ { - <-errors - } - - // Return the original error. - return err -} - -type actor struct { - execute func() error - interrupt func(error) -} diff --git a/vendor/github.com/pierrec/lz4/.gitignore b/vendor/github.com/pierrec/lz4/.gitignore deleted file mode 100644 index 5e9873504..000000000 --- a/vendor/github.com/pierrec/lz4/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -# Created by https://www.gitignore.io/api/macos - -### macOS ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# End of https://www.gitignore.io/api/macos - -cmd/*/*exe -.idea \ No newline at end of file diff --git a/vendor/github.com/pierrec/lz4/.travis.yml b/vendor/github.com/pierrec/lz4/.travis.yml deleted file mode 100644 index fd6c6db71..000000000 --- a/vendor/github.com/pierrec/lz4/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: go - -env: - - GO111MODULE=off - -go: - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - master - -matrix: - fast_finish: true - allow_failures: - - go: master - -sudo: false - -script: - - go test -v -cpu=2 - - go test -v -cpu=2 -race - - go test -v -cpu=2 -tags noasm - - go test -v -cpu=2 -race -tags noasm diff --git a/vendor/github.com/pierrec/lz4/LICENSE b/vendor/github.com/pierrec/lz4/LICENSE deleted file mode 100644 index bd899d835..000000000 --- a/vendor/github.com/pierrec/lz4/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2015, Pierre Curto -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of xxHash nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/pierrec/lz4/README.md b/vendor/github.com/pierrec/lz4/README.md deleted file mode 100644 index 4ee388e81..000000000 --- a/vendor/github.com/pierrec/lz4/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# lz4 : LZ4 compression in pure Go - -[![GoDoc](https://godoc.org/github.com/pierrec/lz4?status.svg)](https://godoc.org/github.com/pierrec/lz4) -[![Build Status](https://travis-ci.org/pierrec/lz4.svg?branch=master)](https://travis-ci.org/pierrec/lz4) -[![Go Report Card](https://goreportcard.com/badge/github.com/pierrec/lz4)](https://goreportcard.com/report/github.com/pierrec/lz4) -[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/pierrec/lz4.svg?style=social)](https://github.com/pierrec/lz4/tags) - -## Overview - -This package provides a streaming interface to [LZ4 data streams](http://fastcompression.blogspot.fr/2013/04/lz4-streaming-format-final.html) as well as low level compress and uncompress functions for LZ4 data blocks. -The implementation is based on the reference C [one](https://github.com/lz4/lz4). - -## Install - -Assuming you have the go toolchain installed: - -``` -go get github.com/pierrec/lz4 -``` - -There is a command line interface tool to compress and decompress LZ4 files. - -``` -go install github.com/pierrec/lz4/cmd/lz4c -``` - -Usage - -``` -Usage of lz4c: - -version - print the program version - -Subcommands: -Compress the given files or from stdin to stdout. -compress [arguments] [ ...] - -bc - enable block checksum - -l int - compression level (0=fastest) - -sc - disable stream checksum - -size string - block max size [64K,256K,1M,4M] (default "4M") - -Uncompress the given files or from stdin to stdout. -uncompress [arguments] [ ...] - -``` - - -## Example - -``` -// Compress and uncompress an input string. -s := "hello world" -r := strings.NewReader(s) - -// The pipe will uncompress the data from the writer. -pr, pw := io.Pipe() -zw := lz4.NewWriter(pw) -zr := lz4.NewReader(pr) - -go func() { - // Compress the input string. - _, _ = io.Copy(zw, r) - _ = zw.Close() // Make sure the writer is closed - _ = pw.Close() // Terminate the pipe -}() - -_, _ = io.Copy(os.Stdout, zr) - -// Output: -// hello world -``` - -## Contributing - -Contributions are very welcome for bug fixing, performance improvements...! - -- Open an issue with a proper description -- Send a pull request with appropriate test case(s) - -## Contributors - -Thanks to all [contributors](https://github.com/pierrec/lz4/graphs/contributors) so far! - -Special thanks to [@Zariel](https://github.com/Zariel) for his asm implementation of the decoder. - -Special thanks to [@klauspost](https://github.com/klauspost) for his work on optimizing the code. diff --git a/vendor/github.com/pierrec/lz4/block.go b/vendor/github.com/pierrec/lz4/block.go deleted file mode 100644 index 664d9be58..000000000 --- a/vendor/github.com/pierrec/lz4/block.go +++ /dev/null @@ -1,413 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "math/bits" - "sync" -) - -// blockHash hashes the lower 6 bytes into a value < htSize. -func blockHash(x uint64) uint32 { - const prime6bytes = 227718039650203 - return uint32(((x << (64 - 48)) * prime6bytes) >> (64 - hashLog)) -} - -// CompressBlockBound returns the maximum size of a given buffer of size n, when not compressible. -func CompressBlockBound(n int) int { - return n + n/255 + 16 -} - -// UncompressBlock uncompresses the source buffer into the destination one, -// and returns the uncompressed size. -// -// The destination buffer must be sized appropriately. -// -// An error is returned if the source data is invalid or the destination buffer is too small. -func UncompressBlock(src, dst []byte) (int, error) { - if len(src) == 0 { - return 0, nil - } - if di := decodeBlock(dst, src); di >= 0 { - return di, nil - } - return 0, ErrInvalidSourceShortBuffer -} - -// CompressBlock compresses the source buffer into the destination one. -// This is the fast version of LZ4 compression and also the default one. -// -// The argument hashTable is scratch space for a hash table used by the -// compressor. If provided, it should have length at least 1<<16. If it is -// shorter (or nil), CompressBlock allocates its own hash table. -// -// The size of the compressed data is returned. -// -// If the destination buffer size is lower than CompressBlockBound and -// the compressed size is 0 and no error, then the data is incompressible. -// -// An error is returned if the destination buffer is too small. -func CompressBlock(src, dst []byte, hashTable []int) (_ int, err error) { - defer recoverBlock(&err) - - // Return 0, nil only if the destination buffer size is < CompressBlockBound. - isNotCompressible := len(dst) < CompressBlockBound(len(src)) - - // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible. - // This significantly speeds up incompressible data and usually has very small impact on compression. - // bytes to skip = 1 + (bytes since last match >> adaptSkipLog) - const adaptSkipLog = 7 - if len(hashTable) < htSize { - htIface := htPool.Get() - defer htPool.Put(htIface) - hashTable = (*(htIface).(*[htSize]int))[:] - } - // Prove to the compiler the table has at least htSize elements. - // The compiler can see that "uint32() >> hashShift" cannot be out of bounds. - hashTable = hashTable[:htSize] - - // si: Current position of the search. - // anchor: Position of the current literals. - var si, di, anchor int - sn := len(src) - mfLimit - if sn <= 0 { - goto lastLiterals - } - - // Fast scan strategy: the hash table only stores the last 4 bytes sequences. - for si < sn { - // Hash the next 6 bytes (sequence)... - match := binary.LittleEndian.Uint64(src[si:]) - h := blockHash(match) - h2 := blockHash(match >> 8) - - // We check a match at s, s+1 and s+2 and pick the first one we get. - // Checking 3 only requires us to load the source one. - ref := hashTable[h] - ref2 := hashTable[h2] - hashTable[h] = si - hashTable[h2] = si + 1 - offset := si - ref - - // If offset <= 0 we got an old entry in the hash table. - if offset <= 0 || offset >= winSize || // Out of window. - uint32(match) != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches. - // No match. Start calculating another hash. - // The processor can usually do this out-of-order. - h = blockHash(match >> 16) - ref = hashTable[h] - - // Check the second match at si+1 - si += 1 - offset = si - ref2 - - if offset <= 0 || offset >= winSize || - uint32(match>>8) != binary.LittleEndian.Uint32(src[ref2:]) { - // No match. Check the third match at si+2 - si += 1 - offset = si - ref - hashTable[h] = si - - if offset <= 0 || offset >= winSize || - uint32(match>>16) != binary.LittleEndian.Uint32(src[ref:]) { - // Skip one extra byte (at si+3) before we check 3 matches again. - si += 2 + (si-anchor)>>adaptSkipLog - continue - } - } - } - - // Match found. - lLen := si - anchor // Literal length. - // We already matched 4 bytes. - mLen := 4 - - // Extend backwards if we can, reducing literals. - tOff := si - offset - 1 - for lLen > 0 && tOff >= 0 && src[si-1] == src[tOff] { - si-- - tOff-- - lLen-- - mLen++ - } - - // Add the match length, so we continue search at the end. - // Use mLen to store the offset base. - si, mLen = si+mLen, si+minMatch - - // Find the longest match by looking by batches of 8 bytes. - for si+8 < sn { - x := binary.LittleEndian.Uint64(src[si:]) ^ binary.LittleEndian.Uint64(src[si-offset:]) - if x == 0 { - si += 8 - } else { - // Stop is first non-zero byte. - si += bits.TrailingZeros64(x) >> 3 - break - } - } - - mLen = si - mLen - if mLen < 0xF { - dst[di] = byte(mLen) - } else { - dst[di] = 0xF - } - - // Encode literals length. - if lLen < 0xF { - dst[di] |= byte(lLen << 4) - } else { - dst[di] |= 0xF0 - di++ - l := lLen - 0xF - for ; l >= 0xFF; l -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(l) - } - di++ - - // Literals. - copy(dst[di:di+lLen], src[anchor:anchor+lLen]) - di += lLen + 2 - anchor = si - - // Encode offset. - _ = dst[di] // Bound check elimination. - dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) - - // Encode match length part 2. - if mLen >= 0xF { - for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(mLen) - di++ - } - // Check if we can load next values. - if si >= sn { - break - } - // Hash match end-2 - h = blockHash(binary.LittleEndian.Uint64(src[si-2:])) - hashTable[h] = si - 2 - } - -lastLiterals: - if isNotCompressible && anchor == 0 { - // Incompressible. - return 0, nil - } - - // Last literals. - lLen := len(src) - anchor - if lLen < 0xF { - dst[di] = byte(lLen << 4) - } else { - dst[di] = 0xF0 - di++ - for lLen -= 0xF; lLen >= 0xFF; lLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(lLen) - } - di++ - - // Write the last literals. - if isNotCompressible && di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:di+len(src)-anchor], src[anchor:]) - return di, nil -} - -// Pool of hash tables for CompressBlock. -var htPool = sync.Pool{ - New: func() interface{} { - return new([htSize]int) - }, -} - -// blockHash hashes 4 bytes into a value < winSize. -func blockHashHC(x uint32) uint32 { - const hasher uint32 = 2654435761 // Knuth multiplicative hash. - return x * hasher >> (32 - winSizeLog) -} - -// CompressBlockHC compresses the source buffer src into the destination dst -// with max search depth (use 0 or negative value for no max). -// -// CompressBlockHC compression ratio is better than CompressBlock but it is also slower. -// -// The size of the compressed data is returned. -// -// If the destination buffer size is lower than CompressBlockBound and -// the compressed size is 0 and no error, then the data is incompressible. -// -// An error is returned if the destination buffer is too small. -func CompressBlockHC(src, dst []byte, depth int) (_ int, err error) { - defer recoverBlock(&err) - - // Return 0, nil only if the destination buffer size is < CompressBlockBound. - isNotCompressible := len(dst) < CompressBlockBound(len(src)) - - // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible. - // This significantly speeds up incompressible data and usually has very small impact on compression. - // bytes to skip = 1 + (bytes since last match >> adaptSkipLog) - const adaptSkipLog = 7 - - var si, di, anchor int - - // hashTable: stores the last position found for a given hash - // chainTable: stores previous positions for a given hash - var hashTable, chainTable [winSize]int - - if depth <= 0 { - depth = winSize - } - - sn := len(src) - mfLimit - if sn <= 0 { - goto lastLiterals - } - - for si < sn { - // Hash the next 4 bytes (sequence). - match := binary.LittleEndian.Uint32(src[si:]) - h := blockHashHC(match) - - // Follow the chain until out of window and give the longest match. - mLen := 0 - offset := 0 - for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] { - // The first (mLen==0) or next byte (mLen>=minMatch) at current match length - // must match to improve on the match length. - if src[next+mLen] != src[si+mLen] { - continue - } - ml := 0 - // Compare the current position with a previous with the same hash. - for ml < sn-si { - x := binary.LittleEndian.Uint64(src[next+ml:]) ^ binary.LittleEndian.Uint64(src[si+ml:]) - if x == 0 { - ml += 8 - } else { - // Stop is first non-zero byte. - ml += bits.TrailingZeros64(x) >> 3 - break - } - } - if ml < minMatch || ml <= mLen { - // Match too small (>adaptSkipLog - continue - } - - // Match found. - // Update hash/chain tables with overlapping bytes: - // si already hashed, add everything from si+1 up to the match length. - winStart := si + 1 - if ws := si + mLen - winSize; ws > winStart { - winStart = ws - } - for si, ml := winStart, si+mLen; si < ml; { - match >>= 8 - match |= uint32(src[si+3]) << 24 - h := blockHashHC(match) - chainTable[si&winMask] = hashTable[h] - hashTable[h] = si - si++ - } - - lLen := si - anchor - si += mLen - mLen -= minMatch // Match length does not include minMatch. - - if mLen < 0xF { - dst[di] = byte(mLen) - } else { - dst[di] = 0xF - } - - // Encode literals length. - if lLen < 0xF { - dst[di] |= byte(lLen << 4) - } else { - dst[di] |= 0xF0 - di++ - l := lLen - 0xF - for ; l >= 0xFF; l -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(l) - } - di++ - - // Literals. - copy(dst[di:di+lLen], src[anchor:anchor+lLen]) - di += lLen - anchor = si - - // Encode offset. - di += 2 - dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) - - // Encode match length part 2. - if mLen >= 0xF { - for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(mLen) - di++ - } - } - - if isNotCompressible && anchor == 0 { - // Incompressible. - return 0, nil - } - - // Last literals. -lastLiterals: - lLen := len(src) - anchor - if lLen < 0xF { - dst[di] = byte(lLen << 4) - } else { - dst[di] = 0xF0 - di++ - lLen -= 0xF - for ; lLen >= 0xFF; lLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(lLen) - } - di++ - - // Write the last literals. - if isNotCompressible && di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:di+len(src)-anchor], src[anchor:]) - return di, nil -} diff --git a/vendor/github.com/pierrec/lz4/debug.go b/vendor/github.com/pierrec/lz4/debug.go deleted file mode 100644 index bc5e78d40..000000000 --- a/vendor/github.com/pierrec/lz4/debug.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build lz4debug - -package lz4 - -import ( - "fmt" - "os" - "path/filepath" - "runtime" -) - -const debugFlag = true - -func debug(args ...interface{}) { - _, file, line, _ := runtime.Caller(1) - file = filepath.Base(file) - - f := fmt.Sprintf("LZ4: %s:%d %s", file, line, args[0]) - if f[len(f)-1] != '\n' { - f += "\n" - } - fmt.Fprintf(os.Stderr, f, args[1:]...) -} diff --git a/vendor/github.com/pierrec/lz4/debug_stub.go b/vendor/github.com/pierrec/lz4/debug_stub.go deleted file mode 100644 index 44211ad96..000000000 --- a/vendor/github.com/pierrec/lz4/debug_stub.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !lz4debug - -package lz4 - -const debugFlag = false - -func debug(args ...interface{}) {} diff --git a/vendor/github.com/pierrec/lz4/decode_amd64.go b/vendor/github.com/pierrec/lz4/decode_amd64.go deleted file mode 100644 index 43cc14fbe..000000000 --- a/vendor/github.com/pierrec/lz4/decode_amd64.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !appengine -// +build gc -// +build !noasm - -package lz4 - -//go:noescape -func decodeBlock(dst, src []byte) int diff --git a/vendor/github.com/pierrec/lz4/decode_amd64.s b/vendor/github.com/pierrec/lz4/decode_amd64.s deleted file mode 100644 index 20fef3975..000000000 --- a/vendor/github.com/pierrec/lz4/decode_amd64.s +++ /dev/null @@ -1,375 +0,0 @@ -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// AX scratch -// BX scratch -// CX scratch -// DX token -// -// DI &dst -// SI &src -// R8 &dst + len(dst) -// R9 &src + len(src) -// R11 &dst -// R12 short output end -// R13 short input end -// func decodeBlock(dst, src []byte) int -// using 50 bytes of stack currently -TEXT ·decodeBlock(SB), NOSPLIT, $64-56 - MOVQ dst_base+0(FP), DI - MOVQ DI, R11 - MOVQ dst_len+8(FP), R8 - ADDQ DI, R8 - - MOVQ src_base+24(FP), SI - MOVQ src_len+32(FP), R9 - ADDQ SI, R9 - - // shortcut ends - // short output end - MOVQ R8, R12 - SUBQ $32, R12 - // short input end - MOVQ R9, R13 - SUBQ $16, R13 - -loop: - // for si < len(src) - CMPQ SI, R9 - JGE end - - // token := uint32(src[si]) - MOVBQZX (SI), DX - INCQ SI - - // lit_len = token >> 4 - // if lit_len > 0 - // CX = lit_len - MOVQ DX, CX - SHRQ $4, CX - - // if lit_len != 0xF - CMPQ CX, $0xF - JEQ lit_len_loop_pre - CMPQ DI, R12 - JGE lit_len_loop_pre - CMPQ SI, R13 - JGE lit_len_loop_pre - - // copy shortcut - - // A two-stage shortcut for the most common case: - // 1) If the literal length is 0..14, and there is enough space, - // enter the shortcut and copy 16 bytes on behalf of the literals - // (in the fast mode, only 8 bytes can be safely copied this way). - // 2) Further if the match length is 4..18, copy 18 bytes in a similar - // manner; but we ensure that there's enough space in the output for - // those 18 bytes earlier, upon entering the shortcut (in other words, - // there is a combined check for both stages). - - // copy literal - MOVOU (SI), X0 - MOVOU X0, (DI) - ADDQ CX, DI - ADDQ CX, SI - - MOVQ DX, CX - ANDQ $0xF, CX - - // The second stage: prepare for match copying, decode full info. - // If it doesn't work out, the info won't be wasted. - // offset := uint16(data[:2]) - MOVWQZX (SI), DX - ADDQ $2, SI - - MOVQ DI, AX - SUBQ DX, AX - CMPQ AX, DI - JGT err_short_buf - - // if we can't do the second stage then jump straight to read the - // match length, we already have the offset. - CMPQ CX, $0xF - JEQ match_len_loop_pre - CMPQ DX, $8 - JLT match_len_loop_pre - CMPQ AX, R11 - JLT err_short_buf - - // memcpy(op + 0, match + 0, 8); - MOVQ (AX), BX - MOVQ BX, (DI) - // memcpy(op + 8, match + 8, 8); - MOVQ 8(AX), BX - MOVQ BX, 8(DI) - // memcpy(op +16, match +16, 2); - MOVW 16(AX), BX - MOVW BX, 16(DI) - - ADDQ $4, DI // minmatch - ADDQ CX, DI - - // shortcut complete, load next token - JMP loop - -lit_len_loop_pre: - // if lit_len > 0 - CMPQ CX, $0 - JEQ offset - CMPQ CX, $0xF - JNE copy_literal - -lit_len_loop: - // for src[si] == 0xFF - CMPB (SI), $0xFF - JNE lit_len_finalise - - // bounds check src[si+1] - MOVQ SI, AX - ADDQ $1, AX - CMPQ AX, R9 - JGT err_short_buf - - // lit_len += 0xFF - ADDQ $0xFF, CX - INCQ SI - JMP lit_len_loop - -lit_len_finalise: - // lit_len += int(src[si]) - // si++ - MOVBQZX (SI), AX - ADDQ AX, CX - INCQ SI - -copy_literal: - // bounds check src and dst - MOVQ SI, AX - ADDQ CX, AX - CMPQ AX, R9 - JGT err_short_buf - - MOVQ DI, AX - ADDQ CX, AX - CMPQ AX, R8 - JGT err_short_buf - - // whats a good cut off to call memmove? - CMPQ CX, $16 - JGT memmove_lit - - // if len(dst[di:]) < 16 - MOVQ R8, AX - SUBQ DI, AX - CMPQ AX, $16 - JLT memmove_lit - - // if len(src[si:]) < 16 - MOVQ R9, AX - SUBQ SI, AX - CMPQ AX, $16 - JLT memmove_lit - - MOVOU (SI), X0 - MOVOU X0, (DI) - - JMP finish_lit_copy - -memmove_lit: - // memmove(to, from, len) - MOVQ DI, 0(SP) - MOVQ SI, 8(SP) - MOVQ CX, 16(SP) - // spill - MOVQ DI, 24(SP) - MOVQ SI, 32(SP) - MOVQ CX, 40(SP) // need len to inc SI, DI after - MOVB DX, 48(SP) - CALL runtime·memmove(SB) - - // restore registers - MOVQ 24(SP), DI - MOVQ 32(SP), SI - MOVQ 40(SP), CX - MOVB 48(SP), DX - - // recalc initial values - MOVQ dst_base+0(FP), R8 - MOVQ R8, R11 - ADDQ dst_len+8(FP), R8 - MOVQ src_base+24(FP), R9 - ADDQ src_len+32(FP), R9 - MOVQ R8, R12 - SUBQ $32, R12 - MOVQ R9, R13 - SUBQ $16, R13 - -finish_lit_copy: - ADDQ CX, SI - ADDQ CX, DI - - CMPQ SI, R9 - JGE end - -offset: - // CX := mLen - // free up DX to use for offset - MOVQ DX, CX - - MOVQ SI, AX - ADDQ $2, AX - CMPQ AX, R9 - JGT err_short_buf - - // offset - // DX := int(src[si]) | int(src[si+1])<<8 - MOVWQZX (SI), DX - ADDQ $2, SI - - // 0 offset is invalid - CMPQ DX, $0 - JEQ err_corrupt - - ANDB $0xF, CX - -match_len_loop_pre: - // if mlen != 0xF - CMPB CX, $0xF - JNE copy_match - -match_len_loop: - // for src[si] == 0xFF - // lit_len += 0xFF - CMPB (SI), $0xFF - JNE match_len_finalise - - // bounds check src[si+1] - MOVQ SI, AX - ADDQ $1, AX - CMPQ AX, R9 - JGT err_short_buf - - ADDQ $0xFF, CX - INCQ SI - JMP match_len_loop - -match_len_finalise: - // lit_len += int(src[si]) - // si++ - MOVBQZX (SI), AX - ADDQ AX, CX - INCQ SI - -copy_match: - // mLen += minMatch - ADDQ $4, CX - - // check we have match_len bytes left in dst - // di+match_len < len(dst) - MOVQ DI, AX - ADDQ CX, AX - CMPQ AX, R8 - JGT err_short_buf - - // DX = offset - // CX = match_len - // BX = &dst + (di - offset) - MOVQ DI, BX - SUBQ DX, BX - - // check BX is within dst - // if BX < &dst - CMPQ BX, R11 - JLT err_short_buf - - // if offset + match_len < di - MOVQ BX, AX - ADDQ CX, AX - CMPQ DI, AX - JGT copy_interior_match - - // AX := len(dst[:di]) - // MOVQ DI, AX - // SUBQ R11, AX - - // copy 16 bytes at a time - // if di-offset < 16 copy 16-(di-offset) bytes to di - // then do the remaining - -copy_match_loop: - // for match_len >= 0 - // dst[di] = dst[i] - // di++ - // i++ - MOVB (BX), AX - MOVB AX, (DI) - INCQ DI - INCQ BX - DECQ CX - - CMPQ CX, $0 - JGT copy_match_loop - - JMP loop - -copy_interior_match: - CMPQ CX, $16 - JGT memmove_match - - // if len(dst[di:]) < 16 - MOVQ R8, AX - SUBQ DI, AX - CMPQ AX, $16 - JLT memmove_match - - MOVOU (BX), X0 - MOVOU X0, (DI) - - ADDQ CX, DI - JMP loop - -memmove_match: - // memmove(to, from, len) - MOVQ DI, 0(SP) - MOVQ BX, 8(SP) - MOVQ CX, 16(SP) - // spill - MOVQ DI, 24(SP) - MOVQ SI, 32(SP) - MOVQ CX, 40(SP) // need len to inc SI, DI after - CALL runtime·memmove(SB) - - // restore registers - MOVQ 24(SP), DI - MOVQ 32(SP), SI - MOVQ 40(SP), CX - - // recalc initial values - MOVQ dst_base+0(FP), R8 - MOVQ R8, R11 // TODO: make these sensible numbers - ADDQ dst_len+8(FP), R8 - MOVQ src_base+24(FP), R9 - ADDQ src_len+32(FP), R9 - MOVQ R8, R12 - SUBQ $32, R12 - MOVQ R9, R13 - SUBQ $16, R13 - - ADDQ CX, DI - JMP loop - -err_corrupt: - MOVQ $-1, ret+48(FP) - RET - -err_short_buf: - MOVQ $-2, ret+48(FP) - RET - -end: - SUBQ R11, DI - MOVQ DI, ret+48(FP) - RET diff --git a/vendor/github.com/pierrec/lz4/decode_other.go b/vendor/github.com/pierrec/lz4/decode_other.go deleted file mode 100644 index 919888edf..000000000 --- a/vendor/github.com/pierrec/lz4/decode_other.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build !amd64 appengine !gc noasm - -package lz4 - -func decodeBlock(dst, src []byte) (ret int) { - const hasError = -2 - defer func() { - if recover() != nil { - ret = hasError - } - }() - - var si, di int - for { - // Literals and match lengths (token). - b := int(src[si]) - si++ - - // Literals. - if lLen := b >> 4; lLen > 0 { - switch { - case lLen < 0xF && si+16 < len(src): - // Shortcut 1 - // if we have enough room in src and dst, and the literals length - // is small enough (0..14) then copy all 16 bytes, even if not all - // are part of the literals. - copy(dst[di:], src[si:si+16]) - si += lLen - di += lLen - if mLen := b & 0xF; mLen < 0xF { - // Shortcut 2 - // if the match length (4..18) fits within the literals, then copy - // all 18 bytes, even if not all are part of the literals. - mLen += 4 - if offset := int(src[si]) | int(src[si+1])<<8; mLen <= offset { - i := di - offset - end := i + 18 - if end > len(dst) { - // The remaining buffer may not hold 18 bytes. - // See https://github.com/pierrec/lz4/issues/51. - end = len(dst) - } - copy(dst[di:], dst[i:end]) - si += 2 - di += mLen - continue - } - } - case lLen == 0xF: - for src[si] == 0xFF { - lLen += 0xFF - si++ - } - lLen += int(src[si]) - si++ - fallthrough - default: - copy(dst[di:di+lLen], src[si:si+lLen]) - si += lLen - di += lLen - } - } - if si >= len(src) { - return di - } - - offset := int(src[si]) | int(src[si+1])<<8 - if offset == 0 { - return hasError - } - si += 2 - - // Match. - mLen := b & 0xF - if mLen == 0xF { - for src[si] == 0xFF { - mLen += 0xFF - si++ - } - mLen += int(src[si]) - si++ - } - mLen += minMatch - - // Copy the match. - expanded := dst[di-offset:] - if mLen > offset { - // Efficiently copy the match dst[di-offset:di] into the dst slice. - bytesToCopy := offset * (mLen / offset) - for n := offset; n <= bytesToCopy+offset; n *= 2 { - copy(expanded[n:], expanded[:n]) - } - di += bytesToCopy - mLen -= bytesToCopy - } - di += copy(dst[di:di+mLen], expanded[:mLen]) - } -} diff --git a/vendor/github.com/pierrec/lz4/errors.go b/vendor/github.com/pierrec/lz4/errors.go deleted file mode 100644 index 1c45d1813..000000000 --- a/vendor/github.com/pierrec/lz4/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package lz4 - -import ( - "errors" - "fmt" - "os" - rdebug "runtime/debug" -) - -var ( - // ErrInvalidSourceShortBuffer is returned by UncompressBlock or CompressBLock when a compressed - // block is corrupted or the destination buffer is not large enough for the uncompressed data. - ErrInvalidSourceShortBuffer = errors.New("lz4: invalid source or destination buffer too short") - // ErrInvalid is returned when reading an invalid LZ4 archive. - ErrInvalid = errors.New("lz4: bad magic number") - // ErrBlockDependency is returned when attempting to decompress an archive created with block dependency. - ErrBlockDependency = errors.New("lz4: block dependency not supported") - // ErrUnsupportedSeek is returned when attempting to Seek any way but forward from the current position. - ErrUnsupportedSeek = errors.New("lz4: can only seek forward from io.SeekCurrent") -) - -func recoverBlock(e *error) { - if r := recover(); r != nil && *e == nil { - if debugFlag { - fmt.Fprintln(os.Stderr, r) - rdebug.PrintStack() - } - *e = ErrInvalidSourceShortBuffer - } -} diff --git a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go b/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go deleted file mode 100644 index 7a76a6bce..000000000 --- a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go +++ /dev/null @@ -1,223 +0,0 @@ -// Package xxh32 implements the very fast XXH hashing algorithm (32 bits version). -// (https://github.com/Cyan4973/XXH/) -package xxh32 - -import ( - "encoding/binary" -) - -const ( - prime1 uint32 = 2654435761 - prime2 uint32 = 2246822519 - prime3 uint32 = 3266489917 - prime4 uint32 = 668265263 - prime5 uint32 = 374761393 - - primeMask = 0xFFFFFFFF - prime1plus2 = uint32((uint64(prime1) + uint64(prime2)) & primeMask) // 606290984 - prime1minus = uint32((-int64(prime1)) & primeMask) // 1640531535 -) - -// XXHZero represents an xxhash32 object with seed 0. -type XXHZero struct { - v1 uint32 - v2 uint32 - v3 uint32 - v4 uint32 - totalLen uint64 - buf [16]byte - bufused int -} - -// Sum appends the current hash to b and returns the resulting slice. -// It does not change the underlying hash state. -func (xxh XXHZero) Sum(b []byte) []byte { - h32 := xxh.Sum32() - return append(b, byte(h32), byte(h32>>8), byte(h32>>16), byte(h32>>24)) -} - -// Reset resets the Hash to its initial state. -func (xxh *XXHZero) Reset() { - xxh.v1 = prime1plus2 - xxh.v2 = prime2 - xxh.v3 = 0 - xxh.v4 = prime1minus - xxh.totalLen = 0 - xxh.bufused = 0 -} - -// Size returns the number of bytes returned by Sum(). -func (xxh *XXHZero) Size() int { - return 4 -} - -// BlockSize gives the minimum number of bytes accepted by Write(). -func (xxh *XXHZero) BlockSize() int { - return 1 -} - -// Write adds input bytes to the Hash. -// It never returns an error. -func (xxh *XXHZero) Write(input []byte) (int, error) { - if xxh.totalLen == 0 { - xxh.Reset() - } - n := len(input) - m := xxh.bufused - - xxh.totalLen += uint64(n) - - r := len(xxh.buf) - m - if n < r { - copy(xxh.buf[m:], input) - xxh.bufused += len(input) - return n, nil - } - - p := 0 - // Causes compiler to work directly from registers instead of stack: - v1, v2, v3, v4 := xxh.v1, xxh.v2, xxh.v3, xxh.v4 - if m > 0 { - // some data left from previous update - copy(xxh.buf[xxh.bufused:], input[:r]) - xxh.bufused += len(input) - r - - // fast rotl(13) - buf := xxh.buf[:16] // BCE hint. - v1 = rol13(v1+binary.LittleEndian.Uint32(buf[:])*prime2) * prime1 - v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime2) * prime1 - v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime2) * prime1 - v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime2) * prime1 - p = r - xxh.bufused = 0 - } - - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime2) * prime1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime2) * prime1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime2) * prime1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime2) * prime1 - } - xxh.v1, xxh.v2, xxh.v3, xxh.v4 = v1, v2, v3, v4 - - copy(xxh.buf[xxh.bufused:], input[p:]) - xxh.bufused += len(input) - p - - return n, nil -} - -// Sum32 returns the 32 bits Hash value. -func (xxh *XXHZero) Sum32() uint32 { - h32 := uint32(xxh.totalLen) - if h32 >= 16 { - h32 += rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) - } else { - h32 += prime5 - } - - p := 0 - n := xxh.bufused - buf := xxh.buf - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(buf[p:p+4]) * prime3 - h32 = rol17(h32) * prime4 - } - for ; p < n; p++ { - h32 += uint32(buf[p]) * prime5 - h32 = rol11(h32) * prime1 - } - - h32 ^= h32 >> 15 - h32 *= prime2 - h32 ^= h32 >> 13 - h32 *= prime3 - h32 ^= h32 >> 16 - - return h32 -} - -// ChecksumZero returns the 32bits Hash value. -func ChecksumZero(input []byte) uint32 { - n := len(input) - h32 := uint32(n) - - if n < 16 { - h32 += prime5 - } else { - v1 := prime1plus2 - v2 := prime2 - v3 := uint32(0) - v4 := prime1minus - p := 0 - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime2) * prime1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime2) * prime1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime2) * prime1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime2) * prime1 - } - input = input[p:] - n -= p - h32 += rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - } - - p := 0 - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(input[p:p+4]) * prime3 - h32 = rol17(h32) * prime4 - } - for p < n { - h32 += uint32(input[p]) * prime5 - h32 = rol11(h32) * prime1 - p++ - } - - h32 ^= h32 >> 15 - h32 *= prime2 - h32 ^= h32 >> 13 - h32 *= prime3 - h32 ^= h32 >> 16 - - return h32 -} - -// Uint32Zero hashes x with seed 0. -func Uint32Zero(x uint32) uint32 { - h := prime5 + 4 + x*prime3 - h = rol17(h) * prime4 - h ^= h >> 15 - h *= prime2 - h ^= h >> 13 - h *= prime3 - h ^= h >> 16 - return h -} - -func rol1(u uint32) uint32 { - return u<<1 | u>>31 -} - -func rol7(u uint32) uint32 { - return u<<7 | u>>25 -} - -func rol11(u uint32) uint32 { - return u<<11 | u>>21 -} - -func rol12(u uint32) uint32 { - return u<<12 | u>>20 -} - -func rol13(u uint32) uint32 { - return u<<13 | u>>19 -} - -func rol17(u uint32) uint32 { - return u<<17 | u>>15 -} - -func rol18(u uint32) uint32 { - return u<<18 | u>>14 -} diff --git a/vendor/github.com/pierrec/lz4/lz4.go b/vendor/github.com/pierrec/lz4/lz4.go deleted file mode 100644 index a3284bdf7..000000000 --- a/vendor/github.com/pierrec/lz4/lz4.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package lz4 implements reading and writing lz4 compressed data (a frame), -// as specified in http://fastcompression.blogspot.fr/2013/04/lz4-streaming-format-final.html. -// -// Although the block level compression and decompression functions are exposed and are fully compatible -// with the lz4 block format definition, they are low level and should not be used directly. -// For a complete description of an lz4 compressed block, see: -// http://fastcompression.blogspot.fr/2011/05/lz4-explained.html -// -// See https://github.com/Cyan4973/lz4 for the reference C implementation. -// -package lz4 - -import ( - "math/bits" - "sync" -) - -const ( - // Extension is the LZ4 frame file name extension - Extension = ".lz4" - // Version is the LZ4 frame format version - Version = 1 - - frameMagic uint32 = 0x184D2204 - frameSkipMagic uint32 = 0x184D2A50 - frameMagicLegacy uint32 = 0x184C2102 - - // The following constants are used to setup the compression algorithm. - minMatch = 4 // the minimum size of the match sequence size (4 bytes) - winSizeLog = 16 // LZ4 64Kb window size limit - winSize = 1 << winSizeLog - winMask = winSize - 1 // 64Kb window of previous data for dependent blocks - compressedBlockFlag = 1 << 31 - compressedBlockMask = compressedBlockFlag - 1 - - // hashLog determines the size of the hash table used to quickly find a previous match position. - // Its value influences the compression speed and memory usage, the lower the faster, - // but at the expense of the compression ratio. - // 16 seems to be the best compromise for fast compression. - hashLog = 16 - htSize = 1 << hashLog - - mfLimit = 10 + minMatch // The last match cannot start within the last 14 bytes. -) - -// map the block max size id with its value in bytes: 64Kb, 256Kb, 1Mb and 4Mb. -const ( - blockSize64K = 1 << (16 + 2*iota) - blockSize256K - blockSize1M - blockSize4M -) - -var ( - // Keep a pool of buffers for each valid block sizes. - bsMapValue = [...]*sync.Pool{ - newBufferPool(2 * blockSize64K), - newBufferPool(2 * blockSize256K), - newBufferPool(2 * blockSize1M), - newBufferPool(2 * blockSize4M), - } -) - -// newBufferPool returns a pool for buffers of the given size. -func newBufferPool(size int) *sync.Pool { - return &sync.Pool{ - New: func() interface{} { - return make([]byte, size) - }, - } -} - -// getBuffer returns a buffer to its pool. -func getBuffer(size int) []byte { - idx := blockSizeValueToIndex(size) - 4 - return bsMapValue[idx].Get().([]byte) -} - -// putBuffer returns a buffer to its pool. -func putBuffer(size int, buf []byte) { - if cap(buf) > 0 { - idx := blockSizeValueToIndex(size) - 4 - bsMapValue[idx].Put(buf[:cap(buf)]) - } -} -func blockSizeIndexToValue(i byte) int { - return 1 << (16 + 2*uint(i)) -} -func isValidBlockSize(size int) bool { - const blockSizeMask = blockSize64K | blockSize256K | blockSize1M | blockSize4M - - return size&blockSizeMask > 0 && bits.OnesCount(uint(size)) == 1 -} -func blockSizeValueToIndex(size int) byte { - return 4 + byte(bits.TrailingZeros(uint(size)>>16)/2) -} - -// Header describes the various flags that can be set on a Writer or obtained from a Reader. -// The default values match those of the LZ4 frame format definition -// (http://fastcompression.blogspot.com/2013/04/lz4-streaming-format-final.html). -// -// NB. in a Reader, in case of concatenated frames, the Header values may change between Read() calls. -// It is the caller's responsibility to check them if necessary. -type Header struct { - BlockChecksum bool // Compressed blocks checksum flag. - NoChecksum bool // Frame checksum flag. - BlockMaxSize int // Size of the uncompressed data block (one of [64KB, 256KB, 1MB, 4MB]). Default=4MB. - Size uint64 // Frame total size. It is _not_ computed by the Writer. - CompressionLevel int // Compression level (higher is better, use 0 for fastest compression). - done bool // Header processed flag (Read or Write and checked). -} - -// Reset reset internal status -func (h *Header) Reset() { - h.done = false -} diff --git a/vendor/github.com/pierrec/lz4/lz4_go1.10.go b/vendor/github.com/pierrec/lz4/lz4_go1.10.go deleted file mode 100644 index 9a0fb0070..000000000 --- a/vendor/github.com/pierrec/lz4/lz4_go1.10.go +++ /dev/null @@ -1,29 +0,0 @@ -//+build go1.10 - -package lz4 - -import ( - "fmt" - "strings" -) - -func (h Header) String() string { - var s strings.Builder - - s.WriteString(fmt.Sprintf("%T{", h)) - if h.BlockChecksum { - s.WriteString("BlockChecksum: true ") - } - if h.NoChecksum { - s.WriteString("NoChecksum: true ") - } - if bs := h.BlockMaxSize; bs != 0 && bs != 4<<20 { - s.WriteString(fmt.Sprintf("BlockMaxSize: %d ", bs)) - } - if l := h.CompressionLevel; l != 0 { - s.WriteString(fmt.Sprintf("CompressionLevel: %d ", l)) - } - s.WriteByte('}') - - return s.String() -} diff --git a/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go b/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go deleted file mode 100644 index 12c761a2e..000000000 --- a/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go +++ /dev/null @@ -1,29 +0,0 @@ -//+build !go1.10 - -package lz4 - -import ( - "bytes" - "fmt" -) - -func (h Header) String() string { - var s bytes.Buffer - - s.WriteString(fmt.Sprintf("%T{", h)) - if h.BlockChecksum { - s.WriteString("BlockChecksum: true ") - } - if h.NoChecksum { - s.WriteString("NoChecksum: true ") - } - if bs := h.BlockMaxSize; bs != 0 && bs != 4<<20 { - s.WriteString(fmt.Sprintf("BlockMaxSize: %d ", bs)) - } - if l := h.CompressionLevel; l != 0 { - s.WriteString(fmt.Sprintf("CompressionLevel: %d ", l)) - } - s.WriteByte('}') - - return s.String() -} diff --git a/vendor/github.com/pierrec/lz4/reader.go b/vendor/github.com/pierrec/lz4/reader.go deleted file mode 100644 index 87dd72bd0..000000000 --- a/vendor/github.com/pierrec/lz4/reader.go +++ /dev/null @@ -1,335 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" - "io/ioutil" - - "github.com/pierrec/lz4/internal/xxh32" -) - -// Reader implements the LZ4 frame decoder. -// The Header is set after the first call to Read(). -// The Header may change between Read() calls in case of concatenated frames. -type Reader struct { - Header - // Handler called when a block has been successfully read. - // It provides the number of bytes read. - OnBlockDone func(size int) - - buf [8]byte // Scrap buffer. - pos int64 // Current position in src. - src io.Reader // Source. - zdata []byte // Compressed data. - data []byte // Uncompressed data. - idx int // Index of unread bytes into data. - checksum xxh32.XXHZero // Frame hash. - skip int64 // Bytes to skip before next read. - dpos int64 // Position in dest -} - -// NewReader returns a new LZ4 frame decoder. -// No access to the underlying io.Reader is performed. -func NewReader(src io.Reader) *Reader { - r := &Reader{src: src} - return r -} - -// readHeader checks the frame magic number and parses the frame descriptoz. -// Skippable frames are supported even as a first frame although the LZ4 -// specifications recommends skippable frames not to be used as first frames. -func (z *Reader) readHeader(first bool) error { - defer z.checksum.Reset() - - buf := z.buf[:] - for { - magic, err := z.readUint32() - if err != nil { - z.pos += 4 - if !first && err == io.ErrUnexpectedEOF { - return io.EOF - } - return err - } - if magic == frameMagic { - break - } - if magic>>8 != frameSkipMagic>>8 { - return ErrInvalid - } - skipSize, err := z.readUint32() - if err != nil { - return err - } - z.pos += 4 - m, err := io.CopyN(ioutil.Discard, z.src, int64(skipSize)) - if err != nil { - return err - } - z.pos += m - } - - // Header. - if _, err := io.ReadFull(z.src, buf[:2]); err != nil { - return err - } - z.pos += 8 - - b := buf[0] - if v := b >> 6; v != Version { - return fmt.Errorf("lz4: invalid version: got %d; expected %d", v, Version) - } - if b>>5&1 == 0 { - return ErrBlockDependency - } - z.BlockChecksum = b>>4&1 > 0 - frameSize := b>>3&1 > 0 - z.NoChecksum = b>>2&1 == 0 - - bmsID := buf[1] >> 4 & 0x7 - if bmsID < 4 || bmsID > 7 { - return fmt.Errorf("lz4: invalid block max size ID: %d", bmsID) - } - bSize := blockSizeIndexToValue(bmsID - 4) - z.BlockMaxSize = bSize - - // Allocate the compressed/uncompressed buffers. - // The compressed buffer cannot exceed the uncompressed one. - if n := 2 * bSize; cap(z.zdata) < n { - z.zdata = make([]byte, n, n) - } - if debugFlag { - debug("header block max size id=%d size=%d", bmsID, bSize) - } - z.zdata = z.zdata[:bSize] - z.data = z.zdata[:cap(z.zdata)][bSize:] - z.idx = len(z.data) - - _, _ = z.checksum.Write(buf[0:2]) - - if frameSize { - buf := buf[:8] - if _, err := io.ReadFull(z.src, buf); err != nil { - return err - } - z.Size = binary.LittleEndian.Uint64(buf) - z.pos += 8 - _, _ = z.checksum.Write(buf) - } - - // Header checksum. - if _, err := io.ReadFull(z.src, buf[:1]); err != nil { - return err - } - z.pos++ - if h := byte(z.checksum.Sum32() >> 8 & 0xFF); h != buf[0] { - return fmt.Errorf("lz4: invalid header checksum: got %x; expected %x", buf[0], h) - } - - z.Header.done = true - if debugFlag { - debug("header read: %v", z.Header) - } - - return nil -} - -// Read decompresses data from the underlying source into the supplied buffer. -// -// Since there can be multiple streams concatenated, Header values may -// change between calls to Read(). If that is the case, no data is actually read from -// the underlying io.Reader, to allow for potential input buffer resizing. -func (z *Reader) Read(buf []byte) (int, error) { - if debugFlag { - debug("Read buf len=%d", len(buf)) - } - if !z.Header.done { - if err := z.readHeader(true); err != nil { - return 0, err - } - if debugFlag { - debug("header read OK compressed buffer %d / %d uncompressed buffer %d : %d index=%d", - len(z.zdata), cap(z.zdata), len(z.data), cap(z.data), z.idx) - } - } - - if len(buf) == 0 { - return 0, nil - } - - if z.idx == len(z.data) { - // No data ready for reading, process the next block. - if debugFlag { - debug("reading block from writer") - } - // Reset uncompressed buffer - z.data = z.zdata[:cap(z.zdata)][len(z.zdata):] - - // Block length: 0 = end of frame, highest bit set: uncompressed. - bLen, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if bLen == 0 { - // End of frame reached. - if !z.NoChecksum { - // Validate the frame checksum. - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - if debugFlag { - debug("frame checksum got=%x / want=%x", z.checksum.Sum32(), checksum) - } - z.pos += 4 - if h := z.checksum.Sum32(); checksum != h { - return 0, fmt.Errorf("lz4: invalid frame checksum: got %x; expected %x", h, checksum) - } - } - - // Get ready for the next concatenated frame and keep the position. - pos := z.pos - z.Reset(z.src) - z.pos = pos - - // Since multiple frames can be concatenated, check for more. - return 0, z.readHeader(false) - } - - if debugFlag { - debug("raw block size %d", bLen) - } - if bLen&compressedBlockFlag > 0 { - // Uncompressed block. - bLen &= compressedBlockMask - if debugFlag { - debug("uncompressed block size %d", bLen) - } - if int(bLen) > cap(z.data) { - return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) - } - z.data = z.data[:bLen] - if _, err := io.ReadFull(z.src, z.data); err != nil { - return 0, err - } - z.pos += int64(bLen) - if z.OnBlockDone != nil { - z.OnBlockDone(int(bLen)) - } - - if z.BlockChecksum { - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if h := xxh32.ChecksumZero(z.data); h != checksum { - return 0, fmt.Errorf("lz4: invalid block checksum: got %x; expected %x", h, checksum) - } - } - - } else { - // Compressed block. - if debugFlag { - debug("compressed block size %d", bLen) - } - if int(bLen) > cap(z.data) { - return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) - } - zdata := z.zdata[:bLen] - if _, err := io.ReadFull(z.src, zdata); err != nil { - return 0, err - } - z.pos += int64(bLen) - - if z.BlockChecksum { - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if h := xxh32.ChecksumZero(zdata); h != checksum { - return 0, fmt.Errorf("lz4: invalid block checksum: got %x; expected %x", h, checksum) - } - } - - n, err := UncompressBlock(zdata, z.data) - if err != nil { - return 0, err - } - z.data = z.data[:n] - if z.OnBlockDone != nil { - z.OnBlockDone(n) - } - } - - if !z.NoChecksum { - _, _ = z.checksum.Write(z.data) - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - } - z.idx = 0 - } - - if z.skip > int64(len(z.data[z.idx:])) { - z.skip -= int64(len(z.data[z.idx:])) - z.dpos += int64(len(z.data[z.idx:])) - z.idx = len(z.data) - return 0, nil - } - - z.idx += int(z.skip) - z.dpos += z.skip - z.skip = 0 - - n := copy(buf, z.data[z.idx:]) - z.idx += n - z.dpos += int64(n) - if debugFlag { - debug("copied %d bytes to input", n) - } - - return n, nil -} - -// Seek implements io.Seeker, but supports seeking forward from the current -// position only. Any other seek will return an error. Allows skipping output -// bytes which aren't needed, which in some scenarios is faster than reading -// and discarding them. -// Note this may cause future calls to Read() to read 0 bytes if all of the -// data they would have returned is skipped. -func (z *Reader) Seek(offset int64, whence int) (int64, error) { - if offset < 0 || whence != io.SeekCurrent { - return z.dpos + z.skip, ErrUnsupportedSeek - } - z.skip += offset - return z.dpos + z.skip, nil -} - -// Reset discards the Reader's state and makes it equivalent to the -// result of its original state from NewReader, but reading from r instead. -// This permits reusing a Reader rather than allocating a new one. -func (z *Reader) Reset(r io.Reader) { - z.Header = Header{} - z.pos = 0 - z.src = r - z.zdata = z.zdata[:0] - z.data = z.data[:0] - z.idx = 0 - z.checksum.Reset() -} - -// readUint32 reads an uint32 into the supplied buffer. -// The idea is to make use of the already allocated buffers avoiding additional allocations. -func (z *Reader) readUint32() (uint32, error) { - buf := z.buf[:4] - _, err := io.ReadFull(z.src, buf) - x := binary.LittleEndian.Uint32(buf) - return x, err -} diff --git a/vendor/github.com/pierrec/lz4/reader_legacy.go b/vendor/github.com/pierrec/lz4/reader_legacy.go deleted file mode 100644 index 1670a77d0..000000000 --- a/vendor/github.com/pierrec/lz4/reader_legacy.go +++ /dev/null @@ -1,207 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" -) - -// ReaderLegacy implements the LZ4Demo frame decoder. -// The Header is set after the first call to Read(). -type ReaderLegacy struct { - Header - // Handler called when a block has been successfully read. - // It provides the number of bytes read. - OnBlockDone func(size int) - - lastBlock bool - buf [8]byte // Scrap buffer. - pos int64 // Current position in src. - src io.Reader // Source. - zdata []byte // Compressed data. - data []byte // Uncompressed data. - idx int // Index of unread bytes into data. - skip int64 // Bytes to skip before next read. - dpos int64 // Position in dest -} - -// NewReaderLegacy returns a new LZ4Demo frame decoder. -// No access to the underlying io.Reader is performed. -func NewReaderLegacy(src io.Reader) *ReaderLegacy { - r := &ReaderLegacy{src: src} - return r -} - -// readHeader checks the frame magic number and parses the frame descriptoz. -// Skippable frames are supported even as a first frame although the LZ4 -// specifications recommends skippable frames not to be used as first frames. -func (z *ReaderLegacy) readLegacyHeader() error { - z.lastBlock = false - magic, err := z.readUint32() - if err != nil { - z.pos += 4 - if err == io.ErrUnexpectedEOF { - return io.EOF - } - return err - } - if magic != frameMagicLegacy { - return ErrInvalid - } - z.pos += 4 - - // Legacy has fixed 8MB blocksizes - // https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md#legacy-frame - bSize := blockSize4M * 2 - - // Allocate the compressed/uncompressed buffers. - // The compressed buffer cannot exceed the uncompressed one. - if n := 2 * bSize; cap(z.zdata) < n { - z.zdata = make([]byte, n, n) - } - if debugFlag { - debug("header block max size size=%d", bSize) - } - z.zdata = z.zdata[:bSize] - z.data = z.zdata[:cap(z.zdata)][bSize:] - z.idx = len(z.data) - - z.Header.done = true - if debugFlag { - debug("header read: %v", z.Header) - } - - return nil -} - -// Read decompresses data from the underlying source into the supplied buffer. -// -// Since there can be multiple streams concatenated, Header values may -// change between calls to Read(). If that is the case, no data is actually read from -// the underlying io.Reader, to allow for potential input buffer resizing. -func (z *ReaderLegacy) Read(buf []byte) (int, error) { - if debugFlag { - debug("Read buf len=%d", len(buf)) - } - if !z.Header.done { - if err := z.readLegacyHeader(); err != nil { - return 0, err - } - if debugFlag { - debug("header read OK compressed buffer %d / %d uncompressed buffer %d : %d index=%d", - len(z.zdata), cap(z.zdata), len(z.data), cap(z.data), z.idx) - } - } - - if len(buf) == 0 { - return 0, nil - } - - if z.idx == len(z.data) { - // No data ready for reading, process the next block. - if debugFlag { - debug(" reading block from writer %d %d", z.idx, blockSize4M*2) - } - - // Reset uncompressed buffer - z.data = z.zdata[:cap(z.zdata)][len(z.zdata):] - - bLen, err := z.readUint32() - if err != nil { - return 0, err - } - if debugFlag { - debug(" bLen %d (0x%x) offset = %d (0x%x)", bLen, bLen, z.pos, z.pos) - } - z.pos += 4 - - // Legacy blocks are always compressed, even when detrimental - if debugFlag { - debug(" compressed block size %d", bLen) - } - - if int(bLen) > cap(z.data) { - return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) - } - zdata := z.zdata[:bLen] - if _, err := io.ReadFull(z.src, zdata); err != nil { - return 0, err - } - z.pos += int64(bLen) - - n, err := UncompressBlock(zdata, z.data) - if err != nil { - return 0, err - } - - z.data = z.data[:n] - if z.OnBlockDone != nil { - z.OnBlockDone(n) - } - - z.idx = 0 - - // Legacy blocks are fixed to 8MB, if we read a decompressed block smaller than this - // it means we've reached the end... - if n < blockSize4M*2 { - z.lastBlock = true - } - } - - if z.skip > int64(len(z.data[z.idx:])) { - z.skip -= int64(len(z.data[z.idx:])) - z.dpos += int64(len(z.data[z.idx:])) - z.idx = len(z.data) - return 0, nil - } - - z.idx += int(z.skip) - z.dpos += z.skip - z.skip = 0 - - n := copy(buf, z.data[z.idx:]) - z.idx += n - z.dpos += int64(n) - if debugFlag { - debug("%v] copied %d bytes to input (%d:%d)", z.lastBlock, n, z.idx, len(z.data)) - } - if z.lastBlock && len(z.data) == z.idx { - return n, io.EOF - } - return n, nil -} - -// Seek implements io.Seeker, but supports seeking forward from the current -// position only. Any other seek will return an error. Allows skipping output -// bytes which aren't needed, which in some scenarios is faster than reading -// and discarding them. -// Note this may cause future calls to Read() to read 0 bytes if all of the -// data they would have returned is skipped. -func (z *ReaderLegacy) Seek(offset int64, whence int) (int64, error) { - if offset < 0 || whence != io.SeekCurrent { - return z.dpos + z.skip, ErrUnsupportedSeek - } - z.skip += offset - return z.dpos + z.skip, nil -} - -// Reset discards the Reader's state and makes it equivalent to the -// result of its original state from NewReader, but reading from r instead. -// This permits reusing a Reader rather than allocating a new one. -func (z *ReaderLegacy) Reset(r io.Reader) { - z.Header = Header{} - z.pos = 0 - z.src = r - z.zdata = z.zdata[:0] - z.data = z.data[:0] - z.idx = 0 -} - -// readUint32 reads an uint32 into the supplied buffer. -// The idea is to make use of the already allocated buffers avoiding additional allocations. -func (z *ReaderLegacy) readUint32() (uint32, error) { - buf := z.buf[:4] - _, err := io.ReadFull(z.src, buf) - x := binary.LittleEndian.Uint32(buf) - return x, err -} diff --git a/vendor/github.com/pierrec/lz4/writer.go b/vendor/github.com/pierrec/lz4/writer.go deleted file mode 100644 index f066d5630..000000000 --- a/vendor/github.com/pierrec/lz4/writer.go +++ /dev/null @@ -1,422 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" - "runtime" - - "github.com/pierrec/lz4/internal/xxh32" -) - -// zResult contains the results of compressing a block. -type zResult struct { - size uint32 // Block header - data []byte // Compressed data - checksum uint32 // Data checksum -} - -// Writer implements the LZ4 frame encoder. -type Writer struct { - Header - // Handler called when a block has been successfully written out. - // It provides the number of bytes written. - OnBlockDone func(size int) - - buf [19]byte // magic number(4) + header(flags(2)+[Size(8)+DictID(4)]+checksum(1)) does not exceed 19 bytes - dst io.Writer // Destination. - checksum xxh32.XXHZero // Frame checksum. - data []byte // Data to be compressed + buffer for compressed data. - idx int // Index into data. - hashtable [winSize]int // Hash table used in CompressBlock(). - - // For concurrency. - c chan chan zResult // Channel for block compression goroutines and writer goroutine. - err error // Any error encountered while writing to the underlying destination. -} - -// NewWriter returns a new LZ4 frame encoder. -// No access to the underlying io.Writer is performed. -// The supplied Header is checked at the first Write. -// It is ok to change it before the first Write but then not until a Reset() is performed. -func NewWriter(dst io.Writer) *Writer { - z := new(Writer) - z.Reset(dst) - return z -} - -// WithConcurrency sets the number of concurrent go routines used for compression. -// A negative value sets the concurrency to GOMAXPROCS. -func (z *Writer) WithConcurrency(n int) *Writer { - switch { - case n == 0 || n == 1: - z.c = nil - return z - case n < 0: - n = runtime.GOMAXPROCS(0) - } - z.c = make(chan chan zResult, n) - // Writer goroutine managing concurrent block compression goroutines. - go func() { - // Process next block compression item. - for c := range z.c { - // Read the next compressed block result. - // Waiting here ensures that the blocks are output in the order they were sent. - // The incoming channel is always closed as it indicates to the caller that - // the block has been processed. - res := <-c - n := len(res.data) - if n == 0 { - // Notify the block compression routine that we are done with its result. - // This is used when a sentinel block is sent to terminate the compression. - close(c) - return - } - // Write the block. - if err := z.writeUint32(res.size); err != nil && z.err == nil { - z.err = err - } - if _, err := z.dst.Write(res.data); err != nil && z.err == nil { - z.err = err - } - if z.BlockChecksum { - if err := z.writeUint32(res.checksum); err != nil && z.err == nil { - z.err = err - } - } - // It is now safe to release the buffer as no longer in use by any goroutine. - putBuffer(cap(res.data), res.data) - if h := z.OnBlockDone; h != nil { - h(n) - } - close(c) - } - }() - return z -} - -// newBuffers instantiates new buffers which size matches the one in Header. -// The returned buffers are for decompression and compression respectively. -func (z *Writer) newBuffers() { - bSize := z.Header.BlockMaxSize - buf := getBuffer(bSize) - z.data = buf[:bSize] // Uncompressed buffer is the first half. -} - -// freeBuffers puts the writer's buffers back to the pool. -func (z *Writer) freeBuffers() { - // Put the buffer back into the pool, if any. - putBuffer(z.Header.BlockMaxSize, z.data) - z.data = nil -} - -// writeHeader builds and writes the header (magic+header) to the underlying io.Writer. -func (z *Writer) writeHeader() error { - // Default to 4Mb if BlockMaxSize is not set. - if z.Header.BlockMaxSize == 0 { - z.Header.BlockMaxSize = blockSize4M - } - // The only option that needs to be validated. - bSize := z.Header.BlockMaxSize - if !isValidBlockSize(z.Header.BlockMaxSize) { - return fmt.Errorf("lz4: invalid block max size: %d", bSize) - } - // Allocate the compressed/uncompressed buffers. - // The compressed buffer cannot exceed the uncompressed one. - z.newBuffers() - z.idx = 0 - - // Size is optional. - buf := z.buf[:] - - // Set the fixed size data: magic number, block max size and flags. - binary.LittleEndian.PutUint32(buf[0:], frameMagic) - flg := byte(Version << 6) - flg |= 1 << 5 // No block dependency. - if z.Header.BlockChecksum { - flg |= 1 << 4 - } - if z.Header.Size > 0 { - flg |= 1 << 3 - } - if !z.Header.NoChecksum { - flg |= 1 << 2 - } - buf[4] = flg - buf[5] = blockSizeValueToIndex(z.Header.BlockMaxSize) << 4 - - // Current buffer size: magic(4) + flags(1) + block max size (1). - n := 6 - // Optional items. - if z.Header.Size > 0 { - binary.LittleEndian.PutUint64(buf[n:], z.Header.Size) - n += 8 - } - - // The header checksum includes the flags, block max size and optional Size. - buf[n] = byte(xxh32.ChecksumZero(buf[4:n]) >> 8 & 0xFF) - z.checksum.Reset() - - // Header ready, write it out. - if _, err := z.dst.Write(buf[0 : n+1]); err != nil { - return err - } - z.Header.done = true - if debugFlag { - debug("wrote header %v", z.Header) - } - - return nil -} - -// Write compresses data from the supplied buffer into the underlying io.Writer. -// Write does not return until the data has been written. -func (z *Writer) Write(buf []byte) (int, error) { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return 0, err - } - } - if debugFlag { - debug("input buffer len=%d index=%d", len(buf), z.idx) - } - - zn := len(z.data) - var n int - for len(buf) > 0 { - if z.idx == 0 && len(buf) >= zn { - // Avoid a copy as there is enough data for a block. - if err := z.compressBlock(buf[:zn]); err != nil { - return n, err - } - n += zn - buf = buf[zn:] - continue - } - // Accumulate the data to be compressed. - m := copy(z.data[z.idx:], buf) - n += m - z.idx += m - buf = buf[m:] - if debugFlag { - debug("%d bytes copied to buf, current index %d", n, z.idx) - } - - if z.idx < len(z.data) { - // Buffer not filled. - if debugFlag { - debug("need more data for compression") - } - return n, nil - } - - // Buffer full. - if err := z.compressBlock(z.data); err != nil { - return n, err - } - z.idx = 0 - } - - return n, nil -} - -// compressBlock compresses a block. -func (z *Writer) compressBlock(data []byte) error { - if !z.NoChecksum { - _, _ = z.checksum.Write(data) - } - - if z.c != nil { - c := make(chan zResult) - z.c <- c // Send now to guarantee order - - // get a buffer from the pool and copy the data over - block := getBuffer(z.Header.BlockMaxSize)[:len(data)] - copy(block, data) - - go writerCompressBlock(c, z.Header, block) - return nil - } - - zdata := z.data[z.Header.BlockMaxSize:cap(z.data)] - // The compressed block size cannot exceed the input's. - var zn int - - if level := z.Header.CompressionLevel; level != 0 { - zn, _ = CompressBlockHC(data, zdata, level) - } else { - zn, _ = CompressBlock(data, zdata, z.hashtable[:]) - } - - var bLen uint32 - if debugFlag { - debug("block compression %d => %d", len(data), zn) - } - if zn > 0 && zn < len(data) { - // Compressible and compressed size smaller than uncompressed: ok! - bLen = uint32(zn) - zdata = zdata[:zn] - } else { - // Uncompressed block. - bLen = uint32(len(data)) | compressedBlockFlag - zdata = data - } - if debugFlag { - debug("block compression to be written len=%d data len=%d", bLen, len(zdata)) - } - - // Write the block. - if err := z.writeUint32(bLen); err != nil { - return err - } - written, err := z.dst.Write(zdata) - if err != nil { - return err - } - if h := z.OnBlockDone; h != nil { - h(written) - } - - if !z.BlockChecksum { - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - return nil - } - checksum := xxh32.ChecksumZero(zdata) - if debugFlag { - debug("block checksum %x", checksum) - defer func() { debug("current frame checksum %x", z.checksum.Sum32()) }() - } - return z.writeUint32(checksum) -} - -// Flush flushes any pending compressed data to the underlying writer. -// Flush does not return until the data has been written. -// If the underlying writer returns an error, Flush returns that error. -func (z *Writer) Flush() error { - if debugFlag { - debug("flush with index %d", z.idx) - } - if z.idx == 0 { - return nil - } - - data := getBuffer(z.Header.BlockMaxSize)[:len(z.data[:z.idx])] - copy(data, z.data[:z.idx]) - - z.idx = 0 - if z.c == nil { - return z.compressBlock(data) - } - if !z.NoChecksum { - _, _ = z.checksum.Write(data) - } - c := make(chan zResult) - z.c <- c - writerCompressBlock(c, z.Header, data) - return nil -} - -func (z *Writer) close() error { - if z.c == nil { - return nil - } - // Send a sentinel block (no data to compress) to terminate the writer main goroutine. - c := make(chan zResult) - z.c <- c - c <- zResult{} - // Wait for the main goroutine to complete. - <-c - // At this point the main goroutine has shut down or is about to return. - z.c = nil - return z.err -} - -// Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer. -func (z *Writer) Close() error { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return err - } - } - if err := z.Flush(); err != nil { - return err - } - if err := z.close(); err != nil { - return err - } - z.freeBuffers() - - if debugFlag { - debug("writing last empty block") - } - if err := z.writeUint32(0); err != nil { - return err - } - if z.NoChecksum { - return nil - } - checksum := z.checksum.Sum32() - if debugFlag { - debug("stream checksum %x", checksum) - } - return z.writeUint32(checksum) -} - -// Reset clears the state of the Writer z such that it is equivalent to its -// initial state from NewWriter, but instead writing to w. -// No access to the underlying io.Writer is performed. -func (z *Writer) Reset(w io.Writer) { - n := cap(z.c) - _ = z.close() - z.freeBuffers() - z.Header.Reset() - z.dst = w - z.checksum.Reset() - z.idx = 0 - z.err = nil - // reset hashtable to ensure deterministic output. - for i := range z.hashtable { - z.hashtable[i] = 0 - } - z.WithConcurrency(n) -} - -// writeUint32 writes a uint32 to the underlying writer. -func (z *Writer) writeUint32(x uint32) error { - buf := z.buf[:4] - binary.LittleEndian.PutUint32(buf, x) - _, err := z.dst.Write(buf) - return err -} - -// writerCompressBlock compresses data into a pooled buffer and writes its result -// out to the input channel. -func writerCompressBlock(c chan zResult, header Header, data []byte) { - zdata := getBuffer(header.BlockMaxSize) - // The compressed block size cannot exceed the input's. - var zn int - if level := header.CompressionLevel; level != 0 { - zn, _ = CompressBlockHC(data, zdata, level) - } else { - var hashTable [winSize]int - zn, _ = CompressBlock(data, zdata, hashTable[:]) - } - var res zResult - if zn > 0 && zn < len(data) { - res.size = uint32(zn) - res.data = zdata[:zn] - // release the uncompressed block since it is not used anymore - putBuffer(header.BlockMaxSize, data) - } else { - res.size = uint32(len(data)) | compressedBlockFlag - res.data = data - // release the compressed block since it was not used - putBuffer(header.BlockMaxSize, zdata) - } - if header.BlockChecksum { - res.checksum = xxh32.ChecksumZero(res.data) - } - c <- res -} diff --git a/vendor/github.com/pierrec/lz4/writer_legacy.go b/vendor/github.com/pierrec/lz4/writer_legacy.go deleted file mode 100644 index ca8dc8c7f..000000000 --- a/vendor/github.com/pierrec/lz4/writer_legacy.go +++ /dev/null @@ -1,182 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "io" -) - -// WriterLegacy implements the LZ4Demo frame decoder. -type WriterLegacy struct { - Header - // Handler called when a block has been successfully read. - // It provides the number of bytes read. - OnBlockDone func(size int) - - dst io.Writer // Destination. - data []byte // Data to be compressed + buffer for compressed data. - idx int // Index into data. - hashtable [winSize]int // Hash table used in CompressBlock(). -} - -// NewWriterLegacy returns a new LZ4 encoder for the legacy frame format. -// No access to the underlying io.Writer is performed. -// The supplied Header is checked at the first Write. -// It is ok to change it before the first Write but then not until a Reset() is performed. -func NewWriterLegacy(dst io.Writer) *WriterLegacy { - z := new(WriterLegacy) - z.Reset(dst) - return z -} - -// Write compresses data from the supplied buffer into the underlying io.Writer. -// Write does not return until the data has been written. -func (z *WriterLegacy) Write(buf []byte) (int, error) { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return 0, err - } - } - if debugFlag { - debug("input buffer len=%d index=%d", len(buf), z.idx) - } - - zn := len(z.data) - var n int - for len(buf) > 0 { - if z.idx == 0 && len(buf) >= zn { - // Avoid a copy as there is enough data for a block. - if err := z.compressBlock(buf[:zn]); err != nil { - return n, err - } - n += zn - buf = buf[zn:] - continue - } - // Accumulate the data to be compressed. - m := copy(z.data[z.idx:], buf) - n += m - z.idx += m - buf = buf[m:] - if debugFlag { - debug("%d bytes copied to buf, current index %d", n, z.idx) - } - - if z.idx < len(z.data) { - // Buffer not filled. - if debugFlag { - debug("need more data for compression") - } - return n, nil - } - - // Buffer full. - if err := z.compressBlock(z.data); err != nil { - return n, err - } - z.idx = 0 - } - - return n, nil -} - -// writeHeader builds and writes the header to the underlying io.Writer. -func (z *WriterLegacy) writeHeader() error { - // Legacy has fixed 8MB blocksizes - // https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md#legacy-frame - bSize := 2 * blockSize4M - - buf := make([]byte, 2*bSize, 2*bSize) - z.data = buf[:bSize] // Uncompressed buffer is the first half. - - z.idx = 0 - - // Header consists of one mageic number, write it out. - if err := binary.Write(z.dst, binary.LittleEndian, frameMagicLegacy); err != nil { - return err - } - z.Header.done = true - if debugFlag { - debug("wrote header %v", z.Header) - } - - return nil -} - -// compressBlock compresses a block. -func (z *WriterLegacy) compressBlock(data []byte) error { - bSize := 2 * blockSize4M - zdata := z.data[bSize:cap(z.data)] - // The compressed block size cannot exceed the input's. - var zn int - - if level := z.Header.CompressionLevel; level != 0 { - zn, _ = CompressBlockHC(data, zdata, level) - } else { - zn, _ = CompressBlock(data, zdata, z.hashtable[:]) - } - - if debugFlag { - debug("block compression %d => %d", len(data), zn) - } - zdata = zdata[:zn] - - // Write the block. - if err := binary.Write(z.dst, binary.LittleEndian, uint32(zn)); err != nil { - return err - } - written, err := z.dst.Write(zdata) - if err != nil { - return err - } - if h := z.OnBlockDone; h != nil { - h(written) - } - return nil -} - -// Flush flushes any pending compressed data to the underlying writer. -// Flush does not return until the data has been written. -// If the underlying writer returns an error, Flush returns that error. -func (z *WriterLegacy) Flush() error { - if debugFlag { - debug("flush with index %d", z.idx) - } - if z.idx == 0 { - return nil - } - - data := z.data[:z.idx] - z.idx = 0 - return z.compressBlock(data) -} - -// Close closes the WriterLegacy, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer. -func (z *WriterLegacy) Close() error { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return err - } - } - if err := z.Flush(); err != nil { - return err - } - - if debugFlag { - debug("writing last empty block") - } - - return nil -} - -// Reset clears the state of the WriterLegacy z such that it is equivalent to its -// initial state from NewWriterLegacy, but instead writing to w. -// No access to the underlying io.Writer is performed. -func (z *WriterLegacy) Reset(w io.Writer) { - z.Header.Reset() - z.dst = w - z.idx = 0 - // reset hashtable to ensure deterministic output. - for i := range z.hashtable { - z.hashtable[i] = 0 - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b.go b/vendor/golang.org/x/crypto/blake2b/blake2b.go deleted file mode 100644 index d2e98d429..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 -// and the extendable output function (XOF) BLAKE2Xb. -// -// BLAKE2b is optimized for 64-bit platforms—including NEON-enabled ARMs—and -// produces digests of any size between 1 and 64 bytes. -// For a detailed specification of BLAKE2b see https://blake2.net/blake2.pdf -// and for BLAKE2Xb see https://blake2.net/blake2x.pdf -// -// If you aren't sure which function you need, use BLAKE2b (Sum512 or New512). -// If you need a secret-key MAC (message authentication code), use the New512 -// function with a non-nil key. -// -// BLAKE2X is a construction to compute hash values larger than 64 bytes. It -// can produce hash values between 0 and 4 GiB. -package blake2b - -import ( - "encoding/binary" - "errors" - "hash" -) - -const ( - // The blocksize of BLAKE2b in bytes. - BlockSize = 128 - // The hash size of BLAKE2b-512 in bytes. - Size = 64 - // The hash size of BLAKE2b-384 in bytes. - Size384 = 48 - // The hash size of BLAKE2b-256 in bytes. - Size256 = 32 -) - -var ( - useAVX2 bool - useAVX bool - useSSE4 bool -) - -var ( - errKeySize = errors.New("blake2b: invalid key size") - errHashSize = errors.New("blake2b: invalid hash size") -) - -var iv = [8]uint64{ - 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, - 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, -} - -// Sum512 returns the BLAKE2b-512 checksum of the data. -func Sum512(data []byte) [Size]byte { - var sum [Size]byte - checkSum(&sum, Size, data) - return sum -} - -// Sum384 returns the BLAKE2b-384 checksum of the data. -func Sum384(data []byte) [Size384]byte { - var sum [Size]byte - var sum384 [Size384]byte - checkSum(&sum, Size384, data) - copy(sum384[:], sum[:Size384]) - return sum384 -} - -// Sum256 returns the BLAKE2b-256 checksum of the data. -func Sum256(data []byte) [Size256]byte { - var sum [Size]byte - var sum256 [Size256]byte - checkSum(&sum, Size256, data) - copy(sum256[:], sum[:Size256]) - return sum256 -} - -// New512 returns a new hash.Hash computing the BLAKE2b-512 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New512(key []byte) (hash.Hash, error) { return newDigest(Size, key) } - -// New384 returns a new hash.Hash computing the BLAKE2b-384 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New384(key []byte) (hash.Hash, error) { return newDigest(Size384, key) } - -// New256 returns a new hash.Hash computing the BLAKE2b-256 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New256(key []byte) (hash.Hash, error) { return newDigest(Size256, key) } - -// New returns a new hash.Hash computing the BLAKE2b checksum with a custom length. -// A non-nil key turns the hash into a MAC. The key must be between zero and 64 bytes long. -// The hash size can be a value between 1 and 64 but it is highly recommended to use -// values equal or greater than: -// - 32 if BLAKE2b is used as a hash function (The key is zero bytes long). -// - 16 if BLAKE2b is used as a MAC function (The key is at least 16 bytes long). -// When the key is nil, the returned hash.Hash implements BinaryMarshaler -// and BinaryUnmarshaler for state (de)serialization as documented by hash.Hash. -func New(size int, key []byte) (hash.Hash, error) { return newDigest(size, key) } - -func newDigest(hashSize int, key []byte) (*digest, error) { - if hashSize < 1 || hashSize > Size { - return nil, errHashSize - } - if len(key) > Size { - return nil, errKeySize - } - d := &digest{ - size: hashSize, - keyLen: len(key), - } - copy(d.key[:], key) - d.Reset() - return d, nil -} - -func checkSum(sum *[Size]byte, hashSize int, data []byte) { - h := iv - h[0] ^= uint64(hashSize) | (1 << 16) | (1 << 24) - var c [2]uint64 - - if length := len(data); length > BlockSize { - n := length &^ (BlockSize - 1) - if length == n { - n -= BlockSize - } - hashBlocks(&h, &c, 0, data[:n]) - data = data[n:] - } - - var block [BlockSize]byte - offset := copy(block[:], data) - remaining := uint64(BlockSize - offset) - if c[0] < remaining { - c[1]-- - } - c[0] -= remaining - - hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) - - for i, v := range h[:(hashSize+7)/8] { - binary.LittleEndian.PutUint64(sum[8*i:], v) - } -} - -type digest struct { - h [8]uint64 - c [2]uint64 - size int - block [BlockSize]byte - offset int - - key [BlockSize]byte - keyLen int -} - -const ( - magic = "b2b" - marshaledSize = len(magic) + 8*8 + 2*8 + 1 + BlockSize + 1 -) - -func (d *digest) MarshalBinary() ([]byte, error) { - if d.keyLen != 0 { - return nil, errors.New("crypto/blake2b: cannot marshal MACs") - } - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - for i := 0; i < 8; i++ { - b = appendUint64(b, d.h[i]) - } - b = appendUint64(b, d.c[0]) - b = appendUint64(b, d.c[1]) - // Maximum value for size is 64 - b = append(b, byte(d.size)) - b = append(b, d.block[:]...) - b = append(b, byte(d.offset)) - return b, nil -} - -func (d *digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("crypto/blake2b: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("crypto/blake2b: invalid hash state size") - } - b = b[len(magic):] - for i := 0; i < 8; i++ { - b, d.h[i] = consumeUint64(b) - } - b, d.c[0] = consumeUint64(b) - b, d.c[1] = consumeUint64(b) - d.size = int(b[0]) - b = b[1:] - copy(d.block[:], b[:BlockSize]) - b = b[BlockSize:] - d.offset = int(b[0]) - return nil -} - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Size() int { return d.size } - -func (d *digest) Reset() { - d.h = iv - d.h[0] ^= uint64(d.size) | (uint64(d.keyLen) << 8) | (1 << 16) | (1 << 24) - d.offset, d.c[0], d.c[1] = 0, 0, 0 - if d.keyLen > 0 { - d.block = d.key - d.offset = BlockSize - } -} - -func (d *digest) Write(p []byte) (n int, err error) { - n = len(p) - - if d.offset > 0 { - remaining := BlockSize - d.offset - if n <= remaining { - d.offset += copy(d.block[d.offset:], p) - return - } - copy(d.block[d.offset:], p[:remaining]) - hashBlocks(&d.h, &d.c, 0, d.block[:]) - d.offset = 0 - p = p[remaining:] - } - - if length := len(p); length > BlockSize { - nn := length &^ (BlockSize - 1) - if length == nn { - nn -= BlockSize - } - hashBlocks(&d.h, &d.c, 0, p[:nn]) - p = p[nn:] - } - - if len(p) > 0 { - d.offset += copy(d.block[:], p) - } - - return -} - -func (d *digest) Sum(sum []byte) []byte { - var hash [Size]byte - d.finalize(&hash) - return append(sum, hash[:d.size]...) -} - -func (d *digest) finalize(hash *[Size]byte) { - var block [BlockSize]byte - copy(block[:], d.block[:d.offset]) - remaining := uint64(BlockSize - d.offset) - - c := d.c - if c[0] < remaining { - c[1]-- - } - c[0] -= remaining - - h := d.h - hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) - - for i, v := range h { - binary.LittleEndian.PutUint64(hash[8*i:], v) - } -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.BigEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func appendUint32(b []byte, x uint32) []byte { - var a [4]byte - binary.BigEndian.PutUint32(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := binary.BigEndian.Uint64(b) - return b[8:], x -} - -func consumeUint32(b []byte) ([]byte, uint32) { - x := binary.BigEndian.Uint32(b) - return b[4:], x -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go deleted file mode 100644 index 56bfaaa17..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.7 && amd64 && gc && !purego -// +build go1.7,amd64,gc,!purego - -package blake2b - -import "golang.org/x/sys/cpu" - -func init() { - useAVX2 = cpu.X86.HasAVX2 - useAVX = cpu.X86.HasAVX - useSSE4 = cpu.X86.HasSSE41 -} - -//go:noescape -func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -//go:noescape -func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -//go:noescape -func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - switch { - case useAVX2: - hashBlocksAVX2(h, c, flag, blocks) - case useAVX: - hashBlocksAVX(h, c, flag, blocks) - case useSSE4: - hashBlocksSSE4(h, c, flag, blocks) - default: - hashBlocksGeneric(h, c, flag, blocks) - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s deleted file mode 100644 index 4b9daa18d..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s +++ /dev/null @@ -1,745 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.7 && amd64 && gc && !purego -// +build go1.7,amd64,gc,!purego - -#include "textflag.h" - -DATA ·AVX2_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·AVX2_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -DATA ·AVX2_iv0<>+0x10(SB)/8, $0x3c6ef372fe94f82b -DATA ·AVX2_iv0<>+0x18(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·AVX2_iv0<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_iv1<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·AVX2_iv1<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -DATA ·AVX2_iv1<>+0x10(SB)/8, $0x1f83d9abfb41bd6b -DATA ·AVX2_iv1<>+0x18(SB)/8, $0x5be0cd19137e2179 -GLOBL ·AVX2_iv1<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·AVX2_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -DATA ·AVX2_c40<>+0x10(SB)/8, $0x0201000706050403 -DATA ·AVX2_c40<>+0x18(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·AVX2_c40<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·AVX2_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -DATA ·AVX2_c48<>+0x10(SB)/8, $0x0100070605040302 -DATA ·AVX2_c48<>+0x18(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·AVX2_c48<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·AVX_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -GLOBL ·AVX_iv0<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b -DATA ·AVX_iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·AVX_iv1<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv2<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·AVX_iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -GLOBL ·AVX_iv2<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b -DATA ·AVX_iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 -GLOBL ·AVX_iv3<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·AVX_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·AVX_c40<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·AVX_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·AVX_c48<>(SB), (NOPTR+RODATA), $16 - -#define VPERMQ_0x39_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x39 -#define VPERMQ_0x93_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x93 -#define VPERMQ_0x4E_Y2_Y2 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xd2; BYTE $0x4e -#define VPERMQ_0x93_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x93 -#define VPERMQ_0x39_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x39 - -#define ROUND_AVX2(m0, m1, m2, m3, t, c40, c48) \ - VPADDQ m0, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFD $-79, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPSHUFB c40, Y1, Y1; \ - VPADDQ m1, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFB c48, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPADDQ Y1, Y1, t; \ - VPSRLQ $63, Y1, Y1; \ - VPXOR t, Y1, Y1; \ - VPERMQ_0x39_Y1_Y1; \ - VPERMQ_0x4E_Y2_Y2; \ - VPERMQ_0x93_Y3_Y3; \ - VPADDQ m2, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFD $-79, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPSHUFB c40, Y1, Y1; \ - VPADDQ m3, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFB c48, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPADDQ Y1, Y1, t; \ - VPSRLQ $63, Y1, Y1; \ - VPXOR t, Y1, Y1; \ - VPERMQ_0x39_Y3_Y3; \ - VPERMQ_0x4E_Y2_Y2; \ - VPERMQ_0x93_Y1_Y1 - -#define VMOVQ_SI_X11_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x1E -#define VMOVQ_SI_X12_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x26 -#define VMOVQ_SI_X13_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x2E -#define VMOVQ_SI_X14_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x36 -#define VMOVQ_SI_X15_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x3E - -#define VMOVQ_SI_X11(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x5E; BYTE $n -#define VMOVQ_SI_X12(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x66; BYTE $n -#define VMOVQ_SI_X13(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x6E; BYTE $n -#define VMOVQ_SI_X14(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x76; BYTE $n -#define VMOVQ_SI_X15(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x7E; BYTE $n - -#define VPINSRQ_1_SI_X11_0 BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x1E; BYTE $0x01 -#define VPINSRQ_1_SI_X12_0 BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x26; BYTE $0x01 -#define VPINSRQ_1_SI_X13_0 BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x2E; BYTE $0x01 -#define VPINSRQ_1_SI_X14_0 BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x36; BYTE $0x01 -#define VPINSRQ_1_SI_X15_0 BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x3E; BYTE $0x01 - -#define VPINSRQ_1_SI_X11(n) BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x5E; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X12(n) BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x66; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X13(n) BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x6E; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X14(n) BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x76; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X15(n) BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x7E; BYTE $n; BYTE $0x01 - -#define VMOVQ_R8_X15 BYTE $0xC4; BYTE $0x41; BYTE $0xF9; BYTE $0x6E; BYTE $0xF8 -#define VPINSRQ_1_R9_X15 BYTE $0xC4; BYTE $0x43; BYTE $0x81; BYTE $0x22; BYTE $0xF9; BYTE $0x01 - -// load msg: Y12 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y12(i0, i1, i2, i3) \ - VMOVQ_SI_X12(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X12(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y12, Y12 - -// load msg: Y13 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y13(i0, i1, i2, i3) \ - VMOVQ_SI_X13(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X13(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y13, Y13 - -// load msg: Y14 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y14(i0, i1, i2, i3) \ - VMOVQ_SI_X14(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X14(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y14, Y14 - -// load msg: Y15 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y15(i0, i1, i2, i3) \ - VMOVQ_SI_X15(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X15(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() \ - VMOVQ_SI_X12_0; \ - VMOVQ_SI_X11(4*8); \ - VPINSRQ_1_SI_X12(2*8); \ - VPINSRQ_1_SI_X11(6*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(1, 3, 5, 7); \ - LOAD_MSG_AVX2_Y14(8, 10, 12, 14); \ - LOAD_MSG_AVX2_Y15(9, 11, 13, 15) - -#define LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() \ - LOAD_MSG_AVX2_Y12(14, 4, 9, 13); \ - LOAD_MSG_AVX2_Y13(10, 8, 15, 6); \ - VMOVQ_SI_X11(11*8); \ - VPSHUFD $0x4E, 0*8(SI), X14; \ - VPINSRQ_1_SI_X11(5*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - LOAD_MSG_AVX2_Y15(12, 2, 7, 3) - -#define LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() \ - VMOVQ_SI_X11(5*8); \ - VMOVDQU 11*8(SI), X12; \ - VPINSRQ_1_SI_X11(15*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - VMOVQ_SI_X13(8*8); \ - VMOVQ_SI_X11(2*8); \ - VPINSRQ_1_SI_X13_0; \ - VPINSRQ_1_SI_X11(13*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(10, 3, 7, 9); \ - LOAD_MSG_AVX2_Y15(14, 6, 1, 4) - -#define LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() \ - LOAD_MSG_AVX2_Y12(7, 3, 13, 11); \ - LOAD_MSG_AVX2_Y13(9, 1, 12, 14); \ - LOAD_MSG_AVX2_Y14(2, 5, 4, 15); \ - VMOVQ_SI_X15(6*8); \ - VMOVQ_SI_X11_0; \ - VPINSRQ_1_SI_X15(10*8); \ - VPINSRQ_1_SI_X11(8*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() \ - LOAD_MSG_AVX2_Y12(9, 5, 2, 10); \ - VMOVQ_SI_X13_0; \ - VMOVQ_SI_X11(4*8); \ - VPINSRQ_1_SI_X13(7*8); \ - VPINSRQ_1_SI_X11(15*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(14, 11, 6, 3); \ - LOAD_MSG_AVX2_Y15(1, 12, 8, 13) - -#define LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X11_0; \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X11(8*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(12, 10, 11, 3); \ - LOAD_MSG_AVX2_Y14(4, 7, 15, 1); \ - LOAD_MSG_AVX2_Y15(13, 5, 14, 9) - -#define LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() \ - LOAD_MSG_AVX2_Y12(12, 1, 14, 4); \ - LOAD_MSG_AVX2_Y13(5, 15, 13, 10); \ - VMOVQ_SI_X14_0; \ - VPSHUFD $0x4E, 8*8(SI), X11; \ - VPINSRQ_1_SI_X14(6*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - LOAD_MSG_AVX2_Y15(7, 3, 2, 11) - -#define LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() \ - LOAD_MSG_AVX2_Y12(13, 7, 12, 3); \ - LOAD_MSG_AVX2_Y13(11, 14, 1, 9); \ - LOAD_MSG_AVX2_Y14(5, 15, 8, 2); \ - VMOVQ_SI_X15_0; \ - VMOVQ_SI_X11(6*8); \ - VPINSRQ_1_SI_X15(4*8); \ - VPINSRQ_1_SI_X11(10*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() \ - VMOVQ_SI_X12(6*8); \ - VMOVQ_SI_X11(11*8); \ - VPINSRQ_1_SI_X12(14*8); \ - VPINSRQ_1_SI_X11_0; \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(15, 9, 3, 8); \ - VMOVQ_SI_X11(1*8); \ - VMOVDQU 12*8(SI), X14; \ - VPINSRQ_1_SI_X11(10*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - VMOVQ_SI_X15(2*8); \ - VMOVDQU 4*8(SI), X11; \ - VPINSRQ_1_SI_X15(7*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() \ - LOAD_MSG_AVX2_Y12(10, 8, 7, 1); \ - VMOVQ_SI_X13(2*8); \ - VPSHUFD $0x4E, 5*8(SI), X11; \ - VPINSRQ_1_SI_X13(4*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(15, 9, 3, 13); \ - VMOVQ_SI_X15(11*8); \ - VMOVQ_SI_X11(12*8); \ - VPINSRQ_1_SI_X15(14*8); \ - VPINSRQ_1_SI_X11_0; \ - VINSERTI128 $1, X11, Y15, Y15 - -// func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksAVX2(SB), 4, $320-48 // frame size = 288 + 32 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, DX - ADDQ $31, DX - ANDQ $~31, DX - - MOVQ CX, 16(DX) - XORQ CX, CX - MOVQ CX, 24(DX) - - VMOVDQU ·AVX2_c40<>(SB), Y4 - VMOVDQU ·AVX2_c48<>(SB), Y5 - - VMOVDQU 0(AX), Y8 - VMOVDQU 32(AX), Y9 - VMOVDQU ·AVX2_iv0<>(SB), Y6 - VMOVDQU ·AVX2_iv1<>(SB), Y7 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - MOVQ R9, 8(DX) - -loop: - ADDQ $128, R8 - MOVQ R8, 0(DX) - CMPQ R8, $128 - JGE noinc - INCQ R9 - MOVQ R9, 8(DX) - -noinc: - VMOVDQA Y8, Y0 - VMOVDQA Y9, Y1 - VMOVDQA Y6, Y2 - VPXOR 0(DX), Y7, Y3 - - LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() - VMOVDQA Y12, 32(DX) - VMOVDQA Y13, 64(DX) - VMOVDQA Y14, 96(DX) - VMOVDQA Y15, 128(DX) - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() - VMOVDQA Y12, 160(DX) - VMOVDQA Y13, 192(DX) - VMOVDQA Y14, 224(DX) - VMOVDQA Y15, 256(DX) - - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - - ROUND_AVX2(32(DX), 64(DX), 96(DX), 128(DX), Y10, Y4, Y5) - ROUND_AVX2(160(DX), 192(DX), 224(DX), 256(DX), Y10, Y4, Y5) - - VPXOR Y0, Y8, Y8 - VPXOR Y1, Y9, Y9 - VPXOR Y2, Y8, Y8 - VPXOR Y3, Y9, Y9 - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - - VMOVDQU Y8, 0(AX) - VMOVDQU Y9, 32(AX) - VZEROUPPER - - RET - -#define VPUNPCKLQDQ_X2_X2_X15 BYTE $0xC5; BYTE $0x69; BYTE $0x6C; BYTE $0xFA -#define VPUNPCKLQDQ_X3_X3_X15 BYTE $0xC5; BYTE $0x61; BYTE $0x6C; BYTE $0xFB -#define VPUNPCKLQDQ_X7_X7_X15 BYTE $0xC5; BYTE $0x41; BYTE $0x6C; BYTE $0xFF -#define VPUNPCKLQDQ_X13_X13_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x11; BYTE $0x6C; BYTE $0xFD -#define VPUNPCKLQDQ_X14_X14_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x09; BYTE $0x6C; BYTE $0xFE - -#define VPUNPCKHQDQ_X15_X2_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x69; BYTE $0x6D; BYTE $0xD7 -#define VPUNPCKHQDQ_X15_X3_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xDF -#define VPUNPCKHQDQ_X15_X6_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x49; BYTE $0x6D; BYTE $0xF7 -#define VPUNPCKHQDQ_X15_X7_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xFF -#define VPUNPCKHQDQ_X15_X3_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xD7 -#define VPUNPCKHQDQ_X15_X7_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xF7 -#define VPUNPCKHQDQ_X15_X13_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xDF -#define VPUNPCKHQDQ_X15_X13_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xFF - -#define SHUFFLE_AVX() \ - VMOVDQA X6, X13; \ - VMOVDQA X2, X14; \ - VMOVDQA X4, X6; \ - VPUNPCKLQDQ_X13_X13_X15; \ - VMOVDQA X5, X4; \ - VMOVDQA X6, X5; \ - VPUNPCKHQDQ_X15_X7_X6; \ - VPUNPCKLQDQ_X7_X7_X15; \ - VPUNPCKHQDQ_X15_X13_X7; \ - VPUNPCKLQDQ_X3_X3_X15; \ - VPUNPCKHQDQ_X15_X2_X2; \ - VPUNPCKLQDQ_X14_X14_X15; \ - VPUNPCKHQDQ_X15_X3_X3; \ - -#define SHUFFLE_AVX_INV() \ - VMOVDQA X2, X13; \ - VMOVDQA X4, X14; \ - VPUNPCKLQDQ_X2_X2_X15; \ - VMOVDQA X5, X4; \ - VPUNPCKHQDQ_X15_X3_X2; \ - VMOVDQA X14, X5; \ - VPUNPCKLQDQ_X3_X3_X15; \ - VMOVDQA X6, X14; \ - VPUNPCKHQDQ_X15_X13_X3; \ - VPUNPCKLQDQ_X7_X7_X15; \ - VPUNPCKHQDQ_X15_X6_X6; \ - VPUNPCKLQDQ_X14_X14_X15; \ - VPUNPCKHQDQ_X15_X7_X7; \ - -#define HALF_ROUND_AVX(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ - VPADDQ m0, v0, v0; \ - VPADDQ v2, v0, v0; \ - VPADDQ m1, v1, v1; \ - VPADDQ v3, v1, v1; \ - VPXOR v0, v6, v6; \ - VPXOR v1, v7, v7; \ - VPSHUFD $-79, v6, v6; \ - VPSHUFD $-79, v7, v7; \ - VPADDQ v6, v4, v4; \ - VPADDQ v7, v5, v5; \ - VPXOR v4, v2, v2; \ - VPXOR v5, v3, v3; \ - VPSHUFB c40, v2, v2; \ - VPSHUFB c40, v3, v3; \ - VPADDQ m2, v0, v0; \ - VPADDQ v2, v0, v0; \ - VPADDQ m3, v1, v1; \ - VPADDQ v3, v1, v1; \ - VPXOR v0, v6, v6; \ - VPXOR v1, v7, v7; \ - VPSHUFB c48, v6, v6; \ - VPSHUFB c48, v7, v7; \ - VPADDQ v6, v4, v4; \ - VPADDQ v7, v5, v5; \ - VPXOR v4, v2, v2; \ - VPXOR v5, v3, v3; \ - VPADDQ v2, v2, t0; \ - VPSRLQ $63, v2, v2; \ - VPXOR t0, v2, v2; \ - VPADDQ v3, v3, t0; \ - VPSRLQ $63, v3, v3; \ - VPXOR t0, v3, v3 - -// load msg: X12 = (i0, i1), X13 = (i2, i3), X14 = (i4, i5), X15 = (i6, i7) -// i0, i1, i2, i3, i4, i5, i6, i7 must not be 0 -#define LOAD_MSG_AVX(i0, i1, i2, i3, i4, i5, i6, i7) \ - VMOVQ_SI_X12(i0*8); \ - VMOVQ_SI_X13(i2*8); \ - VMOVQ_SI_X14(i4*8); \ - VMOVQ_SI_X15(i6*8); \ - VPINSRQ_1_SI_X12(i1*8); \ - VPINSRQ_1_SI_X13(i3*8); \ - VPINSRQ_1_SI_X14(i5*8); \ - VPINSRQ_1_SI_X15(i7*8) - -// load msg: X12 = (0, 2), X13 = (4, 6), X14 = (1, 3), X15 = (5, 7) -#define LOAD_MSG_AVX_0_2_4_6_1_3_5_7() \ - VMOVQ_SI_X12_0; \ - VMOVQ_SI_X13(4*8); \ - VMOVQ_SI_X14(1*8); \ - VMOVQ_SI_X15(5*8); \ - VPINSRQ_1_SI_X12(2*8); \ - VPINSRQ_1_SI_X13(6*8); \ - VPINSRQ_1_SI_X14(3*8); \ - VPINSRQ_1_SI_X15(7*8) - -// load msg: X12 = (1, 0), X13 = (11, 5), X14 = (12, 2), X15 = (7, 3) -#define LOAD_MSG_AVX_1_0_11_5_12_2_7_3() \ - VPSHUFD $0x4E, 0*8(SI), X12; \ - VMOVQ_SI_X13(11*8); \ - VMOVQ_SI_X14(12*8); \ - VMOVQ_SI_X15(7*8); \ - VPINSRQ_1_SI_X13(5*8); \ - VPINSRQ_1_SI_X14(2*8); \ - VPINSRQ_1_SI_X15(3*8) - -// load msg: X12 = (11, 12), X13 = (5, 15), X14 = (8, 0), X15 = (2, 13) -#define LOAD_MSG_AVX_11_12_5_15_8_0_2_13() \ - VMOVDQU 11*8(SI), X12; \ - VMOVQ_SI_X13(5*8); \ - VMOVQ_SI_X14(8*8); \ - VMOVQ_SI_X15(2*8); \ - VPINSRQ_1_SI_X13(15*8); \ - VPINSRQ_1_SI_X14_0; \ - VPINSRQ_1_SI_X15(13*8) - -// load msg: X12 = (2, 5), X13 = (4, 15), X14 = (6, 10), X15 = (0, 8) -#define LOAD_MSG_AVX_2_5_4_15_6_10_0_8() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X13(4*8); \ - VMOVQ_SI_X14(6*8); \ - VMOVQ_SI_X15_0; \ - VPINSRQ_1_SI_X12(5*8); \ - VPINSRQ_1_SI_X13(15*8); \ - VPINSRQ_1_SI_X14(10*8); \ - VPINSRQ_1_SI_X15(8*8) - -// load msg: X12 = (9, 5), X13 = (2, 10), X14 = (0, 7), X15 = (4, 15) -#define LOAD_MSG_AVX_9_5_2_10_0_7_4_15() \ - VMOVQ_SI_X12(9*8); \ - VMOVQ_SI_X13(2*8); \ - VMOVQ_SI_X14_0; \ - VMOVQ_SI_X15(4*8); \ - VPINSRQ_1_SI_X12(5*8); \ - VPINSRQ_1_SI_X13(10*8); \ - VPINSRQ_1_SI_X14(7*8); \ - VPINSRQ_1_SI_X15(15*8) - -// load msg: X12 = (2, 6), X13 = (0, 8), X14 = (12, 10), X15 = (11, 3) -#define LOAD_MSG_AVX_2_6_0_8_12_10_11_3() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X13_0; \ - VMOVQ_SI_X14(12*8); \ - VMOVQ_SI_X15(11*8); \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X13(8*8); \ - VPINSRQ_1_SI_X14(10*8); \ - VPINSRQ_1_SI_X15(3*8) - -// load msg: X12 = (0, 6), X13 = (9, 8), X14 = (7, 3), X15 = (2, 11) -#define LOAD_MSG_AVX_0_6_9_8_7_3_2_11() \ - MOVQ 0*8(SI), X12; \ - VPSHUFD $0x4E, 8*8(SI), X13; \ - MOVQ 7*8(SI), X14; \ - MOVQ 2*8(SI), X15; \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X14(3*8); \ - VPINSRQ_1_SI_X15(11*8) - -// load msg: X12 = (6, 14), X13 = (11, 0), X14 = (15, 9), X15 = (3, 8) -#define LOAD_MSG_AVX_6_14_11_0_15_9_3_8() \ - MOVQ 6*8(SI), X12; \ - MOVQ 11*8(SI), X13; \ - MOVQ 15*8(SI), X14; \ - MOVQ 3*8(SI), X15; \ - VPINSRQ_1_SI_X12(14*8); \ - VPINSRQ_1_SI_X13_0; \ - VPINSRQ_1_SI_X14(9*8); \ - VPINSRQ_1_SI_X15(8*8) - -// load msg: X12 = (5, 15), X13 = (8, 2), X14 = (0, 4), X15 = (6, 10) -#define LOAD_MSG_AVX_5_15_8_2_0_4_6_10() \ - MOVQ 5*8(SI), X12; \ - MOVQ 8*8(SI), X13; \ - MOVQ 0*8(SI), X14; \ - MOVQ 6*8(SI), X15; \ - VPINSRQ_1_SI_X12(15*8); \ - VPINSRQ_1_SI_X13(2*8); \ - VPINSRQ_1_SI_X14(4*8); \ - VPINSRQ_1_SI_X15(10*8) - -// load msg: X12 = (12, 13), X13 = (1, 10), X14 = (2, 7), X15 = (4, 5) -#define LOAD_MSG_AVX_12_13_1_10_2_7_4_5() \ - VMOVDQU 12*8(SI), X12; \ - MOVQ 1*8(SI), X13; \ - MOVQ 2*8(SI), X14; \ - VPINSRQ_1_SI_X13(10*8); \ - VPINSRQ_1_SI_X14(7*8); \ - VMOVDQU 4*8(SI), X15 - -// load msg: X12 = (15, 9), X13 = (3, 13), X14 = (11, 14), X15 = (12, 0) -#define LOAD_MSG_AVX_15_9_3_13_11_14_12_0() \ - MOVQ 15*8(SI), X12; \ - MOVQ 3*8(SI), X13; \ - MOVQ 11*8(SI), X14; \ - MOVQ 12*8(SI), X15; \ - VPINSRQ_1_SI_X12(9*8); \ - VPINSRQ_1_SI_X13(13*8); \ - VPINSRQ_1_SI_X14(14*8); \ - VPINSRQ_1_SI_X15_0 - -// func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksAVX(SB), 4, $288-48 // frame size = 272 + 16 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, R10 - ADDQ $15, R10 - ANDQ $~15, R10 - - VMOVDQU ·AVX_c40<>(SB), X0 - VMOVDQU ·AVX_c48<>(SB), X1 - VMOVDQA X0, X8 - VMOVDQA X1, X9 - - VMOVDQU ·AVX_iv3<>(SB), X0 - VMOVDQA X0, 0(R10) - XORQ CX, 0(R10) // 0(R10) = ·AVX_iv3 ^ (CX || 0) - - VMOVDQU 0(AX), X10 - VMOVDQU 16(AX), X11 - VMOVDQU 32(AX), X2 - VMOVDQU 48(AX), X3 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - -loop: - ADDQ $128, R8 - CMPQ R8, $128 - JGE noinc - INCQ R9 - -noinc: - VMOVQ_R8_X15 - VPINSRQ_1_R9_X15 - - VMOVDQA X10, X0 - VMOVDQA X11, X1 - VMOVDQU ·AVX_iv0<>(SB), X4 - VMOVDQU ·AVX_iv1<>(SB), X5 - VMOVDQU ·AVX_iv2<>(SB), X6 - - VPXOR X15, X6, X6 - VMOVDQA 0(R10), X7 - - LOAD_MSG_AVX_0_2_4_6_1_3_5_7() - VMOVDQA X12, 16(R10) - VMOVDQA X13, 32(R10) - VMOVDQA X14, 48(R10) - VMOVDQA X15, 64(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(8, 10, 12, 14, 9, 11, 13, 15) - VMOVDQA X12, 80(R10) - VMOVDQA X13, 96(R10) - VMOVDQA X14, 112(R10) - VMOVDQA X15, 128(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(14, 4, 9, 13, 10, 8, 15, 6) - VMOVDQA X12, 144(R10) - VMOVDQA X13, 160(R10) - VMOVDQA X14, 176(R10) - VMOVDQA X15, 192(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_1_0_11_5_12_2_7_3() - VMOVDQA X12, 208(R10) - VMOVDQA X13, 224(R10) - VMOVDQA X14, 240(R10) - VMOVDQA X15, 256(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_11_12_5_15_8_0_2_13() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(10, 3, 7, 9, 14, 6, 1, 4) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(7, 3, 13, 11, 9, 1, 12, 14) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_2_5_4_15_6_10_0_8() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_9_5_2_10_0_7_4_15() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(14, 11, 6, 3, 1, 12, 8, 13) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_2_6_0_8_12_10_11_3() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(4, 7, 15, 1, 13, 5, 14, 9) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(12, 1, 14, 4, 5, 15, 13, 10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_0_6_9_8_7_3_2_11() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(13, 7, 12, 3, 11, 14, 1, 9) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_5_15_8_2_0_4_6_10() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_6_14_11_0_15_9_3_8() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_12_13_1_10_2_7_4_5() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(10, 8, 7, 1, 2, 4, 6, 5) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_15_9_3_13_11_14_12_0() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 16(R10), 32(R10), 48(R10), 64(R10), X15, X8, X9) - SHUFFLE_AVX() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 80(R10), 96(R10), 112(R10), 128(R10), X15, X8, X9) - SHUFFLE_AVX_INV() - - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 144(R10), 160(R10), 176(R10), 192(R10), X15, X8, X9) - SHUFFLE_AVX() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 208(R10), 224(R10), 240(R10), 256(R10), X15, X8, X9) - SHUFFLE_AVX_INV() - - VMOVDQU 32(AX), X14 - VMOVDQU 48(AX), X15 - VPXOR X0, X10, X10 - VPXOR X1, X11, X11 - VPXOR X2, X14, X14 - VPXOR X3, X15, X15 - VPXOR X4, X10, X10 - VPXOR X5, X11, X11 - VPXOR X6, X14, X2 - VPXOR X7, X15, X3 - VMOVDQU X2, 32(AX) - VMOVDQU X3, 48(AX) - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - VMOVDQU X10, 0(AX) - VMOVDQU X11, 16(AX) - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - VZEROUPPER - - RET diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go deleted file mode 100644 index 5fa1b3284..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.7 && amd64 && gc && !purego -// +build !go1.7,amd64,gc,!purego - -package blake2b - -import "golang.org/x/sys/cpu" - -func init() { - useSSE4 = cpu.X86.HasSSE41 -} - -//go:noescape -func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - if useSSE4 { - hashBlocksSSE4(h, c, flag, blocks) - } else { - hashBlocksGeneric(h, c, flag, blocks) - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s deleted file mode 100644 index ae75eb9af..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build amd64 && gc && !purego -// +build amd64,gc,!purego - -#include "textflag.h" - -DATA ·iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -GLOBL ·iv0<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b -DATA ·iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·iv1<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv2<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -GLOBL ·iv2<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b -DATA ·iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 -GLOBL ·iv3<>(SB), (NOPTR+RODATA), $16 - -DATA ·c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·c40<>(SB), (NOPTR+RODATA), $16 - -DATA ·c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·c48<>(SB), (NOPTR+RODATA), $16 - -#define SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v6, t1; \ - PUNPCKLQDQ v6, t2; \ - PUNPCKHQDQ v7, v6; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ v7, t2; \ - MOVO t1, v7; \ - MOVO v2, t1; \ - PUNPCKHQDQ t2, v7; \ - PUNPCKLQDQ v3, t2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v3 - -#define SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v2, t1; \ - PUNPCKLQDQ v2, t2; \ - PUNPCKHQDQ v3, v2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ v3, t2; \ - MOVO t1, v3; \ - MOVO v6, t1; \ - PUNPCKHQDQ t2, v3; \ - PUNPCKLQDQ v7, t2; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v7 - -#define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ - PADDQ m0, v0; \ - PADDQ m1, v1; \ - PADDQ v2, v0; \ - PADDQ v3, v1; \ - PXOR v0, v6; \ - PXOR v1, v7; \ - PSHUFD $0xB1, v6, v6; \ - PSHUFD $0xB1, v7, v7; \ - PADDQ v6, v4; \ - PADDQ v7, v5; \ - PXOR v4, v2; \ - PXOR v5, v3; \ - PSHUFB c40, v2; \ - PSHUFB c40, v3; \ - PADDQ m2, v0; \ - PADDQ m3, v1; \ - PADDQ v2, v0; \ - PADDQ v3, v1; \ - PXOR v0, v6; \ - PXOR v1, v7; \ - PSHUFB c48, v6; \ - PSHUFB c48, v7; \ - PADDQ v6, v4; \ - PADDQ v7, v5; \ - PXOR v4, v2; \ - PXOR v5, v3; \ - MOVOU v2, t0; \ - PADDQ v2, t0; \ - PSRLQ $63, v2; \ - PXOR t0, v2; \ - MOVOU v3, t0; \ - PADDQ v3, t0; \ - PSRLQ $63, v3; \ - PXOR t0, v3 - -#define LOAD_MSG(m0, m1, m2, m3, src, i0, i1, i2, i3, i4, i5, i6, i7) \ - MOVQ i0*8(src), m0; \ - PINSRQ $1, i1*8(src), m0; \ - MOVQ i2*8(src), m1; \ - PINSRQ $1, i3*8(src), m1; \ - MOVQ i4*8(src), m2; \ - PINSRQ $1, i5*8(src), m2; \ - MOVQ i6*8(src), m3; \ - PINSRQ $1, i7*8(src), m3 - -// func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksSSE4(SB), 4, $288-48 // frame size = 272 + 16 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, R10 - ADDQ $15, R10 - ANDQ $~15, R10 - - MOVOU ·iv3<>(SB), X0 - MOVO X0, 0(R10) - XORQ CX, 0(R10) // 0(R10) = ·iv3 ^ (CX || 0) - - MOVOU ·c40<>(SB), X13 - MOVOU ·c48<>(SB), X14 - - MOVOU 0(AX), X12 - MOVOU 16(AX), X15 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - -loop: - ADDQ $128, R8 - CMPQ R8, $128 - JGE noinc - INCQ R9 - -noinc: - MOVQ R8, X8 - PINSRQ $1, R9, X8 - - MOVO X12, X0 - MOVO X15, X1 - MOVOU 32(AX), X2 - MOVOU 48(AX), X3 - MOVOU ·iv0<>(SB), X4 - MOVOU ·iv1<>(SB), X5 - MOVOU ·iv2<>(SB), X6 - - PXOR X8, X6 - MOVO 0(R10), X7 - - LOAD_MSG(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7) - MOVO X8, 16(R10) - MOVO X9, 32(R10) - MOVO X10, 48(R10) - MOVO X11, 64(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 8, 10, 12, 14, 9, 11, 13, 15) - MOVO X8, 80(R10) - MOVO X9, 96(R10) - MOVO X10, 112(R10) - MOVO X11, 128(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6) - MOVO X8, 144(R10) - MOVO X9, 160(R10) - MOVO X10, 176(R10) - MOVO X11, 192(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 1, 0, 11, 5, 12, 2, 7, 3) - MOVO X8, 208(R10) - MOVO X9, 224(R10) - MOVO X10, 240(R10) - MOVO X11, 256(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 10, 3, 7, 9, 14, 6, 1, 4) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 2, 5, 4, 15, 6, 10, 0, 8) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 14, 11, 6, 3, 1, 12, 8, 13) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 4, 7, 15, 1, 13, 5, 14, 9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 0, 6, 9, 8, 7, 3, 2, 11) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 5, 15, 8, 2, 0, 4, 6, 10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 12, 13, 1, 10, 2, 7, 4, 5) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 15, 9, 3, 13, 11, 14, 12, 0) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 16(R10), 32(R10), 48(R10), 64(R10), X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 80(R10), 96(R10), 112(R10), 128(R10), X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 144(R10), 160(R10), 176(R10), 192(R10), X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 208(R10), 224(R10), 240(R10), 256(R10), X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - MOVOU 32(AX), X10 - MOVOU 48(AX), X11 - PXOR X0, X12 - PXOR X1, X15 - PXOR X2, X10 - PXOR X3, X11 - PXOR X4, X12 - PXOR X5, X15 - PXOR X6, X10 - PXOR X7, X11 - MOVOU X10, 32(AX) - MOVOU X11, 48(AX) - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - MOVOU X12, 0(AX) - MOVOU X15, 16(AX) - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - - RET diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go b/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go deleted file mode 100644 index 3168a8aa3..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package blake2b - -import ( - "encoding/binary" - "math/bits" -) - -// the precomputed values for BLAKE2b -// there are 12 16-byte arrays - one for each round -// the entries are calculated from the sigma constants. -var precomputed = [12][16]byte{ - {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, - {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, - {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, - {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, - {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, - {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, - {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, - {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, - {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, - {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, - {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, // equal to the first - {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, // equal to the second -} - -func hashBlocksGeneric(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - var m [16]uint64 - c0, c1 := c[0], c[1] - - for i := 0; i < len(blocks); { - c0 += BlockSize - if c0 < BlockSize { - c1++ - } - - v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] - v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] - v12 ^= c0 - v13 ^= c1 - v14 ^= flag - - for j := range m { - m[j] = binary.LittleEndian.Uint64(blocks[i:]) - i += 8 - } - - for j := range precomputed { - s := &(precomputed[j]) - - v0 += m[s[0]] - v0 += v4 - v12 ^= v0 - v12 = bits.RotateLeft64(v12, -32) - v8 += v12 - v4 ^= v8 - v4 = bits.RotateLeft64(v4, -24) - v1 += m[s[1]] - v1 += v5 - v13 ^= v1 - v13 = bits.RotateLeft64(v13, -32) - v9 += v13 - v5 ^= v9 - v5 = bits.RotateLeft64(v5, -24) - v2 += m[s[2]] - v2 += v6 - v14 ^= v2 - v14 = bits.RotateLeft64(v14, -32) - v10 += v14 - v6 ^= v10 - v6 = bits.RotateLeft64(v6, -24) - v3 += m[s[3]] - v3 += v7 - v15 ^= v3 - v15 = bits.RotateLeft64(v15, -32) - v11 += v15 - v7 ^= v11 - v7 = bits.RotateLeft64(v7, -24) - - v0 += m[s[4]] - v0 += v4 - v12 ^= v0 - v12 = bits.RotateLeft64(v12, -16) - v8 += v12 - v4 ^= v8 - v4 = bits.RotateLeft64(v4, -63) - v1 += m[s[5]] - v1 += v5 - v13 ^= v1 - v13 = bits.RotateLeft64(v13, -16) - v9 += v13 - v5 ^= v9 - v5 = bits.RotateLeft64(v5, -63) - v2 += m[s[6]] - v2 += v6 - v14 ^= v2 - v14 = bits.RotateLeft64(v14, -16) - v10 += v14 - v6 ^= v10 - v6 = bits.RotateLeft64(v6, -63) - v3 += m[s[7]] - v3 += v7 - v15 ^= v3 - v15 = bits.RotateLeft64(v15, -16) - v11 += v15 - v7 ^= v11 - v7 = bits.RotateLeft64(v7, -63) - - v0 += m[s[8]] - v0 += v5 - v15 ^= v0 - v15 = bits.RotateLeft64(v15, -32) - v10 += v15 - v5 ^= v10 - v5 = bits.RotateLeft64(v5, -24) - v1 += m[s[9]] - v1 += v6 - v12 ^= v1 - v12 = bits.RotateLeft64(v12, -32) - v11 += v12 - v6 ^= v11 - v6 = bits.RotateLeft64(v6, -24) - v2 += m[s[10]] - v2 += v7 - v13 ^= v2 - v13 = bits.RotateLeft64(v13, -32) - v8 += v13 - v7 ^= v8 - v7 = bits.RotateLeft64(v7, -24) - v3 += m[s[11]] - v3 += v4 - v14 ^= v3 - v14 = bits.RotateLeft64(v14, -32) - v9 += v14 - v4 ^= v9 - v4 = bits.RotateLeft64(v4, -24) - - v0 += m[s[12]] - v0 += v5 - v15 ^= v0 - v15 = bits.RotateLeft64(v15, -16) - v10 += v15 - v5 ^= v10 - v5 = bits.RotateLeft64(v5, -63) - v1 += m[s[13]] - v1 += v6 - v12 ^= v1 - v12 = bits.RotateLeft64(v12, -16) - v11 += v12 - v6 ^= v11 - v6 = bits.RotateLeft64(v6, -63) - v2 += m[s[14]] - v2 += v7 - v13 ^= v2 - v13 = bits.RotateLeft64(v13, -16) - v8 += v13 - v7 ^= v8 - v7 = bits.RotateLeft64(v7, -63) - v3 += m[s[15]] - v3 += v4 - v14 ^= v3 - v14 = bits.RotateLeft64(v14, -16) - v9 += v14 - v4 ^= v9 - v4 = bits.RotateLeft64(v4, -63) - - } - - h[0] ^= v0 ^ v8 - h[1] ^= v1 ^ v9 - h[2] ^= v2 ^ v10 - h[3] ^= v3 ^ v11 - h[4] ^= v4 ^ v12 - h[5] ^= v5 ^ v13 - h[6] ^= v6 ^ v14 - h[7] ^= v7 ^ v15 - } - c[0], c[1] = c0, c1 -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go b/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go deleted file mode 100644 index b0137cdf0..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !amd64 || purego || !gc -// +build !amd64 purego !gc - -package blake2b - -func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - hashBlocksGeneric(h, c, flag, blocks) -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2x.go b/vendor/golang.org/x/crypto/blake2b/blake2x.go deleted file mode 100644 index 52c414db0..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2x.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package blake2b - -import ( - "encoding/binary" - "errors" - "io" -) - -// XOF defines the interface to hash functions that -// support arbitrary-length output. -type XOF interface { - // Write absorbs more data into the hash's state. It panics if called - // after Read. - io.Writer - - // Read reads more output from the hash. It returns io.EOF if the limit - // has been reached. - io.Reader - - // Clone returns a copy of the XOF in its current state. - Clone() XOF - - // Reset resets the XOF to its initial state. - Reset() -} - -// OutputLengthUnknown can be used as the size argument to NewXOF to indicate -// the length of the output is not known in advance. -const OutputLengthUnknown = 0 - -// magicUnknownOutputLength is a magic value for the output size that indicates -// an unknown number of output bytes. -const magicUnknownOutputLength = (1 << 32) - 1 - -// maxOutputLength is the absolute maximum number of bytes to produce when the -// number of output bytes is unknown. -const maxOutputLength = (1 << 32) * 64 - -// NewXOF creates a new variable-output-length hash. The hash either produce a -// known number of bytes (1 <= size < 2**32-1), or an unknown number of bytes -// (size == OutputLengthUnknown). In the latter case, an absolute limit of -// 256GiB applies. -// -// A non-nil key turns the hash into a MAC. The key must between -// zero and 32 bytes long. -func NewXOF(size uint32, key []byte) (XOF, error) { - if len(key) > Size { - return nil, errKeySize - } - if size == magicUnknownOutputLength { - // 2^32-1 indicates an unknown number of bytes and thus isn't a - // valid length. - return nil, errors.New("blake2b: XOF length too large") - } - if size == OutputLengthUnknown { - size = magicUnknownOutputLength - } - x := &xof{ - d: digest{ - size: Size, - keyLen: len(key), - }, - length: size, - } - copy(x.d.key[:], key) - x.Reset() - return x, nil -} - -type xof struct { - d digest - length uint32 - remaining uint64 - cfg, root, block [Size]byte - offset int - nodeOffset uint32 - readMode bool -} - -func (x *xof) Write(p []byte) (n int, err error) { - if x.readMode { - panic("blake2b: write to XOF after read") - } - return x.d.Write(p) -} - -func (x *xof) Clone() XOF { - clone := *x - return &clone -} - -func (x *xof) Reset() { - x.cfg[0] = byte(Size) - binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length - binary.LittleEndian.PutUint32(x.cfg[12:], x.length) // XOF length - x.cfg[17] = byte(Size) // inner hash size - - x.d.Reset() - x.d.h[1] ^= uint64(x.length) << 32 - - x.remaining = uint64(x.length) - if x.remaining == magicUnknownOutputLength { - x.remaining = maxOutputLength - } - x.offset, x.nodeOffset = 0, 0 - x.readMode = false -} - -func (x *xof) Read(p []byte) (n int, err error) { - if !x.readMode { - x.d.finalize(&x.root) - x.readMode = true - } - - if x.remaining == 0 { - return 0, io.EOF - } - - n = len(p) - if uint64(n) > x.remaining { - n = int(x.remaining) - p = p[:n] - } - - if x.offset > 0 { - blockRemaining := Size - x.offset - if n < blockRemaining { - x.offset += copy(p, x.block[x.offset:]) - x.remaining -= uint64(n) - return - } - copy(p, x.block[x.offset:]) - p = p[blockRemaining:] - x.offset = 0 - x.remaining -= uint64(blockRemaining) - } - - for len(p) >= Size { - binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) - x.nodeOffset++ - - x.d.initConfig(&x.cfg) - x.d.Write(x.root[:]) - x.d.finalize(&x.block) - - copy(p, x.block[:]) - p = p[Size:] - x.remaining -= uint64(Size) - } - - if todo := len(p); todo > 0 { - if x.remaining < uint64(Size) { - x.cfg[0] = byte(x.remaining) - } - binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) - x.nodeOffset++ - - x.d.initConfig(&x.cfg) - x.d.Write(x.root[:]) - x.d.finalize(&x.block) - - x.offset = copy(p, x.block[:todo]) - x.remaining -= uint64(todo) - } - return -} - -func (d *digest) initConfig(cfg *[Size]byte) { - d.offset, d.c[0], d.c[1] = 0, 0, 0 - for i := range d.h { - d.h[i] = iv[i] ^ binary.LittleEndian.Uint64(cfg[i*8:]) - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/register.go b/vendor/golang.org/x/crypto/blake2b/register.go deleted file mode 100644 index 9d8633963..000000000 --- a/vendor/golang.org/x/crypto/blake2b/register.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.9 -// +build go1.9 - -package blake2b - -import ( - "crypto" - "hash" -) - -func init() { - newHash256 := func() hash.Hash { - h, _ := New256(nil) - return h - } - newHash384 := func() hash.Hash { - h, _ := New384(nil) - return h - } - - newHash512 := func() hash.Hash { - h, _ := New512(nil) - return h - } - - crypto.RegisterHash(crypto.BLAKE2b_256, newHash256) - crypto.RegisterHash(crypto.BLAKE2b_384, newHash384) - crypto.RegisterHash(crypto.BLAKE2b_512, newHash512) -} diff --git a/vendor/golang.org/x/crypto/cryptobyte/asn1.go b/vendor/golang.org/x/crypto/cryptobyte/asn1.go deleted file mode 100644 index 6fc2838a3..000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/asn1.go +++ /dev/null @@ -1,824 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cryptobyte - -import ( - encoding_asn1 "encoding/asn1" - "fmt" - "math/big" - "reflect" - "time" - - "golang.org/x/crypto/cryptobyte/asn1" -) - -// This file contains ASN.1-related methods for String and Builder. - -// Builder - -// AddASN1Int64 appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1Int64(v int64) { - b.addASN1Signed(asn1.INTEGER, v) -} - -// AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the -// given tag. -func (b *Builder) AddASN1Int64WithTag(v int64, tag asn1.Tag) { - b.addASN1Signed(tag, v) -} - -// AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION. -func (b *Builder) AddASN1Enum(v int64) { - b.addASN1Signed(asn1.ENUM, v) -} - -func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) { - b.AddASN1(tag, func(c *Builder) { - length := 1 - for i := v; i >= 0x80 || i < -0x80; i >>= 8 { - length++ - } - - for ; length > 0; length-- { - i := v >> uint((length-1)*8) & 0xff - c.AddUint8(uint8(i)) - } - }) -} - -// AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1Uint64(v uint64) { - b.AddASN1(asn1.INTEGER, func(c *Builder) { - length := 1 - for i := v; i >= 0x80; i >>= 8 { - length++ - } - - for ; length > 0; length-- { - i := v >> uint((length-1)*8) & 0xff - c.AddUint8(uint8(i)) - } - }) -} - -// AddASN1BigInt appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1BigInt(n *big.Int) { - if b.err != nil { - return - } - - b.AddASN1(asn1.INTEGER, func(c *Builder) { - if n.Sign() < 0 { - // A negative number has to be converted to two's-complement form. So we - // invert and subtract 1. If the most-significant-bit isn't set then - // we'll need to pad the beginning with 0xff in order to keep the number - // negative. - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bytes := nMinus1.Bytes() - for i := range bytes { - bytes[i] ^= 0xff - } - if len(bytes) == 0 || bytes[0]&0x80 == 0 { - c.add(0xff) - } - c.add(bytes...) - } else if n.Sign() == 0 { - c.add(0) - } else { - bytes := n.Bytes() - if bytes[0]&0x80 != 0 { - c.add(0) - } - c.add(bytes...) - } - }) -} - -// AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING. -func (b *Builder) AddASN1OctetString(bytes []byte) { - b.AddASN1(asn1.OCTET_STRING, func(c *Builder) { - c.AddBytes(bytes) - }) -} - -const generalizedTimeFormatStr = "20060102150405Z0700" - -// AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME. -func (b *Builder) AddASN1GeneralizedTime(t time.Time) { - if t.Year() < 0 || t.Year() > 9999 { - b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t) - return - } - b.AddASN1(asn1.GeneralizedTime, func(c *Builder) { - c.AddBytes([]byte(t.Format(generalizedTimeFormatStr))) - }) -} - -// AddASN1UTCTime appends a DER-encoded ASN.1 UTCTime. -func (b *Builder) AddASN1UTCTime(t time.Time) { - b.AddASN1(asn1.UTCTime, func(c *Builder) { - // As utilized by the X.509 profile, UTCTime can only - // represent the years 1950 through 2049. - if t.Year() < 1950 || t.Year() >= 2050 { - b.err = fmt.Errorf("cryptobyte: cannot represent %v as a UTCTime", t) - return - } - c.AddBytes([]byte(t.Format(defaultUTCTimeFormatStr))) - }) -} - -// AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not -// support BIT STRINGs that are not a whole number of bytes. -func (b *Builder) AddASN1BitString(data []byte) { - b.AddASN1(asn1.BIT_STRING, func(b *Builder) { - b.AddUint8(0) - b.AddBytes(data) - }) -} - -func (b *Builder) addBase128Int(n int64) { - var length int - if n == 0 { - length = 1 - } else { - for i := n; i > 0; i >>= 7 { - length++ - } - } - - for i := length - 1; i >= 0; i-- { - o := byte(n >> uint(i*7)) - o &= 0x7f - if i != 0 { - o |= 0x80 - } - - b.add(o) - } -} - -func isValidOID(oid encoding_asn1.ObjectIdentifier) bool { - if len(oid) < 2 { - return false - } - - if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) { - return false - } - - for _, v := range oid { - if v < 0 { - return false - } - } - - return true -} - -func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) { - b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) { - if !isValidOID(oid) { - b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid) - return - } - - b.addBase128Int(int64(oid[0])*40 + int64(oid[1])) - for _, v := range oid[2:] { - b.addBase128Int(int64(v)) - } - }) -} - -func (b *Builder) AddASN1Boolean(v bool) { - b.AddASN1(asn1.BOOLEAN, func(b *Builder) { - if v { - b.AddUint8(0xff) - } else { - b.AddUint8(0) - } - }) -} - -func (b *Builder) AddASN1NULL() { - b.add(uint8(asn1.NULL), 0) -} - -// MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if -// successful or records an error if one occurred. -func (b *Builder) MarshalASN1(v interface{}) { - // NOTE(martinkr): This is somewhat of a hack to allow propagation of - // encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a - // value embedded into a struct, its tag information is lost. - if b.err != nil { - return - } - bytes, err := encoding_asn1.Marshal(v) - if err != nil { - b.err = err - return - } - b.AddBytes(bytes) -} - -// AddASN1 appends an ASN.1 object. The object is prefixed with the given tag. -// Tags greater than 30 are not supported and result in an error (i.e. -// low-tag-number form only). The child builder passed to the -// BuilderContinuation can be used to build the content of the ASN.1 object. -func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) { - if b.err != nil { - return - } - // Identifiers with the low five bits set indicate high-tag-number format - // (two or more octets), which we don't support. - if tag&0x1f == 0x1f { - b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag) - return - } - b.AddUint8(uint8(tag)) - b.addLengthPrefixed(1, true, f) -} - -// String - -// ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean -// representation into out and advances. It reports whether the read -// was successful. -func (s *String) ReadASN1Boolean(out *bool) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.BOOLEAN) || len(bytes) != 1 { - return false - } - - switch bytes[0] { - case 0: - *out = false - case 0xff: - *out = true - default: - return false - } - - return true -} - -// ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does -// not point to an integer, to a big.Int, or to a []byte it panics. Only -// positive and zero values can be decoded into []byte, and they are returned as -// big-endian binary values that share memory with s. Positive values will have -// no leading zeroes, and zero will be returned as a single zero byte. -// ReadASN1Integer reports whether the read was successful. -func (s *String) ReadASN1Integer(out interface{}) bool { - switch out := out.(type) { - case *int, *int8, *int16, *int32, *int64: - var i int64 - if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) { - return false - } - reflect.ValueOf(out).Elem().SetInt(i) - return true - case *uint, *uint8, *uint16, *uint32, *uint64: - var u uint64 - if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) { - return false - } - reflect.ValueOf(out).Elem().SetUint(u) - return true - case *big.Int: - return s.readASN1BigInt(out) - case *[]byte: - return s.readASN1Bytes(out) - default: - panic("out does not point to an integer type") - } -} - -func checkASN1Integer(bytes []byte) bool { - if len(bytes) == 0 { - // An INTEGER is encoded with at least one octet. - return false - } - if len(bytes) == 1 { - return true - } - if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 { - // Value is not minimally encoded. - return false - } - return true -} - -var bigOne = big.NewInt(1) - -func (s *String) readASN1BigInt(out *big.Int) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) { - return false - } - if bytes[0]&0x80 == 0x80 { - // Negative number. - neg := make([]byte, len(bytes)) - for i, b := range bytes { - neg[i] = ^b - } - out.SetBytes(neg) - out.Add(out, bigOne) - out.Neg(out) - } else { - out.SetBytes(bytes) - } - return true -} - -func (s *String) readASN1Bytes(out *[]byte) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) { - return false - } - if bytes[0]&0x80 == 0x80 { - return false - } - for len(bytes) > 1 && bytes[0] == 0 { - bytes = bytes[1:] - } - *out = bytes - return true -} - -func (s *String) readASN1Int64(out *int64) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) { - return false - } - return true -} - -func asn1Signed(out *int64, n []byte) bool { - length := len(n) - if length > 8 { - return false - } - for i := 0; i < length; i++ { - *out <<= 8 - *out |= int64(n[i]) - } - // Shift up and down in order to sign extend the result. - *out <<= 64 - uint8(length)*8 - *out >>= 64 - uint8(length)*8 - return true -} - -func (s *String) readASN1Uint64(out *uint64) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) { - return false - } - return true -} - -func asn1Unsigned(out *uint64, n []byte) bool { - length := len(n) - if length > 9 || length == 9 && n[0] != 0 { - // Too large for uint64. - return false - } - if n[0]&0x80 != 0 { - // Negative number. - return false - } - for i := 0; i < length; i++ { - *out <<= 8 - *out |= uint64(n[i]) - } - return true -} - -// ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out -// and advances. It reports whether the read was successful and resulted in a -// value that can be represented in an int64. -func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool { - var bytes String - return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes) -} - -// ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports -// whether the read was successful. -func (s *String) ReadASN1Enum(out *int) bool { - var bytes String - var i int64 - if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) { - return false - } - if int64(int(i)) != i { - return false - } - *out = int(i) - return true -} - -func (s *String) readBase128Int(out *int) bool { - ret := 0 - for i := 0; len(*s) > 0; i++ { - if i == 5 { - return false - } - // Avoid overflowing int on a 32-bit platform. - // We don't want different behavior based on the architecture. - if ret >= 1<<(31-7) { - return false - } - ret <<= 7 - b := s.read(1)[0] - - // ITU-T X.690, section 8.19.2: - // The subidentifier shall be encoded in the fewest possible octets, - // that is, the leading octet of the subidentifier shall not have the value 0x80. - if i == 0 && b == 0x80 { - return false - } - - ret |= int(b & 0x7f) - if b&0x80 == 0 { - *out = ret - return true - } - } - return false // truncated -} - -// ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and -// advances. It reports whether the read was successful. -func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 { - return false - } - - // In the worst case, we get two elements from the first byte (which is - // encoded differently) and then every varint is a single byte long. - components := make([]int, len(bytes)+1) - - // The first varint is 40*value1 + value2: - // According to this packing, value1 can take the values 0, 1 and 2 only. - // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, - // then there are no restrictions on value2. - var v int - if !bytes.readBase128Int(&v) { - return false - } - if v < 80 { - components[0] = v / 40 - components[1] = v % 40 - } else { - components[0] = 2 - components[1] = v - 80 - } - - i := 2 - for ; len(bytes) > 0; i++ { - if !bytes.readBase128Int(&v) { - return false - } - components[i] = v - } - *out = components[:i] - return true -} - -// ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and -// advances. It reports whether the read was successful. -func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.GeneralizedTime) { - return false - } - t := string(bytes) - res, err := time.Parse(generalizedTimeFormatStr, t) - if err != nil { - return false - } - if serialized := res.Format(generalizedTimeFormatStr); serialized != t { - return false - } - *out = res - return true -} - -const defaultUTCTimeFormatStr = "060102150405Z0700" - -// ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances. -// It reports whether the read was successful. -func (s *String) ReadASN1UTCTime(out *time.Time) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.UTCTime) { - return false - } - t := string(bytes) - - formatStr := defaultUTCTimeFormatStr - var err error - res, err := time.Parse(formatStr, t) - if err != nil { - // Fallback to minute precision if we can't parse second - // precision. If we are following X.509 or X.690 we shouldn't - // support this, but we do. - formatStr = "0601021504Z0700" - res, err = time.Parse(formatStr, t) - } - if err != nil { - return false - } - - if serialized := res.Format(formatStr); serialized != t { - return false - } - - if res.Year() >= 2050 { - // UTCTime interprets the low order digits 50-99 as 1950-99. - // This only applies to its use in the X.509 profile. - // See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 - res = res.AddDate(-100, 0, 0) - } - *out = res - return true -} - -// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. -// It reports whether the read was successful. -func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 || - len(bytes)*8/8 != len(bytes) { - return false - } - - paddingBits := bytes[0] - bytes = bytes[1:] - if paddingBits > 7 || - len(bytes) == 0 && paddingBits != 0 || - len(bytes) > 0 && bytes[len(bytes)-1]&(1< 4 || len(*s) < int(2+lenLen) { - return false - } - - lenBytes := String((*s)[2 : 2+lenLen]) - if !lenBytes.readUnsigned(&len32, int(lenLen)) { - return false - } - - // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length - // with the minimum number of octets. - if len32 < 128 { - // Length should have used short-form encoding. - return false - } - if len32>>((lenLen-1)*8) == 0 { - // Leading octet is 0. Length should have been at least one byte shorter. - return false - } - - headerLen = 2 + uint32(lenLen) - if headerLen+len32 < len32 { - // Overflow. - return false - } - length = headerLen + len32 - } - - if int(length) < 0 || !s.ReadBytes((*[]byte)(out), int(length)) { - return false - } - if skipHeader && !out.Skip(int(headerLen)) { - panic("cryptobyte: internal error") - } - - return true -} diff --git a/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go b/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go deleted file mode 100644 index cda8e3edf..000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package asn1 contains supporting types for parsing and building ASN.1 -// messages with the cryptobyte package. -package asn1 // import "golang.org/x/crypto/cryptobyte/asn1" - -// Tag represents an ASN.1 identifier octet, consisting of a tag number -// (indicating a type) and class (such as context-specific or constructed). -// -// Methods in the cryptobyte package only support the low-tag-number form, i.e. -// a single identifier octet with bits 7-8 encoding the class and bits 1-6 -// encoding the tag number. -type Tag uint8 - -const ( - classConstructed = 0x20 - classContextSpecific = 0x80 -) - -// Constructed returns t with the constructed class bit set. -func (t Tag) Constructed() Tag { return t | classConstructed } - -// ContextSpecific returns t with the context-specific class bit set. -func (t Tag) ContextSpecific() Tag { return t | classContextSpecific } - -// The following is a list of standard tag and class combinations. -const ( - BOOLEAN = Tag(1) - INTEGER = Tag(2) - BIT_STRING = Tag(3) - OCTET_STRING = Tag(4) - NULL = Tag(5) - OBJECT_IDENTIFIER = Tag(6) - ENUM = Tag(10) - UTF8String = Tag(12) - SEQUENCE = Tag(16 | classConstructed) - SET = Tag(17 | classConstructed) - PrintableString = Tag(19) - T61String = Tag(20) - IA5String = Tag(22) - UTCTime = Tag(23) - GeneralizedTime = Tag(24) - GeneralString = Tag(27) -) diff --git a/vendor/golang.org/x/crypto/cryptobyte/builder.go b/vendor/golang.org/x/crypto/cryptobyte/builder.go deleted file mode 100644 index cf254f5f1..000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/builder.go +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cryptobyte - -import ( - "errors" - "fmt" -) - -// A Builder builds byte strings from fixed-length and length-prefixed values. -// Builders either allocate space as needed, or are ‘fixed’, which means that -// they write into a given buffer and produce an error if it's exhausted. -// -// The zero value is a usable Builder that allocates space as needed. -// -// Simple values are marshaled and appended to a Builder using methods on the -// Builder. Length-prefixed values are marshaled by providing a -// BuilderContinuation, which is a function that writes the inner contents of -// the value to a given Builder. See the documentation for BuilderContinuation -// for details. -type Builder struct { - err error - result []byte - fixedSize bool - child *Builder - offset int - pendingLenLen int - pendingIsASN1 bool - inContinuation *bool -} - -// NewBuilder creates a Builder that appends its output to the given buffer. -// Like append(), the slice will be reallocated if its capacity is exceeded. -// Use Bytes to get the final buffer. -func NewBuilder(buffer []byte) *Builder { - return &Builder{ - result: buffer, - } -} - -// NewFixedBuilder creates a Builder that appends its output into the given -// buffer. This builder does not reallocate the output buffer. Writes that -// would exceed the buffer's capacity are treated as an error. -func NewFixedBuilder(buffer []byte) *Builder { - return &Builder{ - result: buffer, - fixedSize: true, - } -} - -// SetError sets the value to be returned as the error from Bytes. Writes -// performed after calling SetError are ignored. -func (b *Builder) SetError(err error) { - b.err = err -} - -// Bytes returns the bytes written by the builder or an error if one has -// occurred during building. -func (b *Builder) Bytes() ([]byte, error) { - if b.err != nil { - return nil, b.err - } - return b.result[b.offset:], nil -} - -// BytesOrPanic returns the bytes written by the builder or panics if an error -// has occurred during building. -func (b *Builder) BytesOrPanic() []byte { - if b.err != nil { - panic(b.err) - } - return b.result[b.offset:] -} - -// AddUint8 appends an 8-bit value to the byte string. -func (b *Builder) AddUint8(v uint8) { - b.add(byte(v)) -} - -// AddUint16 appends a big-endian, 16-bit value to the byte string. -func (b *Builder) AddUint16(v uint16) { - b.add(byte(v>>8), byte(v)) -} - -// AddUint24 appends a big-endian, 24-bit value to the byte string. The highest -// byte of the 32-bit input value is silently truncated. -func (b *Builder) AddUint24(v uint32) { - b.add(byte(v>>16), byte(v>>8), byte(v)) -} - -// AddUint32 appends a big-endian, 32-bit value to the byte string. -func (b *Builder) AddUint32(v uint32) { - b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -// AddUint48 appends a big-endian, 48-bit value to the byte string. -func (b *Builder) AddUint48(v uint64) { - b.add(byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -// AddUint64 appends a big-endian, 64-bit value to the byte string. -func (b *Builder) AddUint64(v uint64) { - b.add(byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -// AddBytes appends a sequence of bytes to the byte string. -func (b *Builder) AddBytes(v []byte) { - b.add(v...) -} - -// BuilderContinuation is a continuation-passing interface for building -// length-prefixed byte sequences. Builder methods for length-prefixed -// sequences (AddUint8LengthPrefixed etc) will invoke the BuilderContinuation -// supplied to them. The child builder passed to the continuation can be used -// to build the content of the length-prefixed sequence. For example: -// -// parent := cryptobyte.NewBuilder() -// parent.AddUint8LengthPrefixed(func (child *Builder) { -// child.AddUint8(42) -// child.AddUint8LengthPrefixed(func (grandchild *Builder) { -// grandchild.AddUint8(5) -// }) -// }) -// -// It is an error to write more bytes to the child than allowed by the reserved -// length prefix. After the continuation returns, the child must be considered -// invalid, i.e. users must not store any copies or references of the child -// that outlive the continuation. -// -// If the continuation panics with a value of type BuildError then the inner -// error will be returned as the error from Bytes. If the child panics -// otherwise then Bytes will repanic with the same value. -type BuilderContinuation func(child *Builder) - -// BuildError wraps an error. If a BuilderContinuation panics with this value, -// the panic will be recovered and the inner error will be returned from -// Builder.Bytes. -type BuildError struct { - Err error -} - -// AddUint8LengthPrefixed adds a 8-bit length-prefixed byte sequence. -func (b *Builder) AddUint8LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(1, false, f) -} - -// AddUint16LengthPrefixed adds a big-endian, 16-bit length-prefixed byte sequence. -func (b *Builder) AddUint16LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(2, false, f) -} - -// AddUint24LengthPrefixed adds a big-endian, 24-bit length-prefixed byte sequence. -func (b *Builder) AddUint24LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(3, false, f) -} - -// AddUint32LengthPrefixed adds a big-endian, 32-bit length-prefixed byte sequence. -func (b *Builder) AddUint32LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(4, false, f) -} - -func (b *Builder) callContinuation(f BuilderContinuation, arg *Builder) { - if !*b.inContinuation { - *b.inContinuation = true - - defer func() { - *b.inContinuation = false - - r := recover() - if r == nil { - return - } - - if buildError, ok := r.(BuildError); ok { - b.err = buildError.Err - } else { - panic(r) - } - }() - } - - f(arg) -} - -func (b *Builder) addLengthPrefixed(lenLen int, isASN1 bool, f BuilderContinuation) { - // Subsequent writes can be ignored if the builder has encountered an error. - if b.err != nil { - return - } - - offset := len(b.result) - b.add(make([]byte, lenLen)...) - - if b.inContinuation == nil { - b.inContinuation = new(bool) - } - - b.child = &Builder{ - result: b.result, - fixedSize: b.fixedSize, - offset: offset, - pendingLenLen: lenLen, - pendingIsASN1: isASN1, - inContinuation: b.inContinuation, - } - - b.callContinuation(f, b.child) - b.flushChild() - if b.child != nil { - panic("cryptobyte: internal error") - } -} - -func (b *Builder) flushChild() { - if b.child == nil { - return - } - b.child.flushChild() - child := b.child - b.child = nil - - if child.err != nil { - b.err = child.err - return - } - - length := len(child.result) - child.pendingLenLen - child.offset - - if length < 0 { - panic("cryptobyte: internal error") // result unexpectedly shrunk - } - - if child.pendingIsASN1 { - // For ASN.1, we reserved a single byte for the length. If that turned out - // to be incorrect, we have to move the contents along in order to make - // space. - if child.pendingLenLen != 1 { - panic("cryptobyte: internal error") - } - var lenLen, lenByte uint8 - if int64(length) > 0xfffffffe { - b.err = errors.New("pending ASN.1 child too long") - return - } else if length > 0xffffff { - lenLen = 5 - lenByte = 0x80 | 4 - } else if length > 0xffff { - lenLen = 4 - lenByte = 0x80 | 3 - } else if length > 0xff { - lenLen = 3 - lenByte = 0x80 | 2 - } else if length > 0x7f { - lenLen = 2 - lenByte = 0x80 | 1 - } else { - lenLen = 1 - lenByte = uint8(length) - length = 0 - } - - // Insert the initial length byte, make space for successive length bytes, - // and adjust the offset. - child.result[child.offset] = lenByte - extraBytes := int(lenLen - 1) - if extraBytes != 0 { - child.add(make([]byte, extraBytes)...) - childStart := child.offset + child.pendingLenLen - copy(child.result[childStart+extraBytes:], child.result[childStart:]) - } - child.offset++ - child.pendingLenLen = extraBytes - } - - l := length - for i := child.pendingLenLen - 1; i >= 0; i-- { - child.result[child.offset+i] = uint8(l) - l >>= 8 - } - if l != 0 { - b.err = fmt.Errorf("cryptobyte: pending child length %d exceeds %d-byte length prefix", length, child.pendingLenLen) - return - } - - if b.fixedSize && &b.result[0] != &child.result[0] { - panic("cryptobyte: BuilderContinuation reallocated a fixed-size buffer") - } - - b.result = child.result -} - -func (b *Builder) add(bytes ...byte) { - if b.err != nil { - return - } - if b.child != nil { - panic("cryptobyte: attempted write while child is pending") - } - if len(b.result)+len(bytes) < len(bytes) { - b.err = errors.New("cryptobyte: length overflow") - } - if b.fixedSize && len(b.result)+len(bytes) > cap(b.result) { - b.err = errors.New("cryptobyte: Builder is exceeding its fixed-size buffer") - return - } - b.result = append(b.result, bytes...) -} - -// Unwrite rolls back non-negative n bytes written directly to the Builder. -// An attempt by a child builder passed to a continuation to unwrite bytes -// from its parent will panic. -func (b *Builder) Unwrite(n int) { - if b.err != nil { - return - } - if b.child != nil { - panic("cryptobyte: attempted unwrite while child is pending") - } - length := len(b.result) - b.pendingLenLen - b.offset - if length < 0 { - panic("cryptobyte: internal error") - } - if n < 0 { - panic("cryptobyte: attempted to unwrite negative number of bytes") - } - if n > length { - panic("cryptobyte: attempted to unwrite more than was written") - } - b.result = b.result[:len(b.result)-n] -} - -// A MarshalingValue marshals itself into a Builder. -type MarshalingValue interface { - // Marshal is called by Builder.AddValue. It receives a pointer to a builder - // to marshal itself into. It may return an error that occurred during - // marshaling, such as unset or invalid values. - Marshal(b *Builder) error -} - -// AddValue calls Marshal on v, passing a pointer to the builder to append to. -// If Marshal returns an error, it is set on the Builder so that subsequent -// appends don't have an effect. -func (b *Builder) AddValue(v MarshalingValue) { - err := v.Marshal(b) - if err != nil { - b.err = err - } -} diff --git a/vendor/golang.org/x/crypto/cryptobyte/string.go b/vendor/golang.org/x/crypto/cryptobyte/string.go deleted file mode 100644 index 10692a8a3..000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/string.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cryptobyte contains types that help with parsing and constructing -// length-prefixed, binary messages, including ASN.1 DER. (The asn1 subpackage -// contains useful ASN.1 constants.) -// -// The String type is for parsing. It wraps a []byte slice and provides helper -// functions for consuming structures, value by value. -// -// The Builder type is for constructing messages. It providers helper functions -// for appending values and also for appending length-prefixed submessages – -// without having to worry about calculating the length prefix ahead of time. -// -// See the documentation and examples for the Builder and String types to get -// started. -package cryptobyte // import "golang.org/x/crypto/cryptobyte" - -// String represents a string of bytes. It provides methods for parsing -// fixed-length and length-prefixed values from it. -type String []byte - -// read advances a String by n bytes and returns them. If less than n bytes -// remain, it returns nil. -func (s *String) read(n int) []byte { - if len(*s) < n || n < 0 { - return nil - } - v := (*s)[:n] - *s = (*s)[n:] - return v -} - -// Skip advances the String by n byte and reports whether it was successful. -func (s *String) Skip(n int) bool { - return s.read(n) != nil -} - -// ReadUint8 decodes an 8-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint8(out *uint8) bool { - v := s.read(1) - if v == nil { - return false - } - *out = uint8(v[0]) - return true -} - -// ReadUint16 decodes a big-endian, 16-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint16(out *uint16) bool { - v := s.read(2) - if v == nil { - return false - } - *out = uint16(v[0])<<8 | uint16(v[1]) - return true -} - -// ReadUint24 decodes a big-endian, 24-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint24(out *uint32) bool { - v := s.read(3) - if v == nil { - return false - } - *out = uint32(v[0])<<16 | uint32(v[1])<<8 | uint32(v[2]) - return true -} - -// ReadUint32 decodes a big-endian, 32-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint32(out *uint32) bool { - v := s.read(4) - if v == nil { - return false - } - *out = uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3]) - return true -} - -// ReadUint48 decodes a big-endian, 48-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint48(out *uint64) bool { - v := s.read(6) - if v == nil { - return false - } - *out = uint64(v[0])<<40 | uint64(v[1])<<32 | uint64(v[2])<<24 | uint64(v[3])<<16 | uint64(v[4])<<8 | uint64(v[5]) - return true -} - -// ReadUint64 decodes a big-endian, 64-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint64(out *uint64) bool { - v := s.read(8) - if v == nil { - return false - } - *out = uint64(v[0])<<56 | uint64(v[1])<<48 | uint64(v[2])<<40 | uint64(v[3])<<32 | uint64(v[4])<<24 | uint64(v[5])<<16 | uint64(v[6])<<8 | uint64(v[7]) - return true -} - -func (s *String) readUnsigned(out *uint32, length int) bool { - v := s.read(length) - if v == nil { - return false - } - var result uint32 - for i := 0; i < length; i++ { - result <<= 8 - result |= uint32(v[i]) - } - *out = result - return true -} - -func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool { - lenBytes := s.read(lenLen) - if lenBytes == nil { - return false - } - var length uint32 - for _, b := range lenBytes { - length = length << 8 - length = length | uint32(b) - } - v := s.read(int(length)) - if v == nil { - return false - } - *outChild = v - return true -} - -// ReadUint8LengthPrefixed reads the content of an 8-bit length-prefixed value -// into out and advances over it. It reports whether the read was successful. -func (s *String) ReadUint8LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(1, out) -} - -// ReadUint16LengthPrefixed reads the content of a big-endian, 16-bit -// length-prefixed value into out and advances over it. It reports whether the -// read was successful. -func (s *String) ReadUint16LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(2, out) -} - -// ReadUint24LengthPrefixed reads the content of a big-endian, 24-bit -// length-prefixed value into out and advances over it. It reports whether -// the read was successful. -func (s *String) ReadUint24LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(3, out) -} - -// ReadBytes reads n bytes into out and advances over them. It reports -// whether the read was successful. -func (s *String) ReadBytes(out *[]byte, n int) bool { - v := s.read(n) - if v == nil { - return false - } - *out = v - return true -} - -// CopyBytes copies len(out) bytes into out and advances over them. It reports -// whether the copy operation was successful -func (s *String) CopyBytes(out []byte) bool { - n := len(out) - v := s.read(n) - if v == nil { - return false - } - return copy(out, v) == n -} - -// Empty reports whether the string does not contain any bytes. -func (s String) Empty() bool { - return len(s) == 0 -} diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go deleted file mode 100644 index cf66309c4..000000000 --- a/vendor/golang.org/x/net/context/context.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// As of Go 1.7 this package is available in the standard library under the -// name context. https://golang.org/pkg/context. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context // import "golang.org/x/net/context" - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} diff --git a/vendor/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go deleted file mode 100644 index 2cb9c408f..000000000 --- a/vendor/golang.org/x/net/context/go17.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.7 -// +build go1.7 - -package context - -import ( - "context" // standard library's context, as of Go 1.7 - "time" -) - -var ( - todo = context.TODO() - background = context.Background() -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = context.Canceled - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = context.DeadlineExceeded - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - ctx, f := context.WithCancel(parent) - return ctx, f -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - ctx, f := context.WithDeadline(parent, deadline) - return ctx, f -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return context.WithValue(parent, key, val) -} diff --git a/vendor/golang.org/x/net/context/go19.go b/vendor/golang.org/x/net/context/go19.go deleted file mode 100644 index 64d31ecc3..000000000 --- a/vendor/golang.org/x/net/context/go19.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.9 -// +build go1.9 - -package context - -import "context" // standard library's context, as of Go 1.7 - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context = context.Context - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc = context.CancelFunc diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go deleted file mode 100644 index 7b6b68511..000000000 --- a/vendor/golang.org/x/net/context/pre_go17.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.7 -// +build !go1.7 - -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, c) - return c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - *cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/vendor/golang.org/x/net/context/pre_go19.go b/vendor/golang.org/x/net/context/pre_go19.go deleted file mode 100644 index 1f9715341..000000000 --- a/vendor/golang.org/x/net/context/pre_go19.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.9 -// +build !go1.9 - -package context - -import "time" - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out chan<- Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() diff --git a/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s b/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s deleted file mode 100644 index db9171c2e..000000000 --- a/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -// +build gc - -#include "textflag.h" - -// -// System calls for ppc64, AIX are implemented in runtime/syscall_aix.go -// - -TEXT ·syscall6(SB),NOSPLIT,$0-88 - JMP syscall·syscall6(SB) - -TEXT ·rawSyscall6(SB),NOSPLIT,$0-88 - JMP syscall·rawSyscall6(SB) diff --git a/vendor/golang.org/x/sys/cpu/byteorder.go b/vendor/golang.org/x/sys/cpu/byteorder.go deleted file mode 100644 index 271055be0..000000000 --- a/vendor/golang.org/x/sys/cpu/byteorder.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import ( - "runtime" -) - -// byteOrder is a subset of encoding/binary.ByteOrder. -type byteOrder interface { - Uint32([]byte) uint32 - Uint64([]byte) uint64 -} - -type littleEndian struct{} -type bigEndian struct{} - -func (littleEndian) Uint32(b []byte) uint32 { - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func (littleEndian) Uint64(b []byte) uint64 { - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -func (bigEndian) Uint32(b []byte) uint32 { - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 -} - -func (bigEndian) Uint64(b []byte) uint64 { - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | - uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 -} - -// hostByteOrder returns littleEndian on little-endian machines and -// bigEndian on big-endian machines. -func hostByteOrder() byteOrder { - switch runtime.GOARCH { - case "386", "amd64", "amd64p32", - "alpha", - "arm", "arm64", - "loong64", - "mipsle", "mips64le", "mips64p32le", - "nios2", - "ppc64le", - "riscv", "riscv64", - "sh": - return littleEndian{} - case "armbe", "arm64be", - "m68k", - "mips", "mips64", "mips64p32", - "ppc", "ppc64", - "s390", "s390x", - "shbe", - "sparc", "sparc64": - return bigEndian{} - } - panic("unknown architecture") -} diff --git a/vendor/golang.org/x/sys/cpu/cpu.go b/vendor/golang.org/x/sys/cpu/cpu.go deleted file mode 100644 index 4756ad5f7..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cpu implements processor feature detection for -// various CPU architectures. -package cpu - -import ( - "os" - "strings" -) - -// Initialized reports whether the CPU features were initialized. -// -// For some GOOS/GOARCH combinations initialization of the CPU features depends -// on reading an operating specific file, e.g. /proc/self/auxv on linux/arm -// Initialized will report false if reading the file fails. -var Initialized bool - -// CacheLinePad is used to pad structs to avoid false sharing. -type CacheLinePad struct{ _ [cacheLineSize]byte } - -// X86 contains the supported CPU features of the -// current X86/AMD64 platform. If the current platform -// is not X86/AMD64 then all feature flags are false. -// -// X86 is padded to avoid false sharing. Further the HasAVX -// and HasAVX2 are only set if the OS supports XMM and YMM -// registers in addition to the CPUID feature bit being set. -var X86 struct { - _ CacheLinePad - HasAES bool // AES hardware implementation (AES NI) - HasADX bool // Multi-precision add-carry instruction extensions - HasAVX bool // Advanced vector extension - HasAVX2 bool // Advanced vector extension 2 - HasAVX512 bool // Advanced vector extension 512 - HasAVX512F bool // Advanced vector extension 512 Foundation Instructions - HasAVX512CD bool // Advanced vector extension 512 Conflict Detection Instructions - HasAVX512ER bool // Advanced vector extension 512 Exponential and Reciprocal Instructions - HasAVX512PF bool // Advanced vector extension 512 Prefetch Instructions - HasAVX512VL bool // Advanced vector extension 512 Vector Length Extensions - HasAVX512BW bool // Advanced vector extension 512 Byte and Word Instructions - HasAVX512DQ bool // Advanced vector extension 512 Doubleword and Quadword Instructions - HasAVX512IFMA bool // Advanced vector extension 512 Integer Fused Multiply Add - HasAVX512VBMI bool // Advanced vector extension 512 Vector Byte Manipulation Instructions - HasAVX5124VNNIW bool // Advanced vector extension 512 Vector Neural Network Instructions Word variable precision - HasAVX5124FMAPS bool // Advanced vector extension 512 Fused Multiply Accumulation Packed Single precision - HasAVX512VPOPCNTDQ bool // Advanced vector extension 512 Double and quad word population count instructions - HasAVX512VPCLMULQDQ bool // Advanced vector extension 512 Vector carry-less multiply operations - HasAVX512VNNI bool // Advanced vector extension 512 Vector Neural Network Instructions - HasAVX512GFNI bool // Advanced vector extension 512 Galois field New Instructions - HasAVX512VAES bool // Advanced vector extension 512 Vector AES instructions - HasAVX512VBMI2 bool // Advanced vector extension 512 Vector Byte Manipulation Instructions 2 - HasAVX512BITALG bool // Advanced vector extension 512 Bit Algorithms - HasAVX512BF16 bool // Advanced vector extension 512 BFloat16 Instructions - HasAMXTile bool // Advanced Matrix Extension Tile instructions - HasAMXInt8 bool // Advanced Matrix Extension Int8 instructions - HasAMXBF16 bool // Advanced Matrix Extension BFloat16 instructions - HasBMI1 bool // Bit manipulation instruction set 1 - HasBMI2 bool // Bit manipulation instruction set 2 - HasCX16 bool // Compare and exchange 16 Bytes - HasERMS bool // Enhanced REP for MOVSB and STOSB - HasFMA bool // Fused-multiply-add instructions - HasOSXSAVE bool // OS supports XSAVE/XRESTOR for saving/restoring XMM registers. - HasPCLMULQDQ bool // PCLMULQDQ instruction - most often used for AES-GCM - HasPOPCNT bool // Hamming weight instruction POPCNT. - HasRDRAND bool // RDRAND instruction (on-chip random number generator) - HasRDSEED bool // RDSEED instruction (on-chip random number generator) - HasSSE2 bool // Streaming SIMD extension 2 (always available on amd64) - HasSSE3 bool // Streaming SIMD extension 3 - HasSSSE3 bool // Supplemental streaming SIMD extension 3 - HasSSE41 bool // Streaming SIMD extension 4 and 4.1 - HasSSE42 bool // Streaming SIMD extension 4 and 4.2 - _ CacheLinePad -} - -// ARM64 contains the supported CPU features of the -// current ARMv8(aarch64) platform. If the current platform -// is not arm64 then all feature flags are false. -var ARM64 struct { - _ CacheLinePad - HasFP bool // Floating-point instruction set (always available) - HasASIMD bool // Advanced SIMD (always available) - HasEVTSTRM bool // Event stream support - HasAES bool // AES hardware implementation - HasPMULL bool // Polynomial multiplication instruction set - HasSHA1 bool // SHA1 hardware implementation - HasSHA2 bool // SHA2 hardware implementation - HasCRC32 bool // CRC32 hardware implementation - HasATOMICS bool // Atomic memory operation instruction set - HasFPHP bool // Half precision floating-point instruction set - HasASIMDHP bool // Advanced SIMD half precision instruction set - HasCPUID bool // CPUID identification scheme registers - HasASIMDRDM bool // Rounding double multiply add/subtract instruction set - HasJSCVT bool // Javascript conversion from floating-point to integer - HasFCMA bool // Floating-point multiplication and addition of complex numbers - HasLRCPC bool // Release Consistent processor consistent support - HasDCPOP bool // Persistent memory support - HasSHA3 bool // SHA3 hardware implementation - HasSM3 bool // SM3 hardware implementation - HasSM4 bool // SM4 hardware implementation - HasASIMDDP bool // Advanced SIMD double precision instruction set - HasSHA512 bool // SHA512 hardware implementation - HasSVE bool // Scalable Vector Extensions - HasASIMDFHM bool // Advanced SIMD multiplication FP16 to FP32 - _ CacheLinePad -} - -// ARM contains the supported CPU features of the current ARM (32-bit) platform. -// All feature flags are false if: -// 1. the current platform is not arm, or -// 2. the current operating system is not Linux. -var ARM struct { - _ CacheLinePad - HasSWP bool // SWP instruction support - HasHALF bool // Half-word load and store support - HasTHUMB bool // ARM Thumb instruction set - Has26BIT bool // Address space limited to 26-bits - HasFASTMUL bool // 32-bit operand, 64-bit result multiplication support - HasFPA bool // Floating point arithmetic support - HasVFP bool // Vector floating point support - HasEDSP bool // DSP Extensions support - HasJAVA bool // Java instruction set - HasIWMMXT bool // Intel Wireless MMX technology support - HasCRUNCH bool // MaverickCrunch context switching and handling - HasTHUMBEE bool // Thumb EE instruction set - HasNEON bool // NEON instruction set - HasVFPv3 bool // Vector floating point version 3 support - HasVFPv3D16 bool // Vector floating point version 3 D8-D15 - HasTLS bool // Thread local storage support - HasVFPv4 bool // Vector floating point version 4 support - HasIDIVA bool // Integer divide instruction support in ARM mode - HasIDIVT bool // Integer divide instruction support in Thumb mode - HasVFPD32 bool // Vector floating point version 3 D15-D31 - HasLPAE bool // Large Physical Address Extensions - HasEVTSTRM bool // Event stream support - HasAES bool // AES hardware implementation - HasPMULL bool // Polynomial multiplication instruction set - HasSHA1 bool // SHA1 hardware implementation - HasSHA2 bool // SHA2 hardware implementation - HasCRC32 bool // CRC32 hardware implementation - _ CacheLinePad -} - -// MIPS64X contains the supported CPU features of the current mips64/mips64le -// platforms. If the current platform is not mips64/mips64le or the current -// operating system is not Linux then all feature flags are false. -var MIPS64X struct { - _ CacheLinePad - HasMSA bool // MIPS SIMD architecture - _ CacheLinePad -} - -// PPC64 contains the supported CPU features of the current ppc64/ppc64le platforms. -// If the current platform is not ppc64/ppc64le then all feature flags are false. -// -// For ppc64/ppc64le, it is safe to check only for ISA level starting on ISA v3.00, -// since there are no optional categories. There are some exceptions that also -// require kernel support to work (DARN, SCV), so there are feature bits for -// those as well. The struct is padded to avoid false sharing. -var PPC64 struct { - _ CacheLinePad - HasDARN bool // Hardware random number generator (requires kernel enablement) - HasSCV bool // Syscall vectored (requires kernel enablement) - IsPOWER8 bool // ISA v2.07 (POWER8) - IsPOWER9 bool // ISA v3.00 (POWER9), implies IsPOWER8 - _ CacheLinePad -} - -// S390X contains the supported CPU features of the current IBM Z -// (s390x) platform. If the current platform is not IBM Z then all -// feature flags are false. -// -// S390X is padded to avoid false sharing. Further HasVX is only set -// if the OS supports vector registers in addition to the STFLE -// feature bit being set. -var S390X struct { - _ CacheLinePad - HasZARCH bool // z/Architecture mode is active [mandatory] - HasSTFLE bool // store facility list extended - HasLDISP bool // long (20-bit) displacements - HasEIMM bool // 32-bit immediates - HasDFP bool // decimal floating point - HasETF3EH bool // ETF-3 enhanced - HasMSA bool // message security assist (CPACF) - HasAES bool // KM-AES{128,192,256} functions - HasAESCBC bool // KMC-AES{128,192,256} functions - HasAESCTR bool // KMCTR-AES{128,192,256} functions - HasAESGCM bool // KMA-GCM-AES{128,192,256} functions - HasGHASH bool // KIMD-GHASH function - HasSHA1 bool // K{I,L}MD-SHA-1 functions - HasSHA256 bool // K{I,L}MD-SHA-256 functions - HasSHA512 bool // K{I,L}MD-SHA-512 functions - HasSHA3 bool // K{I,L}MD-SHA3-{224,256,384,512} and K{I,L}MD-SHAKE-{128,256} functions - HasVX bool // vector facility - HasVXE bool // vector-enhancements facility 1 - _ CacheLinePad -} - -func init() { - archInit() - initOptions() - processOptions() -} - -// options contains the cpu debug options that can be used in GODEBUG. -// Options are arch dependent and are added by the arch specific initOptions functions. -// Features that are mandatory for the specific GOARCH should have the Required field set -// (e.g. SSE2 on amd64). -var options []option - -// Option names should be lower case. e.g. avx instead of AVX. -type option struct { - Name string - Feature *bool - Specified bool // whether feature value was specified in GODEBUG - Enable bool // whether feature should be enabled - Required bool // whether feature is mandatory and can not be disabled -} - -func processOptions() { - env := os.Getenv("GODEBUG") -field: - for env != "" { - field := "" - i := strings.IndexByte(env, ',') - if i < 0 { - field, env = env, "" - } else { - field, env = env[:i], env[i+1:] - } - if len(field) < 4 || field[:4] != "cpu." { - continue - } - i = strings.IndexByte(field, '=') - if i < 0 { - print("GODEBUG sys/cpu: no value specified for \"", field, "\"\n") - continue - } - key, value := field[4:i], field[i+1:] // e.g. "SSE2", "on" - - var enable bool - switch value { - case "on": - enable = true - case "off": - enable = false - default: - print("GODEBUG sys/cpu: value \"", value, "\" not supported for cpu option \"", key, "\"\n") - continue field - } - - if key == "all" { - for i := range options { - options[i].Specified = true - options[i].Enable = enable || options[i].Required - } - continue field - } - - for i := range options { - if options[i].Name == key { - options[i].Specified = true - options[i].Enable = enable - continue field - } - } - - print("GODEBUG sys/cpu: unknown cpu feature \"", key, "\"\n") - } - - for _, o := range options { - if !o.Specified { - continue - } - - if o.Enable && !*o.Feature { - print("GODEBUG sys/cpu: can not enable \"", o.Name, "\", missing CPU support\n") - continue - } - - if !o.Enable && o.Required { - print("GODEBUG sys/cpu: can not disable \"", o.Name, "\", required CPU feature\n") - continue - } - - *o.Feature = o.Enable - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_aix.go b/vendor/golang.org/x/sys/cpu/cpu_aix.go deleted file mode 100644 index 8aaeef545..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_aix.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build aix -// +build aix - -package cpu - -const ( - // getsystemcfg constants - _SC_IMPL = 2 - _IMPL_POWER8 = 0x10000 - _IMPL_POWER9 = 0x20000 -) - -func archInit() { - impl := getsystemcfg(_SC_IMPL) - if impl&_IMPL_POWER8 != 0 { - PPC64.IsPOWER8 = true - } - if impl&_IMPL_POWER9 != 0 { - PPC64.IsPOWER8 = true - PPC64.IsPOWER9 = true - } - - Initialized = true -} - -func getsystemcfg(label int) (n uint64) { - r0, _ := callgetsystemcfg(label) - n = uint64(r0) - return -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm.go b/vendor/golang.org/x/sys/cpu/cpu_arm.go deleted file mode 100644 index 301b752e9..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -const cacheLineSize = 32 - -// HWCAP/HWCAP2 bits. -// These are specific to Linux. -const ( - hwcap_SWP = 1 << 0 - hwcap_HALF = 1 << 1 - hwcap_THUMB = 1 << 2 - hwcap_26BIT = 1 << 3 - hwcap_FAST_MULT = 1 << 4 - hwcap_FPA = 1 << 5 - hwcap_VFP = 1 << 6 - hwcap_EDSP = 1 << 7 - hwcap_JAVA = 1 << 8 - hwcap_IWMMXT = 1 << 9 - hwcap_CRUNCH = 1 << 10 - hwcap_THUMBEE = 1 << 11 - hwcap_NEON = 1 << 12 - hwcap_VFPv3 = 1 << 13 - hwcap_VFPv3D16 = 1 << 14 - hwcap_TLS = 1 << 15 - hwcap_VFPv4 = 1 << 16 - hwcap_IDIVA = 1 << 17 - hwcap_IDIVT = 1 << 18 - hwcap_VFPD32 = 1 << 19 - hwcap_LPAE = 1 << 20 - hwcap_EVTSTRM = 1 << 21 - - hwcap2_AES = 1 << 0 - hwcap2_PMULL = 1 << 1 - hwcap2_SHA1 = 1 << 2 - hwcap2_SHA2 = 1 << 3 - hwcap2_CRC32 = 1 << 4 -) - -func initOptions() { - options = []option{ - {Name: "pmull", Feature: &ARM.HasPMULL}, - {Name: "sha1", Feature: &ARM.HasSHA1}, - {Name: "sha2", Feature: &ARM.HasSHA2}, - {Name: "swp", Feature: &ARM.HasSWP}, - {Name: "thumb", Feature: &ARM.HasTHUMB}, - {Name: "thumbee", Feature: &ARM.HasTHUMBEE}, - {Name: "tls", Feature: &ARM.HasTLS}, - {Name: "vfp", Feature: &ARM.HasVFP}, - {Name: "vfpd32", Feature: &ARM.HasVFPD32}, - {Name: "vfpv3", Feature: &ARM.HasVFPv3}, - {Name: "vfpv3d16", Feature: &ARM.HasVFPv3D16}, - {Name: "vfpv4", Feature: &ARM.HasVFPv4}, - {Name: "half", Feature: &ARM.HasHALF}, - {Name: "26bit", Feature: &ARM.Has26BIT}, - {Name: "fastmul", Feature: &ARM.HasFASTMUL}, - {Name: "fpa", Feature: &ARM.HasFPA}, - {Name: "edsp", Feature: &ARM.HasEDSP}, - {Name: "java", Feature: &ARM.HasJAVA}, - {Name: "iwmmxt", Feature: &ARM.HasIWMMXT}, - {Name: "crunch", Feature: &ARM.HasCRUNCH}, - {Name: "neon", Feature: &ARM.HasNEON}, - {Name: "idivt", Feature: &ARM.HasIDIVT}, - {Name: "idiva", Feature: &ARM.HasIDIVA}, - {Name: "lpae", Feature: &ARM.HasLPAE}, - {Name: "evtstrm", Feature: &ARM.HasEVTSTRM}, - {Name: "aes", Feature: &ARM.HasAES}, - {Name: "crc32", Feature: &ARM.HasCRC32}, - } - -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_arm64.go deleted file mode 100644 index f3eb993bf..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import "runtime" - -// cacheLineSize is used to prevent false sharing of cache lines. -// We choose 128 because Apple Silicon, a.k.a. M1, has 128-byte cache line size. -// It doesn't cost much and is much more future-proof. -const cacheLineSize = 128 - -func initOptions() { - options = []option{ - {Name: "fp", Feature: &ARM64.HasFP}, - {Name: "asimd", Feature: &ARM64.HasASIMD}, - {Name: "evstrm", Feature: &ARM64.HasEVTSTRM}, - {Name: "aes", Feature: &ARM64.HasAES}, - {Name: "fphp", Feature: &ARM64.HasFPHP}, - {Name: "jscvt", Feature: &ARM64.HasJSCVT}, - {Name: "lrcpc", Feature: &ARM64.HasLRCPC}, - {Name: "pmull", Feature: &ARM64.HasPMULL}, - {Name: "sha1", Feature: &ARM64.HasSHA1}, - {Name: "sha2", Feature: &ARM64.HasSHA2}, - {Name: "sha3", Feature: &ARM64.HasSHA3}, - {Name: "sha512", Feature: &ARM64.HasSHA512}, - {Name: "sm3", Feature: &ARM64.HasSM3}, - {Name: "sm4", Feature: &ARM64.HasSM4}, - {Name: "sve", Feature: &ARM64.HasSVE}, - {Name: "crc32", Feature: &ARM64.HasCRC32}, - {Name: "atomics", Feature: &ARM64.HasATOMICS}, - {Name: "asimdhp", Feature: &ARM64.HasASIMDHP}, - {Name: "cpuid", Feature: &ARM64.HasCPUID}, - {Name: "asimrdm", Feature: &ARM64.HasASIMDRDM}, - {Name: "fcma", Feature: &ARM64.HasFCMA}, - {Name: "dcpop", Feature: &ARM64.HasDCPOP}, - {Name: "asimddp", Feature: &ARM64.HasASIMDDP}, - {Name: "asimdfhm", Feature: &ARM64.HasASIMDFHM}, - } -} - -func archInit() { - switch runtime.GOOS { - case "freebsd": - readARM64Registers() - case "linux", "netbsd", "openbsd": - doinit() - default: - // Many platforms don't seem to allow reading these registers. - setMinimalFeatures() - } -} - -// setMinimalFeatures fakes the minimal ARM64 features expected by -// TestARM64minimalFeatures. -func setMinimalFeatures() { - ARM64.HasASIMD = true - ARM64.HasFP = true -} - -func readARM64Registers() { - Initialized = true - - parseARM64SystemRegisters(getisar0(), getisar1(), getpfr0()) -} - -func parseARM64SystemRegisters(isar0, isar1, pfr0 uint64) { - // ID_AA64ISAR0_EL1 - switch extractBits(isar0, 4, 7) { - case 1: - ARM64.HasAES = true - case 2: - ARM64.HasAES = true - ARM64.HasPMULL = true - } - - switch extractBits(isar0, 8, 11) { - case 1: - ARM64.HasSHA1 = true - } - - switch extractBits(isar0, 12, 15) { - case 1: - ARM64.HasSHA2 = true - case 2: - ARM64.HasSHA2 = true - ARM64.HasSHA512 = true - } - - switch extractBits(isar0, 16, 19) { - case 1: - ARM64.HasCRC32 = true - } - - switch extractBits(isar0, 20, 23) { - case 2: - ARM64.HasATOMICS = true - } - - switch extractBits(isar0, 28, 31) { - case 1: - ARM64.HasASIMDRDM = true - } - - switch extractBits(isar0, 32, 35) { - case 1: - ARM64.HasSHA3 = true - } - - switch extractBits(isar0, 36, 39) { - case 1: - ARM64.HasSM3 = true - } - - switch extractBits(isar0, 40, 43) { - case 1: - ARM64.HasSM4 = true - } - - switch extractBits(isar0, 44, 47) { - case 1: - ARM64.HasASIMDDP = true - } - - // ID_AA64ISAR1_EL1 - switch extractBits(isar1, 0, 3) { - case 1: - ARM64.HasDCPOP = true - } - - switch extractBits(isar1, 12, 15) { - case 1: - ARM64.HasJSCVT = true - } - - switch extractBits(isar1, 16, 19) { - case 1: - ARM64.HasFCMA = true - } - - switch extractBits(isar1, 20, 23) { - case 1: - ARM64.HasLRCPC = true - } - - // ID_AA64PFR0_EL1 - switch extractBits(pfr0, 16, 19) { - case 0: - ARM64.HasFP = true - case 1: - ARM64.HasFP = true - ARM64.HasFPHP = true - } - - switch extractBits(pfr0, 20, 23) { - case 0: - ARM64.HasASIMD = true - case 1: - ARM64.HasASIMD = true - ARM64.HasASIMDHP = true - } - - switch extractBits(pfr0, 32, 35) { - case 1: - ARM64.HasSVE = true - } -} - -func extractBits(data uint64, start, end uint) uint { - return (uint)(data>>start) & ((1 << (end - start + 1)) - 1) -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.s b/vendor/golang.org/x/sys/cpu/cpu_arm64.s deleted file mode 100644 index c61f95a05..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.s +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -// +build gc - -#include "textflag.h" - -// func getisar0() uint64 -TEXT ·getisar0(SB),NOSPLIT,$0-8 - // get Instruction Set Attributes 0 into x0 - // mrs x0, ID_AA64ISAR0_EL1 = d5380600 - WORD $0xd5380600 - MOVD R0, ret+0(FP) - RET - -// func getisar1() uint64 -TEXT ·getisar1(SB),NOSPLIT,$0-8 - // get Instruction Set Attributes 1 into x0 - // mrs x0, ID_AA64ISAR1_EL1 = d5380620 - WORD $0xd5380620 - MOVD R0, ret+0(FP) - RET - -// func getpfr0() uint64 -TEXT ·getpfr0(SB),NOSPLIT,$0-8 - // get Processor Feature Register 0 into x0 - // mrs x0, ID_AA64PFR0_EL1 = d5380400 - WORD $0xd5380400 - MOVD R0, ret+0(FP) - RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go deleted file mode 100644 index ccf542a73..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -// +build gc - -package cpu - -func getisar0() uint64 -func getisar1() uint64 -func getpfr0() uint64 diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go deleted file mode 100644 index 0af2f2484..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -// +build gc - -package cpu - -// haveAsmFunctions reports whether the other functions in this file can -// be safely called. -func haveAsmFunctions() bool { return true } - -// The following feature detection functions are defined in cpu_s390x.s. -// They are likely to be expensive to call so the results should be cached. -func stfle() facilityList -func kmQuery() queryResult -func kmcQuery() queryResult -func kmctrQuery() queryResult -func kmaQuery() queryResult -func kimdQuery() queryResult -func klmdQuery() queryResult diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go deleted file mode 100644 index fa7cdb9bc..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (386 || amd64 || amd64p32) && gc -// +build 386 amd64 amd64p32 -// +build gc - -package cpu - -// cpuid is implemented in cpu_x86.s for gc compiler -// and in cpu_gccgo.c for gccgo. -func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) - -// xgetbv with ecx = 0 is implemented in cpu_x86.s for gc compiler -// and in cpu_gccgo.c for gccgo. -func xgetbv() (eax, edx uint32) diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go deleted file mode 100644 index 2aff31891..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gccgo -// +build gccgo - -package cpu - -func getisar0() uint64 { return 0 } -func getisar1() uint64 { return 0 } -func getpfr0() uint64 { return 0 } diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go deleted file mode 100644 index 4bfbda619..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gccgo -// +build gccgo - -package cpu - -// haveAsmFunctions reports whether the other functions in this file can -// be safely called. -func haveAsmFunctions() bool { return false } - -// TODO(mundaym): the following feature detection functions are currently -// stubs. See https://golang.org/cl/162887 for how to fix this. -// They are likely to be expensive to call so the results should be cached. -func stfle() facilityList { panic("not implemented for gccgo") } -func kmQuery() queryResult { panic("not implemented for gccgo") } -func kmcQuery() queryResult { panic("not implemented for gccgo") } -func kmctrQuery() queryResult { panic("not implemented for gccgo") } -func kmaQuery() queryResult { panic("not implemented for gccgo") } -func kimdQuery() queryResult { panic("not implemented for gccgo") } -func klmdQuery() queryResult { panic("not implemented for gccgo") } diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c deleted file mode 100644 index 6cc73109f..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (386 || amd64 || amd64p32) && gccgo -// +build 386 amd64 amd64p32 -// +build gccgo - -#include -#include -#include - -// Need to wrap __get_cpuid_count because it's declared as static. -int -gccgoGetCpuidCount(uint32_t leaf, uint32_t subleaf, - uint32_t *eax, uint32_t *ebx, - uint32_t *ecx, uint32_t *edx) -{ - return __get_cpuid_count(leaf, subleaf, eax, ebx, ecx, edx); -} - -#pragma GCC diagnostic ignored "-Wunknown-pragmas" -#pragma GCC push_options -#pragma GCC target("xsave") -#pragma clang attribute push (__attribute__((target("xsave"))), apply_to=function) - -// xgetbv reads the contents of an XCR (Extended Control Register) -// specified in the ECX register into registers EDX:EAX. -// Currently, the only supported value for XCR is 0. -void -gccgoXgetbv(uint32_t *eax, uint32_t *edx) -{ - uint64_t v = _xgetbv(0); - *eax = v & 0xffffffff; - *edx = v >> 32; -} - -#pragma clang attribute pop -#pragma GCC pop_options diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go deleted file mode 100644 index 863d415ab..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (386 || amd64 || amd64p32) && gccgo -// +build 386 amd64 amd64p32 -// +build gccgo - -package cpu - -//extern gccgoGetCpuidCount -func gccgoGetCpuidCount(eaxArg, ecxArg uint32, eax, ebx, ecx, edx *uint32) - -func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) { - var a, b, c, d uint32 - gccgoGetCpuidCount(eaxArg, ecxArg, &a, &b, &c, &d) - return a, b, c, d -} - -//extern gccgoXgetbv -func gccgoXgetbv(eax, edx *uint32) - -func xgetbv() (eax, edx uint32) { - var a, d uint32 - gccgoXgetbv(&a, &d) - return a, d -} - -// gccgo doesn't build on Darwin, per: -// https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/gcc.rb#L76 -func darwinSupportsAVX512() bool { - return false -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux.go b/vendor/golang.org/x/sys/cpu/cpu_linux.go deleted file mode 100644 index 159a686f6..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !386 && !amd64 && !amd64p32 && !arm64 -// +build !386,!amd64,!amd64p32,!arm64 - -package cpu - -func archInit() { - if err := readHWCAP(); err != nil { - return - } - doinit() - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go deleted file mode 100644 index 2057006dc..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -func doinit() { - ARM.HasSWP = isSet(hwCap, hwcap_SWP) - ARM.HasHALF = isSet(hwCap, hwcap_HALF) - ARM.HasTHUMB = isSet(hwCap, hwcap_THUMB) - ARM.Has26BIT = isSet(hwCap, hwcap_26BIT) - ARM.HasFASTMUL = isSet(hwCap, hwcap_FAST_MULT) - ARM.HasFPA = isSet(hwCap, hwcap_FPA) - ARM.HasVFP = isSet(hwCap, hwcap_VFP) - ARM.HasEDSP = isSet(hwCap, hwcap_EDSP) - ARM.HasJAVA = isSet(hwCap, hwcap_JAVA) - ARM.HasIWMMXT = isSet(hwCap, hwcap_IWMMXT) - ARM.HasCRUNCH = isSet(hwCap, hwcap_CRUNCH) - ARM.HasTHUMBEE = isSet(hwCap, hwcap_THUMBEE) - ARM.HasNEON = isSet(hwCap, hwcap_NEON) - ARM.HasVFPv3 = isSet(hwCap, hwcap_VFPv3) - ARM.HasVFPv3D16 = isSet(hwCap, hwcap_VFPv3D16) - ARM.HasTLS = isSet(hwCap, hwcap_TLS) - ARM.HasVFPv4 = isSet(hwCap, hwcap_VFPv4) - ARM.HasIDIVA = isSet(hwCap, hwcap_IDIVA) - ARM.HasIDIVT = isSet(hwCap, hwcap_IDIVT) - ARM.HasVFPD32 = isSet(hwCap, hwcap_VFPD32) - ARM.HasLPAE = isSet(hwCap, hwcap_LPAE) - ARM.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) - ARM.HasAES = isSet(hwCap2, hwcap2_AES) - ARM.HasPMULL = isSet(hwCap2, hwcap2_PMULL) - ARM.HasSHA1 = isSet(hwCap2, hwcap2_SHA1) - ARM.HasSHA2 = isSet(hwCap2, hwcap2_SHA2) - ARM.HasCRC32 = isSet(hwCap2, hwcap2_CRC32) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go deleted file mode 100644 index a968b80fa..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import ( - "strings" - "syscall" -) - -// HWCAP/HWCAP2 bits. These are exposed by Linux. -const ( - hwcap_FP = 1 << 0 - hwcap_ASIMD = 1 << 1 - hwcap_EVTSTRM = 1 << 2 - hwcap_AES = 1 << 3 - hwcap_PMULL = 1 << 4 - hwcap_SHA1 = 1 << 5 - hwcap_SHA2 = 1 << 6 - hwcap_CRC32 = 1 << 7 - hwcap_ATOMICS = 1 << 8 - hwcap_FPHP = 1 << 9 - hwcap_ASIMDHP = 1 << 10 - hwcap_CPUID = 1 << 11 - hwcap_ASIMDRDM = 1 << 12 - hwcap_JSCVT = 1 << 13 - hwcap_FCMA = 1 << 14 - hwcap_LRCPC = 1 << 15 - hwcap_DCPOP = 1 << 16 - hwcap_SHA3 = 1 << 17 - hwcap_SM3 = 1 << 18 - hwcap_SM4 = 1 << 19 - hwcap_ASIMDDP = 1 << 20 - hwcap_SHA512 = 1 << 21 - hwcap_SVE = 1 << 22 - hwcap_ASIMDFHM = 1 << 23 -) - -// linuxKernelCanEmulateCPUID reports whether we're running -// on Linux 4.11+. Ideally we'd like to ask the question about -// whether the current kernel contains -// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=77c97b4ee21290f5f083173d957843b615abbff2 -// but the version number will have to do. -func linuxKernelCanEmulateCPUID() bool { - var un syscall.Utsname - syscall.Uname(&un) - var sb strings.Builder - for _, b := range un.Release[:] { - if b == 0 { - break - } - sb.WriteByte(byte(b)) - } - major, minor, _, ok := parseRelease(sb.String()) - return ok && (major > 4 || major == 4 && minor >= 11) -} - -func doinit() { - if err := readHWCAP(); err != nil { - // We failed to read /proc/self/auxv. This can happen if the binary has - // been given extra capabilities(7) with /bin/setcap. - // - // When this happens, we have two options. If the Linux kernel is new - // enough (4.11+), we can read the arm64 registers directly which'll - // trap into the kernel and then return back to userspace. - // - // But on older kernels, such as Linux 4.4.180 as used on many Synology - // devices, calling readARM64Registers (specifically getisar0) will - // cause a SIGILL and we'll die. So for older kernels, parse /proc/cpuinfo - // instead. - // - // See golang/go#57336. - if linuxKernelCanEmulateCPUID() { - readARM64Registers() - } else { - readLinuxProcCPUInfo() - } - return - } - - // HWCAP feature bits - ARM64.HasFP = isSet(hwCap, hwcap_FP) - ARM64.HasASIMD = isSet(hwCap, hwcap_ASIMD) - ARM64.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) - ARM64.HasAES = isSet(hwCap, hwcap_AES) - ARM64.HasPMULL = isSet(hwCap, hwcap_PMULL) - ARM64.HasSHA1 = isSet(hwCap, hwcap_SHA1) - ARM64.HasSHA2 = isSet(hwCap, hwcap_SHA2) - ARM64.HasCRC32 = isSet(hwCap, hwcap_CRC32) - ARM64.HasATOMICS = isSet(hwCap, hwcap_ATOMICS) - ARM64.HasFPHP = isSet(hwCap, hwcap_FPHP) - ARM64.HasASIMDHP = isSet(hwCap, hwcap_ASIMDHP) - ARM64.HasCPUID = isSet(hwCap, hwcap_CPUID) - ARM64.HasASIMDRDM = isSet(hwCap, hwcap_ASIMDRDM) - ARM64.HasJSCVT = isSet(hwCap, hwcap_JSCVT) - ARM64.HasFCMA = isSet(hwCap, hwcap_FCMA) - ARM64.HasLRCPC = isSet(hwCap, hwcap_LRCPC) - ARM64.HasDCPOP = isSet(hwCap, hwcap_DCPOP) - ARM64.HasSHA3 = isSet(hwCap, hwcap_SHA3) - ARM64.HasSM3 = isSet(hwCap, hwcap_SM3) - ARM64.HasSM4 = isSet(hwCap, hwcap_SM4) - ARM64.HasASIMDDP = isSet(hwCap, hwcap_ASIMDDP) - ARM64.HasSHA512 = isSet(hwCap, hwcap_SHA512) - ARM64.HasSVE = isSet(hwCap, hwcap_SVE) - ARM64.HasASIMDFHM = isSet(hwCap, hwcap_ASIMDFHM) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go deleted file mode 100644 index 6000db4cd..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux && (mips64 || mips64le) -// +build linux -// +build mips64 mips64le - -package cpu - -// HWCAP bits. These are exposed by the Linux kernel 5.4. -const ( - // CPU features - hwcap_MIPS_MSA = 1 << 1 -) - -func doinit() { - // HWCAP feature bits - MIPS64X.HasMSA = isSet(hwCap, hwcap_MIPS_MSA) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go b/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go deleted file mode 100644 index f4992b1a5..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux && !arm && !arm64 && !mips64 && !mips64le && !ppc64 && !ppc64le && !s390x -// +build linux,!arm,!arm64,!mips64,!mips64le,!ppc64,!ppc64le,!s390x - -package cpu - -func doinit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go deleted file mode 100644 index 021356d6d..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux && (ppc64 || ppc64le) -// +build linux -// +build ppc64 ppc64le - -package cpu - -// HWCAP/HWCAP2 bits. These are exposed by the kernel. -const ( - // ISA Level - _PPC_FEATURE2_ARCH_2_07 = 0x80000000 - _PPC_FEATURE2_ARCH_3_00 = 0x00800000 - - // CPU features - _PPC_FEATURE2_DARN = 0x00200000 - _PPC_FEATURE2_SCV = 0x00100000 -) - -func doinit() { - // HWCAP2 feature bits - PPC64.IsPOWER8 = isSet(hwCap2, _PPC_FEATURE2_ARCH_2_07) - PPC64.IsPOWER9 = isSet(hwCap2, _PPC_FEATURE2_ARCH_3_00) - PPC64.HasDARN = isSet(hwCap2, _PPC_FEATURE2_DARN) - PPC64.HasSCV = isSet(hwCap2, _PPC_FEATURE2_SCV) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go deleted file mode 100644 index 1517ac61d..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -const ( - // bit mask values from /usr/include/bits/hwcap.h - hwcap_ZARCH = 2 - hwcap_STFLE = 4 - hwcap_MSA = 8 - hwcap_LDISP = 16 - hwcap_EIMM = 32 - hwcap_DFP = 64 - hwcap_ETF3EH = 256 - hwcap_VX = 2048 - hwcap_VXE = 8192 -) - -func initS390Xbase() { - // test HWCAP bit vector - has := func(featureMask uint) bool { - return hwCap&featureMask == featureMask - } - - // mandatory - S390X.HasZARCH = has(hwcap_ZARCH) - - // optional - S390X.HasSTFLE = has(hwcap_STFLE) - S390X.HasLDISP = has(hwcap_LDISP) - S390X.HasEIMM = has(hwcap_EIMM) - S390X.HasETF3EH = has(hwcap_ETF3EH) - S390X.HasDFP = has(hwcap_DFP) - S390X.HasMSA = has(hwcap_MSA) - S390X.HasVX = has(hwcap_VX) - if S390X.HasVX { - S390X.HasVXE = has(hwcap_VXE) - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_loong64.go b/vendor/golang.org/x/sys/cpu/cpu_loong64.go deleted file mode 100644 index 0f57b05bd..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_loong64.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build loong64 -// +build loong64 - -package cpu - -const cacheLineSize = 64 - -func initOptions() { -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_mips64x.go deleted file mode 100644 index f4063c664..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_mips64x.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build mips64 || mips64le -// +build mips64 mips64le - -package cpu - -const cacheLineSize = 32 - -func initOptions() { - options = []option{ - {Name: "msa", Feature: &MIPS64X.HasMSA}, - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_mipsx.go b/vendor/golang.org/x/sys/cpu/cpu_mipsx.go deleted file mode 100644 index 07c4e36d8..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_mipsx.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build mips || mipsle -// +build mips mipsle - -package cpu - -const cacheLineSize = 32 - -func initOptions() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go deleted file mode 100644 index ebfb3fc8e..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import ( - "syscall" - "unsafe" -) - -// Minimal copy of functionality from x/sys/unix so the cpu package can call -// sysctl without depending on x/sys/unix. - -const ( - _CTL_QUERY = -2 - - _SYSCTL_VERS_1 = 0x1000000 -) - -var _zero uintptr - -func sysctl(mib []int32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, errno := syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(_p0), - uintptr(len(mib)), - uintptr(unsafe.Pointer(old)), - uintptr(unsafe.Pointer(oldlen)), - uintptr(unsafe.Pointer(new)), - uintptr(newlen)) - if errno != 0 { - return errno - } - return nil -} - -type sysctlNode struct { - Flags uint32 - Num int32 - Name [32]int8 - Ver uint32 - __rsvd uint32 - Un [16]byte - _sysctl_size [8]byte - _sysctl_func [8]byte - _sysctl_parent [8]byte - _sysctl_desc [8]byte -} - -func sysctlNodes(mib []int32) ([]sysctlNode, error) { - var olen uintptr - - // Get a list of all sysctl nodes below the given MIB by performing - // a sysctl for the given MIB with CTL_QUERY appended. - mib = append(mib, _CTL_QUERY) - qnode := sysctlNode{Flags: _SYSCTL_VERS_1} - qp := (*byte)(unsafe.Pointer(&qnode)) - sz := unsafe.Sizeof(qnode) - if err := sysctl(mib, nil, &olen, qp, sz); err != nil { - return nil, err - } - - // Now that we know the size, get the actual nodes. - nodes := make([]sysctlNode, olen/sz) - np := (*byte)(unsafe.Pointer(&nodes[0])) - if err := sysctl(mib, np, &olen, qp, sz); err != nil { - return nil, err - } - - return nodes, nil -} - -func nametomib(name string) ([]int32, error) { - // Split name into components. - var parts []string - last := 0 - for i := 0; i < len(name); i++ { - if name[i] == '.' { - parts = append(parts, name[last:i]) - last = i + 1 - } - } - parts = append(parts, name[last:]) - - mib := []int32{} - // Discover the nodes and construct the MIB OID. - for partno, part := range parts { - nodes, err := sysctlNodes(mib) - if err != nil { - return nil, err - } - for _, node := range nodes { - n := make([]byte, 0) - for i := range node.Name { - if node.Name[i] != 0 { - n = append(n, byte(node.Name[i])) - } - } - if string(n) == part { - mib = append(mib, int32(node.Num)) - break - } - } - if len(mib) != partno+1 { - return nil, err - } - } - - return mib, nil -} - -// aarch64SysctlCPUID is struct aarch64_sysctl_cpu_id from NetBSD's -type aarch64SysctlCPUID struct { - midr uint64 /* Main ID Register */ - revidr uint64 /* Revision ID Register */ - mpidr uint64 /* Multiprocessor Affinity Register */ - aa64dfr0 uint64 /* A64 Debug Feature Register 0 */ - aa64dfr1 uint64 /* A64 Debug Feature Register 1 */ - aa64isar0 uint64 /* A64 Instruction Set Attribute Register 0 */ - aa64isar1 uint64 /* A64 Instruction Set Attribute Register 1 */ - aa64mmfr0 uint64 /* A64 Memory Model Feature Register 0 */ - aa64mmfr1 uint64 /* A64 Memory Model Feature Register 1 */ - aa64mmfr2 uint64 /* A64 Memory Model Feature Register 2 */ - aa64pfr0 uint64 /* A64 Processor Feature Register 0 */ - aa64pfr1 uint64 /* A64 Processor Feature Register 1 */ - aa64zfr0 uint64 /* A64 SVE Feature ID Register 0 */ - mvfr0 uint32 /* Media and VFP Feature Register 0 */ - mvfr1 uint32 /* Media and VFP Feature Register 1 */ - mvfr2 uint32 /* Media and VFP Feature Register 2 */ - pad uint32 - clidr uint64 /* Cache Level ID Register */ - ctr uint64 /* Cache Type Register */ -} - -func sysctlCPUID(name string) (*aarch64SysctlCPUID, error) { - mib, err := nametomib(name) - if err != nil { - return nil, err - } - - out := aarch64SysctlCPUID{} - n := unsafe.Sizeof(out) - _, _, errno := syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - uintptr(len(mib)), - uintptr(unsafe.Pointer(&out)), - uintptr(unsafe.Pointer(&n)), - uintptr(0), - uintptr(0)) - if errno != 0 { - return nil, errno - } - return &out, nil -} - -func doinit() { - cpuid, err := sysctlCPUID("machdep.cpu0.cpu_id") - if err != nil { - setMinimalFeatures() - return - } - parseARM64SystemRegisters(cpuid.aa64isar0, cpuid.aa64isar1, cpuid.aa64pfr0) - - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go deleted file mode 100644 index 85b64d5cc..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import ( - "syscall" - "unsafe" -) - -// Minimal copy of functionality from x/sys/unix so the cpu package can call -// sysctl without depending on x/sys/unix. - -const ( - // From OpenBSD's sys/sysctl.h. - _CTL_MACHDEP = 7 - - // From OpenBSD's machine/cpu.h. - _CPU_ID_AA64ISAR0 = 2 - _CPU_ID_AA64ISAR1 = 3 -) - -// Implemented in the runtime package (runtime/sys_openbsd3.go) -func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - -//go:linkname syscall_syscall6 syscall.syscall6 - -func sysctl(mib []uint32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - _, _, errno := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(unsafe.Pointer(&mib[0])), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if errno != 0 { - return errno - } - return nil -} - -var libc_sysctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" - -func sysctlUint64(mib []uint32) (uint64, bool) { - var out uint64 - nout := unsafe.Sizeof(out) - if err := sysctl(mib, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); err != nil { - return 0, false - } - return out, true -} - -func doinit() { - setMinimalFeatures() - - // Get ID_AA64ISAR0 and ID_AA64ISAR1 from sysctl. - isar0, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR0}) - if !ok { - return - } - isar1, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR1}) - if !ok { - return - } - parseARM64SystemRegisters(isar0, isar1, 0) - - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s b/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s deleted file mode 100644 index 054ba05d6..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 - JMP libc_sysctl(SB) - -GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 -DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_arm.go b/vendor/golang.org/x/sys/cpu/cpu_other_arm.go deleted file mode 100644 index d7b4fb4cc..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_arm.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !linux && arm -// +build !linux,arm - -package cpu - -func archInit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go deleted file mode 100644 index f3cde129b..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !linux && !netbsd && !openbsd && arm64 -// +build !linux,!netbsd,!openbsd,arm64 - -package cpu - -func doinit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go deleted file mode 100644 index 0dafe9644..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !linux && (mips64 || mips64le) -// +build !linux -// +build mips64 mips64le - -package cpu - -func archInit() { - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go deleted file mode 100644 index 060d46b6e..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !aix && !linux && (ppc64 || ppc64le) -// +build !aix -// +build !linux -// +build ppc64 ppc64le - -package cpu - -func archInit() { - PPC64.IsPOWER8 = true - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go deleted file mode 100644 index dd10eb79f..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !linux && riscv64 -// +build !linux,riscv64 - -package cpu - -func archInit() { - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go deleted file mode 100644 index 4e8acd165..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build ppc64 || ppc64le -// +build ppc64 ppc64le - -package cpu - -const cacheLineSize = 128 - -func initOptions() { - options = []option{ - {Name: "darn", Feature: &PPC64.HasDARN}, - {Name: "scv", Feature: &PPC64.HasSCV}, - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_riscv64.go deleted file mode 100644 index ff7da60eb..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build riscv64 -// +build riscv64 - -package cpu - -const cacheLineSize = 64 - -func initOptions() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_s390x.go deleted file mode 100644 index 5881b8833..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_s390x.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -const cacheLineSize = 256 - -func initOptions() { - options = []option{ - {Name: "zarch", Feature: &S390X.HasZARCH, Required: true}, - {Name: "stfle", Feature: &S390X.HasSTFLE, Required: true}, - {Name: "ldisp", Feature: &S390X.HasLDISP, Required: true}, - {Name: "eimm", Feature: &S390X.HasEIMM, Required: true}, - {Name: "dfp", Feature: &S390X.HasDFP}, - {Name: "etf3eh", Feature: &S390X.HasETF3EH}, - {Name: "msa", Feature: &S390X.HasMSA}, - {Name: "aes", Feature: &S390X.HasAES}, - {Name: "aescbc", Feature: &S390X.HasAESCBC}, - {Name: "aesctr", Feature: &S390X.HasAESCTR}, - {Name: "aesgcm", Feature: &S390X.HasAESGCM}, - {Name: "ghash", Feature: &S390X.HasGHASH}, - {Name: "sha1", Feature: &S390X.HasSHA1}, - {Name: "sha256", Feature: &S390X.HasSHA256}, - {Name: "sha3", Feature: &S390X.HasSHA3}, - {Name: "sha512", Feature: &S390X.HasSHA512}, - {Name: "vx", Feature: &S390X.HasVX}, - {Name: "vxe", Feature: &S390X.HasVXE}, - } -} - -// bitIsSet reports whether the bit at index is set. The bit index -// is in big endian order, so bit index 0 is the leftmost bit. -func bitIsSet(bits []uint64, index uint) bool { - return bits[index/64]&((1<<63)>>(index%64)) != 0 -} - -// facility is a bit index for the named facility. -type facility uint8 - -const ( - // mandatory facilities - zarch facility = 1 // z architecture mode is active - stflef facility = 7 // store-facility-list-extended - ldisp facility = 18 // long-displacement - eimm facility = 21 // extended-immediate - - // miscellaneous facilities - dfp facility = 42 // decimal-floating-point - etf3eh facility = 30 // extended-translation 3 enhancement - - // cryptography facilities - msa facility = 17 // message-security-assist - msa3 facility = 76 // message-security-assist extension 3 - msa4 facility = 77 // message-security-assist extension 4 - msa5 facility = 57 // message-security-assist extension 5 - msa8 facility = 146 // message-security-assist extension 8 - msa9 facility = 155 // message-security-assist extension 9 - - // vector facilities - vx facility = 129 // vector facility - vxe facility = 135 // vector-enhancements 1 - vxe2 facility = 148 // vector-enhancements 2 -) - -// facilityList contains the result of an STFLE call. -// Bits are numbered in big endian order so the -// leftmost bit (the MSB) is at index 0. -type facilityList struct { - bits [4]uint64 -} - -// Has reports whether the given facilities are present. -func (s *facilityList) Has(fs ...facility) bool { - if len(fs) == 0 { - panic("no facility bits provided") - } - for _, f := range fs { - if !bitIsSet(s.bits[:], uint(f)) { - return false - } - } - return true -} - -// function is the code for the named cryptographic function. -type function uint8 - -const ( - // KM{,A,C,CTR} function codes - aes128 function = 18 // AES-128 - aes192 function = 19 // AES-192 - aes256 function = 20 // AES-256 - - // K{I,L}MD function codes - sha1 function = 1 // SHA-1 - sha256 function = 2 // SHA-256 - sha512 function = 3 // SHA-512 - sha3_224 function = 32 // SHA3-224 - sha3_256 function = 33 // SHA3-256 - sha3_384 function = 34 // SHA3-384 - sha3_512 function = 35 // SHA3-512 - shake128 function = 36 // SHAKE-128 - shake256 function = 37 // SHAKE-256 - - // KLMD function codes - ghash function = 65 // GHASH -) - -// queryResult contains the result of a Query function -// call. Bits are numbered in big endian order so the -// leftmost bit (the MSB) is at index 0. -type queryResult struct { - bits [2]uint64 -} - -// Has reports whether the given functions are present. -func (q *queryResult) Has(fns ...function) bool { - if len(fns) == 0 { - panic("no function codes provided") - } - for _, f := range fns { - if !bitIsSet(q.bits[:], uint(f)) { - return false - } - } - return true -} - -func doinit() { - initS390Xbase() - - // We need implementations of stfle, km and so on - // to detect cryptographic features. - if !haveAsmFunctions() { - return - } - - // optional cryptographic functions - if S390X.HasMSA { - aes := []function{aes128, aes192, aes256} - - // cipher message - km, kmc := kmQuery(), kmcQuery() - S390X.HasAES = km.Has(aes...) - S390X.HasAESCBC = kmc.Has(aes...) - if S390X.HasSTFLE { - facilities := stfle() - if facilities.Has(msa4) { - kmctr := kmctrQuery() - S390X.HasAESCTR = kmctr.Has(aes...) - } - if facilities.Has(msa8) { - kma := kmaQuery() - S390X.HasAESGCM = kma.Has(aes...) - } - } - - // compute message digest - kimd := kimdQuery() // intermediate (no padding) - klmd := klmdQuery() // last (padding) - S390X.HasSHA1 = kimd.Has(sha1) && klmd.Has(sha1) - S390X.HasSHA256 = kimd.Has(sha256) && klmd.Has(sha256) - S390X.HasSHA512 = kimd.Has(sha512) && klmd.Has(sha512) - S390X.HasGHASH = kimd.Has(ghash) // KLMD-GHASH does not exist - sha3 := []function{ - sha3_224, sha3_256, sha3_384, sha3_512, - shake128, shake256, - } - S390X.HasSHA3 = kimd.Has(sha3...) && klmd.Has(sha3...) - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_s390x.s b/vendor/golang.org/x/sys/cpu/cpu_s390x.s deleted file mode 100644 index 96f81e209..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_s390x.s +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build gc -// +build gc - -#include "textflag.h" - -// func stfle() facilityList -TEXT ·stfle(SB), NOSPLIT|NOFRAME, $0-32 - MOVD $ret+0(FP), R1 - MOVD $3, R0 // last doubleword index to store - XC $32, (R1), (R1) // clear 4 doublewords (32 bytes) - WORD $0xb2b01000 // store facility list extended (STFLE) - RET - -// func kmQuery() queryResult -TEXT ·kmQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KM-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92E0024 // cipher message (KM) - RET - -// func kmcQuery() queryResult -TEXT ·kmcQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMC-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92F0024 // cipher message with chaining (KMC) - RET - -// func kmctrQuery() queryResult -TEXT ·kmctrQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMCTR-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92D4024 // cipher message with counter (KMCTR) - RET - -// func kmaQuery() queryResult -TEXT ·kmaQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMA-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xb9296024 // cipher message with authentication (KMA) - RET - -// func kimdQuery() queryResult -TEXT ·kimdQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KIMD-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB93E0024 // compute intermediate message digest (KIMD) - RET - -// func klmdQuery() queryResult -TEXT ·klmdQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KLMD-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB93F0024 // compute last message digest (KLMD) - RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_wasm.go b/vendor/golang.org/x/sys/cpu/cpu_wasm.go deleted file mode 100644 index 7747d888a..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_wasm.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build wasm -// +build wasm - -package cpu - -// We're compiling the cpu package for an unknown (software-abstracted) CPU. -// Make CacheLinePad an empty struct and hope that the usual struct alignment -// rules are good enough. - -const cacheLineSize = 0 - -func initOptions() {} - -func archInit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go deleted file mode 100644 index 2dcde8285..000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build 386 || amd64 || amd64p32 -// +build 386 amd64 amd64p32 - -package cpu - -import "runtime" - -const cacheLineSize = 64 - -func initOptions() { - options = []option{ - {Name: "adx", Feature: &X86.HasADX}, - {Name: "aes", Feature: &X86.HasAES}, - {Name: "avx", Feature: &X86.HasAVX}, - {Name: "avx2", Feature: &X86.HasAVX2}, - {Name: "avx512", Feature: &X86.HasAVX512}, - {Name: "avx512f", Feature: &X86.HasAVX512F}, - {Name: "avx512cd", Feature: &X86.HasAVX512CD}, - {Name: "avx512er", Feature: &X86.HasAVX512ER}, - {Name: "avx512pf", Feature: &X86.HasAVX512PF}, - {Name: "avx512vl", Feature: &X86.HasAVX512VL}, - {Name: "avx512bw", Feature: &X86.HasAVX512BW}, - {Name: "avx512dq", Feature: &X86.HasAVX512DQ}, - {Name: "avx512ifma", Feature: &X86.HasAVX512IFMA}, - {Name: "avx512vbmi", Feature: &X86.HasAVX512VBMI}, - {Name: "avx512vnniw", Feature: &X86.HasAVX5124VNNIW}, - {Name: "avx5124fmaps", Feature: &X86.HasAVX5124FMAPS}, - {Name: "avx512vpopcntdq", Feature: &X86.HasAVX512VPOPCNTDQ}, - {Name: "avx512vpclmulqdq", Feature: &X86.HasAVX512VPCLMULQDQ}, - {Name: "avx512vnni", Feature: &X86.HasAVX512VNNI}, - {Name: "avx512gfni", Feature: &X86.HasAVX512GFNI}, - {Name: "avx512vaes", Feature: &X86.HasAVX512VAES}, - {Name: "avx512vbmi2", Feature: &X86.HasAVX512VBMI2}, - {Name: "avx512bitalg", Feature: &X86.HasAVX512BITALG}, - {Name: "avx512bf16", Feature: &X86.HasAVX512BF16}, - {Name: "amxtile", Feature: &X86.HasAMXTile}, - {Name: "amxint8", Feature: &X86.HasAMXInt8}, - {Name: "amxbf16", Feature: &X86.HasAMXBF16}, - {Name: "bmi1", Feature: &X86.HasBMI1}, - {Name: "bmi2", Feature: &X86.HasBMI2}, - {Name: "cx16", Feature: &X86.HasCX16}, - {Name: "erms", Feature: &X86.HasERMS}, - {Name: "fma", Feature: &X86.HasFMA}, - {Name: "osxsave", Feature: &X86.HasOSXSAVE}, - {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, - {Name: "popcnt", Feature: &X86.HasPOPCNT}, - {Name: "rdrand", Feature: &X86.HasRDRAND}, - {Name: "rdseed", Feature: &X86.HasRDSEED}, - {Name: "sse3", Feature: &X86.HasSSE3}, - {Name: "sse41", Feature: &X86.HasSSE41}, - {Name: "sse42", Feature: &X86.HasSSE42}, - {Name: "ssse3", Feature: &X86.HasSSSE3}, - - // These capabilities should always be enabled on amd64: - {Name: "sse2", Feature: &X86.HasSSE2, Required: runtime.GOARCH == "amd64"}, - } -} - -func archInit() { - - Initialized = true - - maxID, _, _, _ := cpuid(0, 0) - - if maxID < 1 { - return - } - - _, _, ecx1, edx1 := cpuid(1, 0) - X86.HasSSE2 = isSet(26, edx1) - - X86.HasSSE3 = isSet(0, ecx1) - X86.HasPCLMULQDQ = isSet(1, ecx1) - X86.HasSSSE3 = isSet(9, ecx1) - X86.HasFMA = isSet(12, ecx1) - X86.HasCX16 = isSet(13, ecx1) - X86.HasSSE41 = isSet(19, ecx1) - X86.HasSSE42 = isSet(20, ecx1) - X86.HasPOPCNT = isSet(23, ecx1) - X86.HasAES = isSet(25, ecx1) - X86.HasOSXSAVE = isSet(27, ecx1) - X86.HasRDRAND = isSet(30, ecx1) - - var osSupportsAVX, osSupportsAVX512 bool - // For XGETBV, OSXSAVE bit is required and sufficient. - if X86.HasOSXSAVE { - eax, _ := xgetbv() - // Check if XMM and YMM registers have OS support. - osSupportsAVX = isSet(1, eax) && isSet(2, eax) - - if runtime.GOOS == "darwin" { - // Darwin doesn't save/restore AVX-512 mask registers correctly across signal handlers. - // Since users can't rely on mask register contents, let's not advertise AVX-512 support. - // See issue 49233. - osSupportsAVX512 = false - } else { - // Check if OPMASK and ZMM registers have OS support. - osSupportsAVX512 = osSupportsAVX && isSet(5, eax) && isSet(6, eax) && isSet(7, eax) - } - } - - X86.HasAVX = isSet(28, ecx1) && osSupportsAVX - - if maxID < 7 { - return - } - - _, ebx7, ecx7, edx7 := cpuid(7, 0) - X86.HasBMI1 = isSet(3, ebx7) - X86.HasAVX2 = isSet(5, ebx7) && osSupportsAVX - X86.HasBMI2 = isSet(8, ebx7) - X86.HasERMS = isSet(9, ebx7) - X86.HasRDSEED = isSet(18, ebx7) - X86.HasADX = isSet(19, ebx7) - - X86.HasAVX512 = isSet(16, ebx7) && osSupportsAVX512 // Because avx-512 foundation is the core required extension - if X86.HasAVX512 { - X86.HasAVX512F = true - X86.HasAVX512CD = isSet(28, ebx7) - X86.HasAVX512ER = isSet(27, ebx7) - X86.HasAVX512PF = isSet(26, ebx7) - X86.HasAVX512VL = isSet(31, ebx7) - X86.HasAVX512BW = isSet(30, ebx7) - X86.HasAVX512DQ = isSet(17, ebx7) - X86.HasAVX512IFMA = isSet(21, ebx7) - X86.HasAVX512VBMI = isSet(1, ecx7) - X86.HasAVX5124VNNIW = isSet(2, edx7) - X86.HasAVX5124FMAPS = isSet(3, edx7) - X86.HasAVX512VPOPCNTDQ = isSet(14, ecx7) - X86.HasAVX512VPCLMULQDQ = isSet(10, ecx7) - X86.HasAVX512VNNI = isSet(11, ecx7) - X86.HasAVX512GFNI = isSet(8, ecx7) - X86.HasAVX512VAES = isSet(9, ecx7) - X86.HasAVX512VBMI2 = isSet(6, ecx7) - X86.HasAVX512BITALG = isSet(12, ecx7) - - eax71, _, _, _ := cpuid(7, 1) - X86.HasAVX512BF16 = isSet(5, eax71) - } - - X86.HasAMXTile = isSet(24, edx7) - X86.HasAMXInt8 = isSet(25, edx7) - X86.HasAMXBF16 = isSet(22, edx7) -} - -func isSet(bitpos uint, value uint32) bool { - return value&(1<> 63)) -) - -// For those platforms don't have a 'cpuid' equivalent we use HWCAP/HWCAP2 -// These are initialized in cpu_$GOARCH.go -// and should not be changed after they are initialized. -var hwCap uint -var hwCap2 uint - -func readHWCAP() error { - // For Go 1.21+, get auxv from the Go runtime. - if a := getAuxv(); len(a) > 0 { - for len(a) >= 2 { - tag, val := a[0], uint(a[1]) - a = a[2:] - switch tag { - case _AT_HWCAP: - hwCap = val - case _AT_HWCAP2: - hwCap2 = val - } - } - return nil - } - - buf, err := os.ReadFile(procAuxv) - if err != nil { - // e.g. on android /proc/self/auxv is not accessible, so silently - // ignore the error and leave Initialized = false. On some - // architectures (e.g. arm64) doinit() implements a fallback - // readout and will set Initialized = true again. - return err - } - bo := hostByteOrder() - for len(buf) >= 2*(uintSize/8) { - var tag, val uint - switch uintSize { - case 32: - tag = uint(bo.Uint32(buf[0:])) - val = uint(bo.Uint32(buf[4:])) - buf = buf[8:] - case 64: - tag = uint(bo.Uint64(buf[0:])) - val = uint(bo.Uint64(buf[8:])) - buf = buf[16:] - } - switch tag { - case _AT_HWCAP: - hwCap = val - case _AT_HWCAP2: - hwCap2 = val - } - } - return nil -} diff --git a/vendor/golang.org/x/sys/cpu/parse.go b/vendor/golang.org/x/sys/cpu/parse.go deleted file mode 100644 index 762b63d68..000000000 --- a/vendor/golang.org/x/sys/cpu/parse.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -import "strconv" - -// parseRelease parses a dot-separated version number. It follows the semver -// syntax, but allows the minor and patch versions to be elided. -// -// This is a copy of the Go runtime's parseRelease from -// https://golang.org/cl/209597. -func parseRelease(rel string) (major, minor, patch int, ok bool) { - // Strip anything after a dash or plus. - for i := 0; i < len(rel); i++ { - if rel[i] == '-' || rel[i] == '+' { - rel = rel[:i] - break - } - } - - next := func() (int, bool) { - for i := 0; i < len(rel); i++ { - if rel[i] == '.' { - ver, err := strconv.Atoi(rel[:i]) - rel = rel[i+1:] - return ver, err == nil - } - } - ver, err := strconv.Atoi(rel) - rel = "" - return ver, err == nil - } - if major, ok = next(); !ok || rel == "" { - return - } - if minor, ok = next(); !ok || rel == "" { - return - } - patch, ok = next() - return -} diff --git a/vendor/golang.org/x/sys/cpu/proc_cpuinfo_linux.go b/vendor/golang.org/x/sys/cpu/proc_cpuinfo_linux.go deleted file mode 100644 index d87bd6b3e..000000000 --- a/vendor/golang.org/x/sys/cpu/proc_cpuinfo_linux.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux && arm64 -// +build linux,arm64 - -package cpu - -import ( - "errors" - "io" - "os" - "strings" -) - -func readLinuxProcCPUInfo() error { - f, err := os.Open("/proc/cpuinfo") - if err != nil { - return err - } - defer f.Close() - - var buf [1 << 10]byte // enough for first CPU - n, err := io.ReadFull(f, buf[:]) - if err != nil && err != io.ErrUnexpectedEOF { - return err - } - in := string(buf[:n]) - const features = "\nFeatures : " - i := strings.Index(in, features) - if i == -1 { - return errors.New("no CPU features found") - } - in = in[i+len(features):] - if i := strings.Index(in, "\n"); i != -1 { - in = in[:i] - } - m := map[string]*bool{} - - initOptions() // need it early here; it's harmless to call twice - for _, o := range options { - m[o.Name] = o.Feature - } - // The EVTSTRM field has alias "evstrm" in Go, but Linux calls it "evtstrm". - m["evtstrm"] = &ARM64.HasEVTSTRM - - for _, f := range strings.Fields(in) { - if p, ok := m[f]; ok { - *p = true - } - } - return nil -} diff --git a/vendor/golang.org/x/sys/cpu/runtime_auxv.go b/vendor/golang.org/x/sys/cpu/runtime_auxv.go deleted file mode 100644 index 5f92ac9a2..000000000 --- a/vendor/golang.org/x/sys/cpu/runtime_auxv.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2023 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cpu - -// getAuxvFn is non-nil on Go 1.21+ (via runtime_auxv_go121.go init) -// on platforms that use auxv. -var getAuxvFn func() []uintptr - -func getAuxv() []uintptr { - if getAuxvFn == nil { - return nil - } - return getAuxvFn() -} diff --git a/vendor/golang.org/x/sys/cpu/runtime_auxv_go121.go b/vendor/golang.org/x/sys/cpu/runtime_auxv_go121.go deleted file mode 100644 index b975ea2a0..000000000 --- a/vendor/golang.org/x/sys/cpu/runtime_auxv_go121.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2023 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.21 -// +build go1.21 - -package cpu - -import ( - _ "unsafe" // for linkname -) - -//go:linkname runtime_getAuxv runtime.getAuxv -func runtime_getAuxv() []uintptr - -func init() { - getAuxvFn = runtime_getAuxv -} diff --git a/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go b/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go deleted file mode 100644 index 96134157a..000000000 --- a/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Recreate a getsystemcfg syscall handler instead of -// using the one provided by x/sys/unix to avoid having -// the dependency between them. (See golang.org/issue/32102) -// Moreover, this file will be used during the building of -// gccgo's libgo and thus must not used a CGo method. - -//go:build aix && gccgo -// +build aix,gccgo - -package cpu - -import ( - "syscall" -) - -//extern getsystemcfg -func gccgoGetsystemcfg(label uint32) (r uint64) - -func callgetsystemcfg(label int) (r1 uintptr, e1 syscall.Errno) { - r1 = uintptr(gccgoGetsystemcfg(uint32(label))) - e1 = syscall.GetErrno() - return -} diff --git a/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go b/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go deleted file mode 100644 index 904be42ff..000000000 --- a/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Minimal copy of x/sys/unix so the cpu package can make a -// system call on AIX without depending on x/sys/unix. -// (See golang.org/issue/32102) - -//go:build aix && ppc64 && gc -// +build aix,ppc64,gc - -package cpu - -import ( - "syscall" - "unsafe" -) - -//go:cgo_import_dynamic libc_getsystemcfg getsystemcfg "libc.a/shr_64.o" - -//go:linkname libc_getsystemcfg libc_getsystemcfg - -type syscallFunc uintptr - -var libc_getsystemcfg syscallFunc - -type errno = syscall.Errno - -// Implemented in runtime/syscall_aix.go. -func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) -func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) - -func callgetsystemcfg(label int) (r1 uintptr, e1 errno) { - r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_getsystemcfg)), 1, uintptr(label), 0, 0, 0, 0, 0) - return -} diff --git a/vendor/google.golang.org/grpc/health/client.go b/vendor/google.golang.org/grpc/health/client.go deleted file mode 100644 index b5bee4838..000000000 --- a/vendor/google.golang.org/grpc/health/client.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Copyright 2018 gRPC 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 health - -import ( - "context" - "fmt" - "io" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - healthpb "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/internal/backoff" - "google.golang.org/grpc/status" -) - -var ( - backoffStrategy = backoff.DefaultExponential - backoffFunc = func(ctx context.Context, retries int) bool { - d := backoffStrategy.Backoff(retries) - timer := time.NewTimer(d) - select { - case <-timer.C: - return true - case <-ctx.Done(): - timer.Stop() - return false - } - } -) - -func init() { - internal.HealthCheckFunc = clientHealthCheck -} - -const healthCheckMethod = "/grpc.health.v1.Health/Watch" - -// This function implements the protocol defined at: -// https://github.com/grpc/grpc/blob/master/doc/health-checking.md -func clientHealthCheck(ctx context.Context, newStream func(string) (interface{}, error), setConnectivityState func(connectivity.State, error), service string) error { - tryCnt := 0 - -retryConnection: - for { - // Backs off if the connection has failed in some way without receiving a message in the previous retry. - if tryCnt > 0 && !backoffFunc(ctx, tryCnt-1) { - return nil - } - tryCnt++ - - if ctx.Err() != nil { - return nil - } - setConnectivityState(connectivity.Connecting, nil) - rawS, err := newStream(healthCheckMethod) - if err != nil { - continue retryConnection - } - - s, ok := rawS.(grpc.ClientStream) - // Ideally, this should never happen. But if it happens, the server is marked as healthy for LBing purposes. - if !ok { - setConnectivityState(connectivity.Ready, nil) - return fmt.Errorf("newStream returned %v (type %T); want grpc.ClientStream", rawS, rawS) - } - - if err = s.SendMsg(&healthpb.HealthCheckRequest{Service: service}); err != nil && err != io.EOF { - // Stream should have been closed, so we can safely continue to create a new stream. - continue retryConnection - } - s.CloseSend() - - resp := new(healthpb.HealthCheckResponse) - for { - err = s.RecvMsg(resp) - - // Reports healthy for the LBing purposes if health check is not implemented in the server. - if status.Code(err) == codes.Unimplemented { - setConnectivityState(connectivity.Ready, nil) - return err - } - - // Reports unhealthy if server's Watch method gives an error other than UNIMPLEMENTED. - if err != nil { - setConnectivityState(connectivity.TransientFailure, fmt.Errorf("connection active but received health check RPC error: %v", err)) - continue retryConnection - } - - // As a message has been received, removes the need for backoff for the next retry by resetting the try count. - tryCnt = 0 - if resp.Status == healthpb.HealthCheckResponse_SERVING { - setConnectivityState(connectivity.Ready, nil) - } else { - setConnectivityState(connectivity.TransientFailure, fmt.Errorf("connection active but health check failed. status=%s", resp.Status)) - } - } - } -} diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go deleted file mode 100644 index 142d35f75..000000000 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2015 The gRPC 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. - -// The canonical version of this proto can be found at -// https://github.com/grpc/grpc-proto/blob/master/grpc/health/v1/health.proto - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.30.0 -// protoc v4.22.0 -// source: grpc/health/v1/health.proto - -package grpc_health_v1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type HealthCheckResponse_ServingStatus int32 - -const ( - HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0 - HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1 - HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2 - HealthCheckResponse_SERVICE_UNKNOWN HealthCheckResponse_ServingStatus = 3 // Used only by the Watch method. -) - -// Enum value maps for HealthCheckResponse_ServingStatus. -var ( - HealthCheckResponse_ServingStatus_name = map[int32]string{ - 0: "UNKNOWN", - 1: "SERVING", - 2: "NOT_SERVING", - 3: "SERVICE_UNKNOWN", - } - HealthCheckResponse_ServingStatus_value = map[string]int32{ - "UNKNOWN": 0, - "SERVING": 1, - "NOT_SERVING": 2, - "SERVICE_UNKNOWN": 3, - } -) - -func (x HealthCheckResponse_ServingStatus) Enum() *HealthCheckResponse_ServingStatus { - p := new(HealthCheckResponse_ServingStatus) - *p = x - return p -} - -func (x HealthCheckResponse_ServingStatus) String() string { - return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) -} - -func (HealthCheckResponse_ServingStatus) Descriptor() protoreflect.EnumDescriptor { - return file_grpc_health_v1_health_proto_enumTypes[0].Descriptor() -} - -func (HealthCheckResponse_ServingStatus) Type() protoreflect.EnumType { - return &file_grpc_health_v1_health_proto_enumTypes[0] -} - -func (x HealthCheckResponse_ServingStatus) Number() protoreflect.EnumNumber { - return protoreflect.EnumNumber(x) -} - -// Deprecated: Use HealthCheckResponse_ServingStatus.Descriptor instead. -func (HealthCheckResponse_ServingStatus) EnumDescriptor() ([]byte, []int) { - return file_grpc_health_v1_health_proto_rawDescGZIP(), []int{1, 0} -} - -type HealthCheckRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` -} - -func (x *HealthCheckRequest) Reset() { - *x = HealthCheckRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_health_v1_health_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *HealthCheckRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HealthCheckRequest) ProtoMessage() {} - -func (x *HealthCheckRequest) ProtoReflect() protoreflect.Message { - mi := &file_grpc_health_v1_health_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HealthCheckRequest.ProtoReflect.Descriptor instead. -func (*HealthCheckRequest) Descriptor() ([]byte, []int) { - return file_grpc_health_v1_health_proto_rawDescGZIP(), []int{0} -} - -func (x *HealthCheckRequest) GetService() string { - if x != nil { - return x.Service - } - return "" -} - -type HealthCheckResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=grpc.health.v1.HealthCheckResponse_ServingStatus" json:"status,omitempty"` -} - -func (x *HealthCheckResponse) Reset() { - *x = HealthCheckResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_health_v1_health_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *HealthCheckResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HealthCheckResponse) ProtoMessage() {} - -func (x *HealthCheckResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_health_v1_health_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HealthCheckResponse.ProtoReflect.Descriptor instead. -func (*HealthCheckResponse) Descriptor() ([]byte, []int) { - return file_grpc_health_v1_health_proto_rawDescGZIP(), []int{1} -} - -func (x *HealthCheckResponse) GetStatus() HealthCheckResponse_ServingStatus { - if x != nil { - return x.Status - } - return HealthCheckResponse_UNKNOWN -} - -var File_grpc_health_v1_health_proto protoreflect.FileDescriptor - -var file_grpc_health_v1_health_proto_rawDesc = []byte{ - 0x0a, 0x1b, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2f, 0x76, 0x31, - 0x2f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0e, 0x67, - 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x22, 0x2e, 0x0a, - 0x12, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x22, 0xb1, 0x01, - 0x0a, 0x13, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x31, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, - 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, - 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, - 0x22, 0x4f, 0x0a, 0x0d, 0x53, 0x65, 0x72, 0x76, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x0b, - 0x0a, 0x07, 0x53, 0x45, 0x52, 0x56, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, - 0x4f, 0x54, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x13, 0x0a, 0x0f, - 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, - 0x03, 0x32, 0xae, 0x01, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x50, 0x0a, 0x05, - 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, - 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, 0x70, 0x63, - 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x52, - 0x0a, 0x05, 0x57, 0x61, 0x74, 0x63, 0x68, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, - 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, - 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x30, 0x01, 0x42, 0x61, 0x0a, 0x11, 0x69, 0x6f, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, - 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, - 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x68, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x5f, 0x76, 0x31, 0xaa, 0x02, 0x0e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x61, 0x6c, - 0x74, 0x68, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_grpc_health_v1_health_proto_rawDescOnce sync.Once - file_grpc_health_v1_health_proto_rawDescData = file_grpc_health_v1_health_proto_rawDesc -) - -func file_grpc_health_v1_health_proto_rawDescGZIP() []byte { - file_grpc_health_v1_health_proto_rawDescOnce.Do(func() { - file_grpc_health_v1_health_proto_rawDescData = protoimpl.X.CompressGZIP(file_grpc_health_v1_health_proto_rawDescData) - }) - return file_grpc_health_v1_health_proto_rawDescData -} - -var file_grpc_health_v1_health_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_grpc_health_v1_health_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_grpc_health_v1_health_proto_goTypes = []interface{}{ - (HealthCheckResponse_ServingStatus)(0), // 0: grpc.health.v1.HealthCheckResponse.ServingStatus - (*HealthCheckRequest)(nil), // 1: grpc.health.v1.HealthCheckRequest - (*HealthCheckResponse)(nil), // 2: grpc.health.v1.HealthCheckResponse -} -var file_grpc_health_v1_health_proto_depIdxs = []int32{ - 0, // 0: grpc.health.v1.HealthCheckResponse.status:type_name -> grpc.health.v1.HealthCheckResponse.ServingStatus - 1, // 1: grpc.health.v1.Health.Check:input_type -> grpc.health.v1.HealthCheckRequest - 1, // 2: grpc.health.v1.Health.Watch:input_type -> grpc.health.v1.HealthCheckRequest - 2, // 3: grpc.health.v1.Health.Check:output_type -> grpc.health.v1.HealthCheckResponse - 2, // 4: grpc.health.v1.Health.Watch:output_type -> grpc.health.v1.HealthCheckResponse - 3, // [3:5] is the sub-list for method output_type - 1, // [1:3] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name -} - -func init() { file_grpc_health_v1_health_proto_init() } -func file_grpc_health_v1_health_proto_init() { - if File_grpc_health_v1_health_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_grpc_health_v1_health_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*HealthCheckRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_health_v1_health_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*HealthCheckResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_grpc_health_v1_health_proto_rawDesc, - NumEnums: 1, - NumMessages: 2, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_grpc_health_v1_health_proto_goTypes, - DependencyIndexes: file_grpc_health_v1_health_proto_depIdxs, - EnumInfos: file_grpc_health_v1_health_proto_enumTypes, - MessageInfos: file_grpc_health_v1_health_proto_msgTypes, - }.Build() - File_grpc_health_v1_health_proto = out.File - file_grpc_health_v1_health_proto_rawDesc = nil - file_grpc_health_v1_health_proto_goTypes = nil - file_grpc_health_v1_health_proto_depIdxs = nil -} 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 deleted file mode 100644 index a01a1b4d5..000000000 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2015 The gRPC 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. - -// The canonical version of this proto can be found at -// https://github.com/grpc/grpc-proto/blob/master/grpc/health/v1/health.proto - -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.3.0 -// - protoc v4.22.0 -// source: grpc/health/v1/health.proto - -package grpc_health_v1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -const ( - Health_Check_FullMethodName = "/grpc.health.v1.Health/Check" - Health_Watch_FullMethodName = "/grpc.health.v1.Health/Watch" -) - -// HealthClient is the client API for Health service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type HealthClient interface { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. - Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) -} - -type healthClient struct { - cc grpc.ClientConnInterface -} - -func NewHealthClient(cc grpc.ClientConnInterface) HealthClient { - return &healthClient{cc} -} - -func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { - out := new(HealthCheckResponse) - err := c.cc.Invoke(ctx, Health_Check_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &Health_ServiceDesc.Streams[0], Health_Watch_FullMethodName, opts...) - if err != nil { - return nil, err - } - x := &healthWatchClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Health_WatchClient interface { - Recv() (*HealthCheckResponse, error) - grpc.ClientStream -} - -type healthWatchClient struct { - grpc.ClientStream -} - -func (x *healthWatchClient) Recv() (*HealthCheckResponse, error) { - m := new(HealthCheckResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// HealthServer is the server API for Health service. -// All implementations should embed UnimplementedHealthServer -// for forward compatibility -type HealthServer interface { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. - Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - Watch(*HealthCheckRequest, Health_WatchServer) error -} - -// UnimplementedHealthServer should be embedded to have forward compatible implementations. -type UnimplementedHealthServer struct { -} - -func (UnimplementedHealthServer) Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") -} -func (UnimplementedHealthServer) Watch(*HealthCheckRequest, Health_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} - -// UnsafeHealthServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to HealthServer will -// result in compilation errors. -type UnsafeHealthServer interface { - mustEmbedUnimplementedHealthServer() -} - -func RegisterHealthServer(s grpc.ServiceRegistrar, srv HealthServer) { - s.RegisterService(&Health_ServiceDesc, srv) -} - -func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HealthCheckRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(HealthServer).Check(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: Health_Check_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(HealthCheckRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(HealthServer).Watch(m, &healthWatchServer{stream}) -} - -type Health_WatchServer interface { - Send(*HealthCheckResponse) error - grpc.ServerStream -} - -type healthWatchServer struct { - grpc.ServerStream -} - -func (x *healthWatchServer) Send(m *HealthCheckResponse) error { - return x.ServerStream.SendMsg(m) -} - -// Health_ServiceDesc is the grpc.ServiceDesc for Health service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var Health_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.health.v1.Health", - HandlerType: (*HealthServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Check", - Handler: _Health_Check_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: _Health_Watch_Handler, - ServerStreams: true, - }, - }, - Metadata: "grpc/health/v1/health.proto", -} diff --git a/vendor/google.golang.org/grpc/health/logging.go b/vendor/google.golang.org/grpc/health/logging.go deleted file mode 100644 index 83c6acf55..000000000 --- a/vendor/google.golang.org/grpc/health/logging.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * - * Copyright 2020 gRPC 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 health - -import "google.golang.org/grpc/grpclog" - -var logger = grpclog.Component("health_service") diff --git a/vendor/google.golang.org/grpc/health/server.go b/vendor/google.golang.org/grpc/health/server.go deleted file mode 100644 index cce6312d7..000000000 --- a/vendor/google.golang.org/grpc/health/server.go +++ /dev/null @@ -1,163 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 health provides a service that exposes server's health and it must be -// imported to enable support for client-side health checks. -package health - -import ( - "context" - "sync" - - "google.golang.org/grpc/codes" - healthgrpc "google.golang.org/grpc/health/grpc_health_v1" - healthpb "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/status" -) - -// Server implements `service Health`. -type Server struct { - healthgrpc.UnimplementedHealthServer - mu sync.RWMutex - // If shutdown is true, it's expected all serving status is NOT_SERVING, and - // will stay in NOT_SERVING. - shutdown bool - // statusMap stores the serving status of the services this Server monitors. - statusMap map[string]healthpb.HealthCheckResponse_ServingStatus - updates map[string]map[healthgrpc.Health_WatchServer]chan healthpb.HealthCheckResponse_ServingStatus -} - -// NewServer returns a new Server. -func NewServer() *Server { - return &Server{ - statusMap: map[string]healthpb.HealthCheckResponse_ServingStatus{"": healthpb.HealthCheckResponse_SERVING}, - updates: make(map[string]map[healthgrpc.Health_WatchServer]chan healthpb.HealthCheckResponse_ServingStatus), - } -} - -// Check implements `service Health`. -func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { - s.mu.RLock() - defer s.mu.RUnlock() - if servingStatus, ok := s.statusMap[in.Service]; ok { - return &healthpb.HealthCheckResponse{ - Status: servingStatus, - }, nil - } - return nil, status.Error(codes.NotFound, "unknown service") -} - -// Watch implements `service Health`. -func (s *Server) Watch(in *healthpb.HealthCheckRequest, stream healthgrpc.Health_WatchServer) error { - service := in.Service - // update channel is used for getting service status updates. - update := make(chan healthpb.HealthCheckResponse_ServingStatus, 1) - s.mu.Lock() - // Puts the initial status to the channel. - if servingStatus, ok := s.statusMap[service]; ok { - update <- servingStatus - } else { - update <- healthpb.HealthCheckResponse_SERVICE_UNKNOWN - } - - // Registers the update channel to the correct place in the updates map. - if _, ok := s.updates[service]; !ok { - s.updates[service] = make(map[healthgrpc.Health_WatchServer]chan healthpb.HealthCheckResponse_ServingStatus) - } - s.updates[service][stream] = update - defer func() { - s.mu.Lock() - delete(s.updates[service], stream) - s.mu.Unlock() - }() - s.mu.Unlock() - - var lastSentStatus healthpb.HealthCheckResponse_ServingStatus = -1 - for { - select { - // Status updated. Sends the up-to-date status to the client. - case servingStatus := <-update: - if lastSentStatus == servingStatus { - continue - } - lastSentStatus = servingStatus - err := stream.Send(&healthpb.HealthCheckResponse{Status: servingStatus}) - if err != nil { - return status.Error(codes.Canceled, "Stream has ended.") - } - // Context done. Removes the update channel from the updates map. - case <-stream.Context().Done(): - return status.Error(codes.Canceled, "Stream has ended.") - } - } -} - -// SetServingStatus is called when need to reset the serving status of a service -// or insert a new service entry into the statusMap. -func (s *Server) SetServingStatus(service string, servingStatus healthpb.HealthCheckResponse_ServingStatus) { - s.mu.Lock() - defer s.mu.Unlock() - if s.shutdown { - logger.Infof("health: status changing for %s to %v is ignored because health service is shutdown", service, servingStatus) - return - } - - s.setServingStatusLocked(service, servingStatus) -} - -func (s *Server) setServingStatusLocked(service string, servingStatus healthpb.HealthCheckResponse_ServingStatus) { - s.statusMap[service] = servingStatus - for _, update := range s.updates[service] { - // Clears previous updates, that are not sent to the client, from the channel. - // This can happen if the client is not reading and the server gets flow control limited. - select { - case <-update: - default: - } - // Puts the most recent update to the channel. - update <- servingStatus - } -} - -// Shutdown sets all serving status to NOT_SERVING, and configures the server to -// ignore all future status changes. -// -// This changes serving status for all services. To set status for a particular -// services, call SetServingStatus(). -func (s *Server) Shutdown() { - s.mu.Lock() - defer s.mu.Unlock() - s.shutdown = true - for service := range s.statusMap { - s.setServingStatusLocked(service, healthpb.HealthCheckResponse_NOT_SERVING) - } -} - -// Resume sets all serving status to SERVING, and configures the server to -// accept all future status changes. -// -// This changes serving status for all services. To set status for a particular -// services, call SetServingStatus(). -func (s *Server) Resume() { - s.mu.Lock() - defer s.mu.Unlock() - s.shutdown = false - for service := range s.statusMap { - s.setServingStatusLocked(service, healthpb.HealthCheckResponse_SERVING) - } -} diff --git a/vendor/google.golang.org/grpc/reflection/README.md b/vendor/google.golang.org/grpc/reflection/README.md deleted file mode 100644 index 04b6371af..000000000 --- a/vendor/google.golang.org/grpc/reflection/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Reflection - -Package reflection implements server reflection service. - -The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: -```go -import "google.golang.org/grpc/reflection" - -s := grpc.NewServer() -pb.RegisterYourOwnServer(s, &server{}) - -// Register reflection service on gRPC server. -reflection.Register(s) - -s.Serve(lis) -``` diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go deleted file mode 100644 index d54c07676..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go +++ /dev/null @@ -1,1028 +0,0 @@ -// Copyright 2016 The gRPC 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. -// Service exported by server reflection - -// Warning: this entire file is deprecated. Use this instead: -// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.30.0 -// protoc v4.22.0 -// grpc/reflection/v1alpha/reflection.proto is a deprecated file. - -package grpc_reflection_v1alpha - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// The message sent by the client when calling ServerReflectionInfo method. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ServerReflectionRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - // - // Types that are assignable to MessageRequest: - // - // *ServerReflectionRequest_FileByFilename - // *ServerReflectionRequest_FileContainingSymbol - // *ServerReflectionRequest_FileContainingExtension - // *ServerReflectionRequest_AllExtensionNumbersOfType - // *ServerReflectionRequest_ListServices - MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"` -} - -func (x *ServerReflectionRequest) Reset() { - *x = ServerReflectionRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ServerReflectionRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ServerReflectionRequest) ProtoMessage() {} - -func (x *ServerReflectionRequest) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ServerReflectionRequest.ProtoReflect.Descriptor instead. -func (*ServerReflectionRequest) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{0} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetHost() string { - if x != nil { - return x.Host - } - return "" -} - -func (m *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest { - if m != nil { - return m.MessageRequest - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetFileByFilename() string { - if x, ok := x.GetMessageRequest().(*ServerReflectionRequest_FileByFilename); ok { - return x.FileByFilename - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetFileContainingSymbol() string { - if x, ok := x.GetMessageRequest().(*ServerReflectionRequest_FileContainingSymbol); ok { - return x.FileContainingSymbol - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest { - if x, ok := x.GetMessageRequest().(*ServerReflectionRequest_FileContainingExtension); ok { - return x.FileContainingExtension - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetAllExtensionNumbersOfType() string { - if x, ok := x.GetMessageRequest().(*ServerReflectionRequest_AllExtensionNumbersOfType); ok { - return x.AllExtensionNumbersOfType - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionRequest) GetListServices() string { - if x, ok := x.GetMessageRequest().(*ServerReflectionRequest_ListServices); ok { - return x.ListServices - } - return "" -} - -type isServerReflectionRequest_MessageRequest interface { - isServerReflectionRequest_MessageRequest() -} - -type ServerReflectionRequest_FileByFilename struct { - // Find a proto file by the file name. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,proto3,oneof"` -} - -type ServerReflectionRequest_FileContainingSymbol struct { - // Find the proto file that declares the given fully-qualified symbol name. - // This field should be a fully-qualified symbol name - // (e.g. .[.] or .). - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,proto3,oneof"` -} - -type ServerReflectionRequest_FileContainingExtension struct { - // Find the proto file which defines an extension extending the given - // message type with the given field number. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,proto3,oneof"` -} - -type ServerReflectionRequest_AllExtensionNumbersOfType struct { - // Finds the tag numbers used by all known extensions of extendee_type, and - // appends them to ExtensionNumberResponse in an undefined order. - // Its corresponding method is best-effort: it's not guaranteed that the - // reflection service will implement this method, and it's not guaranteed - // that this method will provide all extensions. Returns - // StatusCode::UNIMPLEMENTED if it's not implemented. - // This field should be a fully-qualified type name. The format is - // . - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,proto3,oneof"` -} - -type ServerReflectionRequest_ListServices struct { - // List the full names of registered services. The content will not be - // checked. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,proto3,oneof"` -} - -func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {} - -func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {} - -func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {} - -func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() { -} - -func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ExtensionRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Fully-qualified type name. The format should be . - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType,proto3" json:"containing_type,omitempty"` - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` -} - -func (x *ExtensionRequest) Reset() { - *x = ExtensionRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ExtensionRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ExtensionRequest) ProtoMessage() {} - -func (x *ExtensionRequest) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ExtensionRequest.ProtoReflect.Descriptor instead. -func (*ExtensionRequest) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{1} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ExtensionRequest) GetContainingType() string { - if x != nil { - return x.ContainingType - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ExtensionRequest) GetExtensionNumber() int32 { - if x != nil { - return x.ExtensionNumber - } - return 0 -} - -// The message sent by the server to answer ServerReflectionInfo method. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ServerReflectionResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost,proto3" json:"valid_host,omitempty"` - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest,proto3" json:"original_request,omitempty"` - // The server set one of the following fields according to the message_request - // in the request. - // - // Types that are assignable to MessageResponse: - // - // *ServerReflectionResponse_FileDescriptorResponse - // *ServerReflectionResponse_AllExtensionNumbersResponse - // *ServerReflectionResponse_ListServicesResponse - // *ServerReflectionResponse_ErrorResponse - MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"` -} - -func (x *ServerReflectionResponse) Reset() { - *x = ServerReflectionResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ServerReflectionResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ServerReflectionResponse) ProtoMessage() {} - -func (x *ServerReflectionResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ServerReflectionResponse.ProtoReflect.Descriptor instead. -func (*ServerReflectionResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{2} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetValidHost() string { - if x != nil { - return x.ValidHost - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest { - if x != nil { - return x.OriginalRequest - } - return nil -} - -func (m *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse { - if m != nil { - return m.MessageResponse - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse { - if x, ok := x.GetMessageResponse().(*ServerReflectionResponse_FileDescriptorResponse); ok { - return x.FileDescriptorResponse - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse { - if x, ok := x.GetMessageResponse().(*ServerReflectionResponse_AllExtensionNumbersResponse); ok { - return x.AllExtensionNumbersResponse - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse { - if x, ok := x.GetMessageResponse().(*ServerReflectionResponse_ListServicesResponse); ok { - return x.ListServicesResponse - } - return nil -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServerReflectionResponse) GetErrorResponse() *ErrorResponse { - if x, ok := x.GetMessageResponse().(*ServerReflectionResponse_ErrorResponse); ok { - return x.ErrorResponse - } - return nil -} - -type isServerReflectionResponse_MessageResponse interface { - isServerReflectionResponse_MessageResponse() -} - -type ServerReflectionResponse_FileDescriptorResponse struct { - // This message is used to answer file_by_filename, file_containing_symbol, - // file_containing_extension requests with transitive dependencies. As - // the repeated label is not allowed in oneof fields, we use a - // FileDescriptorResponse message to encapsulate the repeated fields. - // The reflection service is allowed to avoid sending FileDescriptorProtos - // that were previously sent in response to earlier requests in the stream. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,proto3,oneof"` -} - -type ServerReflectionResponse_AllExtensionNumbersResponse struct { - // This message is used to answer all_extension_numbers_of_type requst. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,proto3,oneof"` -} - -type ServerReflectionResponse_ListServicesResponse struct { - // This message is used to answer list_services request. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,proto3,oneof"` -} - -type ServerReflectionResponse_ErrorResponse struct { - // This message is used when an error occurs. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,proto3,oneof"` -} - -func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() { -} - -func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() { -} - -func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {} - -func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type FileDescriptorResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"` -} - -func (x *FileDescriptorResponse) Reset() { - *x = FileDescriptorResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *FileDescriptorResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*FileDescriptorResponse) ProtoMessage() {} - -func (x *FileDescriptorResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use FileDescriptorResponse.ProtoReflect.Descriptor instead. -func (*FileDescriptorResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{3} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *FileDescriptorResponse) GetFileDescriptorProto() [][]byte { - if x != nil { - return x.FileDescriptorProto - } - return nil -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ExtensionNumberResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Full name of the base type, including the package name. The format - // is . - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName,proto3" json:"base_type_name,omitempty"` - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` -} - -func (x *ExtensionNumberResponse) Reset() { - *x = ExtensionNumberResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ExtensionNumberResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ExtensionNumberResponse) ProtoMessage() {} - -func (x *ExtensionNumberResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ExtensionNumberResponse.ProtoReflect.Descriptor instead. -func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{4} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ExtensionNumberResponse) GetBaseTypeName() string { - if x != nil { - return x.BaseTypeName - } - return "" -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ExtensionNumberResponse) GetExtensionNumber() []int32 { - if x != nil { - return x.ExtensionNumber - } - return nil -} - -// A list of ServiceResponse sent by the server answering list_services request. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ListServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service,proto3" json:"service,omitempty"` -} - -func (x *ListServiceResponse) Reset() { - *x = ListServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListServiceResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListServiceResponse) ProtoMessage() {} - -func (x *ListServiceResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListServiceResponse.ProtoReflect.Descriptor instead. -func (*ListServiceResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{5} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ListServiceResponse) GetService() []*ServiceResponse { - if x != nil { - return x.Service - } - return nil -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Full name of a registered service, including its package name. The format - // is . - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` -} - -func (x *ServiceResponse) Reset() { - *x = ServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ServiceResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ServiceResponse) ProtoMessage() {} - -func (x *ServiceResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ServiceResponse.ProtoReflect.Descriptor instead. -func (*ServiceResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{6} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ServiceResponse) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -// The error code and error message sent by the server when an error occurs. -// -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -type ErrorResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // This field uses the error codes defined in grpc::StatusCode. - // - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"` - // Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` -} - -func (x *ErrorResponse) Reset() { - *x = ErrorResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ErrorResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ErrorResponse) ProtoMessage() {} - -func (x *ErrorResponse) ProtoReflect() protoreflect.Message { - mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ErrorResponse.ProtoReflect.Descriptor instead. -func (*ErrorResponse) Descriptor() ([]byte, []int) { - return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{7} -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ErrorResponse) GetErrorCode() int32 { - if x != nil { - return x.ErrorCode - } - return 0 -} - -// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated. -func (x *ErrorResponse) GetErrorMessage() string { - if x != nil { - return x.ErrorMessage - } - return "" -} - -var File_grpc_reflection_v1alpha_reflection_proto protoreflect.FileDescriptor - -var file_grpc_reflection_v1alpha_reflection_proto_rawDesc = []byte{ - 0x0a, 0x28, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, - 0x6e, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, - 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x17, 0x67, 0x72, 0x70, 0x63, - 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, - 0x70, 0x68, 0x61, 0x22, 0xf8, 0x02, 0x0a, 0x17, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, - 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, - 0x12, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, - 0x6f, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x10, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x62, 0x79, 0x5f, 0x66, - 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, - 0x0e, 0x66, 0x69, 0x6c, 0x65, 0x42, 0x79, 0x46, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x12, - 0x36, 0x0a, 0x16, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x69, - 0x6e, 0x67, 0x5f, 0x73, 0x79, 0x6d, 0x62, 0x6f, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x48, - 0x00, 0x52, 0x14, 0x66, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x69, 0x6e, - 0x67, 0x53, 0x79, 0x6d, 0x62, 0x6f, 0x6c, 0x12, 0x67, 0x0a, 0x19, 0x66, 0x69, 0x6c, 0x65, 0x5f, - 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, - 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x72, 0x70, - 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, - 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, 0x17, 0x66, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x6e, - 0x74, 0x61, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, - 0x12, 0x42, 0x0a, 0x1d, 0x61, 0x6c, 0x6c, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, - 0x6e, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x5f, 0x6f, 0x66, 0x5f, 0x74, 0x79, 0x70, - 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x19, 0x61, 0x6c, 0x6c, 0x45, 0x78, - 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x4f, 0x66, - 0x54, 0x79, 0x70, 0x65, 0x12, 0x25, 0x0a, 0x0d, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x73, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0c, 0x6c, - 0x69, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x42, 0x11, 0x0a, 0x0f, 0x6d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x66, - 0x0a, 0x10, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x69, 0x6e, 0x67, - 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x63, 0x6f, 0x6e, - 0x74, 0x61, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x65, - 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, - 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x22, 0xc7, 0x04, 0x0a, 0x18, 0x53, 0x65, 0x72, 0x76, 0x65, - 0x72, 0x52, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x6f, 0x73, - 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x6f, - 0x73, 0x74, 0x12, 0x5b, 0x0a, 0x10, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x72, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x67, - 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, - 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x66, - 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x0f, - 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, - 0x6b, 0x0a, 0x18, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, - 0x6f, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, - 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x46, 0x69, 0x6c, 0x65, - 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x48, 0x00, 0x52, 0x16, 0x66, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, - 0x70, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x77, 0x0a, 0x1e, - 0x61, 0x6c, 0x6c, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x75, - 0x6d, 0x62, 0x65, 0x72, 0x73, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, - 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x45, - 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x48, 0x00, 0x52, 0x1b, 0x61, 0x6c, 0x6c, 0x45, 0x78, 0x74, - 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x64, 0x0a, 0x16, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x73, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, - 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, - 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x48, 0x00, 0x52, 0x14, 0x6c, 0x69, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4f, 0x0a, 0x0e, 0x65, - 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, - 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x45, 0x72, - 0x72, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x48, 0x00, 0x52, 0x0d, 0x65, - 0x72, 0x72, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x12, 0x0a, 0x10, - 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x22, 0x4c, 0x0a, 0x16, 0x46, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, - 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x15, 0x66, 0x69, - 0x6c, 0x65, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x5f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x13, 0x66, 0x69, 0x6c, 0x65, 0x44, - 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6a, - 0x0a, 0x17, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x75, 0x6d, 0x62, 0x65, - 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x62, 0x61, 0x73, - 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x0c, 0x62, 0x61, 0x73, 0x65, 0x54, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, - 0x29, 0x0a, 0x10, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x75, 0x6d, - 0x62, 0x65, 0x72, 0x18, 0x02, 0x20, 0x03, 0x28, 0x05, 0x52, 0x0f, 0x65, 0x78, 0x74, 0x65, 0x6e, - 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x22, 0x59, 0x0a, 0x13, 0x4c, 0x69, - 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x42, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x18, 0x01, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, - 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x07, 0x73, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x22, 0x25, 0x0a, 0x0f, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x53, 0x0a, 0x0d, - 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, - 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x05, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, - 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, - 0x65, 0x32, 0x93, 0x01, 0x0a, 0x10, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x66, 0x6c, - 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x7f, 0x0a, 0x14, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, - 0x52, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x30, - 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, - 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x31, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, - 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, - 0x72, 0x52, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x28, 0x01, 0x30, 0x01, 0x42, 0x73, 0x0a, 0x1a, 0x69, 0x6f, 0x2e, 0x67, 0x72, - 0x70, 0x63, 0x2e, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x76, 0x31, - 0x61, 0x6c, 0x70, 0x68, 0x61, 0x42, 0x15, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x66, - 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x39, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, - 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, - 0x6e, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x72, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, - 0x6e, 0x5f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0xb8, 0x01, 0x01, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_grpc_reflection_v1alpha_reflection_proto_rawDescOnce sync.Once - file_grpc_reflection_v1alpha_reflection_proto_rawDescData = file_grpc_reflection_v1alpha_reflection_proto_rawDesc -) - -func file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP() []byte { - file_grpc_reflection_v1alpha_reflection_proto_rawDescOnce.Do(func() { - file_grpc_reflection_v1alpha_reflection_proto_rawDescData = protoimpl.X.CompressGZIP(file_grpc_reflection_v1alpha_reflection_proto_rawDescData) - }) - return file_grpc_reflection_v1alpha_reflection_proto_rawDescData -} - -var file_grpc_reflection_v1alpha_reflection_proto_msgTypes = make([]protoimpl.MessageInfo, 8) -var file_grpc_reflection_v1alpha_reflection_proto_goTypes = []interface{}{ - (*ServerReflectionRequest)(nil), // 0: grpc.reflection.v1alpha.ServerReflectionRequest - (*ExtensionRequest)(nil), // 1: grpc.reflection.v1alpha.ExtensionRequest - (*ServerReflectionResponse)(nil), // 2: grpc.reflection.v1alpha.ServerReflectionResponse - (*FileDescriptorResponse)(nil), // 3: grpc.reflection.v1alpha.FileDescriptorResponse - (*ExtensionNumberResponse)(nil), // 4: grpc.reflection.v1alpha.ExtensionNumberResponse - (*ListServiceResponse)(nil), // 5: grpc.reflection.v1alpha.ListServiceResponse - (*ServiceResponse)(nil), // 6: grpc.reflection.v1alpha.ServiceResponse - (*ErrorResponse)(nil), // 7: grpc.reflection.v1alpha.ErrorResponse -} -var file_grpc_reflection_v1alpha_reflection_proto_depIdxs = []int32{ - 1, // 0: grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension:type_name -> grpc.reflection.v1alpha.ExtensionRequest - 0, // 1: grpc.reflection.v1alpha.ServerReflectionResponse.original_request:type_name -> grpc.reflection.v1alpha.ServerReflectionRequest - 3, // 2: grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response:type_name -> grpc.reflection.v1alpha.FileDescriptorResponse - 4, // 3: grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response:type_name -> grpc.reflection.v1alpha.ExtensionNumberResponse - 5, // 4: grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response:type_name -> grpc.reflection.v1alpha.ListServiceResponse - 7, // 5: grpc.reflection.v1alpha.ServerReflectionResponse.error_response:type_name -> grpc.reflection.v1alpha.ErrorResponse - 6, // 6: grpc.reflection.v1alpha.ListServiceResponse.service:type_name -> grpc.reflection.v1alpha.ServiceResponse - 0, // 7: grpc.reflection.v1alpha.ServerReflection.ServerReflectionInfo:input_type -> grpc.reflection.v1alpha.ServerReflectionRequest - 2, // 8: grpc.reflection.v1alpha.ServerReflection.ServerReflectionInfo:output_type -> grpc.reflection.v1alpha.ServerReflectionResponse - 8, // [8:9] is the sub-list for method output_type - 7, // [7:8] is the sub-list for method input_type - 7, // [7:7] is the sub-list for extension type_name - 7, // [7:7] is the sub-list for extension extendee - 0, // [0:7] is the sub-list for field type_name -} - -func init() { file_grpc_reflection_v1alpha_reflection_proto_init() } -func file_grpc_reflection_v1alpha_reflection_proto_init() { - if File_grpc_reflection_v1alpha_reflection_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ServerReflectionRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExtensionRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ServerReflectionResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*FileDescriptorResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExtensionNumberResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ErrorResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0].OneofWrappers = []interface{}{ - (*ServerReflectionRequest_FileByFilename)(nil), - (*ServerReflectionRequest_FileContainingSymbol)(nil), - (*ServerReflectionRequest_FileContainingExtension)(nil), - (*ServerReflectionRequest_AllExtensionNumbersOfType)(nil), - (*ServerReflectionRequest_ListServices)(nil), - } - file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2].OneofWrappers = []interface{}{ - (*ServerReflectionResponse_FileDescriptorResponse)(nil), - (*ServerReflectionResponse_AllExtensionNumbersResponse)(nil), - (*ServerReflectionResponse_ListServicesResponse)(nil), - (*ServerReflectionResponse_ErrorResponse)(nil), - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_grpc_reflection_v1alpha_reflection_proto_rawDesc, - NumEnums: 0, - NumMessages: 8, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_grpc_reflection_v1alpha_reflection_proto_goTypes, - DependencyIndexes: file_grpc_reflection_v1alpha_reflection_proto_depIdxs, - MessageInfos: file_grpc_reflection_v1alpha_reflection_proto_msgTypes, - }.Build() - File_grpc_reflection_v1alpha_reflection_proto = out.File - file_grpc_reflection_v1alpha_reflection_proto_rawDesc = nil - file_grpc_reflection_v1alpha_reflection_proto_goTypes = nil - file_grpc_reflection_v1alpha_reflection_proto_depIdxs = nil -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go deleted file mode 100644 index 367a029be..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2016 The gRPC 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. -// Service exported by server reflection - -// Warning: this entire file is deprecated. Use this instead: -// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto - -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.3.0 -// - protoc v4.22.0 -// grpc/reflection/v1alpha/reflection.proto is a deprecated file. - -package grpc_reflection_v1alpha - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -const ( - ServerReflection_ServerReflectionInfo_FullMethodName = "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo" -) - -// ServerReflectionClient is the client API for ServerReflection service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type ServerReflectionClient interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) -} - -type serverReflectionClient struct { - cc grpc.ClientConnInterface -} - -func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClient { - return &serverReflectionClient{cc} -} - -func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { - stream, err := c.cc.NewStream(ctx, &ServerReflection_ServiceDesc.Streams[0], ServerReflection_ServerReflectionInfo_FullMethodName, opts...) - if err != nil { - return nil, err - } - x := &serverReflectionServerReflectionInfoClient{stream} - return x, nil -} - -type ServerReflection_ServerReflectionInfoClient interface { - Send(*ServerReflectionRequest) error - Recv() (*ServerReflectionResponse, error) - grpc.ClientStream -} - -type serverReflectionServerReflectionInfoClient struct { - grpc.ClientStream -} - -func (x *serverReflectionServerReflectionInfoClient) Send(m *ServerReflectionRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionResponse, error) { - m := new(ServerReflectionResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// ServerReflectionServer is the server API for ServerReflection service. -// All implementations should embed UnimplementedServerReflectionServer -// for forward compatibility -type ServerReflectionServer interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error -} - -// UnimplementedServerReflectionServer should be embedded to have forward compatible implementations. -type UnimplementedServerReflectionServer struct { -} - -func (UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error { - return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") -} - -// UnsafeServerReflectionServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to ServerReflectionServer will -// result in compilation errors. -type UnsafeServerReflectionServer interface { - mustEmbedUnimplementedServerReflectionServer() -} - -func RegisterServerReflectionServer(s grpc.ServiceRegistrar, srv ServerReflectionServer) { - s.RegisterService(&ServerReflection_ServiceDesc, srv) -} - -func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) -} - -type ServerReflection_ServerReflectionInfoServer interface { - Send(*ServerReflectionResponse) error - Recv() (*ServerReflectionRequest, error) - grpc.ServerStream -} - -type serverReflectionServerReflectionInfoServer struct { - grpc.ServerStream -} - -func (x *serverReflectionServerReflectionInfoServer) Send(m *ServerReflectionResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRequest, error) { - m := new(ServerReflectionRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// ServerReflection_ServiceDesc is the grpc.ServiceDesc for ServerReflection service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var ServerReflection_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.reflection.v1alpha.ServerReflection", - HandlerType: (*ServerReflectionServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerReflectionInfo", - Handler: _ServerReflection_ServerReflectionInfo_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc/reflection/v1alpha/reflection.proto", -} diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection.go b/vendor/google.golang.org/grpc/reflection/serverreflection.go deleted file mode 100644 index e2f9ebfbb..000000000 --- a/vendor/google.golang.org/grpc/reflection/serverreflection.go +++ /dev/null @@ -1,326 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 reflection implements server reflection service. - -The service implemented is defined in: -https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: - - import "google.golang.org/grpc/reflection" - - s := grpc.NewServer() - pb.RegisterYourOwnServer(s, &server{}) - - // Register reflection service on gRPC server. - reflection.Register(s) - - s.Serve(lis) -*/ -package reflection // import "google.golang.org/grpc/reflection" - -import ( - "io" - "sort" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - - v1alphagrpc "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" - v1alphapb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" -) - -// GRPCServer is the interface provided by a gRPC server. It is implemented by -// *grpc.Server, but could also be implemented by other concrete types. It acts -// as a registry, for accumulating the services exposed by the server. -type GRPCServer interface { - grpc.ServiceRegistrar - ServiceInfoProvider -} - -var _ GRPCServer = (*grpc.Server)(nil) - -// Register registers the server reflection service on the given gRPC server. -func Register(s GRPCServer) { - svr := NewServer(ServerOptions{Services: s}) - v1alphagrpc.RegisterServerReflectionServer(s, svr) -} - -// ServiceInfoProvider is an interface used to retrieve metadata about the -// services to expose. -// -// The reflection service is only interested in the service names, but the -// signature is this way so that *grpc.Server implements it. So it is okay -// for a custom implementation to return zero values for the -// grpc.ServiceInfo values in the map. -// -// # Experimental -// -// Notice: This type is EXPERIMENTAL and may be changed or removed in a -// later release. -type ServiceInfoProvider interface { - GetServiceInfo() map[string]grpc.ServiceInfo -} - -// ExtensionResolver is the interface used to query details about extensions. -// This interface is satisfied by protoregistry.GlobalTypes. -// -// # Experimental -// -// Notice: This type is EXPERIMENTAL and may be changed or removed in a -// later release. -type ExtensionResolver interface { - protoregistry.ExtensionTypeResolver - RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) -} - -// ServerOptions represents the options used to construct a reflection server. -// -// # Experimental -// -// Notice: This type is EXPERIMENTAL and may be changed or removed in a -// later release. -type ServerOptions struct { - // The source of advertised RPC services. If not specified, the reflection - // server will report an empty list when asked to list services. - // - // This value will typically be a *grpc.Server. But the set of advertised - // services can be customized by wrapping a *grpc.Server or using an - // alternate implementation that returns a custom set of service names. - Services ServiceInfoProvider - // Optional resolver used to load descriptors. If not specified, - // protoregistry.GlobalFiles will be used. - DescriptorResolver protodesc.Resolver - // Optional resolver used to query for known extensions. If not specified, - // protoregistry.GlobalTypes will be used. - ExtensionResolver ExtensionResolver -} - -// NewServer returns a reflection server implementation using the given options. -// This can be used to customize behavior of the reflection service. Most usages -// should prefer to use Register instead. -// -// # Experimental -// -// Notice: This function is EXPERIMENTAL and may be changed or removed in a -// later release. -func NewServer(opts ServerOptions) v1alphagrpc.ServerReflectionServer { - if opts.DescriptorResolver == nil { - opts.DescriptorResolver = protoregistry.GlobalFiles - } - if opts.ExtensionResolver == nil { - opts.ExtensionResolver = protoregistry.GlobalTypes - } - return &serverReflectionServer{ - s: opts.Services, - descResolver: opts.DescriptorResolver, - extResolver: opts.ExtensionResolver, - } -} - -type serverReflectionServer struct { - v1alphagrpc.UnimplementedServerReflectionServer - s ServiceInfoProvider - descResolver protodesc.Resolver - extResolver ExtensionResolver -} - -// fileDescWithDependencies returns a slice of serialized fileDescriptors in -// wire format ([]byte). The fileDescriptors will include fd and all the -// transitive dependencies of fd with names not in sentFileDescriptors. -func (s *serverReflectionServer) fileDescWithDependencies(fd protoreflect.FileDescriptor, sentFileDescriptors map[string]bool) ([][]byte, error) { - var r [][]byte - queue := []protoreflect.FileDescriptor{fd} - for len(queue) > 0 { - currentfd := queue[0] - queue = queue[1:] - if sent := sentFileDescriptors[currentfd.Path()]; len(r) == 0 || !sent { - sentFileDescriptors[currentfd.Path()] = true - fdProto := protodesc.ToFileDescriptorProto(currentfd) - currentfdEncoded, err := proto.Marshal(fdProto) - if err != nil { - return nil, err - } - r = append(r, currentfdEncoded) - } - for i := 0; i < currentfd.Imports().Len(); i++ { - queue = append(queue, currentfd.Imports().Get(i)) - } - } - return r, nil -} - -// fileDescEncodingContainingSymbol finds the file descriptor containing the -// given symbol, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. The given symbol -// can be a type, a service or a method. -func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { - d, err := s.descResolver.FindDescriptorByName(protoreflect.FullName(name)) - if err != nil { - return nil, err - } - return s.fileDescWithDependencies(d.ParentFile(), sentFileDescriptors) -} - -// fileDescEncodingContainingExtension finds the file descriptor containing -// given extension, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) { - xt, err := s.extResolver.FindExtensionByNumber(protoreflect.FullName(typeName), protoreflect.FieldNumber(extNum)) - if err != nil { - return nil, err - } - return s.fileDescWithDependencies(xt.TypeDescriptor().ParentFile(), sentFileDescriptors) -} - -// allExtensionNumbersForTypeName returns all extension numbers for the given type. -func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { - var numbers []int32 - s.extResolver.RangeExtensionsByMessage(protoreflect.FullName(name), func(xt protoreflect.ExtensionType) bool { - numbers = append(numbers, int32(xt.TypeDescriptor().Number())) - return true - }) - sort.Slice(numbers, func(i, j int) bool { - return numbers[i] < numbers[j] - }) - if len(numbers) == 0 { - // maybe return an error if given type name is not known - if _, err := s.descResolver.FindDescriptorByName(protoreflect.FullName(name)); err != nil { - return nil, err - } - } - return numbers, nil -} - -// listServices returns the names of services this server exposes. -func (s *serverReflectionServer) listServices() []*v1alphapb.ServiceResponse { - serviceInfo := s.s.GetServiceInfo() - resp := make([]*v1alphapb.ServiceResponse, 0, len(serviceInfo)) - for svc := range serviceInfo { - resp = append(resp, &v1alphapb.ServiceResponse{Name: svc}) - } - sort.Slice(resp, func(i, j int) bool { - return resp[i].Name < resp[j].Name - }) - return resp -} - -// ServerReflectionInfo is the reflection service handler. -func (s *serverReflectionServer) ServerReflectionInfo(stream v1alphagrpc.ServerReflection_ServerReflectionInfoServer) error { - sentFileDescriptors := make(map[string]bool) - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - out := &v1alphapb.ServerReflectionResponse{ - ValidHost: in.Host, - OriginalRequest: in, - } - switch req := in.MessageRequest.(type) { - case *v1alphapb.ServerReflectionRequest_FileByFilename: - var b [][]byte - fd, err := s.descResolver.FindFileByPath(req.FileByFilename) - if err == nil { - b, err = s.fileDescWithDependencies(fd, sentFileDescriptors) - } - if err != nil { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &v1alphapb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &v1alphapb.FileDescriptorResponse{FileDescriptorProto: b}, - } - } - case *v1alphapb.ServerReflectionRequest_FileContainingSymbol: - b, err := s.fileDescEncodingContainingSymbol(req.FileContainingSymbol, sentFileDescriptors) - if err != nil { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &v1alphapb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &v1alphapb.FileDescriptorResponse{FileDescriptorProto: b}, - } - } - case *v1alphapb.ServerReflectionRequest_FileContainingExtension: - typeName := req.FileContainingExtension.ContainingType - extNum := req.FileContainingExtension.ExtensionNumber - b, err := s.fileDescEncodingContainingExtension(typeName, extNum, sentFileDescriptors) - if err != nil { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &v1alphapb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &v1alphapb.FileDescriptorResponse{FileDescriptorProto: b}, - } - } - case *v1alphapb.ServerReflectionRequest_AllExtensionNumbersOfType: - extNums, err := s.allExtensionNumbersForTypeName(req.AllExtensionNumbersOfType) - if err != nil { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &v1alphapb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &v1alphapb.ServerReflectionResponse_AllExtensionNumbersResponse{ - AllExtensionNumbersResponse: &v1alphapb.ExtensionNumberResponse{ - BaseTypeName: req.AllExtensionNumbersOfType, - ExtensionNumber: extNums, - }, - } - } - case *v1alphapb.ServerReflectionRequest_ListServices: - out.MessageResponse = &v1alphapb.ServerReflectionResponse_ListServicesResponse{ - ListServicesResponse: &v1alphapb.ListServiceResponse{ - Service: s.listServices(), - }, - } - default: - return status.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest) - } - - if err := stream.Send(out); err != nil { - return err - } - } -} diff --git a/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go b/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go deleted file mode 100644 index 9a7277ba3..000000000 --- a/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go +++ /dev/null @@ -1,166 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/empty.proto - -package emptypb - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -// A generic empty message that you can re-use to avoid defining duplicated -// empty messages in your APIs. A typical example is to use it as the request -// or the response type of an API method. For instance: -// -// service Foo { -// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); -// } -type Empty struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *Empty) Reset() { - *x = Empty{} - if protoimpl.UnsafeEnabled { - mi := &file_google_protobuf_empty_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Empty) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Empty) ProtoMessage() {} - -func (x *Empty) ProtoReflect() protoreflect.Message { - mi := &file_google_protobuf_empty_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Empty.ProtoReflect.Descriptor instead. -func (*Empty) Descriptor() ([]byte, []int) { - return file_google_protobuf_empty_proto_rawDescGZIP(), []int{0} -} - -var File_google_protobuf_empty_proto protoreflect.FileDescriptor - -var file_google_protobuf_empty_proto_rawDesc = []byte{ - 0x0a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x22, 0x07, - 0x0a, 0x05, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x7d, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x42, 0x0a, - 0x45, 0x6d, 0x70, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x6b, - 0x6e, 0x6f, 0x77, 0x6e, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x70, 0x62, 0xf8, 0x01, 0x01, 0xa2, - 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x57, 0x65, 0x6c, 0x6c, 0x4b, 0x6e, 0x6f, 0x77, - 0x6e, 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_google_protobuf_empty_proto_rawDescOnce sync.Once - file_google_protobuf_empty_proto_rawDescData = file_google_protobuf_empty_proto_rawDesc -) - -func file_google_protobuf_empty_proto_rawDescGZIP() []byte { - file_google_protobuf_empty_proto_rawDescOnce.Do(func() { - file_google_protobuf_empty_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_empty_proto_rawDescData) - }) - return file_google_protobuf_empty_proto_rawDescData -} - -var file_google_protobuf_empty_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_google_protobuf_empty_proto_goTypes = []interface{}{ - (*Empty)(nil), // 0: google.protobuf.Empty -} -var file_google_protobuf_empty_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_google_protobuf_empty_proto_init() } -func file_google_protobuf_empty_proto_init() { - if File_google_protobuf_empty_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_google_protobuf_empty_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Empty); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_google_protobuf_empty_proto_rawDesc, - NumEnums: 0, - NumMessages: 1, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_google_protobuf_empty_proto_goTypes, - DependencyIndexes: file_google_protobuf_empty_proto_depIdxs, - MessageInfos: file_google_protobuf_empty_proto_msgTypes, - }.Build() - File_google_protobuf_empty_proto = out.File - file_google_protobuf_empty_proto_rawDesc = nil - file_google_protobuf_empty_proto_goTypes = nil - file_google_protobuf_empty_proto_depIdxs = nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index f20a325ec..f239bee20 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -5,9 +5,6 @@ github.com/BurntSushi/toml/internal # github.com/armon/go-metrics v0.4.1 ## explicit; go 1.12 github.com/armon/go-metrics -# github.com/armon/go-radix v1.0.0 -## explicit -github.com/armon/go-radix # github.com/aws/aws-sdk-go v1.44.266 ## explicit; go 1.11 github.com/aws/aws-sdk-go/aws @@ -83,11 +80,7 @@ github.com/golang/protobuf/proto github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration -github.com/golang/protobuf/ptypes/empty github.com/golang/protobuf/ptypes/timestamp -# github.com/golang/snappy v0.0.4 -## explicit -github.com/golang/snappy # github.com/gomodule/redigo v1.8.9 ## explicit; go 1.16 github.com/gomodule/redigo/redis @@ -109,19 +102,12 @@ github.com/hashicorp/go-immutable-radix # github.com/hashicorp/go-multierror v1.1.1 ## explicit; go 1.13 github.com/hashicorp/go-multierror -# github.com/hashicorp/go-plugin v1.4.5 -## explicit; go 1.17 -github.com/hashicorp/go-plugin -github.com/hashicorp/go-plugin/internal/plugin # github.com/hashicorp/go-retryablehttp v0.7.1 ## explicit; go 1.13 github.com/hashicorp/go-retryablehttp # github.com/hashicorp/go-rootcerts v1.0.2 ## explicit; go 1.12 github.com/hashicorp/go-rootcerts -# github.com/hashicorp/go-secure-stdlib/mlock v0.1.2 -## explicit; go 1.16 -github.com/hashicorp/go-secure-stdlib/mlock # github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7 ## explicit; go 1.16 github.com/hashicorp/go-secure-stdlib/parseutil @@ -133,13 +119,10 @@ github.com/hashicorp/go-secure-stdlib/strutil github.com/hashicorp/go-sockaddr # github.com/hashicorp/go-uuid v1.0.3 ## explicit -github.com/hashicorp/go-uuid # github.com/hashicorp/go-version v1.6.0 ## explicit -github.com/hashicorp/go-version # github.com/hashicorp/golang-lru v0.5.4 ## explicit; go 1.12 -github.com/hashicorp/golang-lru github.com/hashicorp/golang-lru/simplelru # github.com/hashicorp/hcl v1.0.0 ## explicit @@ -155,31 +138,9 @@ github.com/hashicorp/hcl/json/token # github.com/hashicorp/serf v0.10.1 ## explicit; go 1.12 github.com/hashicorp/serf/coordinate -# github.com/hashicorp/vault/api v1.8.3 +# github.com/hashicorp/vault/api v1.9.1 ## explicit; go 1.19 github.com/hashicorp/vault/api -# github.com/hashicorp/vault/sdk v0.7.0 -## explicit; go 1.19 -github.com/hashicorp/vault/sdk/helper/certutil -github.com/hashicorp/vault/sdk/helper/compressutil -github.com/hashicorp/vault/sdk/helper/consts -github.com/hashicorp/vault/sdk/helper/cryptoutil -github.com/hashicorp/vault/sdk/helper/errutil -github.com/hashicorp/vault/sdk/helper/hclutil -github.com/hashicorp/vault/sdk/helper/jsonutil -github.com/hashicorp/vault/sdk/helper/license -github.com/hashicorp/vault/sdk/helper/locksutil -github.com/hashicorp/vault/sdk/helper/logging -github.com/hashicorp/vault/sdk/helper/pathmanager -github.com/hashicorp/vault/sdk/helper/pluginutil -github.com/hashicorp/vault/sdk/helper/strutil -github.com/hashicorp/vault/sdk/helper/wrapping -github.com/hashicorp/vault/sdk/logical -github.com/hashicorp/vault/sdk/physical -github.com/hashicorp/vault/sdk/physical/inmem -# github.com/hashicorp/yamux v0.1.1 -## explicit; go 1.15 -github.com/hashicorp/yamux # github.com/jmespath/go-jmespath v0.4.0 ## explicit; go 1.14 github.com/jmespath/go-jmespath @@ -192,28 +153,12 @@ github.com/mattn/go-colorable # github.com/mattn/go-isatty v0.0.16 ## explicit; go 1.15 github.com/mattn/go-isatty -# github.com/mitchellh/copystructure v1.2.0 -## explicit; go 1.15 -github.com/mitchellh/copystructure # github.com/mitchellh/go-homedir v1.1.0 ## explicit github.com/mitchellh/go-homedir -# github.com/mitchellh/go-testing-interface v1.14.1 -## explicit; go 1.14 -github.com/mitchellh/go-testing-interface # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure -# github.com/mitchellh/reflectwalk v1.0.2 -## explicit -github.com/mitchellh/reflectwalk -# github.com/oklog/run v1.1.0 -## explicit; go 1.13 -github.com/oklog/run -# github.com/pierrec/lz4 v2.6.1+incompatible -## explicit -github.com/pierrec/lz4 -github.com/pierrec/lz4/internal/xxh32 # github.com/ryanuber/go-glob v1.0.0 ## explicit github.com/ryanuber/go-glob @@ -257,14 +202,10 @@ go.uber.org/zap/zapcore go.uber.org/zap/zapgrpc # golang.org/x/crypto v0.14.0 ## explicit; go 1.17 -golang.org/x/crypto/blake2b -golang.org/x/crypto/cryptobyte -golang.org/x/crypto/cryptobyte/asn1 golang.org/x/crypto/ed25519 golang.org/x/crypto/pbkdf2 # golang.org/x/net v0.17.0 ## explicit; go 1.17 -golang.org/x/net/context golang.org/x/net/http/httpguts golang.org/x/net/http2 golang.org/x/net/http2/hpack @@ -273,7 +214,6 @@ golang.org/x/net/internal/timeseries golang.org/x/net/trace # golang.org/x/sys v0.13.0 ## explicit; go 1.17 -golang.org/x/sys/cpu golang.org/x/sys/unix golang.org/x/sys/windows # golang.org/x/text v0.13.0 @@ -308,8 +248,6 @@ google.golang.org/grpc/credentials/insecure google.golang.org/grpc/encoding google.golang.org/grpc/encoding/proto google.golang.org/grpc/grpclog -google.golang.org/grpc/health -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 @@ -337,8 +275,6 @@ google.golang.org/grpc/internal/transport/networktype google.golang.org/grpc/keepalive google.golang.org/grpc/metadata google.golang.org/grpc/peer -google.golang.org/grpc/reflection -google.golang.org/grpc/reflection/grpc_reflection_v1alpha google.golang.org/grpc/resolver google.golang.org/grpc/resolver/manual google.golang.org/grpc/serviceconfig @@ -378,7 +314,6 @@ google.golang.org/protobuf/runtime/protoimpl google.golang.org/protobuf/types/descriptorpb google.golang.org/protobuf/types/known/anypb google.golang.org/protobuf/types/known/durationpb -google.golang.org/protobuf/types/known/emptypb google.golang.org/protobuf/types/known/timestamppb # gopkg.in/square/go-jose.v2 v2.6.0 ## explicit