From bb6fc0bb39a33072f6bd6838ff1d93e6c843872b Mon Sep 17 00:00:00 2001 From: Denis Subbotin Date: Wed, 17 Apr 2019 13:36:47 +0100 Subject: [PATCH] rm vendor from build --- vendor/github.com/Jeffail/gabs/LICENSE | 19 - vendor/github.com/Jeffail/gabs/README.md | 315 - vendor/github.com/Jeffail/gabs/gabs.go | 581 - vendor/github.com/Jeffail/gabs/gabs_logo.png | Bin 167771 -> 0 bytes .../github.com/NYTimes/gziphandler/.gitignore | 1 - .../NYTimes/gziphandler/.travis.yml | 6 - .../NYTimes/gziphandler/CODE_OF_CONDUCT.md | 75 - .../NYTimes/gziphandler/CONTRIBUTING.md | 30 - vendor/github.com/NYTimes/gziphandler/LICENSE | 201 - .../github.com/NYTimes/gziphandler/README.md | 52 - vendor/github.com/NYTimes/gziphandler/gzip.go | 429 - .../NYTimes/gziphandler/gzip_go18.go | 43 - .../github.com/SermoDigital/jose/.gitignore | 29 - .../github.com/SermoDigital/jose/.travis.yml | 14 - vendor/github.com/SermoDigital/jose/LICENSE | 22 - vendor/github.com/SermoDigital/jose/README.md | 40 - vendor/github.com/SermoDigital/jose/_test.sh | 8 - vendor/github.com/SermoDigital/jose/base64.go | 44 - .../SermoDigital/jose/crypto/doc.go | 4 - .../SermoDigital/jose/crypto/ecdsa.go | 117 - .../SermoDigital/jose/crypto/ecdsa_utils.go | 48 - .../SermoDigital/jose/crypto/errors.go | 9 - .../SermoDigital/jose/crypto/hmac.go | 81 - .../SermoDigital/jose/crypto/none.go | 72 - .../SermoDigital/jose/crypto/rsa.go | 80 - .../SermoDigital/jose/crypto/rsa_pss.go | 96 - .../SermoDigital/jose/crypto/rsa_utils.go | 70 - .../SermoDigital/jose/crypto/signature.go | 36 - .../jose/crypto/signing_method.go | 24 - vendor/github.com/SermoDigital/jose/doc.go | 3 - vendor/github.com/SermoDigital/jose/header.go | 124 - .../SermoDigital/jose/jws/claims.go | 190 - .../github.com/SermoDigital/jose/jws/doc.go | 2 - .../SermoDigital/jose/jws/errors.go | 62 - .../github.com/SermoDigital/jose/jws/jws.go | 490 - .../SermoDigital/jose/jws/jws_serialize.go | 132 - .../SermoDigital/jose/jws/jws_validate.go | 203 - .../github.com/SermoDigital/jose/jws/jwt.go | 115 - .../SermoDigital/jose/jws/payload.go | 52 - .../SermoDigital/jose/jws/rawbase64.go | 28 - .../SermoDigital/jose/jws/signing_methods.go | 63 - .../SermoDigital/jose/jwt/claims.go | 274 - .../github.com/SermoDigital/jose/jwt/doc.go | 2 - vendor/github.com/SermoDigital/jose/jwt/eq.go | 47 - .../SermoDigital/jose/jwt/errors.go | 28 - .../github.com/SermoDigital/jose/jwt/jwt.go | 144 - vendor/github.com/SermoDigital/jose/time.go | 6 - vendor/github.com/Venafi/vcert/.gitignore | 15 - vendor/github.com/Venafi/vcert/Dockerfile | 6 - vendor/github.com/Venafi/vcert/Jenkinsfile | 58 - vendor/github.com/Venafi/vcert/LICENSE | 201 - vendor/github.com/Venafi/vcert/Makefile | 47 - vendor/github.com/Venafi/vcert/README.md | 130 - vendor/github.com/Venafi/vcert/client.go | 61 - vendor/github.com/Venafi/vcert/config.go | 214 - .../vcert/pkg/certificate/certificate.go | 312 - .../pkg/certificate/certificateCollection.go | 167 - .../Venafi/vcert/pkg/endpoint/endpoint.go | 321 - .../pkg/venafi/cloud/certificatePolicies.go | 68 - .../Venafi/vcert/pkg/venafi/cloud/cloud.go | 352 - .../Venafi/vcert/pkg/venafi/cloud/company.go | 113 - .../vcert/pkg/venafi/cloud/connector.go | 710 - .../Venafi/vcert/pkg/venafi/cloud/error.go | 59 - .../Venafi/vcert/pkg/venafi/cloud/search.go | 97 - .../Venafi/vcert/pkg/venafi/cloud/user.go | 50 - .../Venafi/vcert/pkg/venafi/fake/ca.go | 82 - .../Venafi/vcert/pkg/venafi/fake/connector.go | 243 - .../Venafi/vcert/pkg/venafi/fake/fake.go | 68 - .../Venafi/vcert/pkg/venafi/tpp/connector.go | 551 - .../Venafi/vcert/pkg/venafi/tpp/error.go | 42 - .../Venafi/vcert/pkg/venafi/tpp/search.go | 105 - .../Venafi/vcert/pkg/venafi/tpp/tpp.go | 456 - .../github.com/Venafi/vcert/test/context.go | 66 - .../github.com/Venafi/vcert/test/fixtures.go | 40 - vendor/github.com/Venafi/vcert/vcert.go | 45 - vendor/github.com/armon/go-metrics/.gitignore | 24 - vendor/github.com/armon/go-metrics/LICENSE | 20 - vendor/github.com/armon/go-metrics/README.md | 91 - .../github.com/armon/go-metrics/const_unix.go | 12 - .../armon/go-metrics/const_windows.go | 13 - vendor/github.com/armon/go-metrics/inmem.go | 348 - .../armon/go-metrics/inmem_endpoint.go | 118 - .../armon/go-metrics/inmem_signal.go | 117 - vendor/github.com/armon/go-metrics/metrics.go | 278 - vendor/github.com/armon/go-metrics/sink.go | 115 - vendor/github.com/armon/go-metrics/start.go | 141 - vendor/github.com/armon/go-metrics/statsd.go | 184 - .../github.com/armon/go-metrics/statsite.go | 172 - 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/go.mod | 1 - vendor/github.com/armon/go-radix/radix.go | 540 - .../elazarl/go-bindata-assetfs/LICENSE | 23 - .../elazarl/go-bindata-assetfs/README.md | 46 - .../elazarl/go-bindata-assetfs/assetfs.go | 167 - .../elazarl/go-bindata-assetfs/doc.go | 13 - .../github.com/go-sql-driver/mysql/.gitignore | 9 - .../go-sql-driver/mysql/.travis.yml | 107 - vendor/github.com/go-sql-driver/mysql/AUTHORS | 89 - .../go-sql-driver/mysql/CHANGELOG.md | 178 - .../go-sql-driver/mysql/CONTRIBUTING.md | 23 - vendor/github.com/go-sql-driver/mysql/LICENSE | 373 - .../github.com/go-sql-driver/mysql/README.md | 490 - .../go-sql-driver/mysql/appengine.go | 19 - vendor/github.com/go-sql-driver/mysql/auth.go | 420 - .../github.com/go-sql-driver/mysql/buffer.go | 147 - .../go-sql-driver/mysql/collations.go | 251 - .../go-sql-driver/mysql/connection.go | 461 - .../go-sql-driver/mysql/connection_go18.go | 207 - .../github.com/go-sql-driver/mysql/const.go | 174 - .../github.com/go-sql-driver/mysql/driver.go | 172 - vendor/github.com/go-sql-driver/mysql/dsn.go | 611 - .../github.com/go-sql-driver/mysql/errors.go | 65 - .../github.com/go-sql-driver/mysql/fields.go | 194 - .../github.com/go-sql-driver/mysql/infile.go | 182 - .../github.com/go-sql-driver/mysql/packets.go | 1286 - .../github.com/go-sql-driver/mysql/result.go | 22 - vendor/github.com/go-sql-driver/mysql/rows.go | 216 - .../go-sql-driver/mysql/statement.go | 211 - .../go-sql-driver/mysql/transaction.go | 31 - .../github.com/go-sql-driver/mysql/utils.go | 726 - .../go-sql-driver/mysql/utils_go17.go | 40 - .../go-sql-driver/mysql/utils_go18.go | 50 - vendor/github.com/golang/protobuf/AUTHORS | 3 - .../github.com/golang/protobuf/CONTRIBUTORS | 3 - vendor/github.com/golang/protobuf/LICENSE | 28 - .../github.com/golang/protobuf/proto/clone.go | 253 - .../golang/protobuf/proto/decode.go | 427 - .../golang/protobuf/proto/deprecated.go | 63 - .../golang/protobuf/proto/discard.go | 350 - .../golang/protobuf/proto/encode.go | 203 - .../github.com/golang/protobuf/proto/equal.go | 301 - .../golang/protobuf/proto/extensions.go | 607 - .../github.com/golang/protobuf/proto/lib.go | 965 - .../golang/protobuf/proto/message_set.go | 181 - .../golang/protobuf/proto/pointer_reflect.go | 360 - .../golang/protobuf/proto/pointer_unsafe.go | 313 - .../golang/protobuf/proto/properties.go | 545 - .../golang/protobuf/proto/table_marshal.go | 2776 - .../golang/protobuf/proto/table_merge.go | 654 - .../golang/protobuf/proto/table_unmarshal.go | 2053 - .../github.com/golang/protobuf/proto/text.go | 843 - .../golang/protobuf/proto/text_parser.go | 880 - .../github.com/golang/protobuf/ptypes/any.go | 141 - .../golang/protobuf/ptypes/any/any.pb.go | 200 - .../golang/protobuf/ptypes/any/any.proto | 154 - .../github.com/golang/protobuf/ptypes/doc.go | 35 - .../golang/protobuf/ptypes/duration.go | 102 - .../protobuf/ptypes/duration/duration.pb.go | 161 - .../protobuf/ptypes/duration/duration.proto | 117 - .../golang/protobuf/ptypes/timestamp.go | 132 - .../protobuf/ptypes/timestamp/timestamp.pb.go | 179 - .../protobuf/ptypes/timestamp/timestamp.proto | 135 - vendor/github.com/golang/snappy/.gitignore | 16 - vendor/github.com/golang/snappy/AUTHORS | 15 - vendor/github.com/golang/snappy/CONTRIBUTORS | 37 - vendor/github.com/golang/snappy/LICENSE | 27 - vendor/github.com/golang/snappy/README | 107 - vendor/github.com/golang/snappy/decode.go | 237 - .../github.com/golang/snappy/decode_amd64.go | 14 - .../github.com/golang/snappy/decode_amd64.s | 490 - .../github.com/golang/snappy/decode_other.go | 101 - vendor/github.com/golang/snappy/encode.go | 285 - .../github.com/golang/snappy/encode_amd64.go | 29 - .../github.com/golang/snappy/encode_amd64.s | 730 - .../github.com/golang/snappy/encode_other.go | 238 - vendor/github.com/golang/snappy/snappy.go | 98 - vendor/github.com/hashicorp/errwrap/LICENSE | 354 - vendor/github.com/hashicorp/errwrap/README.md | 89 - .../github.com/hashicorp/errwrap/errwrap.go | 169 - vendor/github.com/hashicorp/errwrap/go.mod | 1 - .../github.com/hashicorp/go-cleanhttp/LICENSE | 363 - .../hashicorp/go-cleanhttp/README.md | 30 - .../hashicorp/go-cleanhttp/cleanhttp.go | 57 - .../github.com/hashicorp/go-cleanhttp/doc.go | 20 - .../github.com/hashicorp/go-cleanhttp/go.mod | 1 - .../hashicorp/go-cleanhttp/handlers.go | 48 - .../github.com/hashicorp/go-hclog/.gitignore | 1 - vendor/github.com/hashicorp/go-hclog/LICENSE | 21 - .../github.com/hashicorp/go-hclog/README.md | 133 - .../github.com/hashicorp/go-hclog/global.go | 34 - vendor/github.com/hashicorp/go-hclog/go.mod | 7 - vendor/github.com/hashicorp/go-hclog/go.sum | 6 - vendor/github.com/hashicorp/go-hclog/int.go | 507 - vendor/github.com/hashicorp/go-hclog/log.go | 161 - .../hashicorp/go-hclog/nulllogger.go | 47 - .../hashicorp/go-hclog/stacktrace.go | 108 - .../github.com/hashicorp/go-hclog/stdlog.go | 62 - .../hashicorp/go-immutable-radix/.gitignore | 24 - .../hashicorp/go-immutable-radix/.travis.yml | 3 - .../hashicorp/go-immutable-radix/LICENSE | 363 - .../hashicorp/go-immutable-radix/README.md | 41 - .../hashicorp/go-immutable-radix/edges.go | 21 - .../hashicorp/go-immutable-radix/go.mod | 6 - .../hashicorp/go-immutable-radix/go.sum | 4 - .../hashicorp/go-immutable-radix/iradix.go | 662 - .../hashicorp/go-immutable-radix/iter.go | 91 - .../hashicorp/go-immutable-radix/node.go | 292 - .../hashicorp/go-immutable-radix/raw_iter.go | 78 - .../github.com/hashicorp/go-memdb/.gitignore | 24 - .../github.com/hashicorp/go-memdb/.travis.yml | 7 - vendor/github.com/hashicorp/go-memdb/LICENSE | 363 - .../github.com/hashicorp/go-memdb/README.md | 98 - .../github.com/hashicorp/go-memdb/filter.go | 33 - vendor/github.com/hashicorp/go-memdb/index.go | 582 - vendor/github.com/hashicorp/go-memdb/memdb.go | 97 - .../github.com/hashicorp/go-memdb/schema.go | 114 - vendor/github.com/hashicorp/go-memdb/txn.go | 644 - vendor/github.com/hashicorp/go-memdb/watch.go | 129 - .../hashicorp/go-memdb/watch_few.go | 117 - .../hashicorp/go-multierror/.travis.yml | 12 - .../hashicorp/go-multierror/LICENSE | 353 - .../hashicorp/go-multierror/Makefile | 31 - .../hashicorp/go-multierror/README.md | 97 - .../hashicorp/go-multierror/append.go | 41 - .../hashicorp/go-multierror/flatten.go | 26 - .../hashicorp/go-multierror/format.go | 27 - .../github.com/hashicorp/go-multierror/go.mod | 3 - .../github.com/hashicorp/go-multierror/go.sum | 4 - .../hashicorp/go-multierror/multierror.go | 51 - .../hashicorp/go-multierror/prefix.go | 37 - .../hashicorp/go-multierror/sort.go | 16 - .../github.com/hashicorp/go-plugin/.gitignore | 1 - vendor/github.com/hashicorp/go-plugin/LICENSE | 353 - .../github.com/hashicorp/go-plugin/README.md | 168 - .../github.com/hashicorp/go-plugin/client.go | 871 - .../hashicorp/go-plugin/discover.go | 28 - .../github.com/hashicorp/go-plugin/error.go | 24 - vendor/github.com/hashicorp/go-plugin/go.mod | 13 - vendor/github.com/hashicorp/go-plugin/go.sum | 18 - .../hashicorp/go-plugin/grpc_broker.go | 455 - .../hashicorp/go-plugin/grpc_broker.pb.go | 190 - .../hashicorp/go-plugin/grpc_broker.proto | 14 - .../hashicorp/go-plugin/grpc_client.go | 107 - .../hashicorp/go-plugin/grpc_server.go | 132 - .../hashicorp/go-plugin/log_entry.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 | 19 - .../hashicorp/go-plugin/process_windows.go | 29 - .../hashicorp/go-plugin/protocol.go | 45 - .../hashicorp/go-plugin/rpc_client.go | 170 - .../hashicorp/go-plugin/rpc_server.go | 197 - .../github.com/hashicorp/go-plugin/server.go | 404 - .../hashicorp/go-plugin/server_mux.go | 31 - .../github.com/hashicorp/go-plugin/stream.go | 18 - .../github.com/hashicorp/go-plugin/testing.go | 175 - .../hashicorp/go-retryablehttp/.gitignore | 3 - .../hashicorp/go-retryablehttp/.travis.yml | 12 - .../hashicorp/go-retryablehttp/LICENSE | 363 - .../hashicorp/go-retryablehttp/Makefile | 11 - .../hashicorp/go-retryablehttp/README.md | 46 - .../hashicorp/go-retryablehttp/client.go | 500 - .../hashicorp/go-retryablehttp/go.mod | 3 - .../hashicorp/go-retryablehttp/go.sum | 2 - .../hashicorp/go-rootcerts/.travis.yml | 12 - .../github.com/hashicorp/go-rootcerts/LICENSE | 363 - .../hashicorp/go-rootcerts/Makefile | 8 - .../hashicorp/go-rootcerts/README.md | 43 - .../github.com/hashicorp/go-rootcerts/doc.go | 9 - .../github.com/hashicorp/go-rootcerts/go.mod | 3 - .../github.com/hashicorp/go-rootcerts/go.sum | 2 - .../hashicorp/go-rootcerts/rootcerts.go | 103 - .../hashicorp/go-rootcerts/rootcerts_base.go | 12 - .../go-rootcerts/rootcerts_darwin.go | 48 - .../hashicorp/go-sockaddr/.gitignore | 26 - .../hashicorp/go-sockaddr/GNUmakefile | 65 - .../github.com/hashicorp/go-sockaddr/LICENSE | 373 - .../hashicorp/go-sockaddr/README.md | 118 - .../github.com/hashicorp/go-sockaddr/doc.go | 5 - .../github.com/hashicorp/go-sockaddr/go.mod | 1 - .../hashicorp/go-sockaddr/ifaddr.go | 254 - .../hashicorp/go-sockaddr/ifaddrs.go | 1281 - .../hashicorp/go-sockaddr/ifattr.go | 65 - .../hashicorp/go-sockaddr/ipaddr.go | 169 - .../hashicorp/go-sockaddr/ipaddrs.go | 98 - .../hashicorp/go-sockaddr/ipv4addr.go | 516 - .../hashicorp/go-sockaddr/ipv6addr.go | 591 - .../github.com/hashicorp/go-sockaddr/rfc.go | 948 - .../hashicorp/go-sockaddr/route_info.go | 19 - .../hashicorp/go-sockaddr/route_info_bsd.go | 36 - .../go-sockaddr/route_info_default.go | 10 - .../hashicorp/go-sockaddr/route_info_linux.go | 40 - .../go-sockaddr/route_info_solaris.go | 37 - .../go-sockaddr/route_info_windows.go | 41 - .../hashicorp/go-sockaddr/sockaddr.go | 206 - .../hashicorp/go-sockaddr/sockaddrs.go | 193 - .../hashicorp/go-sockaddr/unixsock.go | 135 - .../github.com/hashicorp/go-uuid/.travis.yml | 12 - vendor/github.com/hashicorp/go-uuid/LICENSE | 363 - vendor/github.com/hashicorp/go-uuid/README.md | 8 - vendor/github.com/hashicorp/go-uuid/go.mod | 1 - vendor/github.com/hashicorp/go-uuid/uuid.go | 65 - .../hashicorp/go-version/.travis.yml | 13 - .../github.com/hashicorp/go-version/LICENSE | 354 - .../github.com/hashicorp/go-version/README.md | 65 - .../hashicorp/go-version/constraint.go | 204 - vendor/github.com/hashicorp/go-version/go.mod | 1 - .../hashicorp/go-version/version.go | 347 - .../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/LICENSE | 362 - .../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/go.mod | 1 - vendor/github.com/hashicorp/golang-lru/lru.go | 110 - .../hashicorp/golang-lru/simplelru/lru.go | 161 - .../golang-lru/simplelru/lru_interface.go | 36 - vendor/github.com/hashicorp/hcl/.gitignore | 9 - vendor/github.com/hashicorp/hcl/.travis.yml | 13 - vendor/github.com/hashicorp/hcl/LICENSE | 354 - vendor/github.com/hashicorp/hcl/Makefile | 18 - vendor/github.com/hashicorp/hcl/README.md | 125 - vendor/github.com/hashicorp/hcl/appveyor.yml | 19 - vendor/github.com/hashicorp/hcl/decoder.go | 729 - vendor/github.com/hashicorp/hcl/go.mod | 3 - vendor/github.com/hashicorp/hcl/go.sum | 2 - vendor/github.com/hashicorp/hcl/hcl.go | 11 - .../github.com/hashicorp/hcl/hcl/ast/ast.go | 219 - .../github.com/hashicorp/hcl/hcl/ast/walk.go | 52 - .../hashicorp/hcl/hcl/parser/error.go | 17 - .../hashicorp/hcl/hcl/parser/parser.go | 532 - .../hashicorp/hcl/hcl/scanner/scanner.go | 652 - .../hashicorp/hcl/hcl/strconv/quote.go | 241 - .../hashicorp/hcl/hcl/token/position.go | 46 - .../hashicorp/hcl/hcl/token/token.go | 219 - .../hashicorp/hcl/json/parser/flatten.go | 117 - .../hashicorp/hcl/json/parser/parser.go | 313 - .../hashicorp/hcl/json/scanner/scanner.go | 451 - .../hashicorp/hcl/json/token/position.go | 46 - .../hashicorp/hcl/json/token/token.go | 118 - vendor/github.com/hashicorp/hcl/lex.go | 38 - vendor/github.com/hashicorp/hcl/parse.go | 39 - vendor/github.com/hashicorp/vault/LICENSE | 363 - vendor/github.com/hashicorp/vault/api/auth.go | 11 - .../hashicorp/vault/api/auth_token.go | 275 - .../github.com/hashicorp/vault/api/client.go | 763 - vendor/github.com/hashicorp/vault/api/help.go | 29 - .../github.com/hashicorp/vault/api/logical.go | 267 - .../github.com/hashicorp/vault/api/renewer.go | 349 - .../github.com/hashicorp/vault/api/request.go | 147 - .../hashicorp/vault/api/response.go | 77 - .../github.com/hashicorp/vault/api/secret.go | 320 - vendor/github.com/hashicorp/vault/api/ssh.go | 62 - .../hashicorp/vault/api/ssh_agent.go | 234 - vendor/github.com/hashicorp/vault/api/sys.go | 11 - .../hashicorp/vault/api/sys_audit.go | 136 - .../hashicorp/vault/api/sys_auth.go | 80 - .../hashicorp/vault/api/sys_capabilities.go | 64 - .../hashicorp/vault/api/sys_config_cors.go | 105 - .../hashicorp/vault/api/sys_generate_root.go | 124 - .../hashicorp/vault/api/sys_health.go | 40 - .../hashicorp/vault/api/sys_init.go | 61 - .../hashicorp/vault/api/sys_leader.go | 29 - .../hashicorp/vault/api/sys_leases.go | 105 - .../hashicorp/vault/api/sys_mounts.go | 182 - .../hashicorp/vault/api/sys_plugins.go | 228 - .../hashicorp/vault/api/sys_policy.go | 109 - .../hashicorp/vault/api/sys_rekey.go | 388 - .../hashicorp/vault/api/sys_rotate.go | 77 - .../hashicorp/vault/api/sys_seal.go | 86 - .../hashicorp/vault/api/sys_stepdown.go | 15 - .../github.com/hashicorp/vault/audit/audit.go | 63 - .../hashicorp/vault/audit/format.go | 488 - .../hashicorp/vault/audit/format_json.go | 53 - .../hashicorp/vault/audit/format_jsonx.go | 74 - .../hashicorp/vault/audit/formatter.go | 24 - .../hashicorp/vault/audit/hashstructure.go | 319 - .../logical/database/dbplugin/client.go | 91 - .../logical/database/dbplugin/database.pb.go | 1037 - .../logical/database/dbplugin/database.proto | 93 - .../database/dbplugin/databasemiddleware.go | 275 - .../database/dbplugin/grpc_transport.go | 285 - .../database/dbplugin/netrpc_transport.go | 197 - .../logical/database/dbplugin/plugin.go | 159 - .../logical/database/dbplugin/server.go | 49 - .../hashicorp/vault/builtin/plugin/backend.go | 239 - .../hashicorp/vault/helper/base62/base62.go | 59 - .../vault/helper/certutil/helpers.go | 301 - .../hashicorp/vault/helper/certutil/types.go | 591 - .../vault/helper/compressutil/compress.go | 207 - .../hashicorp/vault/helper/consts/consts.go | 14 - .../hashicorp/vault/helper/consts/error.go | 16 - .../vault/helper/consts/plugin_types.go | 59 - .../vault/helper/consts/replication.go | 87 - .../hashicorp/vault/helper/dbtxn/dbtxn.go | 63 - .../hashicorp/vault/helper/errutil/error.go | 20 - .../vault/helper/forwarding/types.pb.go | 357 - .../vault/helper/forwarding/types.proto | 49 - .../hashicorp/vault/helper/forwarding/util.go | 218 - .../hashicorp/vault/helper/hclutil/hcl.go | 36 - .../vault/helper/identity/identity.go | 65 - .../vault/helper/identity/mfa/types.pb.go | 70 - .../vault/helper/identity/mfa/types.proto | 7 - .../vault/helper/identity/sentinel.go | 125 - .../vault/helper/identity/templating.go | 214 - .../vault/helper/identity/types.pb.go | 796 - .../vault/helper/identity/types.proto | 207 - .../hashicorp/vault/helper/jsonutil/json.go | 100 - .../hashicorp/vault/helper/license/feature.go | 12 - .../hashicorp/vault/helper/locksutil/locks.go | 60 - .../hashicorp/vault/helper/logging/vault.go | 39 - .../hashicorp/vault/helper/mlock/mlock.go | 15 - .../vault/helper/mlock/mlock_unavail.go | 13 - .../vault/helper/mlock/mlock_unix.go | 18 - .../vault/helper/namespace/namespace.go | 127 - .../vault/helper/parseutil/parseutil.go | 163 - .../vault/helper/pathmanager/pathmanager.go | 136 - .../vault/helper/pgpkeys/encrypt_decrypt.go | 118 - .../hashicorp/vault/helper/pgpkeys/flag.go | 140 - .../hashicorp/vault/helper/pgpkeys/keybase.go | 117 - .../vault/helper/pgpkeys/test_keys.go | 271 - .../hashicorp/vault/helper/pluginutil/env.go | 61 - .../vault/helper/pluginutil/runner.go | 193 - .../hashicorp/vault/helper/pluginutil/tls.go | 241 - .../vault/helper/policyutil/policyutil.go | 131 - .../hashicorp/vault/helper/reload/reload.go | 85 - .../hashicorp/vault/helper/salt/salt.go | 178 - .../helper/storagepacker/storagepacker.go | 355 - .../vault/helper/storagepacker/types.pb.go | 141 - .../vault/helper/storagepacker/types.proto | 17 - .../hashicorp/vault/helper/strutil/strutil.go | 381 - .../hashicorp/vault/helper/tlsutil/tlsutil.go | 54 - .../vault/helper/wrapping/wrapinfo.go | 37 - .../hashicorp/vault/helper/xor/xor.go | 48 - .../github.com/hashicorp/vault/http/cors.go | 67 - .../hashicorp/vault/http/handler.go | 808 - .../github.com/hashicorp/vault/http/help.go | 58 - .../hashicorp/vault/http/logical.go | 380 - .../hashicorp/vault/http/stub_assets.go | 16 - .../hashicorp/vault/http/sys_generate_root.go | 211 - .../hashicorp/vault/http/sys_health.go | 202 - .../hashicorp/vault/http/sys_init.go | 165 - .../hashicorp/vault/http/sys_leader.go | 56 - .../hashicorp/vault/http/sys_rekey.go | 411 - .../hashicorp/vault/http/sys_seal.go | 261 - .../hashicorp/vault/http/testing.go | 67 - .../github.com/hashicorp/vault/http/util.go | 22 - .../hashicorp/vault/logical/auth.go | 99 - .../hashicorp/vault/logical/connection.go | 15 - .../hashicorp/vault/logical/error.go | 90 - .../vault/logical/framework/backend.go | 608 - .../vault/logical/framework/field_data.go | 410 - .../vault/logical/framework/field_type.go | 78 - .../vault/logical/framework/lease.go | 106 - .../vault/logical/framework/openapi.go | 613 - .../hashicorp/vault/logical/framework/path.go | 278 - .../vault/logical/framework/path_map.go | 283 - .../vault/logical/framework/path_struct.go | 124 - .../vault/logical/framework/policy_map.go | 65 - .../vault/logical/framework/secret.go | 91 - .../vault/logical/framework/template.go | 42 - .../vault/logical/framework/testing.go | 15 - .../hashicorp/vault/logical/framework/wal.go | 101 - .../hashicorp/vault/logical/identity.pb.go | 187 - .../hashicorp/vault/logical/identity.proto | 34 - .../hashicorp/vault/logical/lease.go | 53 - .../hashicorp/vault/logical/logical.go | 126 - .../hashicorp/vault/logical/plugin.pb.go | 80 - .../hashicorp/vault/logical/plugin.proto | 10 - .../hashicorp/vault/logical/plugin/backend.go | 83 - .../vault/logical/plugin/backend_client.go | 248 - .../vault/logical/plugin/backend_server.go | 148 - .../vault/logical/plugin/grpc_backend.go | 12 - .../logical/plugin/grpc_backend_client.go | 245 - .../logical/plugin/grpc_backend_server.go | 142 - .../vault/logical/plugin/grpc_storage.go | 110 - .../vault/logical/plugin/grpc_system.go | 269 - .../hashicorp/vault/logical/plugin/logger.go | 134 - .../vault/logical/plugin/middleware.go | 91 - .../vault/logical/plugin/pb/backend.pb.go | 3791 -- .../vault/logical/plugin/pb/backend.proto | 594 - .../vault/logical/plugin/pb/translation.go | 622 - .../hashicorp/vault/logical/plugin/plugin.go | 187 - .../hashicorp/vault/logical/plugin/serve.go | 97 - .../hashicorp/vault/logical/plugin/storage.go | 139 - .../hashicorp/vault/logical/plugin/system.go | 351 - .../hashicorp/vault/logical/request.go | 282 - .../hashicorp/vault/logical/request_util.go | 14 - .../hashicorp/vault/logical/response.go | 171 - .../hashicorp/vault/logical/response_util.go | 147 - .../hashicorp/vault/logical/secret.go | 30 - .../hashicorp/vault/logical/storage.go | 121 - .../hashicorp/vault/logical/storage_inmem.go | 67 - .../hashicorp/vault/logical/system_view.go | 139 - .../hashicorp/vault/logical/testing.go | 84 - .../hashicorp/vault/logical/token.go | 181 - .../vault/logical/translate_response.go | 151 - .../hashicorp/vault/physical/cache.go | 219 - .../hashicorp/vault/physical/encoding.go | 104 - .../hashicorp/vault/physical/error.go | 103 - .../hashicorp/vault/physical/inmem/inmem.go | 263 - .../vault/physical/inmem/inmem_ha.go | 167 - .../hashicorp/vault/physical/latency.go | 98 - .../hashicorp/vault/physical/physical.go | 157 - .../vault/physical/physical_access.go | 40 - .../hashicorp/vault/physical/physical_util.go | 10 - .../hashicorp/vault/physical/physical_view.go | 98 - .../hashicorp/vault/physical/testing.go | 488 - .../hashicorp/vault/physical/transactions.go | 131 - .../hashicorp/vault/physical/types.pb.go | 221 - .../hashicorp/vault/physical/types.proto | 38 - .../vault/plugins/database/mysql/mysql.go | 317 - .../plugins/database/postgresql/postgresql.go | 427 - .../helper/database/connutil/connutil.go | 25 - .../plugins/helper/database/connutil/sql.go | 164 - .../helper/database/credsutil/credsutil.go | 46 - .../plugins/helper/database/credsutil/sql.go | 72 - .../plugins/helper/database/dbutil/dbutil.go | 52 - .../hashicorp/vault/plugins/serve.go | 31 - .../hashicorp/vault/shamir/shamir.go | 262 - .../hashicorp/vault/shamir/tables.go | 77 - .../github.com/hashicorp/vault/vault/acl.go | 523 - .../hashicorp/vault/vault/acl_util.go | 14 - .../github.com/hashicorp/vault/vault/audit.go | 502 - .../hashicorp/vault/vault/audit_broker.go | 213 - .../hashicorp/vault/vault/audited_headers.go | 162 - .../github.com/hashicorp/vault/vault/auth.go | 776 - .../hashicorp/vault/vault/barrier.go | 183 - .../hashicorp/vault/vault/barrier_access.go | 24 - .../hashicorp/vault/vault/barrier_aes_gcm.go | 949 - .../hashicorp/vault/vault/barrier_view.go | 154 - .../vault/vault/barrier_view_util.go | 5 - .../hashicorp/vault/vault/capabilities.go | 76 - .../hashicorp/vault/vault/cluster.go | 382 - .../hashicorp/vault/vault/cluster_tls.go | 85 - .../github.com/hashicorp/vault/vault/core.go | 1713 - .../hashicorp/vault/vault/core_util.go | 106 - .../github.com/hashicorp/vault/vault/cors.go | 163 - .../vault/vault/dynamic_system_view.go | 255 - .../hashicorp/vault/vault/expiration.go | 1802 - .../hashicorp/vault/vault/expiration_util.go | 29 - .../hashicorp/vault/vault/generate_root.go | 369 - vendor/github.com/hashicorp/vault/vault/ha.go | 875 - .../hashicorp/vault/vault/identity_lookup.go | 329 - .../hashicorp/vault/vault/identity_store.go | 493 - .../vault/vault/identity_store_aliases.go | 443 - .../vault/vault/identity_store_entities.go | 763 - .../vault/identity_store_group_aliases.go | 329 - .../vault/vault/identity_store_groups.go | 550 - .../vault/vault/identity_store_schema.go | 215 - .../vault/vault/identity_store_structs.go | 83 - .../vault/vault/identity_store_upgrade.go | 168 - .../vault/vault/identity_store_util.go | 1979 - .../github.com/hashicorp/vault/vault/init.go | 323 - .../hashicorp/vault/vault/keyring.go | 203 - .../vault/vault/logical_cubbyhole.go | 240 - .../vault/vault/logical_passthrough.go | 252 - .../hashicorp/vault/vault/logical_system.go | 3845 -- .../vault/vault/logical_system_helpers.go | 133 - .../vault/vault/logical_system_paths.go | 1515 - .../github.com/hashicorp/vault/vault/mount.go | 1343 - .../hashicorp/vault/vault/mount_util.go | 42 - .../hashicorp/vault/vault/namespaces.go | 18 - .../hashicorp/vault/vault/plugin_catalog.go | 368 - .../hashicorp/vault/vault/plugin_reload.go | 193 - .../hashicorp/vault/vault/policy.go | 461 - .../hashicorp/vault/vault/policy_store.go | 840 - .../vault/vault/policy_store_util.go | 47 - .../hashicorp/vault/vault/policy_util.go | 5 - .../github.com/hashicorp/vault/vault/rekey.go | 972 - .../vault/vault/replication_cluster_util.go | 11 - .../vault/vault/request_forwarding.go | 479 - .../vault/vault/request_forwarding_rpc.go | 133 - .../vault/request_forwarding_rpc_util.go | 17 - .../vault/request_forwarding_service.pb.go | 527 - .../vault/request_forwarding_service.proto | 46 - .../vault/vault/request_forwarding_util.go | 18 - .../hashicorp/vault/vault/request_handling.go | 1141 - .../vault/vault/request_handling_util.go | 32 - .../hashicorp/vault/vault/rollback.go | 282 - .../hashicorp/vault/vault/router.go | 823 - .../hashicorp/vault/vault/router_access.go | 16 - .../github.com/hashicorp/vault/vault/seal.go | 376 - .../hashicorp/vault/vault/seal/envelope.go | 72 - .../hashicorp/vault/vault/seal/seal.go | 34 - .../vault/vault/seal/seal_testing.go | 56 - .../hashicorp/vault/vault/seal_access.go | 67 - .../hashicorp/vault/vault/seal_autoseal.go | 467 - .../hashicorp/vault/vault/seal_testing.go | 90 - .../vault/vault/seal_testing_util.go | 9 - .../hashicorp/vault/vault/sealunwrapper.go | 180 - .../hashicorp/vault/vault/testing.go | 1550 - .../hashicorp/vault/vault/testing_util.go | 10 - .../hashicorp/vault/vault/token_store.go | 3166 -- .../hashicorp/vault/vault/token_store_util.go | 27 - vendor/github.com/hashicorp/vault/vault/ui.go | 217 - .../github.com/hashicorp/vault/vault/util.go | 42 - .../hashicorp/vault/vault/wrapping.go | 376 - .../hashicorp/vault/vault/wrapping_util.go | 13 - .../github.com/hashicorp/vault/version/cgo.go | 7 - .../hashicorp/vault/version/version.go | 87 - .../hashicorp/vault/version/version_base.go | 11 - 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 | 157 - vendor/github.com/hashicorp/yamux/go.mod | 1 - vendor/github.com/hashicorp/yamux/mux.go | 98 - vendor/github.com/hashicorp/yamux/session.go | 653 - vendor/github.com/hashicorp/yamux/spec.md | 140 - vendor/github.com/hashicorp/yamux/stream.go | 470 - vendor/github.com/hashicorp/yamux/util.go | 43 - vendor/github.com/hpcloud/tail/.gitignore | 3 - vendor/github.com/hpcloud/tail/.travis.yml | 18 - vendor/github.com/hpcloud/tail/CHANGES.md | 63 - vendor/github.com/hpcloud/tail/Dockerfile | 19 - vendor/github.com/hpcloud/tail/LICENSE.txt | 21 - vendor/github.com/hpcloud/tail/Makefile | 11 - vendor/github.com/hpcloud/tail/README.md | 28 - vendor/github.com/hpcloud/tail/appveyor.yml | 11 - .../hpcloud/tail/ratelimiter/Licence | 7 - .../hpcloud/tail/ratelimiter/leakybucket.go | 97 - .../hpcloud/tail/ratelimiter/memory.go | 58 - .../hpcloud/tail/ratelimiter/storage.go | 6 - vendor/github.com/hpcloud/tail/tail.go | 438 - vendor/github.com/hpcloud/tail/tail_posix.go | 11 - .../github.com/hpcloud/tail/tail_windows.go | 12 - vendor/github.com/hpcloud/tail/util/util.go | 48 - .../hpcloud/tail/watch/filechanges.go | 36 - .../github.com/hpcloud/tail/watch/inotify.go | 128 - .../hpcloud/tail/watch/inotify_tracker.go | 260 - .../github.com/hpcloud/tail/watch/polling.go | 118 - vendor/github.com/hpcloud/tail/watch/watch.go | 20 - .../hpcloud/tail/winfile/winfile.go | 92 - vendor/github.com/jefferai/jsonx/LICENSE | 373 - vendor/github.com/jefferai/jsonx/README.md | 12 - vendor/github.com/jefferai/jsonx/go.mod | 3 - vendor/github.com/jefferai/jsonx/go.sum | 2 - vendor/github.com/jefferai/jsonx/jsonx.go | 132 - vendor/github.com/keybase/go-crypto/AUTHORS | 3 - .../github.com/keybase/go-crypto/CONTRIBUTORS | 3 - vendor/github.com/keybase/go-crypto/LICENSE | 27 - vendor/github.com/keybase/go-crypto/PATENTS | 22 - .../keybase/go-crypto/brainpool/brainpool.go | 134 - .../keybase/go-crypto/brainpool/rcurve.go | 83 - .../keybase/go-crypto/cast5/cast5.go | 526 - .../go-crypto/curve25519/const_amd64.h | 8 - .../go-crypto/curve25519/const_amd64.s | 20 - .../go-crypto/curve25519/cswap_amd64.s | 65 - .../go-crypto/curve25519/curve25519.go | 834 - .../go-crypto/curve25519/curve_impl.go | 124 - .../keybase/go-crypto/curve25519/doc.go | 23 - .../go-crypto/curve25519/freeze_amd64.s | 73 - .../go-crypto/curve25519/ladderstep_amd64.s | 1377 - .../go-crypto/curve25519/mont25519_amd64.go | 240 - .../keybase/go-crypto/curve25519/mul_amd64.s | 169 - .../go-crypto/curve25519/square_amd64.s | 132 - .../keybase/go-crypto/ed25519/ed25519.go | 217 - .../ed25519/internal/edwards25519/const.go | 1422 - .../internal/edwards25519/edwards25519.go | 1793 - .../keybase/go-crypto/openpgp/armor/armor.go | 253 - .../keybase/go-crypto/openpgp/armor/encode.go | 160 - .../go-crypto/openpgp/canonical_text.go | 59 - .../keybase/go-crypto/openpgp/ecdh/ecdh.go | 316 - .../go-crypto/openpgp/elgamal/elgamal.go | 122 - .../go-crypto/openpgp/errors/errors.go | 80 - .../keybase/go-crypto/openpgp/keys.go | 934 - .../go-crypto/openpgp/packet/compressed.go | 124 - .../go-crypto/openpgp/packet/config.go | 98 - .../keybase/go-crypto/openpgp/packet/ecdh.go | 104 - .../go-crypto/openpgp/packet/encrypted_key.go | 227 - .../go-crypto/openpgp/packet/literal.go | 89 - .../keybase/go-crypto/openpgp/packet/ocfb.go | 143 - .../openpgp/packet/one_pass_signature.go | 74 - .../go-crypto/openpgp/packet/opaque.go | 162 - .../go-crypto/openpgp/packet/packet.go | 576 - .../go-crypto/openpgp/packet/private_key.go | 557 - .../go-crypto/openpgp/packet/public_key.go | 990 - .../go-crypto/openpgp/packet/public_key_v3.go | 282 - .../go-crypto/openpgp/packet/reader.go | 76 - .../go-crypto/openpgp/packet/signature.go | 923 - .../go-crypto/openpgp/packet/signature_v3.go | 146 - .../openpgp/packet/symmetric_key_encrypted.go | 158 - .../openpgp/packet/symmetrically_encrypted.go | 291 - .../go-crypto/openpgp/packet/userattribute.go | 91 - .../go-crypto/openpgp/packet/userid.go | 160 - .../keybase/go-crypto/openpgp/patch.sh | 7 - .../keybase/go-crypto/openpgp/read.go | 500 - .../keybase/go-crypto/openpgp/s2k/s2k.go | 326 - .../keybase/go-crypto/openpgp/sig-v3.patch | 135 - .../keybase/go-crypto/openpgp/write.go | 506 - .../keybase/go-crypto/rsa/pkcs1v15.go | 325 - .../github.com/keybase/go-crypto/rsa/pss.go | 297 - .../github.com/keybase/go-crypto/rsa/rsa.go | 646 - vendor/github.com/lib/pq/.gitignore | 4 - vendor/github.com/lib/pq/.travis.sh | 86 - vendor/github.com/lib/pq/.travis.yml | 50 - vendor/github.com/lib/pq/CONTRIBUTING.md | 29 - vendor/github.com/lib/pq/LICENSE.md | 8 - vendor/github.com/lib/pq/README.md | 95 - vendor/github.com/lib/pq/TESTS.md | 33 - vendor/github.com/lib/pq/array.go | 756 - vendor/github.com/lib/pq/buf.go | 91 - vendor/github.com/lib/pq/conn.go | 1854 - vendor/github.com/lib/pq/conn_go18.go | 131 - vendor/github.com/lib/pq/connector.go | 43 - vendor/github.com/lib/pq/copy.go | 282 - vendor/github.com/lib/pq/doc.go | 245 - vendor/github.com/lib/pq/encode.go | 603 - vendor/github.com/lib/pq/error.go | 515 - vendor/github.com/lib/pq/go.mod | 1 - vendor/github.com/lib/pq/notify.go | 797 - vendor/github.com/lib/pq/oid/doc.go | 6 - vendor/github.com/lib/pq/oid/gen.go | 93 - vendor/github.com/lib/pq/oid/types.go | 343 - vendor/github.com/lib/pq/rows.go | 93 - vendor/github.com/lib/pq/ssl.go | 169 - vendor/github.com/lib/pq/ssl_go1.7.go | 14 - vendor/github.com/lib/pq/ssl_permissions.go | 20 - vendor/github.com/lib/pq/ssl_renegotiation.go | 8 - vendor/github.com/lib/pq/ssl_windows.go | 9 - vendor/github.com/lib/pq/url.go | 76 - vendor/github.com/lib/pq/user_posix.go | 24 - vendor/github.com/lib/pq/user_windows.go | 27 - vendor/github.com/lib/pq/uuid.go | 23 - .../mitchellh/copystructure/.travis.yml | 12 - .../mitchellh/copystructure/LICENSE | 21 - .../mitchellh/copystructure/README.md | 21 - .../mitchellh/copystructure/copier_time.go | 15 - .../mitchellh/copystructure/copystructure.go | 548 - .../github.com/mitchellh/copystructure/go.mod | 3 - .../github.com/mitchellh/copystructure/go.sum | 2 - .../github.com/mitchellh/go-homedir/LICENSE | 21 - .../github.com/mitchellh/go-homedir/README.md | 14 - vendor/github.com/mitchellh/go-homedir/go.mod | 1 - .../mitchellh/go-homedir/homedir.go | 167 - .../go-testing-interface/.travis.yml | 13 - .../mitchellh/go-testing-interface/LICENSE | 21 - .../mitchellh/go-testing-interface/README.md | 52 - .../mitchellh/go-testing-interface/go.mod | 1 - .../mitchellh/go-testing-interface/testing.go | 84 - .../go-testing-interface/testing_go19.go | 108 - .../mitchellh/mapstructure/.travis.yml | 8 - .../mitchellh/mapstructure/CHANGELOG.md | 21 - .../github.com/mitchellh/mapstructure/LICENSE | 21 - .../mitchellh/mapstructure/README.md | 46 - .../mitchellh/mapstructure/decode_hooks.go | 217 - .../mitchellh/mapstructure/error.go | 50 - .../github.com/mitchellh/mapstructure/go.mod | 1 - .../mitchellh/mapstructure/mapstructure.go | 1149 - .../mitchellh/reflectwalk/.travis.yml | 1 - .../github.com/mitchellh/reflectwalk/LICENSE | 21 - .../mitchellh/reflectwalk/README.md | 6 - .../github.com/mitchellh/reflectwalk/go.mod | 1 - .../mitchellh/reflectwalk/location.go | 19 - .../mitchellh/reflectwalk/location_string.go | 16 - .../mitchellh/reflectwalk/reflectwalk.go | 401 - vendor/github.com/oklog/run/.gitignore | 14 - vendor/github.com/oklog/run/.travis.yml | 12 - vendor/github.com/oklog/run/LICENSE | 201 - vendor/github.com/oklog/run/README.md | 73 - vendor/github.com/oklog/run/group.go | 62 - vendor/github.com/onsi/ginkgo/.gitignore | 7 - vendor/github.com/onsi/ginkgo/.travis.yml | 17 - vendor/github.com/onsi/ginkgo/CHANGELOG.md | 207 - vendor/github.com/onsi/ginkgo/CONTRIBUTING.md | 33 - vendor/github.com/onsi/ginkgo/LICENSE | 20 - vendor/github.com/onsi/ginkgo/README.md | 121 - vendor/github.com/onsi/ginkgo/RELEASING.md | 14 - .../github.com/onsi/ginkgo/config/config.go | 200 - vendor/github.com/onsi/ginkgo/ginkgo_dsl.go | 619 - .../internal/codelocation/code_location.go | 32 - .../internal/containernode/container_node.go | 151 - .../onsi/ginkgo/internal/failer/failer.go | 92 - .../ginkgo/internal/leafnodes/benchmarker.go | 103 - .../ginkgo/internal/leafnodes/interfaces.go | 19 - .../onsi/ginkgo/internal/leafnodes/it_node.go | 47 - .../ginkgo/internal/leafnodes/measure_node.go | 62 - .../onsi/ginkgo/internal/leafnodes/runner.go | 117 - .../ginkgo/internal/leafnodes/setup_nodes.go | 48 - .../ginkgo/internal/leafnodes/suite_nodes.go | 55 - .../synchronized_after_suite_node.go | 90 - .../synchronized_before_suite_node.go | 181 - .../onsi/ginkgo/internal/remote/aggregator.go | 249 - .../internal/remote/forwarding_reporter.go | 147 - .../internal/remote/output_interceptor.go | 13 - .../remote/output_interceptor_unix.go | 83 - .../internal/remote/output_interceptor_win.go | 36 - .../onsi/ginkgo/internal/remote/server.go | 224 - .../remote/syscall_dup_linux_arm64.go | 11 - .../internal/remote/syscall_dup_solaris.go | 9 - .../internal/remote/syscall_dup_unix.go | 11 - .../onsi/ginkgo/internal/spec/spec.go | 247 - .../onsi/ginkgo/internal/spec/specs.go | 123 - .../internal/spec_iterator/index_computer.go | 55 - .../spec_iterator/parallel_spec_iterator.go | 59 - .../spec_iterator/serial_spec_iterator.go | 45 - .../sharded_parallel_spec_iterator.go | 47 - .../internal/spec_iterator/spec_iterator.go | 20 - .../ginkgo/internal/specrunner/random_id.go | 15 - .../ginkgo/internal/specrunner/spec_runner.go | 411 - .../onsi/ginkgo/internal/suite/suite.go | 190 - .../internal/testingtproxy/testing_t_proxy.go | 76 - .../ginkgo/internal/writer/fake_writer.go | 36 - .../onsi/ginkgo/internal/writer/writer.go | 89 - .../onsi/ginkgo/reporters/default_reporter.go | 84 - .../onsi/ginkgo/reporters/fake_reporter.go | 59 - .../onsi/ginkgo/reporters/junit_reporter.go | 152 - .../onsi/ginkgo/reporters/reporter.go | 15 - .../reporters/stenographer/console_logging.go | 64 - .../stenographer/fake_stenographer.go | 142 - .../reporters/stenographer/stenographer.go | 572 - .../stenographer/support/go-colorable/LICENSE | 21 - .../support/go-colorable/README.md | 43 - .../support/go-colorable/colorable_others.go | 24 - .../support/go-colorable/colorable_windows.go | 783 - .../support/go-colorable/noncolorable.go | 57 - .../stenographer/support/go-isatty/LICENSE | 9 - .../stenographer/support/go-isatty/README.md | 37 - .../stenographer/support/go-isatty/doc.go | 2 - .../support/go-isatty/isatty_appengine.go | 9 - .../support/go-isatty/isatty_bsd.go | 18 - .../support/go-isatty/isatty_linux.go | 18 - .../support/go-isatty/isatty_solaris.go | 16 - .../support/go-isatty/isatty_windows.go | 19 - .../ginkgo/reporters/teamcity_reporter.go | 93 - .../onsi/ginkgo/types/code_location.go | 15 - .../onsi/ginkgo/types/synchronization.go | 30 - vendor/github.com/onsi/ginkgo/types/types.go | 174 - vendor/github.com/onsi/gomega/.gitignore | 5 - vendor/github.com/onsi/gomega/.travis.yml | 23 - vendor/github.com/onsi/gomega/CHANGELOG.md | 125 - vendor/github.com/onsi/gomega/CONTRIBUTING.md | 14 - vendor/github.com/onsi/gomega/LICENSE | 20 - vendor/github.com/onsi/gomega/README.md | 21 - vendor/github.com/onsi/gomega/RELEASING.md | 12 - .../github.com/onsi/gomega/format/format.go | 382 - vendor/github.com/onsi/gomega/go.mod | 15 - vendor/github.com/onsi/gomega/go.sum | 24 - vendor/github.com/onsi/gomega/gomega_dsl.go | 421 - .../gomega/internal/assertion/assertion.go | 105 - .../asyncassertion/async_assertion.go | 194 - .../internal/oraclematcher/oracle_matcher.go | 25 - .../testingtsupport/testing_t_support.go | 60 - vendor/github.com/onsi/gomega/matchers.go | 427 - vendor/github.com/onsi/gomega/matchers/and.go | 63 - .../matchers/assignable_to_type_of_matcher.go | 35 - .../onsi/gomega/matchers/attributes_slice.go | 14 - .../onsi/gomega/matchers/be_a_directory.go | 54 - .../onsi/gomega/matchers/be_a_regular_file.go | 54 - .../gomega/matchers/be_an_existing_file.go | 38 - .../onsi/gomega/matchers/be_closed_matcher.go | 46 - .../onsi/gomega/matchers/be_empty_matcher.go | 27 - .../matchers/be_equivalent_to_matcher.go | 34 - .../onsi/gomega/matchers/be_false_matcher.go | 26 - .../onsi/gomega/matchers/be_identical_to.go | 37 - .../onsi/gomega/matchers/be_nil_matcher.go | 18 - .../gomega/matchers/be_numerically_matcher.go | 132 - .../onsi/gomega/matchers/be_sent_matcher.go | 71 - .../gomega/matchers/be_temporally_matcher.go | 66 - .../onsi/gomega/matchers/be_true_matcher.go | 26 - .../onsi/gomega/matchers/be_zero_matcher.go | 28 - .../onsi/gomega/matchers/consist_of.go | 80 - .../matchers/contain_element_matcher.go | 56 - .../matchers/contain_substring_matcher.go | 38 - .../onsi/gomega/matchers/equal_matcher.go | 42 - .../onsi/gomega/matchers/have_cap_matcher.go | 28 - .../onsi/gomega/matchers/have_key_matcher.go | 54 - .../matchers/have_key_with_value_matcher.go | 74 - .../onsi/gomega/matchers/have_len_matcher.go | 28 - .../gomega/matchers/have_occurred_matcher.go | 33 - .../gomega/matchers/have_prefix_matcher.go | 36 - .../gomega/matchers/have_suffix_matcher.go | 36 - .../gomega/matchers/match_error_matcher.go | 51 - .../gomega/matchers/match_json_matcher.go | 65 - .../gomega/matchers/match_regexp_matcher.go | 43 - .../onsi/gomega/matchers/match_xml_matcher.go | 134 - .../gomega/matchers/match_yaml_matcher.go | 76 - vendor/github.com/onsi/gomega/matchers/not.go | 30 - vendor/github.com/onsi/gomega/matchers/or.go | 67 - .../onsi/gomega/matchers/panic_matcher.go | 46 - .../onsi/gomega/matchers/receive_matcher.go | 128 - .../matchers/semi_structured_data_support.go | 92 - .../onsi/gomega/matchers/succeed_matcher.go | 33 - .../goraph/bipartitegraph/bipartitegraph.go | 41 - .../bipartitegraph/bipartitegraphmatching.go | 159 - .../matchers/support/goraph/edge/edge.go | 61 - .../matchers/support/goraph/node/node.go | 7 - .../matchers/support/goraph/util/util.go | 7 - .../onsi/gomega/matchers/type_support.go | 179 - .../onsi/gomega/matchers/with_transform.go | 72 - vendor/github.com/onsi/gomega/types/types.go | 26 - .../patrickmn/go-cache/CONTRIBUTORS | 9 - vendor/github.com/patrickmn/go-cache/LICENSE | 19 - .../github.com/patrickmn/go-cache/README.md | 83 - vendor/github.com/patrickmn/go-cache/cache.go | 1161 - .../github.com/patrickmn/go-cache/sharded.go | 192 - vendor/github.com/pierrec/lz4/.gitignore | 33 - vendor/github.com/pierrec/lz4/.travis.yml | 18 - vendor/github.com/pierrec/lz4/LICENSE | 28 - vendor/github.com/pierrec/lz4/README.md | 24 - vendor/github.com/pierrec/lz4/block.go | 397 - vendor/github.com/pierrec/lz4/debug.go | 23 - vendor/github.com/pierrec/lz4/debug_stub.go | 7 - .../pierrec/lz4/internal/xxh32/xxh32zero.go | 222 - vendor/github.com/pierrec/lz4/lz4.go | 68 - 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 | 295 - vendor/github.com/pierrec/lz4/writer.go | 267 - vendor/github.com/rendon/testcli/LICENSE | 21 - vendor/github.com/rendon/testcli/README.md | 81 - vendor/github.com/rendon/testcli/main.go | 204 - .../github.com/ryanuber/go-glob/.travis.yml | 5 - vendor/github.com/ryanuber/go-glob/LICENSE | 21 - vendor/github.com/ryanuber/go-glob/README.md | 29 - vendor/github.com/ryanuber/go-glob/glob.go | 51 - vendor/golang.org/x/crypto/AUTHORS | 3 - vendor/golang.org/x/crypto/CONTRIBUTORS | 3 - vendor/golang.org/x/crypto/LICENSE | 27 - vendor/golang.org/x/crypto/PATENTS | 22 - .../x/crypto/curve25519/const_amd64.h | 8 - .../x/crypto/curve25519/const_amd64.s | 20 - .../x/crypto/curve25519/cswap_amd64.s | 65 - .../x/crypto/curve25519/curve25519.go | 834 - vendor/golang.org/x/crypto/curve25519/doc.go | 23 - .../x/crypto/curve25519/freeze_amd64.s | 73 - .../x/crypto/curve25519/ladderstep_amd64.s | 1377 - .../x/crypto/curve25519/mont25519_amd64.go | 240 - .../x/crypto/curve25519/mul_amd64.s | 169 - .../x/crypto/curve25519/square_amd64.s | 132 - vendor/golang.org/x/crypto/ed25519/ed25519.go | 217 - .../ed25519/internal/edwards25519/const.go | 1422 - .../internal/edwards25519/edwards25519.go | 1793 - .../x/crypto/internal/chacha20/asm_arm64.s | 308 - .../crypto/internal/chacha20/chacha_arm64.go | 31 - .../internal/chacha20/chacha_generic.go | 264 - .../crypto/internal/chacha20/chacha_noasm.go | 16 - .../crypto/internal/chacha20/chacha_s390x.go | 29 - .../x/crypto/internal/chacha20/chacha_s390x.s | 260 - .../x/crypto/internal/chacha20/xor.go | 43 - .../x/crypto/internal/subtle/aliasing.go | 32 - .../internal/subtle/aliasing_appengine.go | 35 - .../golang.org/x/crypto/poly1305/mac_noasm.go | 11 - .../golang.org/x/crypto/poly1305/poly1305.go | 83 - .../golang.org/x/crypto/poly1305/sum_amd64.go | 68 - .../golang.org/x/crypto/poly1305/sum_amd64.s | 148 - .../golang.org/x/crypto/poly1305/sum_arm.go | 22 - vendor/golang.org/x/crypto/poly1305/sum_arm.s | 427 - .../x/crypto/poly1305/sum_generic.go | 172 - .../golang.org/x/crypto/poly1305/sum_noasm.go | 16 - .../golang.org/x/crypto/poly1305/sum_s390x.go | 42 - .../golang.org/x/crypto/poly1305/sum_s390x.s | 378 - .../x/crypto/poly1305/sum_vmsl_s390x.s | 909 - vendor/golang.org/x/crypto/ssh/buffer.go | 97 - vendor/golang.org/x/crypto/ssh/certs.go | 535 - vendor/golang.org/x/crypto/ssh/channel.go | 633 - vendor/golang.org/x/crypto/ssh/cipher.go | 770 - vendor/golang.org/x/crypto/ssh/client.go | 278 - vendor/golang.org/x/crypto/ssh/client_auth.go | 525 - vendor/golang.org/x/crypto/ssh/common.go | 383 - vendor/golang.org/x/crypto/ssh/connection.go | 143 - vendor/golang.org/x/crypto/ssh/doc.go | 21 - vendor/golang.org/x/crypto/ssh/handshake.go | 646 - vendor/golang.org/x/crypto/ssh/kex.go | 540 - vendor/golang.org/x/crypto/ssh/keys.go | 1100 - vendor/golang.org/x/crypto/ssh/mac.go | 61 - vendor/golang.org/x/crypto/ssh/messages.go | 766 - vendor/golang.org/x/crypto/ssh/mux.go | 330 - vendor/golang.org/x/crypto/ssh/server.go | 594 - vendor/golang.org/x/crypto/ssh/session.go | 647 - vendor/golang.org/x/crypto/ssh/streamlocal.go | 116 - vendor/golang.org/x/crypto/ssh/tcpip.go | 474 - vendor/golang.org/x/crypto/ssh/transport.go | 353 - vendor/golang.org/x/net/AUTHORS | 3 - vendor/golang.org/x/net/CONTRIBUTORS | 3 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/context/context.go | 56 - vendor/golang.org/x/net/context/go17.go | 72 - vendor/golang.org/x/net/context/go19.go | 20 - vendor/golang.org/x/net/context/pre_go17.go | 300 - vendor/golang.org/x/net/context/pre_go19.go | 109 - vendor/golang.org/x/net/html/atom/atom.go | 78 - vendor/golang.org/x/net/html/atom/gen.go | 712 - vendor/golang.org/x/net/html/atom/table.go | 783 - .../golang.org/x/net/html/charset/charset.go | 257 - vendor/golang.org/x/net/html/const.go | 112 - vendor/golang.org/x/net/html/doc.go | 106 - vendor/golang.org/x/net/html/doctype.go | 156 - vendor/golang.org/x/net/html/entity.go | 2253 - vendor/golang.org/x/net/html/escape.go | 258 - vendor/golang.org/x/net/html/foreign.go | 226 - vendor/golang.org/x/net/html/node.go | 220 - vendor/golang.org/x/net/html/parse.go | 2324 - vendor/golang.org/x/net/html/render.go | 271 - vendor/golang.org/x/net/html/token.go | 1219 - vendor/golang.org/x/net/http/httpguts/guts.go | 50 - .../golang.org/x/net/http/httpguts/httplex.go | 346 - vendor/golang.org/x/net/http2/.gitignore | 2 - vendor/golang.org/x/net/http2/Dockerfile | 51 - vendor/golang.org/x/net/http2/Makefile | 3 - vendor/golang.org/x/net/http2/README | 20 - vendor/golang.org/x/net/http2/ciphers.go | 641 - .../x/net/http2/client_conn_pool.go | 282 - vendor/golang.org/x/net/http2/databuffer.go | 146 - vendor/golang.org/x/net/http2/errors.go | 133 - vendor/golang.org/x/net/http2/flow.go | 50 - vendor/golang.org/x/net/http2/frame.go | 1614 - vendor/golang.org/x/net/http2/go111.go | 29 - vendor/golang.org/x/net/http2/gotrack.go | 170 - vendor/golang.org/x/net/http2/headermap.go | 88 - vendor/golang.org/x/net/http2/hpack/encode.go | 240 - vendor/golang.org/x/net/http2/hpack/hpack.go | 504 - .../golang.org/x/net/http2/hpack/huffman.go | 222 - vendor/golang.org/x/net/http2/hpack/tables.go | 479 - vendor/golang.org/x/net/http2/http2.go | 384 - vendor/golang.org/x/net/http2/not_go111.go | 20 - vendor/golang.org/x/net/http2/pipe.go | 163 - vendor/golang.org/x/net/http2/server.go | 2895 - vendor/golang.org/x/net/http2/transport.go | 2603 - vendor/golang.org/x/net/http2/write.go | 365 - vendor/golang.org/x/net/http2/writesched.go | 242 - .../x/net/http2/writesched_priority.go | 452 - .../x/net/http2/writesched_random.go | 72 - vendor/golang.org/x/net/idna/idna.go | 732 - vendor/golang.org/x/net/idna/punycode.go | 203 - vendor/golang.org/x/net/idna/tables.go | 4557 -- vendor/golang.org/x/net/idna/trie.go | 72 - vendor/golang.org/x/net/idna/trieval.go | 119 - .../x/net/internal/timeseries/timeseries.go | 525 - vendor/golang.org/x/net/trace/events.go | 532 - vendor/golang.org/x/net/trace/histogram.go | 365 - vendor/golang.org/x/net/trace/trace.go | 1130 - vendor/golang.org/x/sys/AUTHORS | 3 - vendor/golang.org/x/sys/CONTRIBUTORS | 3 - vendor/golang.org/x/sys/LICENSE | 27 - vendor/golang.org/x/sys/PATENTS | 22 - vendor/golang.org/x/sys/cpu/byteorder.go | 30 - vendor/golang.org/x/sys/cpu/cpu.go | 126 - vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go | 30 - vendor/golang.org/x/sys/cpu/cpu_arm.go | 9 - vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go | 21 - vendor/golang.org/x/sys/cpu/cpu_gc_x86.go | 16 - vendor/golang.org/x/sys/cpu/cpu_gccgo.c | 43 - vendor/golang.org/x/sys/cpu/cpu_gccgo.go | 26 - .../golang.org/x/sys/cpu/cpu_gccgo_s390x.go | 22 - vendor/golang.org/x/sys/cpu/cpu_linux.go | 59 - .../golang.org/x/sys/cpu/cpu_linux_arm64.go | 67 - .../golang.org/x/sys/cpu/cpu_linux_ppc64x.go | 33 - .../golang.org/x/sys/cpu/cpu_linux_s390x.go | 161 - vendor/golang.org/x/sys/cpu/cpu_mips64x.go | 11 - vendor/golang.org/x/sys/cpu/cpu_mipsx.go | 11 - .../golang.org/x/sys/cpu/cpu_other_arm64.go | 11 - vendor/golang.org/x/sys/cpu/cpu_s390x.s | 57 - vendor/golang.org/x/sys/cpu/cpu_wasm.go | 15 - vendor/golang.org/x/sys/cpu/cpu_x86.go | 59 - vendor/golang.org/x/sys/cpu/cpu_x86.s | 27 - vendor/golang.org/x/sys/unix/.gitignore | 2 - vendor/golang.org/x/sys/unix/README.md | 173 - .../golang.org/x/sys/unix/affinity_linux.go | 124 - vendor/golang.org/x/sys/unix/aliases.go | 14 - vendor/golang.org/x/sys/unix/asm_aix_ppc64.s | 17 - vendor/golang.org/x/sys/unix/asm_darwin_386.s | 29 - .../golang.org/x/sys/unix/asm_darwin_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_darwin_arm.s | 30 - .../golang.org/x/sys/unix/asm_darwin_arm64.s | 30 - .../x/sys/unix/asm_dragonfly_amd64.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_386.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_arm64.s | 29 - vendor/golang.org/x/sys/unix/asm_linux_386.s | 65 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 57 - vendor/golang.org/x/sys/unix/asm_linux_arm.s | 56 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 52 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 56 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 54 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 44 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 56 - vendor/golang.org/x/sys/unix/asm_netbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_netbsd_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_netbsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_netbsd_arm64.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 17 - .../golang.org/x/sys/unix/bluetooth_linux.go | 35 - vendor/golang.org/x/sys/unix/cap_freebsd.go | 195 - vendor/golang.org/x/sys/unix/constants.go | 13 - vendor/golang.org/x/sys/unix/dev_aix_ppc.go | 27 - vendor/golang.org/x/sys/unix/dev_aix_ppc64.go | 29 - vendor/golang.org/x/sys/unix/dev_darwin.go | 24 - vendor/golang.org/x/sys/unix/dev_dragonfly.go | 30 - vendor/golang.org/x/sys/unix/dev_freebsd.go | 30 - vendor/golang.org/x/sys/unix/dev_linux.go | 42 - vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_openbsd.go | 29 - vendor/golang.org/x/sys/unix/dirent.go | 17 - vendor/golang.org/x/sys/unix/endian_big.go | 9 - vendor/golang.org/x/sys/unix/endian_little.go | 9 - vendor/golang.org/x/sys/unix/env_unix.go | 31 - .../x/sys/unix/errors_freebsd_386.go | 227 - .../x/sys/unix/errors_freebsd_amd64.go | 227 - .../x/sys/unix/errors_freebsd_arm.go | 226 - vendor/golang.org/x/sys/unix/fcntl.go | 32 - vendor/golang.org/x/sys/unix/fcntl_darwin.go | 18 - .../x/sys/unix/fcntl_linux_32bit.go | 13 - vendor/golang.org/x/sys/unix/gccgo.go | 62 - vendor/golang.org/x/sys/unix/gccgo_c.c | 39 - .../x/sys/unix/gccgo_linux_amd64.go | 20 - vendor/golang.org/x/sys/unix/ioctl.go | 30 - vendor/golang.org/x/sys/unix/mkall.sh | 212 - vendor/golang.org/x/sys/unix/mkasm_darwin.go | 61 - vendor/golang.org/x/sys/unix/mkerrors.sh | 659 - vendor/golang.org/x/sys/unix/mkpost.go | 106 - vendor/golang.org/x/sys/unix/mksyscall.go | 402 - .../x/sys/unix/mksyscall_aix_ppc.go | 404 - .../x/sys/unix/mksyscall_aix_ppc64.go | 602 - .../x/sys/unix/mksyscall_solaris.go | 335 - .../golang.org/x/sys/unix/mksysctl_openbsd.pl | 265 - vendor/golang.org/x/sys/unix/mksysnum.go | 190 - .../golang.org/x/sys/unix/openbsd_pledge.go | 166 - .../golang.org/x/sys/unix/openbsd_unveil.go | 44 - vendor/golang.org/x/sys/unix/pagesize_unix.go | 15 - vendor/golang.org/x/sys/unix/race.go | 30 - vendor/golang.org/x/sys/unix/race0.go | 25 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 36 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 117 - vendor/golang.org/x/sys/unix/str.go | 26 - vendor/golang.org/x/sys/unix/syscall.go | 54 - vendor/golang.org/x/sys/unix/syscall_aix.go | 549 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 34 - .../x/sys/unix/syscall_aix_ppc64.go | 34 - vendor/golang.org/x/sys/unix/syscall_bsd.go | 624 - .../golang.org/x/sys/unix/syscall_darwin.go | 689 - .../x/sys/unix/syscall_darwin_386.go | 63 - .../x/sys/unix/syscall_darwin_amd64.go | 63 - .../x/sys/unix/syscall_darwin_arm.go | 64 - .../x/sys/unix/syscall_darwin_arm64.go | 66 - .../x/sys/unix/syscall_darwin_libSystem.go | 31 - .../x/sys/unix/syscall_dragonfly.go | 539 - .../x/sys/unix/syscall_dragonfly_amd64.go | 52 - .../golang.org/x/sys/unix/syscall_freebsd.go | 824 - .../x/sys/unix/syscall_freebsd_386.go | 52 - .../x/sys/unix/syscall_freebsd_amd64.go | 52 - .../x/sys/unix/syscall_freebsd_arm.go | 52 - .../x/sys/unix/syscall_freebsd_arm64.go | 52 - vendor/golang.org/x/sys/unix/syscall_linux.go | 1771 - .../x/sys/unix/syscall_linux_386.go | 386 - .../x/sys/unix/syscall_linux_amd64.go | 190 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 - .../x/sys/unix/syscall_linux_arm.go | 274 - .../x/sys/unix/syscall_linux_arm64.go | 223 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 14 - .../x/sys/unix/syscall_linux_gc_386.go | 16 - .../x/sys/unix/syscall_linux_gccgo_386.go | 30 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 20 - .../x/sys/unix/syscall_linux_mips64x.go | 222 - .../x/sys/unix/syscall_linux_mipsx.go | 234 - .../x/sys/unix/syscall_linux_ppc64x.go | 152 - .../x/sys/unix/syscall_linux_riscv64.go | 226 - .../x/sys/unix/syscall_linux_s390x.go | 338 - .../x/sys/unix/syscall_linux_sparc64.go | 147 - .../golang.org/x/sys/unix/syscall_netbsd.go | 622 - .../x/sys/unix/syscall_netbsd_386.go | 33 - .../x/sys/unix/syscall_netbsd_amd64.go | 33 - .../x/sys/unix/syscall_netbsd_arm.go | 33 - .../x/sys/unix/syscall_netbsd_arm64.go | 33 - .../golang.org/x/sys/unix/syscall_openbsd.go | 399 - .../x/sys/unix/syscall_openbsd_386.go | 37 - .../x/sys/unix/syscall_openbsd_amd64.go | 37 - .../x/sys/unix/syscall_openbsd_arm.go | 37 - .../golang.org/x/sys/unix/syscall_solaris.go | 737 - .../x/sys/unix/syscall_solaris_amd64.go | 23 - vendor/golang.org/x/sys/unix/syscall_unix.go | 416 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 15 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 24 - vendor/golang.org/x/sys/unix/timestruct.go | 82 - vendor/golang.org/x/sys/unix/types_aix.go | 236 - vendor/golang.org/x/sys/unix/types_darwin.go | 277 - .../golang.org/x/sys/unix/types_dragonfly.go | 263 - vendor/golang.org/x/sys/unix/types_freebsd.go | 356 - vendor/golang.org/x/sys/unix/types_netbsd.go | 289 - vendor/golang.org/x/sys/unix/types_openbsd.go | 276 - vendor/golang.org/x/sys/unix/types_solaris.go | 266 - vendor/golang.org/x/sys/unix/xattr_bsd.go | 240 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1372 - .../x/sys/unix/zerrors_aix_ppc64.go | 1373 - .../x/sys/unix/zerrors_darwin_386.go | 1783 - .../x/sys/unix/zerrors_darwin_amd64.go | 1783 - .../x/sys/unix/zerrors_darwin_arm.go | 1783 - .../x/sys/unix/zerrors_darwin_arm64.go | 1783 - .../x/sys/unix/zerrors_dragonfly_amd64.go | 1650 - .../x/sys/unix/zerrors_freebsd_386.go | 1793 - .../x/sys/unix/zerrors_freebsd_amd64.go | 1794 - .../x/sys/unix/zerrors_freebsd_arm.go | 1802 - .../x/sys/unix/zerrors_freebsd_arm64.go | 1794 - .../x/sys/unix/zerrors_linux_386.go | 2835 - .../x/sys/unix/zerrors_linux_amd64.go | 2835 - .../x/sys/unix/zerrors_linux_arm.go | 2841 - .../x/sys/unix/zerrors_linux_arm64.go | 2826 - .../x/sys/unix/zerrors_linux_mips.go | 2842 - .../x/sys/unix/zerrors_linux_mips64.go | 2842 - .../x/sys/unix/zerrors_linux_mips64le.go | 2842 - .../x/sys/unix/zerrors_linux_mipsle.go | 2842 - .../x/sys/unix/zerrors_linux_ppc64.go | 2897 - .../x/sys/unix/zerrors_linux_ppc64le.go | 2897 - .../x/sys/unix/zerrors_linux_riscv64.go | 2822 - .../x/sys/unix/zerrors_linux_s390x.go | 2895 - .../x/sys/unix/zerrors_linux_sparc64.go | 2891 - .../x/sys/unix/zerrors_netbsd_386.go | 1772 - .../x/sys/unix/zerrors_netbsd_amd64.go | 1762 - .../x/sys/unix/zerrors_netbsd_arm.go | 1751 - .../x/sys/unix/zerrors_netbsd_arm64.go | 1762 - .../x/sys/unix/zerrors_openbsd_386.go | 1654 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1765 - .../x/sys/unix/zerrors_openbsd_arm.go | 1656 - .../x/sys/unix/zerrors_solaris_amd64.go | 1532 - .../golang.org/x/sys/unix/zptrace386_linux.go | 80 - .../golang.org/x/sys/unix/zptracearm_linux.go | 41 - .../x/sys/unix/zptracemips_linux.go | 50 - .../x/sys/unix/zptracemipsle_linux.go | 50 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1450 - .../x/sys/unix/zsyscall_aix_ppc64.go | 1416 - .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1172 - .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1051 - .../x/sys/unix/zsyscall_darwin_386.1_11.go | 1810 - .../x/sys/unix/zsyscall_darwin_386.go | 2505 - .../x/sys/unix/zsyscall_darwin_386.s | 284 - .../x/sys/unix/zsyscall_darwin_amd64.1_11.go | 1810 - .../x/sys/unix/zsyscall_darwin_amd64.go | 2520 - .../x/sys/unix/zsyscall_darwin_amd64.s | 286 - .../x/sys/unix/zsyscall_darwin_arm.1_11.go | 1793 - .../x/sys/unix/zsyscall_darwin_arm.go | 2483 - .../x/sys/unix/zsyscall_darwin_arm.s | 282 - .../x/sys/unix/zsyscall_darwin_arm64.1_11.go | 1793 - .../x/sys/unix/zsyscall_darwin_arm64.go | 2483 - .../x/sys/unix/zsyscall_darwin_arm64.s | 282 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1659 - .../x/sys/unix/zsyscall_freebsd_386.go | 2015 - .../x/sys/unix/zsyscall_freebsd_amd64.go | 2015 - .../x/sys/unix/zsyscall_freebsd_arm.go | 2015 - .../x/sys/unix/zsyscall_freebsd_arm64.go | 2015 - .../x/sys/unix/zsyscall_linux_386.go | 2220 - .../x/sys/unix/zsyscall_linux_amd64.go | 2387 - .../x/sys/unix/zsyscall_linux_arm.go | 2342 - .../x/sys/unix/zsyscall_linux_arm64.go | 2244 - .../x/sys/unix/zsyscall_linux_mips.go | 2400 - .../x/sys/unix/zsyscall_linux_mips64.go | 2371 - .../x/sys/unix/zsyscall_linux_mips64le.go | 2371 - .../x/sys/unix/zsyscall_linux_mipsle.go | 2400 - .../x/sys/unix/zsyscall_linux_ppc64.go | 2449 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 2449 - .../x/sys/unix/zsyscall_linux_riscv64.go | 2224 - .../x/sys/unix/zsyscall_linux_s390x.go | 2219 - .../x/sys/unix/zsyscall_linux_sparc64.go | 2382 - .../x/sys/unix/zsyscall_netbsd_386.go | 1826 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1826 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1826 - .../x/sys/unix/zsyscall_netbsd_arm64.go | 1826 - .../x/sys/unix/zsyscall_openbsd_386.go | 1692 - .../x/sys/unix/zsyscall_openbsd_amd64.go | 1692 - .../x/sys/unix/zsyscall_openbsd_arm.go | 1692 - .../x/sys/unix/zsyscall_solaris_amd64.go | 1953 - .../x/sys/unix/zsysctl_openbsd_386.go | 270 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 270 - .../x/sys/unix/zsysctl_openbsd_arm.go | 270 - .../x/sys/unix/zsysnum_darwin_386.go | 436 - .../x/sys/unix/zsysnum_darwin_amd64.go | 438 - .../x/sys/unix/zsysnum_darwin_arm.go | 436 - .../x/sys/unix/zsysnum_darwin_arm64.go | 436 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 315 - .../x/sys/unix/zsysnum_freebsd_386.go | 403 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 403 - .../x/sys/unix/zsysnum_freebsd_arm.go | 403 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 395 - .../x/sys/unix/zsysnum_linux_386.go | 392 - .../x/sys/unix/zsysnum_linux_amd64.go | 344 - .../x/sys/unix/zsysnum_linux_arm.go | 364 - .../x/sys/unix/zsysnum_linux_arm64.go | 289 - .../x/sys/unix/zsysnum_linux_mips.go | 377 - .../x/sys/unix/zsysnum_linux_mips64.go | 337 - .../x/sys/unix/zsysnum_linux_mips64le.go | 337 - .../x/sys/unix/zsysnum_linux_mipsle.go | 377 - .../x/sys/unix/zsysnum_linux_ppc64.go | 375 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 375 - .../x/sys/unix/zsysnum_linux_riscv64.go | 288 - .../x/sys/unix/zsysnum_linux_s390x.go | 337 - .../x/sys/unix/zsysnum_linux_sparc64.go | 351 - .../x/sys/unix/zsysnum_netbsd_386.go | 274 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 274 - .../x/sys/unix/zsysnum_netbsd_arm.go | 274 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 274 - .../x/sys/unix/zsysnum_openbsd_386.go | 218 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 218 - .../x/sys/unix/zsysnum_openbsd_arm.go | 218 - .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 345 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 354 - .../x/sys/unix/ztypes_darwin_386.go | 489 - .../x/sys/unix/ztypes_darwin_amd64.go | 499 - .../x/sys/unix/ztypes_darwin_arm.go | 490 - .../x/sys/unix/ztypes_darwin_arm64.go | 499 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 469 - .../x/sys/unix/ztypes_freebsd_386.go | 603 - .../x/sys/unix/ztypes_freebsd_amd64.go | 602 - .../x/sys/unix/ztypes_freebsd_arm.go | 602 - .../x/sys/unix/ztypes_freebsd_arm64.go | 602 - .../golang.org/x/sys/unix/ztypes_linux_386.go | 2083 - .../x/sys/unix/ztypes_linux_amd64.go | 2096 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 2074 - .../x/sys/unix/ztypes_linux_arm64.go | 2075 - .../x/sys/unix/ztypes_linux_mips.go | 2080 - .../x/sys/unix/ztypes_linux_mips64.go | 2077 - .../x/sys/unix/ztypes_linux_mips64le.go | 2077 - .../x/sys/unix/ztypes_linux_mipsle.go | 2080 - .../x/sys/unix/ztypes_linux_ppc64.go | 2085 - .../x/sys/unix/ztypes_linux_ppc64le.go | 2085 - .../x/sys/unix/ztypes_linux_riscv64.go | 2102 - .../x/sys/unix/ztypes_linux_s390x.go | 2099 - .../x/sys/unix/ztypes_linux_sparc64.go | 2080 - .../x/sys/unix/ztypes_netbsd_386.go | 465 - .../x/sys/unix/ztypes_netbsd_amd64.go | 472 - .../x/sys/unix/ztypes_netbsd_arm.go | 470 - .../x/sys/unix/ztypes_netbsd_arm64.go | 472 - .../x/sys/unix/ztypes_openbsd_386.go | 560 - .../x/sys/unix/ztypes_openbsd_amd64.go | 560 - .../x/sys/unix/ztypes_openbsd_arm.go | 561 - .../x/sys/unix/ztypes_solaris_amd64.go | 442 - vendor/golang.org/x/text/AUTHORS | 3 - vendor/golang.org/x/text/CONTRIBUTORS | 3 - vendor/golang.org/x/text/LICENSE | 27 - vendor/golang.org/x/text/PATENTS | 22 - .../x/text/encoding/charmap/charmap.go | 249 - .../x/text/encoding/charmap/maketables.go | 556 - .../x/text/encoding/charmap/tables.go | 7410 --- vendor/golang.org/x/text/encoding/encoding.go | 335 - .../x/text/encoding/htmlindex/gen.go | 173 - .../x/text/encoding/htmlindex/htmlindex.go | 86 - .../x/text/encoding/htmlindex/map.go | 105 - .../x/text/encoding/htmlindex/tables.go | 353 - .../text/encoding/internal/identifier/gen.go | 137 - .../internal/identifier/identifier.go | 81 - .../text/encoding/internal/identifier/mib.go | 1621 - .../x/text/encoding/internal/internal.go | 75 - .../x/text/encoding/japanese/all.go | 12 - .../x/text/encoding/japanese/eucjp.go | 225 - .../x/text/encoding/japanese/iso2022jp.go | 299 - .../x/text/encoding/japanese/maketables.go | 161 - .../x/text/encoding/japanese/shiftjis.go | 189 - .../x/text/encoding/japanese/tables.go | 26971 ---------- .../x/text/encoding/korean/euckr.go | 177 - .../x/text/encoding/korean/maketables.go | 143 - .../x/text/encoding/korean/tables.go | 34152 ------------ .../x/text/encoding/simplifiedchinese/all.go | 12 - .../x/text/encoding/simplifiedchinese/gbk.go | 269 - .../encoding/simplifiedchinese/hzgb2312.go | 245 - .../encoding/simplifiedchinese/maketables.go | 161 - .../text/encoding/simplifiedchinese/tables.go | 43999 ---------------- .../text/encoding/traditionalchinese/big5.go | 199 - .../encoding/traditionalchinese/maketables.go | 140 - .../encoding/traditionalchinese/tables.go | 37142 ------------- .../x/text/encoding/unicode/override.go | 82 - .../x/text/encoding/unicode/unicode.go | 434 - .../x/text/internal/language/common.go | 16 - .../x/text/internal/language/compact.go | 29 - .../text/internal/language/compact/compact.go | 61 - .../x/text/internal/language/compact/gen.go | 64 - .../internal/language/compact/gen_index.go | 113 - .../internal/language/compact/gen_parents.go | 54 - .../internal/language/compact/language.go | 260 - .../text/internal/language/compact/parents.go | 120 - .../text/internal/language/compact/tables.go | 1015 - .../x/text/internal/language/compact/tags.go | 91 - .../x/text/internal/language/compose.go | 167 - .../x/text/internal/language/coverage.go | 28 - .../x/text/internal/language/gen.go | 1520 - .../x/text/internal/language/gen_common.go | 20 - .../x/text/internal/language/language.go | 596 - .../x/text/internal/language/lookup.go | 412 - .../x/text/internal/language/match.go | 226 - .../x/text/internal/language/parse.go | 594 - .../x/text/internal/language/tables.go | 3431 -- .../x/text/internal/language/tags.go | 48 - vendor/golang.org/x/text/internal/tag/tag.go | 100 - .../internal/utf8internal/utf8internal.go | 87 - vendor/golang.org/x/text/language/coverage.go | 187 - vendor/golang.org/x/text/language/doc.go | 102 - vendor/golang.org/x/text/language/gen.go | 305 - vendor/golang.org/x/text/language/go1_1.go | 38 - vendor/golang.org/x/text/language/go1_2.go | 11 - vendor/golang.org/x/text/language/language.go | 601 - vendor/golang.org/x/text/language/match.go | 735 - vendor/golang.org/x/text/language/parse.go | 228 - vendor/golang.org/x/text/language/tables.go | 298 - vendor/golang.org/x/text/language/tags.go | 145 - vendor/golang.org/x/text/runes/cond.go | 187 - vendor/golang.org/x/text/runes/runes.go | 355 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 11 - .../x/text/secure/bidirule/bidirule9.0.0.go | 14 - .../golang.org/x/text/transform/transform.go | 705 - vendor/golang.org/x/text/unicode/bidi/bidi.go | 198 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - vendor/golang.org/x/text/unicode/bidi/core.go | 1058 - vendor/golang.org/x/text/unicode/bidi/gen.go | 133 - .../x/text/unicode/bidi/gen_ranges.go | 57 - .../x/text/unicode/bidi/gen_trieval.go | 64 - vendor/golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1815 - .../x/text/unicode/bidi/tables9.0.0.go | 1781 - .../golang.org/x/text/unicode/bidi/trieval.go | 60 - .../x/text/unicode/norm/composition.go | 512 - .../x/text/unicode/norm/forminfo.go | 278 - .../golang.org/x/text/unicode/norm/input.go | 109 - vendor/golang.org/x/text/unicode/norm/iter.go | 458 - .../x/text/unicode/norm/maketables.go | 986 - .../x/text/unicode/norm/normalize.go | 609 - .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7657 --- .../x/text/unicode/norm/tables9.0.0.go | 7637 --- .../x/text/unicode/norm/transform.go | 88 - vendor/golang.org/x/text/unicode/norm/trie.go | 54 - .../golang.org/x/text/unicode/norm/triegen.go | 117 - vendor/golang.org/x/time/AUTHORS | 3 - vendor/golang.org/x/time/CONTRIBUTORS | 3 - vendor/golang.org/x/time/LICENSE | 27 - vendor/golang.org/x/time/PATENTS | 22 - vendor/golang.org/x/time/rate/rate.go | 374 - vendor/google.golang.org/appengine/LICENSE | 202 - .../appengine/cloudsql/cloudsql.go | 62 - .../appengine/cloudsql/cloudsql_classic.go | 17 - .../appengine/cloudsql/cloudsql_vm.go | 16 - vendor/google.golang.org/genproto/LICENSE | 202 - .../googleapis/rpc/status/status.pb.go | 159 - vendor/google.golang.org/grpc/.travis.yml | 39 - vendor/google.golang.org/grpc/AUTHORS | 1 - vendor/google.golang.org/grpc/CONTRIBUTING.md | 37 - vendor/google.golang.org/grpc/LICENSE | 202 - vendor/google.golang.org/grpc/Makefile | 60 - vendor/google.golang.org/grpc/README.md | 67 - vendor/google.golang.org/grpc/backoff.go | 38 - vendor/google.golang.org/grpc/balancer.go | 391 - .../grpc/balancer/balancer.go | 304 - .../grpc/balancer/base/balancer.go | 171 - .../grpc/balancer/base/base.go | 64 - .../grpc/balancer/roundrobin/roundrobin.go | 83 - .../grpc/balancer_conn_wrappers.go | 328 - .../grpc/balancer_v1_wrapper.go | 341 - .../grpc_binarylog_v1/binarylog.pb.go | 900 - vendor/google.golang.org/grpc/call.go | 74 - vendor/google.golang.org/grpc/clientconn.go | 1446 - vendor/google.golang.org/grpc/codec.go | 50 - vendor/google.golang.org/grpc/codegen.sh | 17 - .../grpc/codes/code_string.go | 62 - vendor/google.golang.org/grpc/codes/codes.go | 197 - .../grpc/connectivity/connectivity.go | 73 - .../grpc/credentials/credentials.go | 328 - .../grpc/credentials/internal/syscallconn.go | 61 - .../internal/syscallconn_appengine.go | 30 - .../grpc/credentials/tls13.go | 30 - vendor/google.golang.org/grpc/dialoptions.go | 502 - vendor/google.golang.org/grpc/doc.go | 24 - .../grpc/encoding/encoding.go | 118 - .../grpc/encoding/proto/proto.go | 110 - vendor/google.golang.org/grpc/go.mod | 20 - vendor/google.golang.org/grpc/go.sum | 32 - .../google.golang.org/grpc/grpclog/grpclog.go | 126 - .../google.golang.org/grpc/grpclog/logger.go | 85 - .../grpc/grpclog/loggerv2.go | 195 - .../google.golang.org/grpc/health/client.go | 107 - .../grpc/health/grpc_health_v1/health.pb.go | 327 - .../grpc/health/regenerate.sh | 33 - .../google.golang.org/grpc/health/server.go | 165 - vendor/google.golang.org/grpc/install_gae.sh | 6 - vendor/google.golang.org/grpc/interceptor.go | 77 - .../grpc/internal/backoff/backoff.go | 78 - .../grpc/internal/binarylog/binarylog.go | 167 - .../internal/binarylog/binarylog_testutil.go | 42 - .../grpc/internal/binarylog/env_config.go | 210 - .../grpc/internal/binarylog/method_logger.go | 423 - .../grpc/internal/binarylog/regenerate.sh | 33 - .../grpc/internal/binarylog/sink.go | 162 - .../grpc/internal/binarylog/util.go | 41 - .../grpc/internal/channelz/funcs.go | 699 - .../grpc/internal/channelz/types.go | 702 - .../grpc/internal/channelz/types_linux.go | 53 - .../grpc/internal/channelz/types_nonlinux.go | 44 - .../grpc/internal/channelz/util_linux.go | 39 - .../grpc/internal/channelz/util_nonlinux.go | 26 - .../grpc/internal/envconfig/envconfig.go | 71 - .../grpc/internal/grpcrand/grpcrand.go | 56 - .../grpc/internal/grpcsync/event.go | 61 - .../grpc/internal/internal.go | 54 - .../grpc/internal/syscall/syscall_linux.go | 114 - .../grpc/internal/syscall/syscall_nonlinux.go | 63 - .../grpc/internal/transport/bdp_estimator.go | 141 - .../grpc/internal/transport/controlbuf.go | 852 - .../grpc/internal/transport/defaults.go | 49 - .../grpc/internal/transport/flowcontrol.go | 218 - .../grpc/internal/transport/handler_server.go | 449 - .../grpc/internal/transport/http2_client.go | 1382 - .../grpc/internal/transport/http2_server.go | 1209 - .../grpc/internal/transport/http_util.go | 623 - .../grpc/internal/transport/log.go | 44 - .../grpc/internal/transport/transport.go | 758 - .../grpc/keepalive/keepalive.go | 85 - .../grpc/metadata/metadata.go | 209 - .../grpc/naming/dns_resolver.go | 293 - .../google.golang.org/grpc/naming/naming.go | 69 - vendor/google.golang.org/grpc/peer/peer.go | 51 - .../google.golang.org/grpc/picker_wrapper.go | 184 - vendor/google.golang.org/grpc/pickfirst.go | 110 - vendor/google.golang.org/grpc/proxy.go | 152 - .../grpc/resolver/dns/dns_resolver.go | 436 - .../grpc/resolver/passthrough/passthrough.go | 57 - .../grpc/resolver/resolver.go | 158 - .../grpc/resolver_conn_wrapper.go | 155 - vendor/google.golang.org/grpc/rpc_util.go | 843 - vendor/google.golang.org/grpc/server.go | 1491 - .../google.golang.org/grpc/service_config.go | 372 - .../google.golang.org/grpc/stats/handlers.go | 63 - vendor/google.golang.org/grpc/stats/stats.go | 295 - .../google.golang.org/grpc/status/status.go | 210 - vendor/google.golang.org/grpc/stream.go | 1485 - vendor/google.golang.org/grpc/tap/tap.go | 51 - vendor/google.golang.org/grpc/trace.go | 113 - vendor/google.golang.org/grpc/version.go | 22 - vendor/google.golang.org/grpc/vet.sh | 123 - vendor/gopkg.in/fsnotify.v1/.editorconfig | 5 - vendor/gopkg.in/fsnotify.v1/.gitignore | 6 - vendor/gopkg.in/fsnotify.v1/.travis.yml | 30 - vendor/gopkg.in/fsnotify.v1/AUTHORS | 52 - vendor/gopkg.in/fsnotify.v1/CHANGELOG.md | 317 - vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md | 77 - vendor/gopkg.in/fsnotify.v1/LICENSE | 28 - vendor/gopkg.in/fsnotify.v1/README.md | 79 - vendor/gopkg.in/fsnotify.v1/fen.go | 37 - vendor/gopkg.in/fsnotify.v1/fsnotify.go | 66 - vendor/gopkg.in/fsnotify.v1/inotify.go | 337 - vendor/gopkg.in/fsnotify.v1/inotify_poller.go | 187 - vendor/gopkg.in/fsnotify.v1/kqueue.go | 521 - vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go | 11 - .../gopkg.in/fsnotify.v1/open_mode_darwin.go | 12 - vendor/gopkg.in/fsnotify.v1/windows.go | 561 - vendor/gopkg.in/ini.v1/.gitignore | 6 - vendor/gopkg.in/ini.v1/.travis.yml | 17 - vendor/gopkg.in/ini.v1/LICENSE | 191 - vendor/gopkg.in/ini.v1/Makefile | 15 - vendor/gopkg.in/ini.v1/README.md | 46 - vendor/gopkg.in/ini.v1/error.go | 32 - vendor/gopkg.in/ini.v1/file.go | 418 - vendor/gopkg.in/ini.v1/ini.go | 217 - vendor/gopkg.in/ini.v1/key.go | 751 - vendor/gopkg.in/ini.v1/parser.go | 494 - vendor/gopkg.in/ini.v1/section.go | 258 - vendor/gopkg.in/ini.v1/struct.go | 512 - vendor/gopkg.in/tomb.v1/LICENSE | 29 - vendor/gopkg.in/tomb.v1/README.md | 4 - vendor/gopkg.in/tomb.v1/tomb.go | 176 - vendor/gopkg.in/yaml.v2/.travis.yml | 12 - vendor/gopkg.in/yaml.v2/LICENSE | 201 - vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - vendor/gopkg.in/yaml.v2/NOTICE | 13 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/apic.go | 739 - vendor/gopkg.in/yaml.v2/decode.go | 775 - vendor/gopkg.in/yaml.v2/emitterc.go | 1685 - vendor/gopkg.in/yaml.v2/encode.go | 390 - vendor/gopkg.in/yaml.v2/go.mod | 5 - vendor/gopkg.in/yaml.v2/parserc.go | 1095 - vendor/gopkg.in/yaml.v2/readerc.go | 412 - vendor/gopkg.in/yaml.v2/resolve.go | 258 - vendor/gopkg.in/yaml.v2/scannerc.go | 2696 - vendor/gopkg.in/yaml.v2/sorter.go | 113 - vendor/gopkg.in/yaml.v2/writerc.go | 26 - vendor/gopkg.in/yaml.v2/yaml.go | 466 - vendor/gopkg.in/yaml.v2/yamlh.go | 738 - vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 - vendor/modules.txt | 291 - 1578 files changed, 671755 deletions(-) delete mode 100644 vendor/github.com/Jeffail/gabs/LICENSE delete mode 100644 vendor/github.com/Jeffail/gabs/README.md delete mode 100644 vendor/github.com/Jeffail/gabs/gabs.go delete mode 100644 vendor/github.com/Jeffail/gabs/gabs_logo.png delete mode 100644 vendor/github.com/NYTimes/gziphandler/.gitignore delete mode 100644 vendor/github.com/NYTimes/gziphandler/.travis.yml delete mode 100644 vendor/github.com/NYTimes/gziphandler/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/NYTimes/gziphandler/CONTRIBUTING.md delete mode 100644 vendor/github.com/NYTimes/gziphandler/LICENSE delete mode 100644 vendor/github.com/NYTimes/gziphandler/README.md delete mode 100644 vendor/github.com/NYTimes/gziphandler/gzip.go delete mode 100644 vendor/github.com/NYTimes/gziphandler/gzip_go18.go delete mode 100644 vendor/github.com/SermoDigital/jose/.gitignore delete mode 100644 vendor/github.com/SermoDigital/jose/.travis.yml delete mode 100644 vendor/github.com/SermoDigital/jose/LICENSE delete mode 100644 vendor/github.com/SermoDigital/jose/README.md delete mode 100644 vendor/github.com/SermoDigital/jose/_test.sh delete mode 100644 vendor/github.com/SermoDigital/jose/base64.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/ecdsa.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/hmac.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/none.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/signature.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/signing_method.go delete mode 100644 vendor/github.com/SermoDigital/jose/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/header.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/claims.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws_serialize.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws_validate.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jwt.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/payload.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/rawbase64.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/signing_methods.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/claims.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/eq.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/jwt.go delete mode 100644 vendor/github.com/SermoDigital/jose/time.go delete mode 100644 vendor/github.com/Venafi/vcert/.gitignore delete mode 100644 vendor/github.com/Venafi/vcert/Dockerfile delete mode 100644 vendor/github.com/Venafi/vcert/Jenkinsfile delete mode 100644 vendor/github.com/Venafi/vcert/LICENSE delete mode 100644 vendor/github.com/Venafi/vcert/Makefile delete mode 100644 vendor/github.com/Venafi/vcert/README.md delete mode 100644 vendor/github.com/Venafi/vcert/client.go delete mode 100644 vendor/github.com/Venafi/vcert/config.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/certificate/certificate.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/certificate/certificateCollection.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/endpoint/endpoint.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/certificatePolicies.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/cloud.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/company.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/connector.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/error.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/search.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/cloud/user.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/fake/ca.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/fake/connector.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/fake/fake.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/tpp/connector.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/tpp/error.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/tpp/search.go delete mode 100644 vendor/github.com/Venafi/vcert/pkg/venafi/tpp/tpp.go delete mode 100644 vendor/github.com/Venafi/vcert/test/context.go delete mode 100644 vendor/github.com/Venafi/vcert/test/fixtures.go delete mode 100644 vendor/github.com/Venafi/vcert/vcert.go delete mode 100644 vendor/github.com/armon/go-metrics/.gitignore delete mode 100644 vendor/github.com/armon/go-metrics/LICENSE delete mode 100644 vendor/github.com/armon/go-metrics/README.md delete mode 100644 vendor/github.com/armon/go-metrics/const_unix.go delete mode 100644 vendor/github.com/armon/go-metrics/const_windows.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem_endpoint.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem_signal.go delete mode 100644 vendor/github.com/armon/go-metrics/metrics.go delete mode 100644 vendor/github.com/armon/go-metrics/sink.go delete mode 100644 vendor/github.com/armon/go-metrics/start.go delete mode 100644 vendor/github.com/armon/go-metrics/statsd.go delete mode 100644 vendor/github.com/armon/go-metrics/statsite.go 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/go.mod delete mode 100644 vendor/github.com/armon/go-radix/radix.go delete mode 100644 vendor/github.com/elazarl/go-bindata-assetfs/LICENSE delete mode 100644 vendor/github.com/elazarl/go-bindata-assetfs/README.md delete mode 100644 vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go delete mode 100644 vendor/github.com/elazarl/go-bindata-assetfs/doc.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/.gitignore delete mode 100644 vendor/github.com/go-sql-driver/mysql/.travis.yml delete mode 100644 vendor/github.com/go-sql-driver/mysql/AUTHORS delete mode 100644 vendor/github.com/go-sql-driver/mysql/CHANGELOG.md delete mode 100644 vendor/github.com/go-sql-driver/mysql/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-sql-driver/mysql/LICENSE delete mode 100644 vendor/github.com/go-sql-driver/mysql/README.md delete mode 100644 vendor/github.com/go-sql-driver/mysql/appengine.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/auth.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/buffer.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/collations.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/connection.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/connection_go18.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/const.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/driver.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/dsn.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/errors.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/fields.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/infile.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/packets.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/result.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/rows.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/statement.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/transaction.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/utils.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/utils_go17.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/utils_go18.go delete mode 100644 vendor/github.com/golang/protobuf/AUTHORS delete mode 100644 vendor/github.com/golang/protobuf/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/protobuf/LICENSE delete mode 100644 vendor/github.com/golang/protobuf/proto/clone.go delete mode 100644 vendor/github.com/golang/protobuf/proto/decode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/deprecated.go delete mode 100644 vendor/github.com/golang/protobuf/proto/discard.go delete mode 100644 vendor/github.com/golang/protobuf/proto/encode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/equal.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions.go delete mode 100644 vendor/github.com/golang/protobuf/proto/lib.go delete mode 100644 vendor/github.com/golang/protobuf/proto/message_set.go delete mode 100644 vendor/github.com/golang/protobuf/proto/pointer_reflect.go delete mode 100644 vendor/github.com/golang/protobuf/proto/pointer_unsafe.go delete mode 100644 vendor/github.com/golang/protobuf/proto/properties.go delete mode 100644 vendor/github.com/golang/protobuf/proto/table_marshal.go delete mode 100644 vendor/github.com/golang/protobuf/proto/table_merge.go delete mode 100644 vendor/github.com/golang/protobuf/proto/table_unmarshal.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_parser.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any/any.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any/any.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/doc.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration/duration.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto 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.go delete mode 100644 vendor/github.com/golang/snappy/decode_amd64.s 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.go delete mode 100644 vendor/github.com/golang/snappy/encode_amd64.s 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/errwrap/LICENSE delete mode 100644 vendor/github.com/hashicorp/errwrap/README.md delete mode 100644 vendor/github.com/hashicorp/errwrap/errwrap.go delete mode 100644 vendor/github.com/hashicorp/errwrap/go.mod delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/doc.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/go.mod delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/handlers.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-hclog/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-hclog/README.md delete mode 100644 vendor/github.com/hashicorp/go-hclog/global.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/go.mod delete mode 100644 vendor/github.com/hashicorp/go-hclog/go.sum delete mode 100644 vendor/github.com/hashicorp/go-hclog/int.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/log.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/nulllogger.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/stacktrace.go delete mode 100644 vendor/github.com/hashicorp/go-hclog/stdlog.go delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/README.md delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/edges.go delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/go.mod delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/go.sum delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/iradix.go delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/iter.go delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/node.go delete mode 100644 vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-memdb/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-memdb/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-memdb/README.md delete mode 100644 vendor/github.com/hashicorp/go-memdb/filter.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/index.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/memdb.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/schema.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/txn.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/watch.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/watch_few.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-multierror/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-multierror/Makefile delete mode 100644 vendor/github.com/hashicorp/go-multierror/README.md delete mode 100644 vendor/github.com/hashicorp/go-multierror/append.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/flatten.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/format.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/go.mod delete mode 100644 vendor/github.com/hashicorp/go-multierror/go.sum delete mode 100644 vendor/github.com/hashicorp/go-multierror/multierror.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/prefix.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/sort.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/.gitignore 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/go.mod delete mode 100644 vendor/github.com/hashicorp/go-plugin/go.sum delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_broker.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_broker.pb.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_broker.proto delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_client.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/grpc_server.go delete mode 100644 vendor/github.com/hashicorp/go-plugin/log_entry.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-retryablehttp/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/Makefile delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/client.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/go.mod delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/go.sum delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/Makefile delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/README.md delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/doc.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/go.mod delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/go.sum delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/GNUmakefile delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/README.md delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/doc.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/go.mod delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifattr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/rfc.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_default.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/sockaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/unixsock.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/go.mod delete mode 100644 vendor/github.com/hashicorp/go-uuid/uuid.go delete mode 100644 vendor/github.com/hashicorp/go-version/.travis.yml 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/go.mod 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/LICENSE 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/go.mod delete mode 100644 vendor/github.com/hashicorp/golang-lru/lru.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go delete mode 100644 vendor/github.com/hashicorp/hcl/.gitignore delete mode 100644 vendor/github.com/hashicorp/hcl/.travis.yml delete mode 100644 vendor/github.com/hashicorp/hcl/LICENSE delete mode 100644 vendor/github.com/hashicorp/hcl/Makefile delete mode 100644 vendor/github.com/hashicorp/hcl/README.md delete mode 100644 vendor/github.com/hashicorp/hcl/appveyor.yml delete mode 100644 vendor/github.com/hashicorp/hcl/decoder.go delete mode 100644 vendor/github.com/hashicorp/hcl/go.mod delete mode 100644 vendor/github.com/hashicorp/hcl/go.sum delete mode 100644 vendor/github.com/hashicorp/hcl/hcl.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/ast/ast.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/ast/walk.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/parser/error.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/parser/parser.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/token/position.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/token/token.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/parser/flatten.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/parser/parser.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/scanner/scanner.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/token/position.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/token/token.go delete mode 100644 vendor/github.com/hashicorp/hcl/lex.go delete mode 100644 vendor/github.com/hashicorp/hcl/parse.go delete mode 100644 vendor/github.com/hashicorp/vault/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault/api/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/api/auth_token.go delete mode 100644 vendor/github.com/hashicorp/vault/api/client.go delete mode 100644 vendor/github.com/hashicorp/vault/api/help.go delete mode 100644 vendor/github.com/hashicorp/vault/api/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/api/renewer.go delete mode 100644 vendor/github.com/hashicorp/vault/api/request.go delete mode 100644 vendor/github.com/hashicorp/vault/api/response.go delete mode 100644 vendor/github.com/hashicorp/vault/api/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/api/ssh.go delete mode 100644 vendor/github.com/hashicorp/vault/api/ssh_agent.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_audit.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_auth.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_capabilities.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_config_cors.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_health.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_init.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_leader.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_leases.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_mounts.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_plugins.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_policy.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_rotate.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_seal.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_stepdown.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format_json.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format_jsonx.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/formatter.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/hashstructure.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/client.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.proto delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/databasemiddleware.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/grpc_transport.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/netrpc_transport.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/plugin.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/server.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/base62/base62.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/certutil/helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/certutil/types.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/compressutil/compress.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/consts.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/error.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/plugin_types.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/replication.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/dbtxn/dbtxn.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/errutil/error.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/util.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/identity.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/mfa/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/mfa/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/sentinel.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/templating.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/jsonutil/json.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/license/feature.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/locksutil/locks.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/logging/vault.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/namespace/namespace.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/env.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/reload/reload.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/salt/salt.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/strutil/strutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/xor/xor.go delete mode 100644 vendor/github.com/hashicorp/vault/http/cors.go delete mode 100644 vendor/github.com/hashicorp/vault/http/handler.go delete mode 100644 vendor/github.com/hashicorp/vault/http/help.go delete mode 100644 vendor/github.com/hashicorp/vault/http/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/http/stub_assets.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_health.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_init.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_leader.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_seal.go delete mode 100644 vendor/github.com/hashicorp/vault/http/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/http/util.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/connection.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/error.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/field_data.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/field_type.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/openapi.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path_map.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path_struct.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/policy_map.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/template.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/wal.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/identity.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/identity.proto delete mode 100644 vendor/github.com/hashicorp/vault/logical/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin.proto delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/logger.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/middleware.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.proto delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/pb/translation.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/plugin.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/serve.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/system.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/request.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/request_util.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/response.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/response_util.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/storage_inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/system_view.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/token.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/translate_response.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/cache.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/encoding.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/error.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/inmem/inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/latency.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical_access.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical_util.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical_view.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/transactions.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/plugins/database/mysql/mysql.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/database/postgresql/postgresql.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/connutil.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/sql.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/credsutil.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/sql.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/helper/database/dbutil/dbutil.go delete mode 100644 vendor/github.com/hashicorp/vault/plugins/serve.go delete mode 100644 vendor/github.com/hashicorp/vault/shamir/shamir.go delete mode 100644 vendor/github.com/hashicorp/vault/shamir/tables.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/acl.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/acl_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audit_broker.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audited_headers.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_view.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_view_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/capabilities.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/cluster.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/cluster_tls.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/core.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/core_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/cors.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/expiration.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/expiration_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/ha.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_lookup.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_entities.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_groups.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_schema.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_structs.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/init.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/keyring.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_passthrough.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_system.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_system_paths.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/mount.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/mount_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/namespaces.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/plugin_catalog.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/plugin_reload.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy_store_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/replication_cluster_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_handling.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_handling_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/rollback.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/router.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/router_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal/envelope.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal/seal.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal/seal_testing.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_autoseal.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_testing.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_testing_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/sealunwrapper.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/testing_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/token_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/token_store_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/ui.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/wrapping.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/wrapping_util.go delete mode 100644 vendor/github.com/hashicorp/vault/version/cgo.go delete mode 100644 vendor/github.com/hashicorp/vault/version/version.go delete mode 100644 vendor/github.com/hashicorp/vault/version/version_base.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/go.mod 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/hpcloud/tail/.gitignore delete mode 100644 vendor/github.com/hpcloud/tail/.travis.yml delete mode 100644 vendor/github.com/hpcloud/tail/CHANGES.md delete mode 100644 vendor/github.com/hpcloud/tail/Dockerfile delete mode 100644 vendor/github.com/hpcloud/tail/LICENSE.txt delete mode 100644 vendor/github.com/hpcloud/tail/Makefile delete mode 100644 vendor/github.com/hpcloud/tail/README.md delete mode 100644 vendor/github.com/hpcloud/tail/appveyor.yml delete mode 100644 vendor/github.com/hpcloud/tail/ratelimiter/Licence delete mode 100644 vendor/github.com/hpcloud/tail/ratelimiter/leakybucket.go delete mode 100644 vendor/github.com/hpcloud/tail/ratelimiter/memory.go delete mode 100644 vendor/github.com/hpcloud/tail/ratelimiter/storage.go delete mode 100644 vendor/github.com/hpcloud/tail/tail.go delete mode 100644 vendor/github.com/hpcloud/tail/tail_posix.go delete mode 100644 vendor/github.com/hpcloud/tail/tail_windows.go delete mode 100644 vendor/github.com/hpcloud/tail/util/util.go delete mode 100644 vendor/github.com/hpcloud/tail/watch/filechanges.go delete mode 100644 vendor/github.com/hpcloud/tail/watch/inotify.go delete mode 100644 vendor/github.com/hpcloud/tail/watch/inotify_tracker.go delete mode 100644 vendor/github.com/hpcloud/tail/watch/polling.go delete mode 100644 vendor/github.com/hpcloud/tail/watch/watch.go delete mode 100644 vendor/github.com/hpcloud/tail/winfile/winfile.go delete mode 100644 vendor/github.com/jefferai/jsonx/LICENSE delete mode 100644 vendor/github.com/jefferai/jsonx/README.md delete mode 100644 vendor/github.com/jefferai/jsonx/go.mod delete mode 100644 vendor/github.com/jefferai/jsonx/go.sum delete mode 100644 vendor/github.com/jefferai/jsonx/jsonx.go delete mode 100644 vendor/github.com/keybase/go-crypto/AUTHORS delete mode 100644 vendor/github.com/keybase/go-crypto/CONTRIBUTORS delete mode 100644 vendor/github.com/keybase/go-crypto/LICENSE delete mode 100644 vendor/github.com/keybase/go-crypto/PATENTS delete mode 100644 vendor/github.com/keybase/go-crypto/brainpool/brainpool.go delete mode 100644 vendor/github.com/keybase/go-crypto/brainpool/rcurve.go delete mode 100644 vendor/github.com/keybase/go-crypto/cast5/cast5.go delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/const_amd64.h delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/const_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/cswap_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/curve25519.go delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/curve_impl.go delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/doc.go delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/freeze_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/ladderstep_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/mont25519_amd64.go delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/mul_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/curve25519/square_amd64.s delete mode 100644 vendor/github.com/keybase/go-crypto/ed25519/ed25519.go delete mode 100644 vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/const.go delete mode 100644 vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/edwards25519.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/armor/armor.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/armor/encode.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/ecdh/ecdh.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/elgamal/elgamal.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/errors/errors.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/keys.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/config.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/patch.sh delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/read.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/s2k/s2k.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/write.go delete mode 100644 vendor/github.com/keybase/go-crypto/rsa/pkcs1v15.go delete mode 100644 vendor/github.com/keybase/go-crypto/rsa/pss.go delete mode 100644 vendor/github.com/keybase/go-crypto/rsa/rsa.go delete mode 100644 vendor/github.com/lib/pq/.gitignore delete mode 100644 vendor/github.com/lib/pq/.travis.sh delete mode 100644 vendor/github.com/lib/pq/.travis.yml delete mode 100644 vendor/github.com/lib/pq/CONTRIBUTING.md delete mode 100644 vendor/github.com/lib/pq/LICENSE.md delete mode 100644 vendor/github.com/lib/pq/README.md delete mode 100644 vendor/github.com/lib/pq/TESTS.md delete mode 100644 vendor/github.com/lib/pq/array.go delete mode 100644 vendor/github.com/lib/pq/buf.go delete mode 100644 vendor/github.com/lib/pq/conn.go delete mode 100644 vendor/github.com/lib/pq/conn_go18.go delete mode 100644 vendor/github.com/lib/pq/connector.go delete mode 100644 vendor/github.com/lib/pq/copy.go delete mode 100644 vendor/github.com/lib/pq/doc.go delete mode 100644 vendor/github.com/lib/pq/encode.go delete mode 100644 vendor/github.com/lib/pq/error.go delete mode 100644 vendor/github.com/lib/pq/go.mod delete mode 100644 vendor/github.com/lib/pq/notify.go delete mode 100644 vendor/github.com/lib/pq/oid/doc.go delete mode 100644 vendor/github.com/lib/pq/oid/gen.go delete mode 100644 vendor/github.com/lib/pq/oid/types.go delete mode 100644 vendor/github.com/lib/pq/rows.go delete mode 100644 vendor/github.com/lib/pq/ssl.go delete mode 100644 vendor/github.com/lib/pq/ssl_go1.7.go delete mode 100644 vendor/github.com/lib/pq/ssl_permissions.go delete mode 100644 vendor/github.com/lib/pq/ssl_renegotiation.go delete mode 100644 vendor/github.com/lib/pq/ssl_windows.go delete mode 100644 vendor/github.com/lib/pq/url.go delete mode 100644 vendor/github.com/lib/pq/user_posix.go delete mode 100644 vendor/github.com/lib/pq/user_windows.go delete mode 100644 vendor/github.com/lib/pq/uuid.go delete mode 100644 vendor/github.com/mitchellh/copystructure/.travis.yml 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/copystructure/go.mod delete mode 100644 vendor/github.com/mitchellh/copystructure/go.sum delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/go.mod delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.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/go.mod delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/testing.go delete mode 100644 vendor/github.com/mitchellh/go-testing-interface/testing_go19.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/.travis.yml delete mode 100644 vendor/github.com/mitchellh/mapstructure/CHANGELOG.md delete mode 100644 vendor/github.com/mitchellh/mapstructure/LICENSE delete mode 100644 vendor/github.com/mitchellh/mapstructure/README.md delete mode 100644 vendor/github.com/mitchellh/mapstructure/decode_hooks.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/error.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/go.mod delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure.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/go.mod 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/.travis.yml 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/group.go delete mode 100644 vendor/github.com/onsi/ginkgo/.gitignore delete mode 100644 vendor/github.com/onsi/ginkgo/.travis.yml delete mode 100644 vendor/github.com/onsi/ginkgo/CHANGELOG.md delete mode 100644 vendor/github.com/onsi/ginkgo/CONTRIBUTING.md delete mode 100644 vendor/github.com/onsi/ginkgo/LICENSE delete mode 100644 vendor/github.com/onsi/ginkgo/README.md delete mode 100644 vendor/github.com/onsi/ginkgo/RELEASING.md delete mode 100644 vendor/github.com/onsi/ginkgo/config/config.go delete mode 100644 vendor/github.com/onsi/ginkgo/ginkgo_dsl.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/failer/failer.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/server.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec/spec.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec/specs.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/suite/suite.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/writer/writer.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/default_reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go delete mode 100644 vendor/github.com/onsi/ginkgo/types/code_location.go delete mode 100644 vendor/github.com/onsi/ginkgo/types/synchronization.go delete mode 100644 vendor/github.com/onsi/ginkgo/types/types.go delete mode 100644 vendor/github.com/onsi/gomega/.gitignore delete mode 100644 vendor/github.com/onsi/gomega/.travis.yml delete mode 100644 vendor/github.com/onsi/gomega/CHANGELOG.md delete mode 100644 vendor/github.com/onsi/gomega/CONTRIBUTING.md delete mode 100644 vendor/github.com/onsi/gomega/LICENSE delete mode 100644 vendor/github.com/onsi/gomega/README.md delete mode 100644 vendor/github.com/onsi/gomega/RELEASING.md delete mode 100644 vendor/github.com/onsi/gomega/format/format.go delete mode 100644 vendor/github.com/onsi/gomega/go.mod delete mode 100644 vendor/github.com/onsi/gomega/go.sum delete mode 100644 vendor/github.com/onsi/gomega/gomega_dsl.go delete mode 100644 vendor/github.com/onsi/gomega/internal/assertion/assertion.go delete mode 100644 vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go delete mode 100644 vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go delete mode 100644 vendor/github.com/onsi/gomega/matchers.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/and.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/attributes_slice.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_a_directory.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_false_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_identical_to.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_true_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/consist_of.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/equal_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_key_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_len_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_error_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_json_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/not.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/or.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/panic_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/receive_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/succeed_matcher.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/type_support.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/with_transform.go delete mode 100644 vendor/github.com/onsi/gomega/types/types.go delete mode 100644 vendor/github.com/patrickmn/go-cache/CONTRIBUTORS delete mode 100644 vendor/github.com/patrickmn/go-cache/LICENSE delete mode 100644 vendor/github.com/patrickmn/go-cache/README.md delete mode 100644 vendor/github.com/patrickmn/go-cache/cache.go delete mode 100644 vendor/github.com/patrickmn/go-cache/sharded.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/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/writer.go delete mode 100644 vendor/github.com/rendon/testcli/LICENSE delete mode 100644 vendor/github.com/rendon/testcli/README.md delete mode 100644 vendor/github.com/rendon/testcli/main.go delete mode 100644 vendor/github.com/ryanuber/go-glob/.travis.yml delete mode 100644 vendor/github.com/ryanuber/go-glob/LICENSE delete mode 100644 vendor/github.com/ryanuber/go-glob/README.md delete mode 100644 vendor/github.com/ryanuber/go-glob/glob.go delete mode 100644 vendor/golang.org/x/crypto/AUTHORS delete mode 100644 vendor/golang.org/x/crypto/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/crypto/LICENSE delete mode 100644 vendor/golang.org/x/crypto/PATENTS delete mode 100644 vendor/golang.org/x/crypto/curve25519/const_amd64.h delete mode 100644 vendor/golang.org/x/crypto/curve25519/const_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/cswap_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/doc.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/freeze_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/mul_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/square_amd64.s delete mode 100644 vendor/golang.org/x/crypto/ed25519/ed25519.go delete mode 100644 vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go delete mode 100644 vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/xor.go delete mode 100644 vendor/golang.org/x/crypto/internal/subtle/aliasing.go delete mode 100644 vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/mac_noasm.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/poly1305.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_amd64.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_amd64.s delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_arm.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_arm.s delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_generic.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_noasm.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_s390x.go delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_s390x.s delete mode 100644 vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s delete mode 100644 vendor/golang.org/x/crypto/ssh/buffer.go delete mode 100644 vendor/golang.org/x/crypto/ssh/certs.go delete mode 100644 vendor/golang.org/x/crypto/ssh/channel.go delete mode 100644 vendor/golang.org/x/crypto/ssh/cipher.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_auth.go delete mode 100644 vendor/golang.org/x/crypto/ssh/common.go delete mode 100644 vendor/golang.org/x/crypto/ssh/connection.go delete mode 100644 vendor/golang.org/x/crypto/ssh/doc.go delete mode 100644 vendor/golang.org/x/crypto/ssh/handshake.go delete mode 100644 vendor/golang.org/x/crypto/ssh/kex.go delete mode 100644 vendor/golang.org/x/crypto/ssh/keys.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mac.go delete mode 100644 vendor/golang.org/x/crypto/ssh/messages.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mux.go delete mode 100644 vendor/golang.org/x/crypto/ssh/server.go delete mode 100644 vendor/golang.org/x/crypto/ssh/session.go delete mode 100644 vendor/golang.org/x/crypto/ssh/streamlocal.go delete mode 100644 vendor/golang.org/x/crypto/ssh/tcpip.go delete mode 100644 vendor/golang.org/x/crypto/ssh/transport.go delete mode 100644 vendor/golang.org/x/net/AUTHORS delete mode 100644 vendor/golang.org/x/net/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS 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/net/html/atom/atom.go delete mode 100644 vendor/golang.org/x/net/html/atom/gen.go delete mode 100644 vendor/golang.org/x/net/html/atom/table.go delete mode 100644 vendor/golang.org/x/net/html/charset/charset.go delete mode 100644 vendor/golang.org/x/net/html/const.go delete mode 100644 vendor/golang.org/x/net/html/doc.go delete mode 100644 vendor/golang.org/x/net/html/doctype.go delete mode 100644 vendor/golang.org/x/net/html/entity.go delete mode 100644 vendor/golang.org/x/net/html/escape.go delete mode 100644 vendor/golang.org/x/net/html/foreign.go delete mode 100644 vendor/golang.org/x/net/html/node.go delete mode 100644 vendor/golang.org/x/net/html/parse.go delete mode 100644 vendor/golang.org/x/net/html/render.go delete mode 100644 vendor/golang.org/x/net/html/token.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/guts.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/httplex.go delete mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/Dockerfile delete mode 100644 vendor/golang.org/x/net/http2/Makefile delete mode 100644 vendor/golang.org/x/net/http2/README delete mode 100644 vendor/golang.org/x/net/http2/ciphers.go delete mode 100644 vendor/golang.org/x/net/http2/client_conn_pool.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer.go delete mode 100644 vendor/golang.org/x/net/http2/errors.go delete mode 100644 vendor/golang.org/x/net/http2/flow.go delete mode 100644 vendor/golang.org/x/net/http2/frame.go delete mode 100644 vendor/golang.org/x/net/http2/go111.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack.go delete mode 100644 vendor/golang.org/x/net/http2/headermap.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/huffman.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables.go delete mode 100644 vendor/golang.org/x/net/http2/http2.go delete mode 100644 vendor/golang.org/x/net/http2/not_go111.go delete mode 100644 vendor/golang.org/x/net/http2/pipe.go delete mode 100644 vendor/golang.org/x/net/http2/server.go delete mode 100644 vendor/golang.org/x/net/http2/transport.go delete mode 100644 vendor/golang.org/x/net/http2/write.go delete mode 100644 vendor/golang.org/x/net/http2/writesched.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random.go delete mode 100644 vendor/golang.org/x/net/idna/idna.go delete mode 100644 vendor/golang.org/x/net/idna/punycode.go delete mode 100644 vendor/golang.org/x/net/idna/tables.go delete mode 100644 vendor/golang.org/x/net/idna/trie.go delete mode 100644 vendor/golang.org/x/net/idna/trieval.go delete mode 100644 vendor/golang.org/x/net/internal/timeseries/timeseries.go delete mode 100644 vendor/golang.org/x/net/trace/events.go delete mode 100644 vendor/golang.org/x/net/trace/histogram.go delete mode 100644 vendor/golang.org/x/net/trace/trace.go delete mode 100644 vendor/golang.org/x/sys/AUTHORS delete mode 100644 vendor/golang.org/x/sys/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/sys/LICENSE delete mode 100644 vendor/golang.org/x/sys/PATENTS 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_ppc64.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_arm.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.c delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux.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_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_mips64x.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_mipsx.go delete mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_arm64.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/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 vendor/golang.org/x/sys/unix/asm_aix_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl.go delete mode 100644 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100644 vendor/golang.org/x/sys/unix/mkasm_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100644 vendor/golang.org/x/sys/unix/mkpost.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/mksysctl_openbsd.pl delete mode 100644 vendor/golang.org/x/sys/unix/mksysnum.go delete mode 100644 vendor/golang.org/x/sys/unix/openbsd_pledge.go delete mode 100644 vendor/golang.org/x/sys/unix/openbsd_unveil.go delete mode 100644 vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/race.go delete mode 100644 vendor/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/str.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 vendor/golang.org/x/sys/unix/types_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/types_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/types_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/types_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace386_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracearm_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracemips_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracemipsle_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_386.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/golang.org/x/text/AUTHORS delete mode 100644 vendor/golang.org/x/text/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/text/LICENSE delete mode 100644 vendor/golang.org/x/text/PATENTS delete mode 100644 vendor/golang.org/x/text/encoding/charmap/charmap.go delete mode 100644 vendor/golang.org/x/text/encoding/charmap/maketables.go delete mode 100644 vendor/golang.org/x/text/encoding/charmap/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/encoding.go delete mode 100644 vendor/golang.org/x/text/encoding/htmlindex/gen.go delete mode 100644 vendor/golang.org/x/text/encoding/htmlindex/htmlindex.go delete mode 100644 vendor/golang.org/x/text/encoding/htmlindex/map.go delete mode 100644 vendor/golang.org/x/text/encoding/htmlindex/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/gen.go delete mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/identifier.go delete mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/mib.go delete mode 100644 vendor/golang.org/x/text/encoding/internal/internal.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/all.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/eucjp.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/iso2022jp.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/maketables.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/shiftjis.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/korean/euckr.go delete mode 100644 vendor/golang.org/x/text/encoding/korean/maketables.go delete mode 100644 vendor/golang.org/x/text/encoding/korean/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/all.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/gbk.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/hzgb2312.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/maketables.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/big5.go delete mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/maketables.go delete mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/tables.go delete mode 100644 vendor/golang.org/x/text/encoding/unicode/override.go delete mode 100644 vendor/golang.org/x/text/encoding/unicode/unicode.go delete mode 100644 vendor/golang.org/x/text/internal/language/common.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/compact.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/gen.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/gen_index.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/gen_parents.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/language.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/parents.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/tables.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/tags.go delete mode 100644 vendor/golang.org/x/text/internal/language/compose.go delete mode 100644 vendor/golang.org/x/text/internal/language/coverage.go delete mode 100644 vendor/golang.org/x/text/internal/language/gen.go delete mode 100644 vendor/golang.org/x/text/internal/language/gen_common.go delete mode 100644 vendor/golang.org/x/text/internal/language/language.go delete mode 100644 vendor/golang.org/x/text/internal/language/lookup.go delete mode 100644 vendor/golang.org/x/text/internal/language/match.go delete mode 100644 vendor/golang.org/x/text/internal/language/parse.go delete mode 100644 vendor/golang.org/x/text/internal/language/tables.go delete mode 100644 vendor/golang.org/x/text/internal/language/tags.go delete mode 100644 vendor/golang.org/x/text/internal/tag/tag.go delete mode 100644 vendor/golang.org/x/text/internal/utf8internal/utf8internal.go delete mode 100644 vendor/golang.org/x/text/language/coverage.go delete mode 100644 vendor/golang.org/x/text/language/doc.go delete mode 100644 vendor/golang.org/x/text/language/gen.go delete mode 100644 vendor/golang.org/x/text/language/go1_1.go delete mode 100644 vendor/golang.org/x/text/language/go1_2.go delete mode 100644 vendor/golang.org/x/text/language/language.go delete mode 100644 vendor/golang.org/x/text/language/match.go delete mode 100644 vendor/golang.org/x/text/language/parse.go delete mode 100644 vendor/golang.org/x/text/language/tables.go delete mode 100644 vendor/golang.org/x/text/language/tags.go delete mode 100644 vendor/golang.org/x/text/runes/cond.go delete mode 100644 vendor/golang.org/x/text/runes/runes.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/transform/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go delete mode 100644 vendor/golang.org/x/time/AUTHORS delete mode 100644 vendor/golang.org/x/time/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/time/LICENSE delete mode 100644 vendor/golang.org/x/time/PATENTS delete mode 100644 vendor/golang.org/x/time/rate/rate.go delete mode 100644 vendor/google.golang.org/appengine/LICENSE delete mode 100644 vendor/google.golang.org/appengine/cloudsql/cloudsql.go delete mode 100644 vendor/google.golang.org/appengine/cloudsql/cloudsql_classic.go delete mode 100644 vendor/google.golang.org/appengine/cloudsql/cloudsql_vm.go delete mode 100644 vendor/google.golang.org/genproto/LICENSE delete mode 100644 vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go delete mode 100644 vendor/google.golang.org/grpc/.travis.yml delete mode 100644 vendor/google.golang.org/grpc/AUTHORS delete mode 100644 vendor/google.golang.org/grpc/CONTRIBUTING.md delete mode 100644 vendor/google.golang.org/grpc/LICENSE delete mode 100644 vendor/google.golang.org/grpc/Makefile delete mode 100644 vendor/google.golang.org/grpc/README.md delete mode 100644 vendor/google.golang.org/grpc/backoff.go delete mode 100644 vendor/google.golang.org/grpc/balancer.go delete mode 100644 vendor/google.golang.org/grpc/balancer/balancer.go delete mode 100644 vendor/google.golang.org/grpc/balancer/base/balancer.go delete mode 100644 vendor/google.golang.org/grpc/balancer/base/base.go delete mode 100644 vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go delete mode 100644 vendor/google.golang.org/grpc/balancer_conn_wrappers.go delete mode 100644 vendor/google.golang.org/grpc/balancer_v1_wrapper.go delete mode 100644 vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go delete mode 100644 vendor/google.golang.org/grpc/call.go delete mode 100644 vendor/google.golang.org/grpc/clientconn.go delete mode 100644 vendor/google.golang.org/grpc/codec.go delete mode 100644 vendor/google.golang.org/grpc/codegen.sh delete mode 100644 vendor/google.golang.org/grpc/codes/code_string.go delete mode 100644 vendor/google.golang.org/grpc/codes/codes.go delete mode 100644 vendor/google.golang.org/grpc/connectivity/connectivity.go delete mode 100644 vendor/google.golang.org/grpc/credentials/credentials.go delete mode 100644 vendor/google.golang.org/grpc/credentials/internal/syscallconn.go delete mode 100644 vendor/google.golang.org/grpc/credentials/internal/syscallconn_appengine.go delete mode 100644 vendor/google.golang.org/grpc/credentials/tls13.go delete mode 100644 vendor/google.golang.org/grpc/dialoptions.go delete mode 100644 vendor/google.golang.org/grpc/doc.go delete mode 100644 vendor/google.golang.org/grpc/encoding/encoding.go delete mode 100644 vendor/google.golang.org/grpc/encoding/proto/proto.go delete mode 100644 vendor/google.golang.org/grpc/go.mod delete mode 100644 vendor/google.golang.org/grpc/go.sum delete mode 100644 vendor/google.golang.org/grpc/grpclog/grpclog.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/logger.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/loggerv2.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/regenerate.sh delete mode 100644 vendor/google.golang.org/grpc/health/server.go delete mode 100644 vendor/google.golang.org/grpc/install_gae.sh delete mode 100644 vendor/google.golang.org/grpc/interceptor.go delete mode 100644 vendor/google.golang.org/grpc/internal/backoff/backoff.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/binarylog.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/binarylog_testutil.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/env_config.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/method_logger.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/regenerate.sh delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/sink.go delete mode 100644 vendor/google.golang.org/grpc/internal/binarylog/util.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/funcs.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/util_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/envconfig/envconfig.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/event.go delete mode 100644 vendor/google.golang.org/grpc/internal/internal.go delete mode 100644 vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go delete mode 100644 vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/controlbuf.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/defaults.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/flowcontrol.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/handler_server.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http2_client.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http2_server.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/http_util.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/log.go delete mode 100644 vendor/google.golang.org/grpc/internal/transport/transport.go delete mode 100644 vendor/google.golang.org/grpc/keepalive/keepalive.go delete mode 100644 vendor/google.golang.org/grpc/metadata/metadata.go delete mode 100644 vendor/google.golang.org/grpc/naming/dns_resolver.go delete mode 100644 vendor/google.golang.org/grpc/naming/naming.go delete mode 100644 vendor/google.golang.org/grpc/peer/peer.go delete mode 100644 vendor/google.golang.org/grpc/picker_wrapper.go delete mode 100644 vendor/google.golang.org/grpc/pickfirst.go delete mode 100644 vendor/google.golang.org/grpc/proxy.go delete mode 100644 vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go delete mode 100644 vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go delete mode 100644 vendor/google.golang.org/grpc/resolver/resolver.go delete mode 100644 vendor/google.golang.org/grpc/resolver_conn_wrapper.go delete mode 100644 vendor/google.golang.org/grpc/rpc_util.go delete mode 100644 vendor/google.golang.org/grpc/server.go delete mode 100644 vendor/google.golang.org/grpc/service_config.go delete mode 100644 vendor/google.golang.org/grpc/stats/handlers.go delete mode 100644 vendor/google.golang.org/grpc/stats/stats.go delete mode 100644 vendor/google.golang.org/grpc/status/status.go delete mode 100644 vendor/google.golang.org/grpc/stream.go delete mode 100644 vendor/google.golang.org/grpc/tap/tap.go delete mode 100644 vendor/google.golang.org/grpc/trace.go delete mode 100644 vendor/google.golang.org/grpc/version.go delete mode 100644 vendor/google.golang.org/grpc/vet.sh delete mode 100644 vendor/gopkg.in/fsnotify.v1/.editorconfig delete mode 100644 vendor/gopkg.in/fsnotify.v1/.gitignore delete mode 100644 vendor/gopkg.in/fsnotify.v1/.travis.yml delete mode 100644 vendor/gopkg.in/fsnotify.v1/AUTHORS delete mode 100644 vendor/gopkg.in/fsnotify.v1/CHANGELOG.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/LICENSE delete mode 100644 vendor/gopkg.in/fsnotify.v1/README.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/fen.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/fsnotify.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/inotify.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/inotify_poller.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/kqueue.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/open_mode_darwin.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/windows.go delete mode 100644 vendor/gopkg.in/ini.v1/.gitignore delete mode 100644 vendor/gopkg.in/ini.v1/.travis.yml delete mode 100644 vendor/gopkg.in/ini.v1/LICENSE delete mode 100644 vendor/gopkg.in/ini.v1/Makefile delete mode 100644 vendor/gopkg.in/ini.v1/README.md delete mode 100644 vendor/gopkg.in/ini.v1/error.go delete mode 100644 vendor/gopkg.in/ini.v1/file.go delete mode 100644 vendor/gopkg.in/ini.v1/ini.go delete mode 100644 vendor/gopkg.in/ini.v1/key.go delete mode 100644 vendor/gopkg.in/ini.v1/parser.go delete mode 100644 vendor/gopkg.in/ini.v1/section.go delete mode 100644 vendor/gopkg.in/ini.v1/struct.go delete mode 100644 vendor/gopkg.in/tomb.v1/LICENSE delete mode 100644 vendor/gopkg.in/tomb.v1/README.md delete mode 100644 vendor/gopkg.in/tomb.v1/tomb.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlprivateh.go delete mode 100644 vendor/modules.txt diff --git a/vendor/github.com/Jeffail/gabs/LICENSE b/vendor/github.com/Jeffail/gabs/LICENSE deleted file mode 100644 index 99a62c62..00000000 --- a/vendor/github.com/Jeffail/gabs/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Ashley Jeffs - -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/Jeffail/gabs/README.md b/vendor/github.com/Jeffail/gabs/README.md deleted file mode 100644 index a58193fd..00000000 --- a/vendor/github.com/Jeffail/gabs/README.md +++ /dev/null @@ -1,315 +0,0 @@ -![Gabs](gabs_logo.png "Gabs") - -Gabs is a small utility for dealing with dynamic or unknown JSON structures in -golang. It's pretty much just a helpful wrapper around the golang -`json.Marshal/json.Unmarshal` behaviour and `map[string]interface{}` objects. -It does nothing spectacular except for being fabulous. - -https://godoc.org/github.com/Jeffail/gabs - -## How to install: - -``` bash -go get github.com/Jeffail/gabs -``` - -## How to use - -### Parsing and searching JSON - -``` go -... - -import "github.com/Jeffail/gabs" - -jsonParsed, err := gabs.ParseJSON([]byte(`{ - "outter":{ - "inner":{ - "value1":10, - "value2":22 - }, - "alsoInner":{ - "value1":20 - } - } -}`)) - -var value float64 -var ok bool - -value, ok = jsonParsed.Path("outter.inner.value1").Data().(float64) -// value == 10.0, ok == true - -value, ok = jsonParsed.Search("outter", "inner", "value1").Data().(float64) -// value == 10.0, ok == true - -value, ok = jsonParsed.Path("does.not.exist").Data().(float64) -// value == 0.0, ok == false - -exists := jsonParsed.Exists("outter", "inner", "value1") -// exists == true - -exists := jsonParsed.Exists("does", "not", "exist") -// exists == false - -exists := jsonParsed.ExistsP("does.not.exist") -// exists == false - -... -``` - -### Iterating objects - -``` go -... - -jsonParsed, _ := gabs.ParseJSON([]byte(`{"object":{ "first": 1, "second": 2, "third": 3 }}`)) - -// S is shorthand for Search -children, _ := jsonParsed.S("object").ChildrenMap() -for key, child := range children { - fmt.Printf("key: %v, value: %v\n", key, child.Data().(string)) -} - -... -``` - -### Iterating arrays - -``` go -... - -jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ "first", "second", "third" ]}`)) - -// S is shorthand for Search -children, _ := jsonParsed.S("array").Children() -for _, child := range children { - fmt.Println(child.Data().(string)) -} - -... -``` - -Will print: - -``` -first -second -third -``` - -Children() will return all children of an array in order. This also works on -objects, however, the children will be returned in a random order. - -### Searching through arrays - -If your JSON structure contains arrays you can still search the fields of the -objects within the array, this returns a JSON array containing the results for -each element. - -``` go -... - -jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ {"value":1}, {"value":2}, {"value":3} ]}`)) -fmt.Println(jsonParsed.Path("array.value").String()) - -... -``` - -Will print: - -``` -[1,2,3] -``` - -### Generating JSON - -``` go -... - -jsonObj := gabs.New() -// or gabs.Consume(jsonObject) to work on an existing map[string]interface{} - -jsonObj.Set(10, "outter", "inner", "value") -jsonObj.SetP(20, "outter.inner.value2") -jsonObj.Set(30, "outter", "inner2", "value3") - -fmt.Println(jsonObj.String()) - -... -``` - -Will print: - -``` -{"outter":{"inner":{"value":10,"value2":20},"inner2":{"value3":30}}} -``` - -To pretty-print: - -``` go -... - -fmt.Println(jsonObj.StringIndent("", " ")) - -... -``` - -Will print: - -``` -{ - "outter": { - "inner": { - "value": 10, - "value2": 20 - }, - "inner2": { - "value3": 30 - } - } -} -``` - -### Generating Arrays - -``` go -... - -jsonObj := gabs.New() - -jsonObj.Array("foo", "array") -// Or .ArrayP("foo.array") - -jsonObj.ArrayAppend(10, "foo", "array") -jsonObj.ArrayAppend(20, "foo", "array") -jsonObj.ArrayAppend(30, "foo", "array") - -fmt.Println(jsonObj.String()) - -... -``` - -Will print: - -``` -{"foo":{"array":[10,20,30]}} -``` - -Working with arrays by index: - -``` go -... - -jsonObj := gabs.New() - -// Create an array with the length of 3 -jsonObj.ArrayOfSize(3, "foo") - -jsonObj.S("foo").SetIndex("test1", 0) -jsonObj.S("foo").SetIndex("test2", 1) - -// Create an embedded array with the length of 3 -jsonObj.S("foo").ArrayOfSizeI(3, 2) - -jsonObj.S("foo").Index(2).SetIndex(1, 0) -jsonObj.S("foo").Index(2).SetIndex(2, 1) -jsonObj.S("foo").Index(2).SetIndex(3, 2) - -fmt.Println(jsonObj.String()) - -... -``` - -Will print: - -``` -{"foo":["test1","test2",[1,2,3]]} -``` - -### Converting back to JSON - -This is the easiest part: - -``` go -... - -jsonParsedObj, _ := gabs.ParseJSON([]byte(`{ - "outter":{ - "values":{ - "first":10, - "second":11 - } - }, - "outter2":"hello world" -}`)) - -jsonOutput := jsonParsedObj.String() -// Becomes `{"outter":{"values":{"first":10,"second":11}},"outter2":"hello world"}` - -... -``` - -And to serialize a specific segment is as simple as: - -``` go -... - -jsonParsedObj := gabs.ParseJSON([]byte(`{ - "outter":{ - "values":{ - "first":10, - "second":11 - } - }, - "outter2":"hello world" -}`)) - -jsonOutput := jsonParsedObj.Search("outter").String() -// Becomes `{"values":{"first":10,"second":11}}` - -... -``` - -### Merge two containers - -You can merge a JSON structure into an existing one, where collisions will be -converted into a JSON array. - -``` go -jsonParsed1, _ := ParseJSON([]byte(`{"outter": {"value1": "one"}}`)) -jsonParsed2, _ := ParseJSON([]byte(`{"outter": {"inner": {"value3": "three"}}, "outter2": {"value2": "two"}}`)) - -jsonParsed1.Merge(jsonParsed2) -// Becomes `{"outter":{"inner":{"value3":"three"},"value1":"one"},"outter2":{"value2":"two"}}` -``` - -Arrays are merged: - -``` go -jsonParsed1, _ := ParseJSON([]byte(`{"array": ["one"]}`)) -jsonParsed2, _ := ParseJSON([]byte(`{"array": ["two"]}`)) - -jsonParsed1.Merge(jsonParsed2) -// Becomes `{"array":["one", "two"]}` -``` - -### Parsing Numbers - -Gabs uses the `json` package under the bonnet, which by default will parse all -number values into `float64`. If you need to parse `Int` values then you should -use a `json.Decoder` (https://golang.org/pkg/encoding/json/#Decoder): - -``` go -sample := []byte(`{"test":{"int":10, "float":6.66}}`) -dec := json.NewDecoder(bytes.NewReader(sample)) -dec.UseNumber() - -val, err := gabs.ParseJSONDecoder(dec) -if err != nil { - t.Errorf("Failed to parse: %v", err) - return -} - -intValue, err := val.Path("test.int").Data().(json.Number).Int64() -``` diff --git a/vendor/github.com/Jeffail/gabs/gabs.go b/vendor/github.com/Jeffail/gabs/gabs.go deleted file mode 100644 index a21a79d7..00000000 --- a/vendor/github.com/Jeffail/gabs/gabs.go +++ /dev/null @@ -1,581 +0,0 @@ -/* -Copyright (c) 2014 Ashley Jeffs - -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. -*/ - -// Package gabs implements a simplified wrapper around creating and parsing JSON. -package gabs - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "io/ioutil" - "strings" -) - -//-------------------------------------------------------------------------------------------------- - -var ( - // ErrOutOfBounds - Index out of bounds. - ErrOutOfBounds = errors.New("out of bounds") - - // ErrNotObjOrArray - The target is not an object or array type. - ErrNotObjOrArray = errors.New("not an object or array") - - // ErrNotObj - The target is not an object type. - ErrNotObj = errors.New("not an object") - - // ErrNotArray - The target is not an array type. - ErrNotArray = errors.New("not an array") - - // ErrPathCollision - Creating a path failed because an element collided with an existing value. - ErrPathCollision = errors.New("encountered value collision whilst building path") - - // ErrInvalidInputObj - The input value was not a map[string]interface{}. - ErrInvalidInputObj = errors.New("invalid input object") - - // ErrInvalidInputText - The input data could not be parsed. - ErrInvalidInputText = errors.New("input text could not be parsed") - - // ErrInvalidPath - The filepath was not valid. - ErrInvalidPath = errors.New("invalid file path") - - // ErrInvalidBuffer - The input buffer contained an invalid JSON string - ErrInvalidBuffer = errors.New("input buffer contained invalid JSON") -) - -//-------------------------------------------------------------------------------------------------- - -// Container - an internal structure that holds a reference to the core interface map of the parsed -// json. Use this container to move context. -type Container struct { - object interface{} -} - -// Data - Return the contained data as an interface{}. -func (g *Container) Data() interface{} { - if g == nil { - return nil - } - return g.object -} - -//-------------------------------------------------------------------------------------------------- - -// Path - Search for a value using dot notation. -func (g *Container) Path(path string) *Container { - return g.Search(strings.Split(path, ".")...) -} - -// Search - Attempt to find and return an object within the JSON structure by specifying the -// hierarchy of field names to locate the target. If the search encounters an array and has not -// reached the end target then it will iterate each object of the array for the target and return -// all of the results in a JSON array. -func (g *Container) Search(hierarchy ...string) *Container { - var object interface{} - - object = g.Data() - for target := 0; target < len(hierarchy); target++ { - if mmap, ok := object.(map[string]interface{}); ok { - object, ok = mmap[hierarchy[target]] - if !ok { - return nil - } - } else if marray, ok := object.([]interface{}); ok { - tmpArray := []interface{}{} - for _, val := range marray { - tmpGabs := &Container{val} - res := tmpGabs.Search(hierarchy[target:]...) - if res != nil { - tmpArray = append(tmpArray, res.Data()) - } - } - if len(tmpArray) == 0 { - return nil - } - return &Container{tmpArray} - } else { - return nil - } - } - return &Container{object} -} - -// S - Shorthand method, does the same thing as Search. -func (g *Container) S(hierarchy ...string) *Container { - return g.Search(hierarchy...) -} - -// Exists - Checks whether a path exists. -func (g *Container) Exists(hierarchy ...string) bool { - return g.Search(hierarchy...) != nil -} - -// ExistsP - Checks whether a dot notation path exists. -func (g *Container) ExistsP(path string) bool { - return g.Exists(strings.Split(path, ".")...) -} - -// Index - Attempt to find and return an object within a JSON array by index. -func (g *Container) Index(index int) *Container { - if array, ok := g.Data().([]interface{}); ok { - if index >= len(array) { - return &Container{nil} - } - return &Container{array[index]} - } - return &Container{nil} -} - -// Children - Return a slice of all the children of the array. This also works for objects, however, -// the children returned for an object will NOT be in order and you lose the names of the returned -// objects this way. -func (g *Container) Children() ([]*Container, error) { - if array, ok := g.Data().([]interface{}); ok { - children := make([]*Container, len(array)) - for i := 0; i < len(array); i++ { - children[i] = &Container{array[i]} - } - return children, nil - } - if mmap, ok := g.Data().(map[string]interface{}); ok { - children := []*Container{} - for _, obj := range mmap { - children = append(children, &Container{obj}) - } - return children, nil - } - return nil, ErrNotObjOrArray -} - -// ChildrenMap - Return a map of all the children of an object. -func (g *Container) ChildrenMap() (map[string]*Container, error) { - if mmap, ok := g.Data().(map[string]interface{}); ok { - children := map[string]*Container{} - for name, obj := range mmap { - children[name] = &Container{obj} - } - return children, nil - } - return nil, ErrNotObj -} - -//-------------------------------------------------------------------------------------------------- - -// Set - Set the value of a field at a JSON path, any parts of the path that do not exist will be -// constructed, and if a collision occurs with a non object type whilst iterating the path an error -// is returned. -func (g *Container) Set(value interface{}, path ...string) (*Container, error) { - if len(path) == 0 { - g.object = value - return g, nil - } - var object interface{} - if g.object == nil { - g.object = map[string]interface{}{} - } - object = g.object - for target := 0; target < len(path); target++ { - if mmap, ok := object.(map[string]interface{}); ok { - if target == len(path)-1 { - mmap[path[target]] = value - } else if mmap[path[target]] == nil { - mmap[path[target]] = map[string]interface{}{} - } - object = mmap[path[target]] - } else { - return &Container{nil}, ErrPathCollision - } - } - return &Container{object}, nil -} - -// SetP - Does the same as Set, but using a dot notation JSON path. -func (g *Container) SetP(value interface{}, path string) (*Container, error) { - return g.Set(value, strings.Split(path, ".")...) -} - -// SetIndex - Set a value of an array element based on the index. -func (g *Container) SetIndex(value interface{}, index int) (*Container, error) { - if array, ok := g.Data().([]interface{}); ok { - if index >= len(array) { - return &Container{nil}, ErrOutOfBounds - } - array[index] = value - return &Container{array[index]}, nil - } - return &Container{nil}, ErrNotArray -} - -// Object - Create a new JSON object at a path. Returns an error if the path contains a collision -// with a non object type. -func (g *Container) Object(path ...string) (*Container, error) { - return g.Set(map[string]interface{}{}, path...) -} - -// ObjectP - Does the same as Object, but using a dot notation JSON path. -func (g *Container) ObjectP(path string) (*Container, error) { - return g.Object(strings.Split(path, ".")...) -} - -// ObjectI - Create a new JSON object at an array index. Returns an error if the object is not an -// array or the index is out of bounds. -func (g *Container) ObjectI(index int) (*Container, error) { - return g.SetIndex(map[string]interface{}{}, index) -} - -// Array - Create a new JSON array at a path. Returns an error if the path contains a collision with -// a non object type. -func (g *Container) Array(path ...string) (*Container, error) { - return g.Set([]interface{}{}, path...) -} - -// ArrayP - Does the same as Array, but using a dot notation JSON path. -func (g *Container) ArrayP(path string) (*Container, error) { - return g.Array(strings.Split(path, ".")...) -} - -// ArrayI - Create a new JSON array at an array index. Returns an error if the object is not an -// array or the index is out of bounds. -func (g *Container) ArrayI(index int) (*Container, error) { - return g.SetIndex([]interface{}{}, index) -} - -// ArrayOfSize - Create a new JSON array of a particular size at a path. Returns an error if the -// path contains a collision with a non object type. -func (g *Container) ArrayOfSize(size int, path ...string) (*Container, error) { - a := make([]interface{}, size) - return g.Set(a, path...) -} - -// ArrayOfSizeP - Does the same as ArrayOfSize, but using a dot notation JSON path. -func (g *Container) ArrayOfSizeP(size int, path string) (*Container, error) { - return g.ArrayOfSize(size, strings.Split(path, ".")...) -} - -// ArrayOfSizeI - Create a new JSON array of a particular size at an array index. Returns an error -// if the object is not an array or the index is out of bounds. -func (g *Container) ArrayOfSizeI(size, index int) (*Container, error) { - a := make([]interface{}, size) - return g.SetIndex(a, index) -} - -// Delete - Delete an element at a JSON path, an error is returned if the element does not exist. -func (g *Container) Delete(path ...string) error { - var object interface{} - - if g.object == nil { - return ErrNotObj - } - object = g.object - for target := 0; target < len(path); target++ { - if mmap, ok := object.(map[string]interface{}); ok { - if target == len(path)-1 { - if _, ok := mmap[path[target]]; ok { - delete(mmap, path[target]) - } else { - return ErrNotObj - } - } - object = mmap[path[target]] - } else { - return ErrNotObj - } - } - return nil -} - -// DeleteP - Does the same as Delete, but using a dot notation JSON path. -func (g *Container) DeleteP(path string) error { - return g.Delete(strings.Split(path, ".")...) -} - -// Merge - Merges two gabs-containers -func (g *Container) Merge(toMerge *Container) error { - var recursiveFnc func(map[string]interface{}, []string) error - recursiveFnc = func(mmap map[string]interface{}, path []string) error { - for key, value := range mmap { - newPath := append(path, key) - if g.Exists(newPath...) { - target := g.Search(newPath...) - switch t := value.(type) { - case map[string]interface{}: - switch targetV := target.Data().(type) { - case map[string]interface{}: - if err := recursiveFnc(t, newPath); err != nil { - return err - } - case []interface{}: - g.Set(append(targetV, t), newPath...) - default: - newSlice := append([]interface{}{}, targetV) - g.Set(append(newSlice, t), newPath...) - } - case []interface{}: - for _, valueOfSlice := range t { - if err := g.ArrayAppend(valueOfSlice, newPath...); err != nil { - return err - } - } - default: - switch targetV := target.Data().(type) { - case []interface{}: - g.Set(append(targetV, t), newPath...) - default: - newSlice := append([]interface{}{}, targetV) - g.Set(append(newSlice, t), newPath...) - } - } - } else { - // path doesn't exist. So set the value - if _, err := g.Set(value, newPath...); err != nil { - return err - } - } - } - return nil - } - if mmap, ok := toMerge.Data().(map[string]interface{}); ok { - return recursiveFnc(mmap, []string{}) - } - return nil -} - -//-------------------------------------------------------------------------------------------------- - -/* -Array modification/search - Keeping these options simple right now, no need for anything more -complicated since you can just cast to []interface{}, modify and then reassign with Set. -*/ - -// ArrayAppend - Append a value onto a JSON array. If the target is not a JSON array then it will be -// converted into one, with its contents as the first element of the array. -func (g *Container) ArrayAppend(value interface{}, path ...string) error { - if array, ok := g.Search(path...).Data().([]interface{}); ok { - array = append(array, value) - _, err := g.Set(array, path...) - return err - } - - newArray := []interface{}{} - if d := g.Search(path...).Data(); d != nil { - newArray = append(newArray, d) - } - newArray = append(newArray, value) - - _, err := g.Set(newArray, path...) - return err -} - -// ArrayAppendP - Append a value onto a JSON array using a dot notation JSON path. -func (g *Container) ArrayAppendP(value interface{}, path string) error { - return g.ArrayAppend(value, strings.Split(path, ".")...) -} - -// ArrayRemove - Remove an element from a JSON array. -func (g *Container) ArrayRemove(index int, path ...string) error { - if index < 0 { - return ErrOutOfBounds - } - array, ok := g.Search(path...).Data().([]interface{}) - if !ok { - return ErrNotArray - } - if index < len(array) { - array = append(array[:index], array[index+1:]...) - } else { - return ErrOutOfBounds - } - _, err := g.Set(array, path...) - return err -} - -// ArrayRemoveP - Remove an element from a JSON array using a dot notation JSON path. -func (g *Container) ArrayRemoveP(index int, path string) error { - return g.ArrayRemove(index, strings.Split(path, ".")...) -} - -// ArrayElement - Access an element from a JSON array. -func (g *Container) ArrayElement(index int, path ...string) (*Container, error) { - if index < 0 { - return &Container{nil}, ErrOutOfBounds - } - array, ok := g.Search(path...).Data().([]interface{}) - if !ok { - return &Container{nil}, ErrNotArray - } - if index < len(array) { - return &Container{array[index]}, nil - } - return &Container{nil}, ErrOutOfBounds -} - -// ArrayElementP - Access an element from a JSON array using a dot notation JSON path. -func (g *Container) ArrayElementP(index int, path string) (*Container, error) { - return g.ArrayElement(index, strings.Split(path, ".")...) -} - -// ArrayCount - Count the number of elements in a JSON array. -func (g *Container) ArrayCount(path ...string) (int, error) { - if array, ok := g.Search(path...).Data().([]interface{}); ok { - return len(array), nil - } - return 0, ErrNotArray -} - -// ArrayCountP - Count the number of elements in a JSON array using a dot notation JSON path. -func (g *Container) ArrayCountP(path string) (int, error) { - return g.ArrayCount(strings.Split(path, ".")...) -} - -//-------------------------------------------------------------------------------------------------- - -// Bytes - Converts the contained object back to a JSON []byte blob. -func (g *Container) Bytes() []byte { - if g.Data() != nil { - if bytes, err := json.Marshal(g.object); err == nil { - return bytes - } - } - return []byte("{}") -} - -// BytesIndent - Converts the contained object to a JSON []byte blob formatted with prefix, indent. -func (g *Container) BytesIndent(prefix string, indent string) []byte { - if g.object != nil { - if bytes, err := json.MarshalIndent(g.object, prefix, indent); err == nil { - return bytes - } - } - return []byte("{}") -} - -// String - Converts the contained object to a JSON formatted string. -func (g *Container) String() string { - return string(g.Bytes()) -} - -// StringIndent - Converts the contained object back to a JSON formatted string with prefix, indent. -func (g *Container) StringIndent(prefix string, indent string) string { - return string(g.BytesIndent(prefix, indent)) -} - -// EncodeOpt is a functional option for the EncodeJSON method. -type EncodeOpt func(e *json.Encoder) - -// EncodeOptHTMLEscape sets the encoder to escape the JSON for html. -func EncodeOptHTMLEscape(doEscape bool) EncodeOpt { - return func(e *json.Encoder) { - e.SetEscapeHTML(doEscape) - } -} - -// EncodeOptIndent sets the encoder to indent the JSON output. -func EncodeOptIndent(prefix string, indent string) EncodeOpt { - return func(e *json.Encoder) { - e.SetIndent(prefix, indent) - } -} - -// EncodeJSON - Encodes the contained object back to a JSON formatted []byte -// using a variant list of modifier functions for the encoder being used. -// Functions for modifying the output are prefixed with EncodeOpt, e.g. -// EncodeOptHTMLEscape. -func (g *Container) EncodeJSON(encodeOpts ...EncodeOpt) []byte { - var b bytes.Buffer - encoder := json.NewEncoder(&b) - encoder.SetEscapeHTML(false) // Do not escape by default. - for _, opt := range encodeOpts { - opt(encoder) - } - if err := encoder.Encode(g.object); err != nil { - return []byte("{}") - } - result := b.Bytes() - if len(result) > 0 { - result = result[:len(result)-1] - } - return result -} - -// New - Create a new gabs JSON object. -func New() *Container { - return &Container{map[string]interface{}{}} -} - -// Consume - Gobble up an already converted JSON object, or a fresh map[string]interface{} object. -func Consume(root interface{}) (*Container, error) { - return &Container{root}, nil -} - -// ParseJSON - Convert a string into a representation of the parsed JSON. -func ParseJSON(sample []byte) (*Container, error) { - var gabs Container - - if err := json.Unmarshal(sample, &gabs.object); err != nil { - return nil, err - } - - return &gabs, nil -} - -// ParseJSONDecoder - Convert a json.Decoder into a representation of the parsed JSON. -func ParseJSONDecoder(decoder *json.Decoder) (*Container, error) { - var gabs Container - - if err := decoder.Decode(&gabs.object); err != nil { - return nil, err - } - - return &gabs, nil -} - -// ParseJSONFile - Read a file and convert into a representation of the parsed JSON. -func ParseJSONFile(path string) (*Container, error) { - if len(path) > 0 { - cBytes, err := ioutil.ReadFile(path) - if err != nil { - return nil, err - } - - container, err := ParseJSON(cBytes) - if err != nil { - return nil, err - } - - return container, nil - } - return nil, ErrInvalidPath -} - -// ParseJSONBuffer - Read the contents of a buffer into a representation of the parsed JSON. -func ParseJSONBuffer(buffer io.Reader) (*Container, error) { - var gabs Container - jsonDecoder := json.NewDecoder(buffer) - if err := jsonDecoder.Decode(&gabs.object); err != nil { - return nil, err - } - - return &gabs, nil -} - -//-------------------------------------------------------------------------------------------------- diff --git a/vendor/github.com/Jeffail/gabs/gabs_logo.png b/vendor/github.com/Jeffail/gabs/gabs_logo.png deleted file mode 100644 index b6c1fad9931d5f5d8269150c097ac749ed32a73b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 167771 zcmeEuhd&mZG&wQ7f@mj24L*v!!Mb z#EwxTVs9eyOZ4;oFMfGExR-}KU+3O)?m5qM&XvzPS}OFkY_u0HT%cEd^<3}5h08J* zE?jK9LPP#d%0Zn9dAQ`Rq-t=5{0g}8?i2avt1hoh+%H^U_(}QtCrOZjo%~Byj~A~! z^quWIyx+LlUhwwz76v*wxZAvOu@!c91Eg=rv0b=u`-1B8X9hkQYtz0NnYMu>(qUl# zn&`Ns(iM|2@1#ox&tD9xCBCNn)?p#wK@SSH@y}IiWtqeW|w>kK@5*5So%v(xUD|gvPpZvx{T_ z|Nra%@4)|dU>I(lM|VDtX2>*E06vvprxr)N(zBfVlR^9JS)F;-2i5JDJ=|9er1(_> zyEhZ^UhePhJy;7$391#uPy9o9tIhRie3UVoM{=c1pKauk|I@T&{YPcDHG5RiN?~Ya zYV<{5TApeG@2j+1uhz4Ng@JEl)Tc$l2>Ds+Lr$s$nmAxX9;e=Sd4nT8t%)1_W0vt= zVyYsRrDk5kwOSPDmMeEwE|JIgk8ghsF*JQ*M!Te*#?3FOLc9EN$Wc{=CgQ9j&j=%x zyLk6;HB_3P+AM!7>}j2l-W&I46A!7=^Ig#Ici4jq(UKLz-AeR5)D%#IR{Oee%Iv-C zrm)38qm^do^;djj;qX@ZO+x^yc4-vaYo1l$d_u}A>IdL{5V_) z4P<3-m=9aH$mi3}lm%H`sWt%J)h}cW9gKnwb0IdalS? z2O%G7Lj){lhtMbw@ZFae#(fS6;mbS2S{BG6jEkRA0G?i4AcB}FvzNW_`V!X=1P4^V zy(_y-{~}I9l~3LDcKd!B@nX4Oir2o&;7W~`D1r5winr>V&4)d_PHV0-b(|`Fvt_pU zQiTko=o#hh9UzQYNWtn3J)e^r?d2iN5ObcaI;6onXm>Ggsa1nY3jDjV>wm%d3lnJ~42^nm>bgOzyU$zzL&aw3~f`hdm6O=7)s( z2EIW93djZ3OPQ46-$}|=RU)8jEOR^A;ht!L3YETrojkbZwRv zI`O)r&1SS4*BNIL^*8t$!~=yUrzxKCshrJvJrf1&38r}QIEYhjdmyrJ_de2OC~wCL z7}Dn`+<&p%n13mnOFu3Jbl{{)Vi!2wY;i89>2!&yH!LAXvK~g(1^LA8J0* z&iwbvIYBJHQFF*zbUKXXjUD_QW5~&&M}Mv8*E3n2quh+N4YIP#ZZcDh{DRFb%rDBA z)oPfohwY)sqocxs6D+eU9SZKX+U-P@Ptc_0ZqI+0@Lqce;e$1J^QHlnv$nKUy)S`I zj%mwqng-V>?~lHdyKVY+HQVwQkACR(IX`%%PK7&Utm6d3L;7yNu!4TU+kAZoLLwa# z9-|$t)9u5jvpu}E>fze*ihea4Gwd)5&;=HrD>4-8i54U~iQKFix;*PTnwmVYu=7p6 zspw$cq`;!o>hK>hwpN=A*An)CWcX%E8zJ9XQ;UeT%9geIBrZ*XiGFKCTs;?PxR@@E zA<2qMt>=Db{#Uc1j)wSd;jz+RoKLGb@B5E`Oi&#)D9C((%apZ=F^zA7>p5u_wWXsiS~&d~XE<2{R9XVR`QN79&x{d{Y|Cj&{Bn zZQ-r?F1OI}yg2|%RgE)alAwI3e}3C)2yJExE_VHl@!V>N^D-=Cl$Ii|6k+?B!UD+% z+8G|)T~*CRFxgsoUGM%{y_9a!0U6&7+=`-lm8%d?V!C?d9qfCPP>S0-TFxpQxgHP=xZC=qgReDY_y*2Jxx}cYFD(Ft*r& z&)kW_jC?zqEPflw9x7Q|4T2t%q)R+0LR4g|r+01EODKEZ!s10S$h)grn{E_< z(`od{Sntlfqht8D@!vAEnrzQH%5rG3m-VyTg6SB8mY+;F30ZnlBzp9uc8B6BbudOC z+l_njTj4sbh6%}Ppoh*2Rrw%rd*5nA+CGyVZ&@BB`CmK65Z=0UK;^8c<_aqu4&LfB znegoKJpl&y4pGpu>{gdcC_8o`(qpwPm#*7_mER|rpVKgC2C#1@-qv?d7c@av@yGkp zK4-88%;|NS!da=;mdUSy-Bg{En#L1SVAw{$otLT<2%Vd`M8CfaL>JpuJm5dA&9hBl zBd@Q@Pc+I!lwe)O1`~7eA7u7MOq4D6`W1+61Eyw0@dM~(N0aoByoQTmR&$mR3fAh? z^HBEw#v#~ZaHzyWFmF~rK}%2(+PB)b8kXJ_N_GHULve3evuDa#Vzy0BdWB&04vDb~ zRYOne%gQW<2GDG&3U_dL|Q`GkEVu%OEgeXV>gU9V4FkN zC47=8c6T9_O$hUyGUPEoRC%Q9T!} zHZ6Iq`8=#J9pnL_ptt| zAe-lVpU|CC65|I5U6|a>OAu{p+H%}z-e#jVR(eJEeBJl-L@=e4hje_?658Z1+U$OM zqQT!MtO#}TpBTL9bOJ927qRY7#4@Oc)I|fLZv=IeJHQ3neELC42_SEUxf?(F`Yb{U_kl@P(aXbXy3rgy;X@3nR(-H-C>d5O?i{wI#|Jq?IXLk@*x~Pt zv|9P{XWJ8Gx>3fmvmC`P?s*}7e^A0mP`^Qs5D0c7gx6%B^-wFbX}#)-eAP9%`|I@i z6`ZDX$9g}9$sia0{hW1^JUkVUbQrJZ3gf2B(|(nv6QtnVVlp|BJ|32y)M|&wwnL=2 z+AQWgntU&IM*FJyOE^QVN_15aI@q&-VDEWR+W}Snbgp@y|1j)uHJO>GfTE@gupe%k zl=WwIIH41+PSc(}(%CXmP3%TBT zd^fu8B6@J*us^Hcl0Zdm<)C-;%eLOLrt@56oe;bw1^M zEx2ZJ@PvzKx?#G>$Fz}#A{eIU*Q%padcd&99Kd$VBz>T20w!leQ$n~%O=2sW+ccu6 z3rJDd>~}w;+qpvmYz$HN5r$6(bxuh4G=&tc8s3ZIR{I>=`%EvVk6SdpP-xfXfzex6 zao+LWVgJ@b}ckX}QjdqLJvX zj!#bVCrYRrSLHCww*r=)Oz$LqdT<_m_08!h9=+(hT2Fs`TkuzpCR~6#O@;zY62|US zFwKUkP$?6hU)_KEL&ke0I*m{DD{F;khJr~LWMpPk0@fl*W*Rzm+EzJcT&^0I$w<~5 zB^U=|^5g=~tesH$XknXG7_GwH2UbB%3RL}hFv&!$yQo%eD(_fn2ela!OvRyM0`@R5 z8mFi{mE5I_S}oft4Q;8qjSIJ=hWb@F`3^qjB!j(oeV12ZL=k!TgM+8x!ad|sM1lez zQ1AG7^>T*lMssS=e!(WS?v!|vszh1e>U^n@_r)?R)y)^Fzchk)I)R4xfvO;~o#Lmn z+eDT|_7)jU(fDr+WWW}wM@AKn6lfnA5AOboS2E)sGfcl?p0}h1_)i>}p^X3|c3!P^ z;-d+pPGX89;{_5<@hNtDr6DMvY{2X7+d=naX)mJ4r!X;PC0UkJp900QaL#VtyMmIE zIYq)qcX53MyW7UDyw|1hw)=Jmb9NG~1-r+#3QH?V!gaC!cw5HuCzVU)l#^<97 zvl><6;Gw7RO2eV3vQi~Y;RAvDbPp4;heOj9h-?7d*q4`HE^(?E?Q;5*KMD&Ccqe1k zLvX1l{IWo?Y|f;cM5Mcl6b(^Mt4~y965cF>F`=t77W>3WoacsLY(b0Yk{80^B#H2| z!E<*vwwNMm^gp@B=kfXJ$0XBKS>5YFPlrYlWHi8zUo3<++f#XGdqMkl>ur6eH0e0R zAgAE`^vDpP^r$T1G8CwUay0Ud)tF87^8|PoZSDGs6BlU9SpT=hx7ar^4dh3(d>bi_ z(h}r9O3tg&TwW-jFYO4Fg0Z^98q}t~8?if~s~SWKxZkrS``5Zjy9`zbR=)z1#Z=GP z)L&kRY!9oV57)`b7Z;rA{7?+fn^L$5i%t26Va!eV`ppj^D0R>ico&FqdF+~0)fGt? zqvI&=KjJ!x+q6{D6DoB?#imuuG$ej!WMq&Qm-VGc7+lf4&Ja`$0rX zY3X+Oi0RIRPMx!wOsj{&jDQvv48lK{E!C`L^&YXSq^np{?gPy%i)OAqPcey06FZHr zVnBP-U@djsF)Fhruyw~!75Aab#w*DL4m1Us<;7p6JB6Fp(xV`$RNskj~X(%yysE06_~P$uzFoU!F)tJ+#@bXp1l9oR3>OT zQ4O#y+R{(hDUfhAay==l=a~KnP+117qLoZkNe?1|7z0OZN-@SA+*OTMMt2+<2i)&b zp-jPm^w!n>v!|^iQw@}W$b#%xg$q&O3#Rk#M_pWO<_RnO)^F^8E-sqvbS`$1-5FVR ziPY&PVQJ=TskV$@-m8iWQwyR&94n&9oAScysOZcV^hp30gJJEd-t^gfI6oQjg6C%k zEAn7{%Y;mdZtl-^-V0RKODxu8f=MNU_1XD2qTR3euY$Gl4dP(&_P**bi?7Uw4gLEc zZa`Cs8BKVhh29hiuNY=O-s^IgQKL_`qHpNQpgLFz6~8vc8!uo>2h#rO5u-e5_1Zc6 ze56Jp#h1U5oNgogJ%aL#Ts!D^$kuGv;D-)QpL|#oT^3lxx~!15fB&qz!$b6^!wtow zUg5nxtHo4Dv&l6oZ7jjtuAv?+_L6@(1=G@Cv=SSW{DAU=;V=JVInfTVYR9@;mV&@Y zTtG&==!QVQBchn|_`Q2xTVLLwtr4?Bli5zJ=5|}N56=m-47_3jGlYy^hPWDgPjqx! zdoFW5IQo6Rev!uJ*}3Q)J`LRzQ+b)Ri3|Bm4>~K!I~1X$&ThwHhb(srd;tVh&j$|f`im4k5 zq01VC^eGQvdBYP-P04IqiuBb{0TieMHH7|$fCFRW=mncN zf=N|P7DxbFOo(Lu7Lm@w=xFEt#ke9RYW!yk?xiYX9qg%uS}otvVDsUv3kD<*KBQel z2{_sMOCO@S8Y9<8C#-09lG{m#wsheOzc){7d z7_#GXD!3|vw&*>6-n`$b_*#R@h8Le|yOsKIPot?@G;lWcUY6WcMXa&6>4_rGqHx`F zNmBO{IWq2hwvx_ss$e~3lAj-Z52s!-WCSM@qX7RZUWi{cFGR+eldoTw(3T2j_QgXVQ|kW{mjYgq_PdAzIRn@Mo`A+O$98S=oXNA1 z|B1(n$JCJJd}={Jl-mPGHY(KX+eQmU%|@2k*u>W1e88o2Elf2AlGg@U z2HzZ9hVLWxCn}c|)`RzaZSqw&TT_1>RFBX}!dS_g&>q;n-GA@{XU1^I@_9g1z^M#8 zi}NS-Pn2!!O?HnOdiy9h&>CA5$<_^4uSp(~A;J$XF0zx8oSC-yH$`Zuzn!y$0fMH6I8)x_j@$Lmy9himGj2%4|WM;0fo zG(B5nQ7)8xI?okY{*lDZ*U$)u=UcDLvqr>BWbN^ z^MU-%4`&CgGRhzWX4jG$Sexqk-Gr!9#ir}%X~5&6A!E7s&=nJYfj4`+$D%E|om-*JS=9jUO+-3G2W_>PS~|C7`Ub{x!Rm_iFE3n~7S{ zcZ>li5s>jqkPRb~%aG4CRr{9Hz*t#_+9dFuuSVnwBT1rYTIn6-=~L`c#uWbb)M9mb zCpP4yJf(Vgv|xf_5WA*ZUusr9Hv9N5{R5b@hWc4fz?7Vucgi$DX%pGz>Ncg15z~!E z&4E}+v4QDa)5{s~>*O>~LSrO8tLeQiaWDw=&O01jXlmN)J-|vq%lV zz}}~(BE+LR>nB*g5#;uZFsiV2ce1Q$K1)h{L7jr0dzWXj$fpfcJ4wR7A=-_L3+(L~ z%0;McycdP70|Tl0rP3F9kt{HyENN2_hN`Qt7Q#YJV!qn0q~18Nc8+|5>Wa^38r<{&{I8o zedZoDPUIgy#QI>k!^W^X_N@5C%Ts!lQ(?ku&jZ=G8z+wIrM7f;JexuK9R*^)L*jx- zeS_>ycAkY=Sj)O48u-I+*~!$R!+yOQ@LulI<}y0Fl@AyaX%#!2X@B-5L9SYZJE-F` z8=0SxT`7kUOcw2Ai|6(N`SS}k8`PW)>v54~e1GlV^KCV(HtkVh5jZW$<3%5@ZFB-R z6mg7n)js=t!%Zz|Kl}vu4)8dU>GDF-HUquK{_9nKc~h=h2vIRO`?CmiQyj}JWI!CY$dB~z30?8d7DS|XIY(PCyOq)twa@V zh8~Nn-Sq0fiQv*Y_bau@y^@e)3Nv}1m!oJwS;oIT-up`jjchW?I3z-%y){knHeK{K zqzp4){7j(`-MpiaS?d;NoW-&j#=bFfQe%}HDza8ml&hy>WCbKNaS}#c=f9-6tWN#* z-Cgfv8}rs_*bE#>%Qoy654iUTQc*f;={n5P4hUR&62tmceg}V3L_dSr3?-!D5?7e7WHz>ud4Ln1GLWEe`f6H&bg&{^r-g=to!=XF1XKh>iDYA zQ9Cxuu%=Jns@CLs(8Ro?628Xa8*1}r7r#`iV^9oS|HZN-(fC;5M&p7=q!ZxAnP z6KV^1T&WBQgs8xbR;@u4Pgk&%-Z*xDX5BBTx?24hI#YDNs<)7m+1`6LaFsl~BPWTO z6Gd%-2~6V?@0i_;4*F`u@kuqoFRMgM*Nk00k_c7o`+vGO)#tYCq7mP23%q`C1|ltp z_+SQPoa=crT&v&6VXl>%2He#kuwu8mxqM%sI3laDL31ZUBG7Ro{VuCy(=~YdOy>G#XV*;6{l1hotMbu=-M>5k^Y6~* zRjV;0B@J9s@>CHLi`>!a3N4a>droxMq9&=2GdycsD*x{;0MqndXWDiLdY;kg2M(q< zng}H{xt7nDWV}(Ybq%>eRZpWRB&8m)oVD>G0kJi5BN0o-#!1E zOhTWW{=C7~(}#E2yoiDXQ0cnU2bG-`idW*&wz!*`^=us^aubV(+r;A1z@J}KGatpYt+5iS2yM4NyRk>|k?;+~Bk z;KW{W{qn}5kT!D3jdL3z8mR8&Hy7@|zrxq#klDlKFvjzH=O9Lux1*%k^XyvZN`XvH z&8Ww(C$1rdQga2UPyN>Ds)Bh%6Gt;aRl=x~M}Oiz)aUf2nw+ujLUn5)?8VdodXL|) zsi?uHzSEnup+dAfu0}xNirkYddP8N7nxg5eoa7X}aDT)pp^e>n=mqqz)y#&T6Q5V) zR&jbYxz!Pzut=(q2yEmcg&qvODw}GHYkWbcxWg0|nM)yk@~3n7yhqg?j0m5f2iG*$ z`7$IVjV$OBCn5#DqqsL`J}k=T^1y~9ba_sGSy4RgE9ZHW&f3d6)xpG z$hQ&D2O-*|0nv1*%HgI)eG7V~^UVK^%zTjcW74~n8jsk=rzxIIc`zK9@mmm|kT}hU zkl@#4QBD7iZeS>pmqnlLWj%SkU|o$H-Z=&BTd=<}o|rfadRSdXl}?1151(#)@9-28Fxm1qYP$Mje0M8aJSS8x z$~-GpbeW(zKhO+QzYLj3_R9ddAz!{JwS4oF_3+U%sQ{N+WF26eBS|PS_@(mU>5DSu zo}y>JzRWkZX1gEAX!6`=t*S%~IDbEup6I7x1h1p+#@}KH%Y1`7#E69#FYQ<+?Os1X z9KzvJa`TbDjq5S|h0P~fIXpLUjvwiy|%X_%DB5$yITbKbQOS~d+`u3B~SnKpma z`2AsyzBSk=sDn5)8K_>XIF>ldIaEZ zzB&1oy-_!$$`xe9wU0|9C*A8UqGz=S*kFGj`;u<)SXnnth52h55v0mJZFa8-Qux3Yph1AHyLJK)n=xc&(lrA_vG`Uy+R@|v?aNo7|$DAwlCy^{L#j~RC=po`$- z{Nr4I4F8(>Fl=iXgP$K?Ixnn+|7DpBne|&M8E%RxO8A)jiQyRqzX#6V5N1W9{70~NjTdSDs*UCdgOmj_ zuuaqbsa;%O0!?}WzX)b14}p%2d>lF6N-t7O$`53O#|%Rq^P&`|#SI}brOidpaN6I6 z{5+tlyStlglW?V>gMMomPs2!N`M5fus^5^w%cx1a(08+3&c^SZZ>E-$!5m~0H^0~X zn`{g%EHBRq!0XbXAsgCmlE%M%y-}@_TiXpYa`->G^4do* zZ+`5IW0`bpAi01beygrZK-_MC?U zT|>~FB3(h$bNR!2&D`6Fsu->wqd?#L2ag@)du><<*GaZ4Wwl0TnFmdXlPMtvGaa2X z0IXUp9a%&v&OZ)6k3{_Lp)*0|mSO&RF0o}XsEEmexL?E*!vn{3No9ADU}Rawn8X>{ zg0^ko2Ae_9BB3?d6_s44FTUTHcyr`vn9tb&H7fu4Vn&fv7w6eg*-WY2BBY0ppPYTF zZt$AOp~wX6=c+@M^E%DK5&YC9I5|i@$Bz)j9dIHa_sNeT^A)+Yb8?tpU2zN;8*V4l z{ce>5T8o8ihlpn9<6#AX_WrtrjXP@;!YlAMV|^h5|1;)CCw(7Ri!#qMr!o7YHq_eJ zP;EOxVp|fApe~PZSLm3{E$2h5ezvwM1RZ> z66FJKELKz{-I}bjB8f2i5qR*h05Ok;poYmI6@QFEnH6%aYT~T@GLHj(yj~^F{6Jiu z5a-RR5=U$ASeA454)#5I`IW&RL%H0|63yn@PFs!((VsykQtb}rDH{<`J6NG(YLo<3$@M!tJ#*s59Y&W9vtvdE8n|c3wiKxkK^|5mr z4tw+WvfXN{&Tm#VmGOzA@C?li=RKGXe8Tsez~z-+bQIxThR zr@W;>@rNpzFL&?A-B z;RlL)84`gY&lmR>iMgu}i9r$l2l+yMDxs0P`F$5vX+v`)mQFNPsBGePf|7VHbtovK z8h4~qV*h1nD&Z&&xMjvz@K^&NFqw*%m(%|DRW?$~EJk<#1;#Gel8r$Y)$qJV!NQjk zQdz9d+ZK;Drt_kfm~Ne>=!Iu&@N_Bl--ej3{K?3j5!!y+_I(hImMEaHxnCWBabrm#)cBsG zI*%5*C_i@$65%{%a@Olu@yzy}ul=9O?^TV?@OG^z@`0&SRk!jlcA9?YKsh+km(PP5 z3&v?U!KBstw=|ZL-#=7LmiY5E54W6If;h(2+~KUW?F;OW9171sWOaLuidXuVN-fYs zJ~O-U(n|)Ky@abtG~e^gfVWiTPoC|kzwI>zZ$Mjl6!!e!5Vt&2rhc7W@klg$@Fxx>=$gf&-qP9nU)Y#R|l(oFZ17N8A3ezR%DW*%uZ%S ztZ<+H=0V`ZcA^TB>b2QVAZ(0FSco_n$sc}UbEHZ(+aNQtQl>$Kn71+^B*M1>Kl1lDBjf%tzftxCBEod(&` z9B>SL;6t#X#QVQxjp{EK0Y{%N%9Y9MXiB6IA{=#0ui{sULllhPiE5S6{_sHa^kT-yY0Lh}9YMbIW`Cv?i>oaHwyPUeK&DWu$b?JlJ@)l$1_ zfvgLB8t6?klv?h^!|EmwUy$ja!&aDgy)4{u{nU`M_8g`DFIK-&#b!BVhJ#MbIrqEh z#1=TCZh~Fe#FoSt`wBtb=~{#C!NDmIBHk?j(J;BJ@ixx3GI;tWVJf^Lyc!@zYJ!LE z)`&nV>Y!Eys?Jh_Y)(uL8REL4*x+)zCX)Gj{q7y`$x+N|pu*%@er;qf>ENw+f7-Y4 zvE!>{2Q80slIIl0KSFdr6#DM%k-xpLt6X;sH1;-nnQ!7~D_h>yFS-M&h3WTTtCbuM z{%7Df|7tj?!Qd_c9NvH)qUUbpEIm#szYwZ>3&zG+4Z{^o1b zdVuTYj887ZgkezTW>xC zu>c6lis%`+B7Gk?FUZ9I+XX(+ZzbnMFD)3CPsiE| zUbxJIkXE1PQfYah+NYw4W<3lrLJRwax#m68H1o3K{pStlM3b?zJ5(VNA-W`hF^78d zb!me}+MF#QU3k&$#+%~!>!_YAfvVGwOcfY^9oH2cbHD^of49WJwtV-3rgkkYPfh-enN+5~@4&6X9lF8SqDm$1vMAhd9iztw_a{8{l9K zwt{NloagwZ0*TN=+(X7g{~MBf)qVfTSIF-4%4}7WEGMwanpJfju8NnvpT8!4M?VRo zc~gkm-3}Cvhz$-(N|qrlPX*(LuSvRu*w1PelZz@bQCW6gYGj%Di;E6cKc6jHxtW)*bKcn2BGsQ$)nSPNzITWDIx%;B6G6J_yhkKxMKexay|0JWoY?;C_iZKrr)UgEbGTmtFOjR zX?oDXSih+7H zUnWgV1FzHbLsYbQu4Tb&f2by?+(Pjv#!qsyT&nqnUZ+Fsh%1)#ovi@T$raqexV&<# zNDS(FyqqScnmFT8xpcZXDWLr^Tf)*4IjpGTE1YdUI0|1>1n9N`JXTCj13e=kOD$D9 zue?4K+9v(U?r8r|2owU?URt%BW@TJvkf$;pGm$YpZ5grz$cJYx0XEq7zmJBrP0GUm z7z%n2Hha%w(_qwjB5c#&XDU%haAW&2_{Ujadg>(dzN*9>#RYqo^4Sn%IcaPo}Zn5&)(+B%d5Ni55EO4;# zwRr8fjX~)=F(;4CG*@L*QH#3|2Q>bBZL_cEA06z`@)+*sluTPcj+)xr19U7cSZ!BWN68Ey$@n_XQLfKKb74mrg^&VMyf`0Y zS!g_(<7JxPr2j8^>HEdNrRVxxpFK%VX1^X|$<#&rH_(ZZ%({-@d?j!6(#bB5og}6O zHpaK5+6LS4uWbljm8ME+K1;$jq;5*9h|c&T=1hL>u0gS-@;B}PvgQGt_9SIgKEybo zeiR((c$4MKBLhkHrQTDuh`Z(p+{p+H_&9>Q6O!xO>LJecxT|8l5h$|}8}~r5_{kAA z7)v8hDpb_DUHly;>%}QS&)H}B#vONtIIrWb8`>@_nMsKi1)+$8gxePN6EzCOxr z&-XIt?UeVAdA^1it)Io-%2)s~bH05Zk)eQ0_?VF}`~)p>Y3Bx$66e%WLPL3^&4K9B z?e?kQArrbx*n;^%X<)r$c=vb|H=IjWz4H`p`*}$K5x8#(ZtCEg8CNPx&MnM`n31=^ zxw04Ne-Iix!Ay=ZXG90d4p8&@Drvao3^KM`4TV3|ZT=jiqA~QNCV1F~gr4bZ*x$R4 z5m@8AW=rr+uAtQt4z?Hf^pG+UNFQ*w|G2{PP<0l^Hh$1h7P-(K18ycF9zD_`mk9Xl zPY8PwVIQ~KU+k`^wrN2RjR>;ku%`C@>D(o}5{cV^Yz$c&=hYbN-q-p0(3Cwb`CD5A7c7&4hHv|WA9&8n%`^J&BfBHm zymV+sqt?-e;b-NMJ4mww`vsL|fSfU#by8-}^6)`qu7018DpB?TKZ_P&>;qhvP^Y^x z++-iLdVKkSYoL`hsrSTcm_$qPt6q+cc#9g@?hfl`HC@uiTva^IGu2MB7_1qXh7}qI zC5tfI;m}(ay9FJ*Bc-4mW~e9TpofF;9k_pgF?AV z{gF4`QZzpRneGpvvS^2`SJG3hq5M|rG<|J$vfN4a^!MFU@hl$0g~B>2G|#XF+NF9V z2-SUeX{vtZU`k;ifCgJtZl#!e`&v|x#Hmu{D7gmm2+6a5I^FDR^z04)rCqwcd%)!q z&mYSm>HZ+X)F^ss<;Y(lKiNibl3c`^aOtWUMjoUN*;n7DUsJGV5o!uAUJuXB$3~SZ zYhzo``?AI{EoiaO2WuQbaaH>Q&=EPPbJj{woZB!cRi2!U%XsOI;q()+s3h6jF-OKY zcNp9wtdr7me>(j)k`#F-CO67`JyX5`y`B=>%OUc8Z&UwC=$$`eF$Smn_MlIt?HHYb zRPb*gUN%5NG5f_$l$saz_nC#oYS3GU7i9&~=>Y9fUFaF{`R=Vr&qMOH_0WA=_v0|V zn@j-r;NDiSO>Su44ih+v`JE`aP4-;!iM{mpr?EgbfU%Q`peni|AV#b4P!yDABV~03 zjtj&NLb&DMuBDG0z+?0$c|v-JHlHU9h^_*9#GT<6Q7hZ`0Q=8e!;%)h*;OOszJU&l z$4SVNv^Ryori5k=)a0HN@agI)v(T0N%_;I#&9%Sr;lp`+$TclY=Dxx2oqiAfq_jOp zN$c??b zag<%C9cOwOGG4wR*6jZ+_IXnrn*)FO_-iHAiiz;d*yUSa-Cj9lOx9TYa?}H0D^HWoxiR6NhY|wYh%UqLhGY8K&S>;6UX_1?LTEu{dDtP}4J2*pSMvz!2rYoYgC9 zhL`pJWymb!C_H_o^VsYd|6elaF5c?2Q4=NksL`*$xVW(bXMfD&p!w`}Si$D2;Tt5= zZs~rmO#O|e29H+uAS>^~Z|7y0{g}T-F#7(aiS^a;2^=|)nK62bHR2LNI%pRB_%*SP4_Btp0r%Z5MHm)K!BYG zzF~^lNm^u2?}5NiB8=HZkXnRIVy3yPX4V>_yiXfg6&_gN8<9sZFKA{=zV#WcupX$P zoB7}h2iN#5uQY+Gu*?F}9OW1O@Phd70SwTAN-}ROHlF&978z1l8}T1Ltw<>M5T_Kg zR~gMPDNWqc5T zf_)pZO5tLGT|G(8+O?UEEF})am+b-h=>~|*ps&2pV6{r=$hDI>T}8=@#BA5zv9RnQ|eV0nEbzbNE zj>L?0Ji=I*xZA=JO^Av$QNr*N8g+tXFyF5YQZk3%E3)~%P9XP+BRI}|K>Z6!tLnXO zp?;6$ecWo1*WjH(D~{RK1;0OLD#t~sG?`${(F;6XmkIfRUKDUiHqqJ4f3_IBI{Bmd zojLjt_ggW*W?niHOc)i3Tzc#pp~7hbHfwOwAB^5`sbbspW}Jqix$d*IHJTfQZHE!5 z!Gxi>{o!LPBP?CR^e!{&SQFMotSLaH%9VXO8+r-48IA0p6Wy?`uJ#;iLCY5$f2oVZ zBg=MlUpT0b0l9d{7yi~;9SyLi;h91EN2mDz3gZZc5(Y;oa!SA!2PCWZeZA7(H7&jr zN;QlheFbuZ?_Oojjs3|W9lCP8HCIVXRp4E%Cs^4(sxw+uNy{DE0pv{EDbQbFG8(lTy`K(Ed40jI>1{JXfXSWNs$dupKmCrJ47@;e3GbC!&f-e?nOrA2 zcFm?uOo6`2lg>#f!du%UM3e5OE3RE@cWh%b%e8#2xzR7lm`fx`LQ#0=wa%M9O;fi# zB!#%@1ph6)fXrbqHur9CwYdxro?p!(fIl6J3|+j4!&*}aDBJl55VRCMCVwsgPgq3^X!)!~I_NhLx-ei2xl@RW zSWNKPO6BBYJOZYPt12Ich?X(z5HDc&(voZX#3e!fDkyEk%_f3mEmh?0fl`I#^Q2i{u_BYSEm*8r-Fu5u<^VjISR3m`uP>{{1>p318R(q5 z)FVUoQBtwjxD zv@rOdo+@_?hJPsotc0tl-0uzlnEd+;pMm)uL^+2&AYkZXEznG5UY6E5}7@<8svH6wks zp|gZ_KZ`*_Tq;6znUmoMdZj)%cWN*vF!qeo!f!)aQeaKQiWP4(hRrRs^oDaO?$S-1 zmH9Is)YcTo#G2=S0FR&cztRg*OLwgBPZ&TG&)!~_TVKvKtD{2sER1(V&U70IaQ!&l z+H$rEISUtE(y2ac(^~k_GIQ5W<)1hO*S3D0IcVun{dY{Jp}Q^h0FK8=M0>Bp<*7f|S~&t;-gJ#zR%jeJ zRvfTdz`06JzZQIcB>c>2J3*``w*5b%t}>|2t?SYvrKK%U+_l9WibL^I+}+)s-~rm= zQrx|Gkl;>%;t<^3Ex1E~FZaFe{brJx{7Gice)idGt-aSdVO1yj7#Unw&Xh%EwW~!u z*0eAiZBFFTGY6S=74V|g(Imhplvt^szz$7}wyogMo899}WQ5jSz0~#1ZO5zovOdYi z2&o2^gnTtUA~l$mWnpu_9b<9hUzZQdm*NQqR=;ynk+r(YVJDZJ~Ps( zhD3OQ4S064>bUYLwe3Q-mNdzpXv)_nt8R!(cX%>fKjxpM9sAHa{o-}~xdB2>nPhLt zogn#{Ftd=THri+(=UJ62+%ZZvu}7|W&UUIkcO_Im!KF7g8|*iw3w-<1`;M#f{?m|! zLt@rE^IRc2X{~S8fJE6@4RYKS?ZkA+S$ZSk{e7$ze1@RpqTPdkN8obhIJ`c??Kw;E zv;rq&`%qt)4V{Bk`QYWmI%iI{&rZFYgp8`#KkKCav(7`M31R6l-JYGd_!}!p6Aze` zE5QRoN?+}k1#N&kAo3{b3O)$yjA7FcPEMXh?jQe{kggleiVuiegbO{lKPfLrS5LW* zLkFVR-avV?nY-vEU2M&G$&jptIUc5Kzds1>-?rQJq~sZgTuGd(jI6Zh$p{kFEr`iR z^QA_mf^@xIK%U-Na|ETns`z{t*$xNGnj7=4?ez}IyWA#sYKiXN)JW*>A&!J(8Hw2} zXcklq9g~!Y$&jhl5Z4+N0{eC^kCheY#)Twdz`<~bK4>e9Ppi#XO$OF^HOznZi%q0sFWOcag z0w2&FflKf_no2IpIzOf{K_jXY>~7a=J0Y$)`3}MpLrPK`K^aOFKMhDut!dA}V%L5D z*g*H+{kuB&Z3x5+-)Hj4`bnN8kMIa#U!n5mNkxRc`dKcOrSY_ETeoHlFTPm%?ymhl zLU2RTYhGd_V!ko=PFs?P9lU~aFyP$&Qh>W=U_^K0_Y6sv7pe68bv4af;GtJtdDah5 zUD=^_^BDgk8rBH9e@`#x(zucmqOj<0K(^Wu zj3%&x~2Sbf*ap5wp!_}d0^^TYBrZ$@bLhg zEzAtPmwNtmCs$Dnd=n!)6L&_a>04HA?aKYnsb%Zv|FL^Fi_#B3{qZ??ITaF!dWCQD zJ$-t2@RCQXk9X4M;QE*wlJYx-Oh6%0g`YUb|6c6olZeDXR{^(E#8#%PU6@UdgeaP~6`P{pXTx=8b}aY9pCNk7pP$Lu@nWWePJzHtM7 z;HNS+o4ti54d1kD>Xb6)yDDKs7IW8Vh}B^f9<|@D6+gRjKw%lXip_#|(1`ckC~8}P zmBcK8ICAU}Vcx!s^Rb+Y@Dq>$_S9OXVS2oQ=RQv=^(erS3c`CDU;3vbUL^QG(40(2 za~*38xG03LQTSJ6{rr39I`Tmrc0aNfho?0}LY`5gQsuOumrSYmG3N{=CuqD33dByg zHk>;f4v?Q8rRM=p6H%YukN(ymOX?SZ%e&l4z%SO|P~M?esYH`rcj=S07j{dfZ59Bp z;50D<_z{s%b)`i9o12espz`&C&garnMW-Qs@QngL-=iz>DJ7wei2ykxZUMz6oNFh<+rc$h1=n#2eQ0>{Hls>|7-sj5!GAnZGP&wj6L%cjP<#(IaouLGzm^GFM$a= z98avyTjVb91C>{{XTz(BO|tLJaa4qQl)Erz zi<$Kz{8=s#NYPnZe>NDrvlzm`?;KuNXDTEv*0s4Kp+*NSm1ZjOLJ<2@N^133xH=Na& z!^RQO75RmurRx;hv$&bcEoqYI9k+-dDH)fRY{_}r!&Q!{xER^vtMLg#WIEuPIih*8 z@7`YRvaoqUbLoD%%8u$a!oc|!2df*TI%9v|y1?&TbuJ{WKWL8TCqw&bU2T6=Ui#$A zO^5~_--1EC_Z0|b_)ro;XQJdfEKU2+FM#dqjay|A8MHn4NmRK;9eXY zJzy%X(5SOeAaxQSJs92_C+6u~!h^!I5=!+`2U>Ig+OQiy?;ds_y|E)TpEc9JfJ;`- zr+5@_{Vd?62nNzWFJe{YCoa=Ka@2obpAiSaH}oWT`R?vlc(xPX9U29%n!|rz;SJsj z!3QGQdrQN#se&;o;e?OHVonza!d*Sx*W@+rYPt&J-wMfzOpY3#BQj^CB=W^t8K|Yi zr|88vxLRpDBLhebqXw5O8-k&GRO8ArJE=>jtCU6^K1f@#^$&UojqrKFf;sLQbDt>0 z%DNsq3hE$c=o>j&u*+Yqcz4dRMxt(-68_O`{nyfQ_8O!#4q2>wW`*U` zo-A%jyeTu%wQlzEDIUn+Kv>5UWOtbFI;9oASvgm-uA*UCT+hAeHpF`EFwa%ELPa+% zPLuCs21k>1NJRN>>M%@>N&iVHW!FzSZ%4WiUO{cU@q#jJ&za-H#pQ3&Cer(2xu`8Y zfeeKD+QH-J(Oc$<-8!k^FVTHpP&w!Y_9V^ZnJn46YH&YeBgtHpHH~BtTMji*_X zO(_;eR~EnD*Arc%)LTkNz$mv4lS*p;orT{|J0P+>`;2a8thJSNERorsRNw9h#%L-} zE5i$14Y%HnNoGwVxy6%Jxv~QKV!7y^H?Uq5+x)0E3{y?dJsuLBcp%I57PIpKRopXH zwUfZVTbK9zNWdgw^WkS&ou<2dv%tnwY#U5;E(<~(DBgY zv|vn8xJn_)9z_0eezTci__ESYoFq0^+hbwcw>0OvVchevg>d#>iK{&nhQAoS`%6Hs zjw0dTJx6}`>>c0B|3xuGY`~cjCgjhd_7E>F^WK{WgI9u!4~I8$S*OAq8<{3rOftrR zvRa_6<2ybqtD59qDwS`IZouhiW&Hb*-95!V@?c&UNO)qDX2N=H@ft=eD044)tB__|ja}T~3+qV@F+;JEYo++db94^ zwQcCrCcV^mt-#>;i2tJd@1nKIbK?Ge?mX0sfjYWM4NuR=XCTu@qK+k$c@$Lzgd_dk zj`wJHpyd04IHu!>re{F;Kky)b`|^TJ>ECj&{)3g&K)>)=VeuVZXyTVEjF9v& zyzG<|US0yBT(q492ao4(SU_7nLik8Fsg-79f+01o6oBpBcw@JVSM~w{B8aP3_sRp9 zG=v;xh7PB{NdfvFoXsP@G`<$Z7rE}y-X@k=gf2L5nN#jWOn#qsltZJeE&K9ZpWPF! z;1{=1wl<{XgR7sS5yAEAA&KSnyaeORvCFl$;X}nDVvHE>*dr0!a(?47&M2N8aqlq* zZIfC2!&a@9*6$syD+P7G>g9SL-ZyHhabJ*U{|xtOZ}%4OQUlO#D%(d&v%0X)@m zV1%P)ZQt=i=~OYaZ!XPt?zt zZ@UWsR zTqPR)4p{9UpnOMv`2F|q5KVmSvJfUf6}Mn1Nc&=YMvW2WatQvw zQ06$`r7LPQ3WbPnfR_3Br|FkeKe+Vd3^y^C7p(h@9*xyD2Cj@&Nzf9`xt8upjY&kr zKy56?sP0lH0m3cc9o?#(SPSwFQ`}~`&e2hi1%8z+Wh7-0^Au{zZe%=Y?%1ZBn*&2LK!P8DnRwEL^1mg!M@WZjm=dzC=g*??`CSbm z&WtVN(?9-z*7#?yqdl=d+3*gAh4#gD7Z?w&ZJuQ~iw$3@k0~f8>~4ZGe+;k365;}S zqeWKO{YvIf$~Eoal=s_l1uaEpa0{5dd++VMGfW((4fT)(W4t?jogYs_aGd-s1hi~N zC7yCsH}f^;T0gap(75bbQ6CzD;`S%QO}uOd^W&V0>GL0KAVoU0n)m+O_d=VJ0K6^M z-mYdsut{fGpMW0^JIW5#{B-0IO9`eO6pL&a6Kg4>gzF4dquy~Rwp!=@%l&dz)2|Ph zVivXplAJF7nN+Gf=5;+alH3|4Iz7V)7iGaXViq3BRNB?l3*fd5@2V<-9?nk_Wo{|e zX;cd{CdXZnzEUxWb_og`>8^xSJ6c{fFPghr0{w`?4W4i_D*&3$|FCRY5mB0dKRS&% zc06bx1(DHD)$r0cUzUz5o zUpf!19oKLCk)6#v3Wqh-&GgvRqIB7wAI}#+p-{n_5rJ3TGsP=>^{3YkrA68AyV_@!elr18RcOdcrP1>8^4d8=6*Z!?Z<>uWEgn7T(b+Ry=^ z26VxsVYyernSrE{FAsBv^@dK<=Qgs<%s**(Jc3Yu0jI?i*c)Aa>vWO}j~(>0%vTO9 z0XjNUZ%1wt-v`{d*HtZLgzjTI;MkRXBZ0 zwf}9sLKanqfOx_ z#O4YgB$DIQZ*9v*EXS3UuiMT=H#wSwCq$M#RaQyV0u{HOIYuK_ybvR8e9mhTQGZkT zmEsBZ(YnIpb%ul8){N&GXZ#Z2<>IZ@z$p>%38ho#Y9Z`l>_gq?-oT*vBl5)P-6WwE zTYo}QC@ef$4G#Z1L^`(LiGMNbbgsv=cuhy7u3Gt77hK+E2sFmgWS&jaUhB#xQV&G= zd4yyL#Eg}b-fG((7)pYP0M8Y8)Nr&tjmuTbx?1|~ko^sc)fN8KZ+f1_*uS-WoUv=& z$-nKH{|H2#aXyrvH9@?q#?9pnS<+2OJ>6i5rWobTYoZ-W8qPNprN`nu{sKYu#Qcdu z{sjp(DO})v!gFXXEzc8v@2zG{JD7lJq+IO!>cRi*jU+bJ@giNH4l7PM<5e})goNXu zkgDDdxhOv&qf3fPuwmcVB&ze|GrzKDO;P313}dHflCBQR!J1+(bUjl}J7Kz3`NJ_}Q8PBJU%FsAVhmdmfo+BAYaZjXb;4lP%+C9UMY09Iwtm>u-;>?Ac zy`VPWYo3@R#lKzvaH$@1rm>$ML};l|?wheAnJD;VeoPx3g^)`XHN8BL zdJ@&%oXqavZ$O9xEN2SEj65SbwiW9lTlv*De8*a%Evrs2g0MBJ5&O7$>jdWRX`S6E`zO z7nW3BF0bTw>!kwS|MvD_Jm15qF_Pd9-tz?he>SX1r)Rv_1v;*$wH?XDIkbnT=N`I- zrBi|^3m0}orW@EjUOhPOm{ZPUir3_01%y3>xPAY*|Cw}9kgfLZuPX(2`cQbgqr^t! zenBUua5f-?xsz+SsBK>Y9SPMV%Z{=aLV-*!tJ0JvGRlD-JbNJdeHM*wB9^*LUv zA6urC+kdRbk>an|-Nh3)S$b_)8Nt-vJIYs1PkgpsNm&#Y@g?J@^5Z%T*7t$zO&=jY z2E2I~y6zGs37O0pWnWCB_2LPGu#`F(c3VS%Fca}qzQ)Gb^UX}2Af1%gBw0{HRr_HZ z(uMor8T8Om0=t8rBZ+G&o|I`>q}l~?NWP;8B!C~6k{v)>Rg0Gf`PQDXa3x3Wux zTuM}51p-XgQu0r!eaqu|?fXYBw}C;wZcPw$X-p1ep&OB}esc_mB6W>0u{c-NOXL~b zWcJNfX9!xcekg-c6gb?G1g+FyJZ?y`O2{L?gL6VA{G961ku7TF(fc**if-t2zo)>h zR$nGUjfr8Z>cPmHxTkx1wX^g980S(--nV(E z_PhOL2d{GWSdK~Iarsu7ro?frk2Iq$hDhv-EVLLpn&=yx3*!Mtkz2F)A$e(N-Y}qi z%C)~L`cTPse@+E%ff`q}a2;T9LS99(&F=6znwze4v9~cQjPZubeBagd5+l}65lcnB2KUgxF)H}rwBsy3( z(HKiDoeu<1|C}v@K!?%(!uESf z8rWt}Y_w}Ee!r4xnxOMY0w}e>K(yg@G4*b7%zs--Xm17<)1(ef@kZw}m@~y(yf8$n zO%e>#^sY3p!5C|^Whzly7trDi7XWm(0 zp^t6?hmJs$1hi(5PAG1m#Udj-LqJ#`shP)z%!w)ZPHT8Si^BHqzIvh@j}W19HA~Yc zvGs55>=XN|m0~_Fckhvsls8Xc%CyD(?$J<*%%6_jklmEs69osP7k4=hy=WJQ{H6%Y z^a)yIMTd9XHG8;zKKekWxj*vb%HBQN1HBpC4IWu945{Z_gM_ zf6J$ot1K_CN3vE~L$#rbf=Q)e8H@^zP7tB-n{!I#TSoJ>z{j2Y)7A*=u0M4`ocKS+ zS_39So_TghO`roG#X!p@SupsUdF)m;D5Fb$42)#)f{;`U8ZnovVDY8wtK*7S54_WS zy398U_$kV}b@iYO7kWwyGA0&~RQKF9c?)-|u}SZO4%lUyY^=3SlHATFWV$}jx*yRB zhfr+cK*?>|x9ENvD+KDWGk+PX8G!DdyQcCKbh$w+$6lPRACeP5s>pJ#Q?UrYDGP^W*-87|H1%i5}2U!I0JcthvqmBFt~fx znB327l-n+u#GvuTUo)2Mb)zPQ(mXEDMyzcaGLfLB!ri>|WS37?4u7kr^H0Bwpg(dE z0rX2kg6$gsfi@mI!w94q={Io2(TA$}d@S?=m^VSSs@Jvk^wFapHfQ>Hy=d>ges-am zehrJsiGtFJvAV%e1e>6IoH3eUt0(L+MS8gbkTe*9%e}{y_q0v6e5P4qy_C8Ofxhh? z&zKmdMNEVkVttvd0-^LbJ#QS-`5VeenSl2QOwoQlhsrpijOD~EVNW}<*gj9D z4OKX#kqja~%W>?Y%OnSV$tbi(@C+tGx83qi3N5lv3SCwQq*uIhBQq>-+oMO%X3#P0 zjyxfymkH*=G^*QsIZcrXv`Kv`^_O+kn-=2)Z$WOXEj*r3-`h)Y)yadVP1SseiFS{x zH<>$$ytUzRuPQX(dTI-*QmnH6Fpe$ZF|_5uC3xNT;oo{1W%>X0w3D6j4$GfxaJIxX zmj@ReM?zjL2i)$UWitcjTrZHoe?0iUt1um}A8lzvp6R;^Q0VS!*IVP!UpjvL-jrq# z=1@rQ{2|WGl@|qO%6x`Lil~tY)5Aoxxys%n%gQ#J+X-#@hMyJS>u*Camj zh#|1mE$@V^D{_j8%U>p1IKhXFELBiAm1p35P#g{_@hsZ~wqUb7CYAlIGP9rlt1|2g zCS#~?W?%iHG0AGPmk%iW5XD5pSx_i%am83l${w6#d{@A~dgeKr<-@kUgR1`C{*d=B z#v$(_42z_9!Kd?ZSKHtXc_d|_d5sI4$L(C4_N8#WO2HafWn%fZef?|(cv5^b5a@&K-){!n!?Do>-0lpxTfBM>VrVqqR7H_r{3B z8F1RUW0M(Ewh^>d!}z4OdJRdCSmOE!F{IA5W9zzuy9VE0SSL$g#YZsraOw2W_ra|Nv_9KyauZ}D zIV3y&bl=NgdClTrJn5@J`E>Ep($BLshxsW&=?w0i5^Nk$zo?CJGRGE|Z)+JAmE44~ z1XMqD%ULM@yu&-U|ww+7fUMPeYs6GFo|*CL)JoJep9~iEZszh^N&h%{Lw@%@dt1j z6HV51Ns@PdYsh~x4L7I~1b|S@d8OlL_y(}@HuqJvs@>XXv`+)AWLZf0fhS1TPcVm| zJ}W)%>nJZikENtcnzv(>;9=_Akv{T-CxF_}>)P?sGNgtnf zL|ZJ5~mYE^rOx#N}DnNm>AIidz?{Y0Sl&fYRvehy0m5n$?mHR;EXoS{d&+L7Ab5Z zNM=U$X_IF5`sBqBjFA(;i#9NffmFP*q~9|l#&b_VsV`ko9NPLs3SgaVpU)l>=qL3?Csj% zSNbFK4;gs<-yDj^m=~8Bp(aJ%XNwt9#R4s?PE)~_x?FFN6>M?351$d#SP+D(BVzrb zP#bY{DW!)ryvAEKW=QjS^$*`6#o`uo%3(cA{k9+i4eDk5D?o)Y)$!n<>2SySPAE5w z2bQNvt=%7LS^NrMEX|scY?9Vadg;&^9ljF1aAjdX9nvR-t<^fHQqvvI9QGnvqq{CC zCYv}UBd9))Hu&>ub*Y>@cJ(<}m^<8<9YUJA3u77BgjQ2zWC=RoCvnqfY1ji%Q)*v_ zL(~C(civwDi27pJzd-Ch5+rC4TNPEROJ1uVv8~gmN32m612EFI)8R}N$W%&wVd?B$ zv{fdzyF6hTMqZKxB;Y^ZbQ)cR__c`8sVH`pRZ@1x^~c((A`!X;^b&sk zu8o)3lVWnqhqL~!dRu2~z!(>0?s?i!Qo>Z5ug6gP%Xa(BfW3}@DC4jy3Cu2&$Ki&m z3%5y+`S;T_<#T>dm(i=m?)*AR#C0zYTB$e4>N#2j=k6ob%D5PSiCauAnaYCEg?BCR zL-et;`VXzeRb`~%fT7c?nB7{9isGaVb;B`HH|~D{aQ$=eUs)#_s^b`rHtG;ti)WCH zYhYOy&EOp0PR=xt34stbV{W@wRg%vQzeEVgxQzAIFwO5cJkNGK1&@2i@t)iiq8{6E zb#IYjGRCMFc7)I-YKhmE$obG5oEFcH6i#uZMvN>;1R?$oHLsJx<>H`D`@RL*6Ne(U=+;vC8DZb=selEq z$LK%R72|9aNd7NsqP~ynyc0lQ2pMZ*j&;+p_*#=)lJki1-P_L92p`Kt8@` z6`HSZFyc2XZ1YM0d2ZbEJ_NaQ7SP)+>-7FRdQf&YV~?iK;gyg=SXHUNS%p)NmY=bc zT)fhDV+_b+I$=Np{3Rlgh3WM2dhrcD@o>jfM%=rNS732h8zq>=X>XBp{YFJ(wbK_s znWeP86vwyOn z+oJLfU23g8EPu}xTY@7_Fm^P@hR?cHZ#Hf0`$q-*;Y{-RMWdR=t`JK$8QZKQNk3{t zWF@jQDt&Bmc17ZTaV=UjdqF30&B1+dH#hZuC$uF+8XJZ={R16jnkY6Few1tufgwyS zHy7WyAkEAkw^XXihaoM~eegNBR804)l@223lC)o&;Q4AIC_yE^x+Q2PP7eo7-#jsY z*Eh!0?VPD$D+QkWmyv(W0~oLW(RbI*F?(&pv|x$LXbt$YH47T{bMEBXRyDgjS+Lda%gwwxZ#r&jiYA5FQ9T-?!~mxm|| z88J0Q8M200a)za+6GJbND`)V25du4V$cBI2d=mQLhGVE~K_Q9cvNrzAtz)9CISwcE zy}?!VZ2t}O8)F)8DE*-KI|w7K z^d_=@f-(31!N?JNawzN!{#;Xuhsm2ME0%fl^Mge3OR)9Ax~61zbgjeNmP*__ZI)mf zVHtb|n;`^j79JEi7Qc>=&JreyW6u|OhBpR@^s38ZMdiq9E8c+w85u8M$HX1m(Y!mS z{-PBShZn%@T!{>M#N<|K++)wecWpT+?U*9Lnjq3Zv}e(clvh9^!{!p5A++;lXJ=PZ zWq;TGK2K4V{kb3TWz|D>AB6dnx%)E#`-<+uGB+}P?>)e5wKvlTGT#qDuQR?~)p>Dp zABnhZkRm-V>r5v(VioFJ2}VD=?jUk8@{*#Hx1sAA)9Y@{$h5@-TNF6Rv^Gx==2?W( zB<~mWxf^HHvU`Fjh(#oRxO{LYh3U+eWY_s=8F*79&=gk%ZCY31nW#-CoLkO<#P!2Rt!l}x z4!+}Gm7W_(RTdBs6|97PHhEF)rS7L7^6^8cm0j))#av zG}$yCK?LWCv00fdcJ1$6Y}?SAacM5oe8sOiHJh{gbbq=S_>1RK*{&03uwVmVD z`kkHOM34!T>Wu$4d^~~w4RI>BtQfr%5ar`)|LMD#i?3&W#^!J@2Cw(MOrqzFJb(LL zCZR?B%@3<%crPA&;PADg1;f1ts2Wg)2V>exNr7qmQpvEo-_{Pm=aZ@rCsxD_Pl)!z ziDO-#H&q+e4s$Sh-tTXq#0|dJ2o{LG;Wo;sAO+f`XNa0-50Z2+e4p|tc0`|F60DDj z>^45Re?Vz|X12lR-boxm3LtzHHW|GlRA=vnHo|o8Ae-ui3(B7D9SOK>xV=+%5iJN)r z*=B|HS;PMfTID?pM^w4tU~x>Aiu~@RKY+Od&Ej+NALpMG>wl_BG|{NvmAp=STEDeA zcFWA9G{sKMWgs*z_ikvKo|0x}ney@U95 zs+YVXfFwg0OvN4BQKPhXBw+hnKJJ|*jr#zoTR+`Yi?>3A4;ZGGVScYFKIdQzZ>0Ec zE4MU!`7f75|H~zes@LJ_2o0a%aney%5*L6r^J?WXjeMl5Gq0U?LJqe->^8u^<{dlW)H8( z5NBALvGnB15dIQ)jOW)JM`6nsS1PlGzmSL6UFF&_$XP zs6Bei$n=1hX~lz%m^T-z|0%DK2>s1sP_)anj*AW9Jb#npxYf*Rjpq!(Hua?>Gne=D zM(B(7uPP%qLh`A0EB#i@WJt(d+-gP-`)0FeQwJg9fr+*K zDKtKf2v`otj=7*#l`*BJ>a)td?RY$iZuljQX)0|!S5pbQ%SzFKo^fkuU-ri6CgA>2 ze!P|7>7+KHA(N4TH1wDb$_q7ufU`b)5~-QX2T%5<_A~ZTKEImIybsr@W7D!;9_MAjp5`hZ&B%T2wDXUZPEUUNx$qwJ@&@h!R8kh zx(`uYG%ub-`h!VP#dLCHT3r$d9t}x3bW2oINmv$Xv zmYg-_);_p@TKu}pus zsbW^BM`_y3rLC_sdhk5HxZggJJD2`DzGO1Qc_~d`Pu!1_E3zJA{)E@te-2q8A>%)v>4McVC0$J7DLJrGSr@18#yrg`{`PqB-)q4-YhJ z&c%V)***ZJhOoE(LZIJxokWQF+gB`%+)<-CeN`MGjGL(nU#W`6Fz7FK0=XlN$ z?&j=b(mGqqqMv{MJb~#dh3VeCZa|XB`qmU_Z2cw0X4G@Xj?(5iFi3=AqO~|cFWOUe zV}2m+#Nz3ew)*Wera+EnDMvd_%c3FMUOBOu^+Do1_qD4V*7NwMU$AorQIRo4S9i{} z$RuF2=gtH7+1X%2g3PNAPC|aiBDN3vOuDB_Qa@4>SZeK;Gk+|V2F++9vR9w68J%g- zG7?73?_Y*|Yu>2yZq?H~boez{ZoDa3rUwE6!tTHoPK+KF>dk%WsjmwWPaB7rGZ!0B zYYog4A0+Ubt3!Mxn_I4C7wDmGlwc{ispZab!&n|3FyYc;WGijbeYAP5u!;Ey) z(daoAlnxF><;-aamqc8fx=@>pBWTsD@3pXK7e}Idj3vI3jI>}9&}%I zz@|!m#)U&dFN0pMuo!NXsV$==xy|w*XEc-l!|&Pt6Pw=bI3eSHJ{K4Ki#r#I0P%bcGWc!#{1YOE-AnR$ z0&zzLs=$S7s>IfSB6BZk1bVF}-hR)RV>|#-A z9;{w>Tod*CPqK&fLE$c!29g6c_aZDmCB`;i=CVABbq+72~uOrKG(p`=Is6p1>G&U?ZlN%UzgeFuksZ6 z|A(O&BteFl{N9G;-KFyJHj>nC{DGrv5^8BIT!BzKSAl;1Hn5L`X+|My<-_E~PQ z&Fl-63o`*t5zIASqT{tla3YeYbo1aGeQ*ecep@({G&e6WW2V^`DdacC9~_|TOxan9 zIK!NX>>3D_8E=Y1K@+>EvH0g^c2a7}Nw0%KMe@hk$xA$WEr|6B- zZ0=6xz{trR8aEX_G$gv&^$qv5eCN>BxF0tEoH4G=2NL7L6360w6Ac&okq*vxfC4XtKT=YnhoC+Ug3BJ%B>psAFAU6?IqP5K7~(zG8@9A57tv99Lm89JS|>BZ zTI!3yY)|}sO+>hQy)7mgMHSw`p=f@&P^DeT06!bY@x1E!^Q5}EkEZ74od=imL}HAt zsdNOaC_8!=Qa9%)>;@47VG5NnvL|%m)-4WG53JMla_JcpkJXWIR_CGDLk2g(Z}X@X z?*iu4Z#c_Kzg2Z98A-6nAo86+G|Hsr@Mb)`< zO`}+FcP9Y?1b3GNC%7)$-Q6X)ES%sLAh^4`I|O%U;qH3Y{@(2UpFu9TVvKb6GrMNZ zs%oL6d>YHAez`e9rD}O8{JFUxf!nq(5!F51$Xc0ZqgsV&=ycCnu8@Ozk$Cgp)BZY3 zB_OgybRhm#VE3HvR}mZne zyX>|@WzPx`8T`{6C6JTJCj(CXt<8;v477wHTNKd}k5fhpO1y-R!6FdJa4oP0?ZAbc z{zk9256-f{cO(cFfslbGl0`r*BnO{h@4Ai^_+$||_Op|a?VS!%d)#t2mm>q%BfGoo zaoKPBR(GrhLr$oy$1DZ_8nQ{YQiV-xy6&vrQ!XEIt-62s8*Sd2bRS<+U?Py?o_fh- zMeDo43Fj~di9l*?ai(tNnQfKzH-73(@2_9dYR51Mr0&`ouj8Q`Zl`Os^~Ne6ujf9D zJePjP-wKz+Or(^hEW>f0#+zK$&i$0sN}4EJ95+>qY()lxmH6B|RiSBviHAns zC_?gKwfwDX^MJ|7BQYwuSt)fS-zb-%m0GEZAayHx0(Ev&c*2CJ!?0waek#5G-Ag*9 z{mA0YS(PMZP{}EoAt?D>*ruO4tiLQbAKjNvJf zquM@aULE3MXbsQsplFBr{6%lEx#XoIbZW7|(4ep|I=aEL%=-w=+^SeQ@`xAQdSU=C zvvH26b!cLqSoq_C265WRNFYOZb~F)k-=^F3op{B@glL6kTQOxB<>$PgF)ApBr$_87 zerqkfr%oeFM+2S2=Lzi2F0gG=A&lMEcc*uMnRg7x|1`!9+85qvh~$O%j~m5C8?)HB zampFrGUOSfea2}!zt8}(+lMRw-+0C3%sP>Vv3Qm+PDSM|CEvp`I64?t1#hH@hnQVe zOwDlg2N04CmRW$Fyu{NKD&&m%cP>_Ux>XCF?|-(51g@p@21Y!sT_7ru$wK7QfCdSm zoYHbqEj0#-e$eD6Y;&Mja2@_SeUV97&v#Qb((iDQ-=q%BfBuXXKLlsP(-M4$8FWU{ z9H+OZy!(@-lWo*@kXrV|G&FVPG?K!zSCv-Y->8#&D}>@5;{6MPEAik>X@B(hvD|x zf?u@qT1MU>T?>wz=8r_)Gm@bs%Mksd}#>!XobNucNe!PagrG^ zq;Y!MXBSc~QA%x`lFq(`oWTO}G&aFe{~#-kTUwNw@(1~yYH+)Mc!cOj^$e3JJ?^*u zG!Qz13rh)C{0`H=RL+co;E6gii32?%VhH|`VRuDNXi7z1g(*b=NoSwhrp!R{p@iEn zlBpkG0Z6*qcNESIT>3pfotUle&^&dt8ys4A)28NY@JvLgzW~$d=Y3j;^Qbc-UV6H} z41V|Z30%um@3iFU&~C?sJEBumP>KGwm!P1alErN3+z>7*U%Q!_4hZ>xw-%l#uMJc< zuikWRWpO@GaBtT=S*nHGvR@>O`6dd?>6r;Ylt)@WAQ_#~!N>d3_gf!>Dma4Wvr44Q z8gy3d0AV5)pKPvXd_v|AbLz!mn-yT3oTC$k#gBqf=_W&q)J8vR%c@kx7>e}-aiK)- zE5~BkQ%#bGggxhfndZ3v-)0PKjj};RIv&~KHa%#O3qA7GnjG<*)bilrKN^0q;>2-K z{amTz>=ifDWI*k>3@`*sm5sRZc!*d79>(qSh7MiL^xraw>~DTvFAD$Kx~r8k%$a`% zoOhncP3&66TR#~dDyrB$!>`Pj^{ta+3om?Vq`GxyG2BH)CUbxaK^4Lc7VC}2O{2*u zhOz&!(&z4Egaf5hj?Zt6NFD7^c{gtM44kT}gv!yU*7banFt;e_Sqyh#0k!E3+>=+aUKks1H(@0k{;9i; z)nlg|4oj30zL|}u_d=0|jqKI{+V+l4zR>$>*VWe>499sMcE**#fFVSdAZqdFH2g0p-L+sN;rx^(0eH4R6PhqjoZwz#qK+8V zlU;-e{_Z&HsPJPrMS&NpzY5Ka+KwYMFnM&2p(o8XllcM=v%zOMbv26!m= z&o>AOVgK#DB0@k@HOI*yfBUC2uAgj>Q6nn z-Jcl2CSnu6=t6{$*Yv?MBLa;k^Jx-%PG?Q+uDbJmcEmK;ba$>osVVmGyf}LZtp)zj z@od51iuIL*nxUbgz9B_w!;^;@X3JT6WB1zaM-wqQUA)4jhMXKsT|Le#Bv^!gsoJFE z1m&PL5?S}xN4*?_cUNR04rnv_rZ2vwn)7r$M~l`L6=J^A`c13bWLhSo@e$+a-N)lS zL)Fw@o~dR4rbe%fZ4FnZC*_Zbg_#}#(R_!FO=|@6%VXzWJ4iT{U%%hX`WxiQ_Z45; z_C4FZd=Y$Ib(-92+KKLM24w-adP9xwPL{$CTB4ViHBT0+p;sDgdZS7Bs!T?4tydak z7aCts>A>P?JMb0QTcnxvraO^)4Fkg_j#P0p%Fhmu z!CTUc=f7viJ~~8$Ua(|Jo;u@U!`Rn>^xt$L;NL+$)B`o{PYCW#zuLu7OL7D`F=v^( zSgdRJh6&McwLd`Yg=;dj!ugr{=G3?mcK?JKASB%-7AWt+u=A@okhJ=cTwWr_pe574 z>HSQWX9*`8kW}lgv4f*@74;?^#(OSz2v|E^Z1eokP^KAjHi0W%|D&Lp*>jAZnB!6= zlGulwpETPb>$4;8>9!21twqT<14R$vvU&{e=b>@3Fz8!8jDwK}*r?d+Kd4PH#MU94qy1b~Z~ z(s}>xf|U5pE&^C5*a|T&>s7UNZMLKAw(0;^Ad?zk&>KRa!;Z4Iw@1UoG#)lckPkQa`5nHIVm>hYe@VY?0H0Ph3jkyy>n=f&h`cAtyXd1TFn=oA=jT)>c z@cY-=+4`*k;6tH?Xh|Zknc9hTv$K^$Q|{(pFF+{hLth;2%FHQ)Mr_EoSEYUJ+yXWS z&rRl9(RSJw&U+5c-tpPwo?X3Hwexfc0}m{ga_#~^U!3f|zOI)q0-kXoe%01u3B5l~ zUM?ENe4^;p9lLesPvLeTr;^JELt<(}hnV{FCtyFwKEI~l)X!3X$A^MJ-+{vY~Zx_ys9u^V3zLS!7&R!LR^ka(5 zDIAqbUf<9MWh*P=?D`rff;HJf2@df(tH?-FyKaMNpg!*#fw)~2}p;eeCaoyAo4+0oHq7`ntG zIB`iR_o!%b#R7&(;M=C`7GN9E#tM>QAUS>{sPK}#q2jh(Q6 z=#tvO=A^^0C7LU%6NRkJfeBal&1{VOHBFRcUl{+bhvWW~sP{4+U%!7!+cu;5KT~>2l7u&|Gv?@HgR)i!lby@qyS8FDO^xcix7wpNV3^u3&;#Wm>+B>j^zQ%@_TNjO z4`YIro)@L7DKHb@9LGkYcw(BV`@P)bt(!CNCc8#9K45?F$85;>f(TT%BM)bSq5hn-5-q zKc|sTS_q4ge76Z;H3rDojFdN+h3Qw2ZxlB}&gdA#mY}f6wYWAHGB&3D#UBd-JYTzf zy6y}Z&Huzkhql(usO6u)1aE0>w-U4Z;xDe4uw_I|b+&wm5fYQ?k8Ib_^?eMkaw94# zTPP;~{ShrPn|Fg2Y`H4SEo?R=y)>G*N~_juTzz336TAn7;L8g>QVKrqV)f5er}BHS z+O}Pax81LMxj$@$Ivf=j3eQ9yTROY#GzOPCn050yTVbegM1?c7UYFc@r}i{UDTKEN zFP~23oA3-gDsdLB(%3QL6svJcyiXvsQSk@%Q!lOjRYz_Z|0hSOkn7i|nCV+*^H6ur znST>5&iF-L(U*!$*XZd1DNj|HS)MsnL`qlviCXhYkB=`dK_|iegDW}6Khm~MS0y23 zMw{DhU4F~a%$}F5Jhz}*T>2%QKAH+~dTLoc*iXQLWZm};4@_vVh)-#QKUTqtmM2Ae zZD&4M6kgg-MVeQi5h|rh(3QW=#1BRq5*Vd8NK1VrJ`7pesm0-j{78H>U`6NWuTTX& znC*=c63vhMY{`{gy8SeGP32+*+sd~!I--0OZLA2WhZGT)aoSw!ZIOQqS3MU9=-+4w zB?w(QT%q=44U+#dt*mrG%w~W}MN-SWRe1c*nkLShg^up^5SV5750d#2+qK`~;?k=_ zB#*j(*;*?jTvfmNbmtjKGU5n=pJ^~G*HKwnF(gK|_K$#>h7smR|7^0~lUHYARH(`*Rj_!c@bHrxvBW&D{o^ zZ+o3a>&chZopa!en+b>ih|9AV-H{woiZ08KjWI)&4XlCO*`9a67@=3Ea&aPT5lH2@ zSrj$GD0{vjQ-AEjDO!1L&TojLFxxCCefM{oc*Tj37AL$`H`Mx|l7td(#Z|6T0A%B- z7~KnrPRWNoPUC31J~}nGEb0rZrrvo_uK2bTE48TgiZio7i%Z=%ZrrL)50yOHtDcjx z%Mb3KZ(X!l%okN88q3xiE@j(pw@K8iZqV>~-i-HNe550hvWce?h=5<*34P>K?kQ^Ned@Py&L(~VY~YIA&WLq&}c?WkwNQ2($Hp|`#JxM0x3V#aqw zUymmc<+{oZ+dXq|JaJ*LJq`M7?Lt!7@l;|QJORFkX>~mhKWn?Kx%`8c0O+0cPcVF} z%P{Nw@$1zgGf~UU-<>Cv`6MFpcyaEH88DqnK=w)bztKy12U+Yr;Xc$)#&LUOUSyn) z{R_XT{*`C-VMHP|vEukWj+Pn9U)sM91+d}`E4M(Dr`m`)?AD|^71Wp!KWmE0&1ub- z2qi0v8zx~e>wYN_9!fk=;P>249lA{(Xe?jLXn(u(i@I+4BvDyZG+1?(FnIYQ)B)TN z`7Yv{JsIP1?HgdHbITkO!!4LK6AP`@O{W?+!)%Pf!x3oXSTR*TdUYi4@g& zp;9#-P2olX?3g_rM<|O={i6>j<6f7$?b2J*5r8nX*NA9P}_tT4MO zgqmSN0idQ~GlHz_r43vI_Tjq^8wvNFA zm4gCDYozhLg;xxR8;4Z2>_o_HQMY(uUhm+`tKMHP*Mn!CFWJYx`dFgw8E(HS)G=^D z2=~fWYzF4RfdWcvo8Q{`=q(`y}lT9wmnPVfiaC+>C!95#^&4+Rj+KXL?8|0?X zk$ER<)vlvVB#`^8w7{XZLGwv*3gOH{AjWWCNA?$ zcDNrOm!q-y{?!89thJ~)d89ml~Bd7qNGwhqTB`Gsnx6QYq;*HYUM+_=bk2d zC1OO_j}I^yDx%o=ZkR!_;Gdh0*6U}A;j@Xc)Ks=sA{g)WN`O8n1LQH`G;uP~<9(G; zTrQ@gLz0`97gulBK1SV#;g5QVmj~)fHJ{1pG*gQ=L~obzkxd1^`Z1t8ywY=T=iAE3 zAg3Z@RVQ@_Y|F@m__5*pjN)~FCMGT(B8S^;FqXpdaM6qA(2K(L>-TRM2nE~X!Mt+c zu4^;#Us1J+Feb5nNhy>3?XQk>CY4WN=lRhSF-H6qagAZ+^C^Z7w^wX;SoNG(OKs(; z^%tkpyg*{cM|eO(2jZxFc!FeF6Tw|72Ij3XVEXbl zT68A`5B+ukS(5`BM4Vc>je#fAF0e1Ep-TsSAu?t$tDce7pu09m&e?(jQEvH->N&kp zpuF-T^?AkB`(fagHja&z6|&Y;AT%{uXcUjf2VQ&E*qe_ePFbV>kk8dvhLv^%Y1bjO zG1vZh0HEl8gua}Q`nA(wp+t16uADAQE`Kj` zaj%<;p{bjHz)`;Rf@5&gnK_-QJW?6FJ%1MGk9gnU+6HJO>{xJT@10uNFwRciP5v!q z+#CN&Z?@48p<4x+{Z1*^vYymD8&k&JX-Y`nL28sC_)@X5Rw8NX0jnt z`iaVTk zSzWz+J)_Zj$uPx_`Eae33ztbZvZ{(%e#OFy1GnyppuX%f8Tq9pghmj~a!glmTxTY# zUCcVQq}Mwm=}GYA^*I32>Sd4NZ`DGBx6zUQKUVV+ZkIyl{1jH^)WV$+DW<#X7T|o- z*dopseJShC#+3jamuO)iWrwTcQx#wvL$KWTqwZOL9yI$mP3)j;X$b4 z)S`X6c=5R5V7vjSaj@Zp8;E{Hdb&$5U>Z0K%eVqD!z%CISj?bvr`up@xrvGRpnU)C zh=I4UKBKJT0!y^O{{aG@?N(7#^s{jBsw4!jD+y%dXfW225JmYh{Au;BWm4$HkXlg* zKSi5ARm{~NZ_)mSZypw;zUvQm#^-uyQq6i=%jOmdvG1Skwkjpjw@O42vGr} z8ZjeR$}|ju{%so#I}bT_iU6&xOdzGf`6O8m^E(8U?kl-)uhDF_+C00}FrQnwd|X*} z&f)mS;%98ZyD9iOxx=W{olYnSFh>*e^5R`*kyl}E^92@-H1hogB-He{pRTC4L1S;W zGIHT~!pN`AI+bT~Y-6ypI79S4q=_HZbv!ev$Q13X{rb{}aX-6)tj5%+ zzprmgsl2jqrx%hcP|-aC9T5IMx)~i0{=eb^*N39Lrd0h}aIAR}%#Oj!~+Hy$%Tue9{ zNNk&YF`n)+2gY@qIV#?88#=SW8B@~^Hs}}xF>P3_ZLaY_QKfjlT8@xC(K--GW|%_G ziTVJ{4WU7KBA`#)Ep~ZjlUnV=n_BfnbqF!m!AB#8dnc;y6RF#U6&;8!95_Ql)zG8w zJ}5PJKKbBe3So*k7H7_ilvZrO#x08+$jo3UMQe)32#Q>*UPRKJy(bqdHYMKwMld0c z=hUw0Eo+j+ailjaOfJ6Pvh1u4CDEjiot8U&e}&y7k5+z8(<0M~OzBU^P;{g1T1mS- zL*Gyw#pNGqrs0OyS3!0(X$mxiM<=0C%}yr+)+F7SHx3#0iglNyFDNe8NH5QH+;sV8 zd&Cw^a3HS13deV0wX@ zA}etjpq-&2u22CaP>cuVL|RkU&_26~diJxH&P7L(VmUW_wYf5tq4M;kr6*9(Pz=I( z&jhw%@fl}XSco|E-U4I6-bnEo6A zy=~FE81uwMgx-PGLyWUJm{!L2f$gC;JN8Cn8`5kL87?W^O3S=aDLVU{-SEJ`O!G4& z#IxVqkeSw!IC(B6i{VvZ(^=M}!*rh)dh#p*oSUzINd!4E;j7t_=0iv#zJ4{|l+Pxz zwhPGdhS)n_W{QsC2}O@FGv=vG`bH z#6~&~b?13%K#v!_RXj{5FtP&8a{-oZ!L6g5z(d7K2K-w)z3AZc>(kApd~V`S0qAe2 z&I{!KtLX!*+JX>YJ*&1Ky{;QSm&olVnbJy)8Rr>w2bIa}nd%13S>hxYrfzo$K_=Q+ z(Q6)oEacE32~&bzVhJZ5(tlULqXBOt!pDUZVtx%*?ps?|RxoxKj=n{(1uwCdb_Z4r zl#OPKnVZ+ef^8QHyFp6y$^&<#*CoPHViN_NWa+bvA`U0^JGG>xw7|>WkYN3>fUz%V zy_RUxW3|og(v>Vl^mOK{a;hSmv*ZP;h~I%u&Z4pfm(axPw*>RP_A#^tb$_Ie0bJAV6pYkWNuHJ-8Q1hkP_#n5mdT@dXYaXwhR ztG9d8)5JM$Q}W2x3@$A?UQuF)sR=YgLP6)9o(T0Edk1X0mXw7z^VoadD|v=m6y?v7 zC#z3!1B--j$YFK~(LFCBf&n?2)+$dN+{aZOx5|rcM^fBGmL{*oYvNlYt%Bn3(~Uir zXbJ6THFtKx7SjmGV;OlRcXPhE20QZikZjCn5rqPV)JC{L5}&*FN*1#7ShIvLW^auk zDq9j*kd&0*JWobPN2~2N1jqR`F$eH4l~B4z++;L#^w-01!m=ucqY1KbG*Eu3@pE{)vkrQ1P=9=d)%>nt0ow zo`LF`WiF|>1NxAS4?ikV^6{_LFt-`uXx5RRom0y#(hyv5JKBjXI-fyWjs>s(1I@NS#Zyd{=rLRkmS$r!y;p9ol-(Z$I{^x?& zMuYvAc=7v~WHg`;K{7d@{-)L#CjR1M%Y3~0qUJ&Xz*ENofAu?bI`5ggQb>ZH9g}Bo*a|-9 z`>h6DbW+rhq2fNbD9^j>h``o`Z}F6oDeg?xcM3LMWd60Oasq4^7@0qORsbch_}qs2 zd44k9UZUdETgG>;y@;b%Y}8dxSwQ^(5(?Y0BwW&G3{n7hv~ z=FOLud#xmMOqQYWS9S0R@&A^SvTAhv2_Mlrp#14_{63XzG{Yv=wuvw@*EfGHcdgJb zy3Z_kHf;>PQ&Tu^0^ZQWoD|rvr0U#o1h1#4RGU_Ncn)huGGFG7UU=2E;>S9`d>Q{d zT?_iW9tk5VN7`m)F~W?=llqNVNK8(Tk7};>(E6*lBiCkRi;=%5H`w9-TH9Ced** zLhp2#wh`BQwyCYKsppPQc7||V+b=%I+hr%kn9(p()}7HFH>$V2pEA+X_VffJv3Nh& zuexpcnAvEp3@1<<&6jCp8F5jzVYfnaj9I)bcl%j{Wu?&A5@nnVPxdlCoc7jDI$rU z0XJs?Via69b&X|nxI8Yw3Z0^Il?SFYj;tYRM{J9)GpyXgy$U)y{f#EE;mvJ`eS#vD zUp1siYfx?H(Yg0J#@{m820mH6bJ_DAs|4i1{A${y5!7SF<4|2c`U>n10Wx`E_foAv zLx5Y8;E^Q|wbwh<@B37EVE>2?+FZsH?|UEH+7i&* z)YK0gIyL=~pI=hg%urp=*T>~4!}u@zuq36VE{Q=aC6{uukRn27w}F>lubl&jF{_vh z-di8P#XH?vYrXN!3Z*V>oSP$RF(r$T5C)&8dw^QWXsoZX0TP@bHQU1cQZtJ3()t(LTJ zwD#s$(ZVPStu@B<|uz#M?`O2X+V`%*C1IeGz$KBtz6nb=uTgs9b zvqO_IE`@eDme#@&mC5}97+YKBR<#ZrjznCxeRUQy%w`kBC(HHH6bW775fME=rVg4? z=2zBj?iy>8knEj(*Gn})&ka=Z1;S~WfcIB7#+y{Vy-oPvzBA80W8du_4gOBDoc_z^ zfBUGuiE0@vve}pc-Ht%CcxuDO)mHx+puB`dOu(gJq4JFD{gIAj2*t*i-o{_mLeHRF zBC~&wCpz5XbmxGA{ToAr&BmRe>uZZJuH8Yb6^r$OOUTN2gtf+TdZR7!I$}f9(9%Om z8#~&wTbZz=Ib}%9JCY|#N{DQBCqyHq!$NGR-Q4z+gOg&4AHK$O=jDU_tGB2~D+QDQ ztXyy9#w);7K@SjoJ9;MJA{JLTXNuPQxmHiOb)uKQx|dulrzBU>X=PcN`aUP81JQ;L zWxE579cu0A2jPYX7f6?8;A+NG3$YTG33vzqhBT^qERZDVX{67f(t5KRmUWWjo*7_G<{3vo&eM$&~#zp-REPE_q>B zfiyTRcwsS(OLQx)0K|EM3RWXlj5u+r**Pepl;bd~o!Z68KqX!L!H|wO?Cs@D7NbaE zcTM-XR%`wUF^-U&`kWa(P8sUrdY^04l|#QPjA#oUI4~r2t*By;{p_p5Fsf7AqHw7j zVKImLDxnP=x5^3~Jyqf3IQ0Eq?a)<3|+t88cjNFw{rEqXF%b!YlAKx zl@{ISI2Om8+J<53KbB&hRm?KL@Nd~u3f%NpT2S$n29H;J_(Hz?oYsq7@|0iC+V6EK zDcu|A1@wgi$%L+}JvkK>#Y@@;Ds=7D}4F4i5L+c)bx*xt?z@!i!fL})O3&MQkEO-bYn zQ03or9crI~z9uE_l5^$+(&C|@%miInXzy9jxI13qtc}dy6J$at6dp7}A8gs{TN+b7 zIl@f#^a!uIuGqL=k8|;8z=*4;V3T?te9~BXRt((?F+SoGeq;IbB*)r;Sl@U1ZjHqr zr_?z4g0uEM$Ls`KA1m%1M2Ge2`fndV^xwIK*7rBzo%qxFItFk1c9Yh5NRXjP=0fRE z-M9y%Uah;uy$mPFp!s-+gkl*dOhiMPA z_wR#ahw{Ca^;Wx9n9+;hHq|tM2O#vjJofK_OyBvp=7!O-|`(1e^jW2utR~5W2#?+~?FCz;wKvdlRqS zrdqFl!U9p$KbzmeKvFgwhxfEW+e>3M3fI=$VCNdH99RQJrADa*jHZ=ssTtil-|}77 z>tK#d$#WBo1#crgl+DU61t#&Wagka=LkuldusyknYi3t%xw1TuzR;^zea#g8q3!#) zCnJ$clSYixCg4e-om?=)7`Lm!dg|wjE%`AMql+X1q-#00^df1C}U+EIe*?$Ls~_J z{AaH2wY-fDkDA{V{LyiV@m;Oy8wsie3`7U>0Z@UXaMBwL2lmDQpG_~t@|6Gd05{qMGzY)qvyN0gVIqnw_pd;h_Y*6<=5CAk|xM44T#$$;j%N z7f;9t(j()N*J65G=W}v$x{VfWHunxVtT_RFKOufQlLn-XU}o@k022@tR23sH%IQ=-i*+`w2k+U(~(xFB0Z;WAg~^eX{H9Cy_aJ>iAURVxI;q6K^|j=e6A5 z9zl;%58?fW-9Gng)K*#qaeKoONUz7yZ!ThJeqvmHAH>Eln>M1>lHx>2{FCzRNet3F(m}=l8}GbI)V&sB%()vr31SJ0T}R2%U$Uu%j=`X+Rl^1w;kf z&%~U5Z%{R8zEfkAfT0Qdo-dZ)bu45kA4>dan0Hk)BP*d8cRh5VAA7G~(Cy6?y8_L_j`W3NnW$z;oSJ}pfxIfr zqNCl;*=zKw`G(tjzP$WSs~0l9Sh_j~Z^hB1hmORLIyLZ(ABu^y{~8wo|Isi|gTWzj z5V=s{IZQ^WQCsh_s(y4|y$)HiGZv$CHeT`c+TFMs%6%|G z-O9wpEJ!IKTqP(iOGkN1f60iJOAtm3CLfDT3fvRVSLl?=b;;u!H60eD8{1e>$g$rYJ|0ToG|aWK!ih8?CE3__B8};^ zL1CHQ)?kHiZFCZ1i%R6_r@Wv2dyoAXUkv)Y*x3eMziU|$p;`!v!)6_Ezl|#542{X^ zIMs{!-xG|brM9Npir;V~v=ZpW6~PgIURN{yCMnsp8p3k2_WarP1&qE7wD)x+rHPJs zP+d6+r<3YSBE(TgEGP8CGv?+#(|`vDESINovlU!i8~YD<@@X+WZ6Xf`w>(Xr>#bq7 ziMgCAQ9H8q^(+1O0;iw6FW;c6_{d}D=@QbNTple>p5|L+Z6zh)LuAup^1L_=4yD;J zur?qK;;M@ng@Rj-Siy|cKmW8DnFppyROx>Hoc+XfEU`=a+KojG*4b#sqoBCpyqp?* zHW@g|Go=VO>o%q$B`P?$siQkd*DE<8=)$HJgEG!m0LPI#w-`fTnB|@jkrITDCnnOE zFVilby6&udor`_{jtEX_aBk~Q<#D3Q^4KR(QB#A0@O91zNRX-;mV<}B)}Z!CQrgLm zV)D^+vF31OIhz3z54j_j7F>_s&uAh!J%Cf^!%X?>`Nsw~jr{kNAT~aH`Zu&GS{Uc= zLnwHH-*9-v`l)64DvC@y?)vVFjEa&YL8>F6#tWz~}YjiYf)lEYAOC8lV1 z%w@pCZB%|s9Lh@$2^3QsPfc#cBbsmj2%ModVueM{$d9AuQZ<57DT!(*Q?(l`Ma{?N z@sNbLiaGy5DJ5xv=~)k+B~__gr(A*naf=N^>w4}u5ppDPpb82{P5}KKnF|GDnme9a zy8zm=pYE4qtGn07QoyEl(dC2d2?r^OSL9%706qBPiw;R+qnY4?Fw^-QA0N+bKJ{_c z`+8ix#ux#tDGfYbY24XM))N;K;{mH*e)zo}>oskK5OooLkM%pjdvU$sJ6U|-)t=ye z6io+hKIds-?O#)5r;qd%W-okMnZWhD8%WGlOZPt3WTqNb*_$Z7sACP8j*F`?b5#QX zcILJ0`VVIc=MWygxw~^SHt%9iIwa;p@`)f4DgU`-b0V3I$#eUBV;7W!FaI;??Tk4w zFQmHJE~Se?GIpYe$?LCTsgqjG2oayBo*Km#r^SME^9!CK>k4Ox&^A#y=z)LF*p#s(Jb@4cJ0zZ+b<+Bb z?}mDLJ@*^T-~r3==jkJfc`%EMi{TM0%B)Z3%Zcc5kx2bs9I&ymf3>s_KHr^+C@Epm z($Ol|d&9{QFa8K}ZAZsQ7}L^zRPmk_E;v$YHFvS{CFceKOiG_lJiU&sMyt(MSmm{l zjU+8m#~u~sN*@P%@Rx&wHr;&$GL&|fO3TXno|6rYncuekDi!8IghYpNO&}iM+K)brC(*ICvUB zBraj*{Hvy%koXs4HvMSETr-2VF3}JYiIX=SY@EZ!PW=;&H~e0GbA?AD%>>(JOdb@Q zVxHm`d!@955INX4s605W>&Bwx|ME*nKEIs^^KIUePHvHQ)1KQqXaXM@pBV|$2uy2K zZ|^)i6g&h`i>nwzRdj5B<`&LlKWnfm`krMQC0F3teYkT|I;LvJ3qcj6o=sfexc&h= z=>AmhRS-M0bTUe>=6vdd5Ft;}zt1uGiJcs^e8tS(MnE=#htlmJ>P{zQdqEa>d0f!A z<=To4W>tlJANgseuRlp)YBS;qlP6RiKcnf_LY*!*^e4!_3H>96GT-QE2WeZe7!RRG zlJMc?=jX$tp!9=x`JWw^j1O9Cbpuauxa)jA3-{#4#m46h=|X2WGwbH{{9Gu1lmi7R zE?KrQSkX@EZ`|!=?Qlbc;{wgh_t285FxdMHzXgnkY#bf&gQ~z{O*k~tzTM#jgKC%t zMHTSzz-7>cDVCBniQI}mLJjftgwkUU;#0Jv(5lv+rPf@L=ZAAT)?Xjt7XO8tMrRBQ zTh&fyZ(sQSx0elb`tOAiM*RxW$xw(J_G3^?3Ki|umwI?7qYtz+mOz_aVIt*K|2t|X zfgCyK_GS-@#iRZHI?sUQbW52`?l#=%dgvc9L zX$c5&YQg`rO?{1)l@45MUqz8!IjEKU?oR>mL7tDp=;%E4SG#*9bw+APf1YK&8e3a= z*Irp?#eD0Wyn`5sGj+jI=Q&@V=qKHrh;2OL$WxGdfv4n`qvSbzersR&W z^;n7p%|#^K-jX(+oLGauR{fWU%MkKf(odg0J!}J+6tq{>WwmXKdlM56^)u-FbL_~RQp0IOIz2v6_>M-EU27nq!>ag224>@H{dK5+5L4>Esobj<#?G&^r~ zA*1bfj`%ZkxW9E$zPsZzTR47|c3j@dN~=@=`*rYzz=?DtsKRFutO+4T4Ta`RN6GX; zh091xVYk54^*ZI~8yvKnSUYv4;NrsLb35y6-0%hJw7Py0653GaIFJToi**kW$<6r& z8Mv?o&RO

a~a10r*i(wnsprjt1)>4_Z)RTB|(Xy+(!t(yF6Y$Iz*DtdQL-6g)zj zw?#vo94Z`ZPmi$;neW3VQtyjzU@(Hh#PVlmMxgRIl?W%vlf>%tex>4@FBi-XpBP#@ zU9Q7R7rkg_txUOpQUmFQWok6D9AcL3U-xu|5zO0Hl)slyhB1%n&4*b1`N;>)DtGMn z@_@wO5cFjPdh4^?(RX=b=03Uc3pC{*=qq)%;QVb0LU?jZl{dBv5 z2pqbLVd`xCjhNB6Bo@@u)~F=v1$HA1F*>Hy{rb4wbJed`4yY!gM zK8X3*4Fx?0>Hdi^UC={zuP+8hQ354#arteX&&{+%QAx=^BxTstlmc6xyQGZFPm*K} zLi8P1_ko2c{=-{>+bmhFY95-hw28tY$^C_)F=F@m{g-j~lo)!^tI(7s5_OM{4>^BR zF*b;nTmH^{piFQ*wUP95HH7k~4xb~6PuxizrI+Xm>a4n}Ra{L6wl{V=e>IewknbFp ziJ&_wuUN)d)RAV3lJ+MXbb4s+?CfCR;e{R@iFZ>|QW8r<`vOZw3}a+hI0aZ-u8gAQ zvLYZ8g>$G{CiiF2zuoqU6yUcuZv+i}iO-Hxuu3VU1vHb?s!w-}D%=oy^3Z-q0@oY5 z#r8dD6##Y*DP}adkz+Q!jNVBo7}W@6u*&KmE+YZgp};j;31b!ZKfDE7w+rtmp}jdH z9CUO@@6Vm@z<-b!xBJCMOP?Tay^@lWD)8j7OuHFVLqp?Wt`rZfdlPv5r)062BAZTT zMcp2AeY83kcRq6?u#RTVHZx_-CYy^dvS6L_HM`Di27H)+U~MgMkOQ6dR|jsmTQ9SQ z;8(B(mbD}(?-l>fT#I&0Mlump&5(#D?q1OIivoL&C>R-|ck(A2Y*wm#o?Ry|KhKd& zjf`W-j$7-E9zt(?1+&5-i@U72DKAd&kNgqpcqR+x*8=*oU(-iJO?@?|Z9UCs3B@b&?9b z-eA35#`x(E#eS-JYii==znz6z^?g2F>^L*g=0BENTIDY#S5D%n0qS^KLvE}c2Dy9ZxfT%uQ3BRo$q;0k>4FxxD%ga4p%3X4%l zan;Dtiuo6qj_di1n!*@6gA=#ACsBqu0mI{8BqHaME6U!CxfDS6N3Ifhdwbn6t%lz;z|xWcoJP^jd7wbn}E4o5TV;W+-BE_(df#8}{R; z`azl-B9DI*oEW5}XG^(vY2e@kutG;=M!nt==d9z|R++qz$;8A2?1SU0vY4S#-I&S| zaX8FR-d;RoQc$uNod7i=zYnecZ{qapfN)6C_0A6B(xx z?j`#|rw3RW`%O7UEx53yWv0*&OHeK#F_TpYf{3zgVPfPd_H@*INEl`rpMxK2v;q^mu1) zz>31dH}fm|N@qAG*<@BsE7^E{q9S22oFeY<(4ZR=(}ULgp%L^DLSzeWm=|kIfS|{W zjygHH!66JM7)*3Ls3@Z^KK-IfyRnU!7UG?++A2 zN=iBf>F#c%OOWnP>F(|>=`QK+?rx;JySw3TzQ=QZcjn&zUL8ipXYY4CYkg`F-OvU! zbnIyfI!CfUbheaUj9Rz(Cn;7+PE!xX&4y|k{OmwS>~EP3(^;r8aC$na2L*|aj;?qJ zq6NC{JoU$*yT(+y&kWzCzKe=(ape@PEEm3L&|i;2wu5o@TDbDlSolW`cD`Z9!3;*(7RmU(xq2vT6* zY+clb>n}wro+cH`mR6tu)icVLCe`wCyQJLWL@z5VJ5g;UZFleo9C+C==(IsnrAXfm zfRU}>uu04(PI7VvCdvkd8zo<+$cmJSS`}L>h59dfA!t>tj(s{827(fi6ysEF`PluX+EgbO2MYPHlMiu9y<5d<%rCJN5by)SO zhMw`;R&r2b*IGG05{q5RTdS5TCIND$9GW(8Xy~6+#)ju1E+qbv3s!Dg05W>DWwpte zb^&)eH6lZww?;q;c4$gzz1hK6CnTN~gFGW3?TQ?LX8M!? zaFT>=Pp6#k-d}@u{XwL-3Fk>6^iGp%eBLKgJ6yU_nI!oU@A~7*6NA>vFq@PGL!IP7 zGq0)4I5E2+a+VmatTr8@lmXwPGOW*t^iy^`%C52>XXIHMbNXuU_ ztR5_4@1M^7I*M7^C{)xYT1ZWt{BtIR1~5i?8jt-EJm=e)?!(a4El-CkU2L0^7pJBu zhj>Wn`2XQeWEmgpBP`(0`rh z5aMYCyai<7fLEQEIFn_JCoN|2LLfBo)8X^_Nk*nbN0BqM#aqgm8BSPk(VLj-}Ke?VCV|pf3?6ea%lNVSNkAG{QVZA|GOuB^MinoLC?aHnN-AnUU4=<;)B}Ns}d|j z2JcJnNM7}$bI^5Cxj#y%rSL3^Ci7PG4RuHfv+|epaM~_U0U%G@D7TMdOe&27pNRxyo|J>AYAlKhuu zyvEWvi~p=N*%udm4+Z8_iznc2WOlE!SfN1X0L_%kmzwunhiOoUt581Sk(j*}|1+Ol z2d!zJucez0(RMK$;`!^wA3G?uO0)0B{DhYPGxL3E9U6_;TeBa1!0pKrAvgCIF)=Yw zadCcQ(^H(2k_mE$=a&wDqYHc1#VT0e6KMTl>PSZ9;fm);C3iI6en4JyfTZ3o2?ymS%d zvv>rjhRl}*sBRm)?6W)g^=6jk!2(@+(S>08=)y>ThDXS|oMSDG(g?$-2x8M>fU z;q8MjHj)F|r^;@bpt)>Ey&oD345o`ZRvHZaM4{dlM#2${q$}Vg*Gc12rq^pCR?~Ph zZ25e9cvSOHAZM>-Sz*C?GdJix@OoZtRxi%35wyqi z(Khd2q=g^}eDkb8wpw-oxm@s09-8k28A#uSc%wb0#}vHOn8VEoB?xn!iL{J zF&u8`K#QN`8fRc;N!P^7T2Ub%W)`Gk6qu36_%9e|vx6so;m-f{zlyN=!S}zj4T`if z$i{}#_z*sIxkN6r|YCxpw# zObwGY9>7b02FB`UMoDkFK&C>qw92D?DO?24U7o~;xW}<)e)7tW;Tmb6uC{4kLGtm7 z#6dB#nur%_`7WStbf$M^af?OC$|-fq1O;5$-8(jgW+x7uq&}&gzL11GJh+6y zVI51B?cw3rtXPjs$Vf=pCbrGk8PEV=s(_dInG1C$jSCUEq|rnUIN3iE3jBG}?T_D= zjOAqQBxkV-@onPS((Zp}e`v(|U}R^Aw<9Bk*wAyO8u5d)o=_ zu-WpPX$M1WJ>+ga910;GOyC7WXZz`Q}}le1!hxOSoxSBZTMU zR7O-xOg5(Hdy>k9$k}ZEdqefz1C}MlHzoKWF6*d7fUzyR+)gHtZslDl+E6(d2ikXK}a_c z6vV5jh$604RA}RSvRx*jSWzx~k!@s2DZ_w88bxqUG_hxT>x)XBVHmGSuNFYwW{E^CeXX z`PdBMv5ONn>tmx-u1YY4xW1*b4L!PJTER3%@G4C3W{DsG3wH4vL>E_y{sXNjg5^I8Sq~?Fbp*m6$9R0@7e<#xEAXz z%T0y{2fb%b`Hb~j?zm@|@HKn$WRK-*T_3aB!>L79F6NnT9xQa!6s)oAnRjrP$U=Jw zCz^?%n*j``yyz3n*lg?QhdqFm4+T&#g|~$~t#*(1TL#ztTE=Xl3OvK(k-Y8kkTUL` z8kFs`tPdDIu`-T5NP=R%uB<(UYGZ8sb|!6n@T}G0j22eEam~3_&6Ud|>1PO4^hKn& zcxu(wLgroV|8x+Y|9N}C{h9Xfu$zf4 zVKEP$FL10I5vhpwW3jGl4tYe@XCl-WiphDSN|d8KbvbIF0!e*&QkhL(wg%zn&-siS z=LL)t1<%5fxZw$!F2Tt3R>1W~)293a)t)0#{W&e_({5pvkS%+j^vrMc8O1s*-Tdk4 zQc?#BN?rr9MI?6qewXl=53dVPDH7Qz@-{9N;65nLburY`Lst@1fD zyZHA8u2pHC@%NIJZr(vf_1hV>8Iw?C2|{>X1wod>L{(!@uPlK;-P7g9fsv7q$jbz? z00|C^27;QJ>G{+g6wnD8k3m+jI(D04F@8SJU~F#t*f{Lha6`jV;ErYs$`+~QBV9>d zRL4*D#8hb5i@CQVs`Zome{8t`FB@Dj_lpbTzCy=gaB9ni`w~X?!4{{!`{2*;_VVb& zMTF)%x6r004mOFQwe~?1BJ4oF|QBpR4T`fejzDamFo?%OO@09Ud z%lY#sD07F24ddItg9q4umHqQ-_YOJIvbhg-EpZVO*v|0|5se{)<^!hLq4CD`!Lb)aS0AM=MTWxXPUu$naum>oO??^WWe(`(6{&69C(Oovk3NJWbb`_)<7*5$Fmq1$?ew4R#q2`Q z>@O{>vE{%NDMWhb^jN|IxhdxY3Zm+W8?fcdx(;9#9RNnCPro~s77EmCzAs#S@16>U zrM_@%fPw^mj$~Mi#0g8@k)l_MShMmMt^VO5Cy%>$*417WgFGwKz$j*SiAuHA+sj=J z(4Ap@8+VWS^^4wem1`u072!Q-3IHl9JziW?;_^eql(9W@(aGdGDbHO4NSrUvn&qNUyPUX@);E5P{UO-vH*ql_Rfir#VPJ~`m*nHORKT*52e8e z-Fg+eOk1u1d+8pb739ercUUU4wWX`JkkGS%(G#S@Gz%PF4SzlGxcMtJatFf%ZBHq7 z;4f#KER?_i(-7b6D_oF-WOqk2D`Dv#TdzZL6ZzGJ5~k7NjeJPzO>G<*=LzcG=F*K{ zudeUMOo2Wpv$tpG64hF9V!H@DUR?Lb>rS8@2Pf5$G&BSjhG1r!Xtla9<806yFWG-| zq-l$b*Vfg|7azE;r7u{VKBA>Lx45AcixJ;G{_`8=U3CbH%_7M>ewFlI1@N+XZ`zk;k24VI(!2p z=zVrC#6R=r*D3r*l zZl$u-!%o6hS@S7>f5aDsm+Vvy`%l$IEqN}rmq*<-Q^DasO3*CmC;ai`?C!6;7TL@wV&Q5I2XPalAGT8({BS*qAb zRy5d~oUr4OK`;$T=`}Yyxweh`W1h z$@nLjvZ8$-O3Eg(T&BUj@m;is!FVQ@*z`w$*pi(WGwk177^D`m{ZqeHZ)+RlZ{Y6Of9Xo#T?`}2VA@5zZPX+b48O7o@-=8luN+kM4uT?avgG7j z%qvsb^Z>=14{!XRx&<3cQTp`ol?Vb;xLDu~g!Oz{T6@Ra6f!V@W3y=7K|5Y z59_=MFZvnUEdJC%qr&9R0sN{3UDb~18o4{sm@1`iDaJcKf2o(sF}y6~40T^=qojW~ zA&xQs*CF#M2VnMt+MV~aT4nt*3Iy?&+M?)Qhsu6-@EWARuRW>hN2-SD;(&ok+l;H; z^fA^O?vEBZ2i!CbU)N-rnVC@|xh|oAV6=kE%Rr+HceLSn>MNY3ldOiHx2C`Zd!?U8 zYS%=B9uiU&o#6@M`~VpRJf@J)NP(DXwa&vy9(p8!l%7!?Zq;s``hnrHOs7#~4!B-v z!VNhZmsw7Y`HCx)Rn-jt?naZ1alnC*NncN>w{J#Ag6`KykbgJvV<7g1F+FHdc(>-uB~-Lmb0Bs=Fpt@c$$x!r^Ny~R%Dp?(7oz_qt_D$xI$y*%2U zy53%4D1N-P2pvHTo-Q}htE5mKk=Ans)pk$OF==}Kvxy!3FP*0D_up{t6_<#p2AS%O z_ts`ABNI)2a{p>5Slb~e^h<5~6I5FEW=_F?sRxz&#jNr^tfZSg11nnJaaTYEGJ`8{ zlPy^^!(Hu-2X=4p(E&*7mv?!B%F=W&LbhYMgn`Oqh#hL25SxM(M*b)GEq&k~+dc80 zQZX`7htU%?MfQEwK$>iqAb_x!;9t5Q$kY6N57p@amnA1VKkzIRK`d&aeYGm*bP`I) z7A04fEd4~&9qs(^0gydmVb}OcWgwp{mCr%$2W5rT*O4s4a^g<9d2} z*7H&sRBE`(Js?X)64IqF{uU6ZNPe|DEeBJYWM^sc?O$1QTP!I%imm)eovUxl$Aaj7B z(%tOkCQLa~*fmjC^sD>t^r6H4eLSiE`SD@A5a`WgKMosux{cFjO+}Wfy;MED_>F02 zAaG|*sY{tes_ypuD)s1!h~mEoCSad;w*7qw^AU1zV0jO;lUGo1UWB+#3Xteu+iGmo zP*Mv2<5 z+eBd_Ds}njowDGynHzxPR~|2IIT?)N%g=BaV2ae6L`syqV@{SX7W+wQWhwIzg5g&m zjOJBx0GhQ5hl>?9=WUU&lowdl+S4%FSNGEXGQG7y4C|e#)dg`2oTVF7_?H%>-bP3n zjrd5G(k1PiLxm!vpDc2!sv!U-vzcPq)(J4lKh)J>#bUH8l|SR*MYg#=5il|$CnY5X zg#lp6!0>Q)IP0q4pG)zuj3=!gBIo*=IO!D;ziDL78^5u>U>n_>LL0eq>D6}UUcG_E z>M^})y93$l{YfzDZ$Lb3+w-Nw`^eh7 zE2MCe`i!K-e8P4_`ql1mho)(aKr|{~w6DmVWaZyBANIdCA0%F8pZs|)+V(#2A*kS4F6)b5#bAHNZ|?S^HkM^9N4LDF7>_0~BM z2!T&R0@3-d!~Y+g6BoDhQ$p&{M@23}aJ3L@U~nlEcn7SS=$5Y0YT%pUR^-(138@iV zIf)4fsX+?|M;mR4IO8x5t~ki}^ON+d=;sO*s-haY_&6@yd|L&e+p0Faa|<}Bo<9y?$z8%e$>iA6^2m;Rppwo3~RpCx-ZEURiTR5W= z5(1-HsRUEX2xF1q+U7C+iliXcf6bMBJ2>bY59;3Nm@QS)sZ@5Fx=sPAZOiSV>HTr_ z_zyKT)5UhZ{)l&zR$nAu>DHVU$yQITg( zN~RsMD0UftCAI&t!&Swyopbj>65(id=sa^NZ$cRH@@_xngJLnPJ(I7R}2 z_uXZ&M3J+rTUSO#rC_VDPge&hl%ZiYMEZ8(f@e}<`?Fc7W{Un8M1__c!)>sJk<9eJgZR4L2=io_iExVfPPX(LHfXchV z2o)-R4*PhNK)aPcj-IX2jM8#B#1H6GK{_`91hrQ$@`bj@)P(-J$SCTMY03DA!7o%K zPQX>t3y6x5qZI6$R-~Tq4rHvFu|PmDF)^LaTJNTRUH{tL)CEK;w#t>d;OaC=KXm*0 z`gFVepc_t`j(k*KsD}WhX<$FDtK_W1Thc3r=F;PFkUIo_{;G1DLUfZuk!Fti3yM}2 zH>rixd)wy*mp1{u{#MqR@0jvmOG50Cp_TC$!Sne9c4S*8{Hcvpx&@XAnObIY%}FzK zy%#1Rt!ZW%6Dgd+Nak8IZonBBCEq)J2IeM2ATQTxH_1pJ*n|gANBjgvvg#jQ9HoSX z^NFrcWBoLLiUq;Kc&kSEwuE;oAIrDSn#u*mNSfg0URa9p>pd`@DSsf^z4Px2^5khZ%3aiT4qG{GfNESp^>zMqIY4 zL}V15V3n5Z{}9?J#_euNu6jh8yEUf=1(^owHMhS%q^^$OD>|!7txk+zaEqRQ+;Gz3O^xI-RTT1VcmYv^Ei1o&x=l5EQ6~A z6mxOxD^X*fxaa#e`Be4;M0U_jV0OTY-?eI9dA~8=HFT0?PX&4I{ zblYFwTSS^Pcqk^-tSLpU$vr4|Tw{B=7Qq{@wI`6DE%)TMUw);u(SKnxBBeqDbSnKo zvJC^WA9wT*n8bty6eN(ur>`wT>UHe8&K38hB>YL zSk0G)3-@E)7USGiXHo;}%Dd+9xcn&3G`#(8Te;kuSzjQV+i!VDE7yA339*hL% zTkElh^ct``|EU%O{WWnS*(chKd40#BI9f*KhQDw8q9d@n>QkMw6teDVG@qrHzNZjKFpv zSZoXU&-B0R|4P;Bvs+r!2WSbXKDsy8e0#Gnr_WT&sleQ=pe(7eaFs}<5zEP#qxou= z>;z#XCPbaxbyA^%(a!?XDOcB8`h0V`CT?{^$(!9Y=1Q}a2iMng^oCIK^GN4+i;?ht zEQovp`etjpbWbL6!$Bq(W5>|D-(W)jq4W*A~y#^Yz%}rh!puG`rzoA88J|lgA z#&4BoI7xjH0S=jm7&&JD>cy=u_0Bz`K9!MCW}J20)#@V6w9@(J3kH)Ri6M=Pto>=Z zmgh&2`gU)LQ}ysy!Z9!e?Ke`-{yNqSKA)9$RXDICI5r_6r?L`pVPWCj>vcY?^@?O} zZfzonn}%B zE0{k4fir(=dHihU|Kn}0{S_5m!wyl`dyB0F5QaNF9^?a_0%CJ2FP|R4Fh>rZaNW?u z^`=&?$f{e1R5MGF!r|XZ7fC?-3fv+uB~atp*#sjQym*?HqR(%29t?SQe!0%|13WXh zi%8P4vnXjAsEH=lCX_M}pVRhX+w+vmWMH$A4e1VG&J{IaHU7$9G(QCY6&CS~L8#M* zLO%Vx7q#Cc=lHEzN~ufD0gA4Lzu211_{VlGg_2-$&@VL9;yaGha>^@sL^A)9l2j4{ zIM9#y4ice`u!`RTZ18VS%VRGRiIRK$w@Oc<)qak*>Wi}o5D3*i6W&W z39=gx9tQ`9Hbatj{nEyT)5Pj(grDC>qP$yyb{R%`<4vwyxa7=N-o6$m)JsPA+Ty+e z9#xkr#*%%M0EIfpy$6@AEw-j7>a16w;|}`yvR?-3(FgnV;$Y5Pn_MsDs`p}i-X zH%BjA&4}*GIu;xgbD`4y9IRhSNx^HcxApHN*oP$yM}%>nC#rP!Ta~QT)B4TEL(GbE z-2*(Mh5W^wqii|L@0GnmBxtUhb`*OdA90_h%lbK&vX6!T;XJPi_A&o@+T3xw2hM#& zBF|YPbJ|;%Z9S#Y4@Oqd(KBr4WD6dxqa)DWm-GB&gSREc#k&BxBzoocHXA&kB=eO9-wnP70@M(sNdm-1`0cryM`%sCX{h{3-jDs1>M3Cp zPO!0;+zhJN(h~h)HaO{f7l62a3sB4ps;Q;qj+)S|laiBT7}mqsPeOfX#sD#l@5RVR z)=QO=cjme;D}*+nN!YGZ07@>kXq4iK8XM+RJ+HlJlTHL0?)Ed1<# z0C#5dbi*B^9S{%}4^vZwm|C{;H_DZjvm1ewyC5Kk%r*K!^Qn)Dh;Id#*X?xz83tQz zMfv5Fhlm)!dK;Z(FNiS(>I8$IVaKpb5JG0O!{i+_d2Q)#IwkB)}v zuaZeWieZK)u7lz%Jg^{5J?fp$PuvzVliqC%E8%?{4;*tozi(ta?;TF$Fv5(f4j>~U zL0BKCFZaE2r8~H6R#*bnzH=QX(3@}yOZMP)0tsFqB(hGwMLTvmb5?g7)BqjCG(j#` z$LAu9O-nwZ|NMPT+e}R^?nl2hPCSi9$ouFoDj@;G`L1U@ZGZEap&I+ff^C@hyR)x~ z9_IT`|3?fJfM*;Z5e#1n*P!UKoh#F5xE!LiUNW!W0AzT8IVIeM+9gqvgzNQw3y5Aq zA-Y(KKpJt_Ay}{sK2o3j{AhA?)L9lfzbfK3#uno|pZJCy@=tHJ|0QbwpZ0oxi*Ehu zp<%eOEHWP_i`7`c-h~H-2~GFx%kcqZAfqrkMObM8Q`5u;TDAaRZ=+}s1n2d(&A(UkkI2l`P0AtSTbW%Ha-ixl~wZ%3%f2|Kmlg#k}U3$1bb`nfS zdjVrydMD5E2ZzZgX}H2cftovGI!Z?6{FvW`WCFxf$g(QX+S{3Su%`)O?!EY83UkX5 zMw(0hlfF}QWRzk=%sX93*?NU7VWJKJG@o%b+2CEp4`o!=XiBzvHpb5vOxt_?d0k;4 za@zJ~rr>&ASG&)}t~%*p-FOh-JuZ;o-7ci9UMFlnBQrwy>Pgb6Apf8{QXH*+?wEb+ zPQ+yGG_EQd+qr4@@woDoXn#~)bvxlzHmeHaMa?czIci~?vM|vbH_*q%h8hfIa36&n zSyawa7LT=&xW$G8piclfO#YsGp>98;pzVLA5ELJeR-)O8^>*LSi?Sq=qJp;fJ6Bu& z<9NTkh8l{jJWkTjN^L1ak|J(gHx;Eoipi#D4_+Yh$rq@zu+rQ&C;*a*ae)&}=X|L@ zlEes^!fFWtQp3no;)vT#i+xiq8iyBIor%1~Ae76VI2ra?XPiwly9|CNju-9k8Z{Tl z);kO2e~@@Y#3O43Xs;IKM}}2QMFxa#1+i>a3!aR8- zy~_OcF6@k6HA;()5+P~b`CMloX*46#*$f^ZCA@Z&P}~=!h#FAu)hq|Pj$n7Z&FZ&i zNLJof^pbD4ZsQ$`i&zwur}cZAP5o^?jP75jq1;ioopZ8GApT$oW6@|P39DtsBzQXd zes7^tY-DjxDbGQr<)vqozkQfkT%?Ev)J5UHB@#CCd0)su)&V=ge2X(9fPe%7ugJh) zt*W(-DpsoS!J1INoUt$iJi@xMDP>z>dEoF_LJcM?#Jiv#z|wsuG1}YLc$_bZ0P78$ z^m|Hxk=qD#|H{kZv> z{{mR69}NDcTwd#F_A(p7Yu+^9%KTyU1kER5e}ZVGY?gDS!|nKH`-P__qen_2j);*F z?H!-=-?nR1f6vN0Kl6N3vvpOCH?ZpL*=W!;1f@yklD%#DE__KyvF-TEjI9tstTxI( zVb4{Q(TS;CvHg(Z&2cf?$S<6C%=S5Xvu0ywO~c<{+&$<_qG)n*kSZazTDwm}McO!yFjNF=iOV_~RiblDn0s;;j567QFpwHl4?>{%wy#GVumxTe=kj zB1gp~PGPmWFIo1SE0P5Sdp_BW_eRAvS22 z{DjM42i1PxOWRe}IYP%q%Z!?X1HYrXiO)ocbqVW6@vt=z?SN6OqPy?W`Zr zGM%5)ujv9t1_0~L=rf+A2gD1@HpA5SPit@RAnP4l_9FDB=82igda(SZB0=1ojIZ2d zuR)0P*Nh`fV_malFT>G)3pc&!e-Ex@9Rd@idm)M10d?-`gIp4K;TOz@#0ydny}C*s zH#5#)gp>Rq7G`j3_#c2)(gV0}U<}IVLgBDk)`9vgC?Mc#k^vNG4~GkVl(F=%5frl3<))X1+0dZJPVy|d;$UG8KLi~{9fikGk zptcil>k$YrLqmP-f^KhVQx|{@d}CAM)z0gV(YYOvN8e-hj`_J$A=S+g%sf&L;w=)4MHTO1FYNcWa!VIKY=Ol z{K2iDyu81-ye))Utq#h)tnJYxH$UHZ&-uNFD^@J!7ZUP6yx$7g+uWrb>lfOK2pBYu zDvO^~b!U38ye!j=&L?FC>*xCF44+@LEx4~7Q&@=4We-joX*E9Ca_JMD$dbqV`sB&e zHz{{x?9fGYTj=R-I-uH&90=Mc>*tru@Eb$1t+3c37il*^Q%xwLj0ru*bgjL{t8&1y~3T zn$PY@t;H0P+d7D{;59W;d8T4S?$@9>HZ$h?H3Xy$Q*~B#hEOjYW+tsPdS9mIH{9^utXNbtCCn@=IEAuPdZ1JE}kgk*d zZxZbjKp5;W?9p;L37T4H*zq>LGuMM*|`(?`d%f8P?NV*2{s3DQss7{rx~(UIvYtOcB(eP^m*vc-WsM0|5sle=7=&pn)RfD!!6)WiK^IqCJC7=rs$LnlT zh@P*08x2nZ3mB{f_s;^%o#edO!mX;I%60j1T(*qLvkMU{G)c+cAlAFNo9xM($mr!M zpxspsJC`5S9Zo+lzqMy%7nHzzssiuiDu;%{s%l84>EU{3*QE0Ko~n~uYQ^mcD0l&T zEgo07+u06AxNt=YDB)NuuH4=#BuNExsgsbAc)LKm&fb1R_e1Ns>k6I9mnLh79L&@; zY~|vb?=3s#;ubtHKrG~anIrwirIw=@6y^RmHQ+lGGG-PkbU#)JVq?y-y=cbos`WY9 zL@&rxm@{plO8NXXiP8An#s3j77GMEz6fk>)*^wv!i8${;67McmzP+;rYG_iKc?KrQ z@qvTJ@eO^!36o^`lnwh^zYS#0!Dq>(^JHMaS zjIbZeF{W!kJ%R8A1yT{Z0p(FtMn*Y<56@Z4RfLrpLlPir4hAxPg%DXyMBz_0xFDzc z5abY(CCM0N`KVZPT0Xe|p~dyts8#fsDwtVY>qy(KiJ$c7|4egqMw$#tOg8@H5s_oV zl;Ks;@H(FUSmJI>qxo?D`StcuY8yecH+vyRJ}??76dvjZGd9T!n+7NB?J1XNqNiJ5 ztb_TkHBe5Zjqj%LY*OC!!wEI>`m-j6B+EQ9V{|MJ1}0cPq3eLWTl0hE02Y@@RH{vK zk+k-7jp?=02%Y!wM5emJTT5aIyp#Iq;#N@8u9g$>t%audWVMCw0@flt+a~PLsoe0j;4&X+h zc-H9`xs_9%VEAYzNXhlIkkY!5vv6gq-SIV^_f7Y*Nr(P#{F920AnE@`1VOw2$jc@* z%G-eB{!^h92?$Ie&L52JoP1Q$E+9II2stQ=#Qzd8asv5mLJv0XEfEb}r zm#m<#F|-I&d@KeznJ{%oI#^$9T1;PwJor8>*5i&FHy-7UmW9IW8JQ>K@S0`pq z55EO2W?Azmwhu?*i`nYnzB3bJup591OR9Y4z!&C_JHO8s@|@K0&(A?MOgk|I^)d*r zAj<8S$!!m}knQ`*q>!-R_Yu>%li+yik}JZa7GBS24N(RU8Yo5b+L(&6yS*{ouLEbN7M#GVJCKD9IJ^&u4VmhZI zEl(ZI4Q~bG$&s==Dj+2<_IEc+n z!cUY_l>N+S8HW%tApnyH`zzqd=QQlZ+y*4U{{36tQwJZ1#fd)+Gc?>*T~%D~4sTRI z)_3cF9o&@%HiMZ-4;~sA)JoSbD%KE0lk01T5F;S?7t1>hXF|n|j|MIJDujg)p}-aV zO2cFX1x-pa>(@GM`K*gcu2HUvT8^BD&jn^4>_B+hVuq3K!gx(JtAWQ8=-hsf{uSA@ zQd>-vUqnrBp3O*=2CF#Ys4sUrOz>iC3|4=%7}x16oCKzC?3Ml2vjK}RpVn_M=Iiwl z61TBAid=OGKUDyCJDu!x$){1WISYN2k-@RPN4flo-J=l;YHI4<_s|C*|5T8(*$>E) z{ATx|WAFA;n0@|cO(op#JhW8$rXL1YS)CK!ihYpiNB+F$5g46agGuY_qXXwElWTi? zW#bWC(gaj3E_t?5)ubP4jSl@8WQCs<2S8%~I?*Qs@&ElK;*5}>mh2s-{PZ?)g}=qB zcTCu83il-p!IDGb+=8FHCF~M2ST0Yp^KxgH-g>i#X1w=`3%FOn0=q$lNpJ$-M*8s1 z+90;BAVc*@2)QA07t)G+enER$qb#+W=$jLev1cWD6{Z7N8y(o>ZS|$ups{69Kf%`> zB)OdLa;ld@H2m#QPa%uwnsgvXJiOkQO=FUcO+y5+ZtdU#edCkLdfWQ&7=a-8t)k*ooXy|R1aSGC zKHxBPZujTPB7MMc5C*g(OstL;;m^NokvOZ0C&nIgutl$p^})uq3s|AImJ1V?qrE#d zYe#kmJl3uuFbmZM{E9=q9-F1%A#AsJaei;_SOW^qUu=I>c6pV9`c1BH+eXeJ^q@IT#;_Xa)8YnS+KXcvXDKgpY{vGQRD-HPK~P9V-t|pbjhf z4TTJUDR-nt3dYFG$PQMjlOQ55=dQ~wchiu$-f>P0r}AKwrU-WMtU>ay4D4eU8f$>D z6n;s{S%2nPY4FxF+K{}UshLfHvFGQv^r`{XTNlOlidn%{=!a^ZO4~D_Q?=?0_w39n zHI=b0p((@BqR$_q% zfvs4gr=XXCx_fZD-@<#t7#v7erb1J*e zAI8;-*KTgZi*ZY-(q`a$9LbF3GDo_dM3;!Pk(4?Ugu~1xBqv|YO}EY;lL-VK_W>)G z`v3fvxB%1{x_|;F2okVQzH1pP9nUny+!a-k(%tvbs8Tt z%{+$Y5+kF;hm8aT36a?48c@}@>kTHu;tFOklcPp%Ffi<>1hZmYuZ zg)x)>OPWAP-#dQ^ET%W<`%Z^35@J87v?Yn>HM=Osc7MQ2Z+ECbmu#L~d1zn{U8EF2 z7C(oPkkA`^?!0Jy-0bLQ6VvJCK{AD)XnZ)iX4u`iYk2=*?qa%74#35!0Le7c;7E}b zP9U(4G%(zj4F~W+2-?^%00OS4s3?%~IhYJ-t=;-c9-KO+bpa9fAxUb{yQQez$d`re z*0{34fzyN<2)ZLJ0U4osX~BP*&Ym>9(~RqXV&Tud2h3pJ>OmihKBfC?g7#6|H7k7OTWu{ zZm{QE?75=jPwJotQznJM9>PFS*kAHwUBSMfWaOwr6^U{Pr75ppV4Y0t6PiZa9T&_J zo1Vqr*q`Avhhkd|+cx_-4(eNLcmAo@`7R2I(aVY9ITIEkDvd^gE>` zAQ&p^%d|!hTolwI$e0Uu2NF z8Xi8cszDtK35VqeH2a^?LWK~qp@A#oT_eF(#+b9JTe)5}Oe65^8>nyuPB17KM5gE4 zD;?HM1}v}{Ea1-{SsYFW*mwB=uoTH^djL^~i&+?0tx<0OnWSNgQ>bmCi}F>xGBgwgqT!LF<;CGYvJy9d;olLS%zvOAqr;%` z_Kan+(B`ViNGN~N#qQDZ*M68_%W2*8dSy)-n{lDiazPrfHCVA+GaOLJVZu`fBZ67B zTtEPd3wR*oVY-saSBs|QV|()vmNK+nJbzY=`gcP;qUS>@^>AOEeUsOiF26yu!wDHp)OFQ{^c`C{(So7r{Z+ zpK4BG?&zDMKWdUV=LrjgleLAD#BgED?q5QMTe!n#WV zYlO9HP(*jwG!2f_0H^{6W7s_-AHFPu9;BE{gFSQD!yqT;b9i&2iw%-E!h-X-%X|LB z4Z^|djH^@a-xg>+FcE8{7;r*~O*#uZI`R2XuORwoZFa+N@RQdu$@{!K5}?kdx}G-5 zj9_%>R%!$IWGD-#Rn zOVbG}`-{&06yxCT%qNEIzKN^76Ghu!NF-cl4swfleuZy&1U4urXgPmuB&6};rUy$l z9+ZLuBZo_7DEIkxNHJnzd8hi>P9H#Flets!Ea>HV< zm#chAqWo+aJl}!snZ+&2Z@xRoki3Gfre8ohAhkOR*Odn+J_oGVi+Q9lYocltO^{(K~ ziYh5{9MpvcN&{o*a#|)4aUaA{8rn8mm?1*k8>0yA`&>$Uzr29$Ka7!CT10=KATZbr zNpK2ZCY^TKAi|Q!;ZX;088D#>+2`vv?h1G+(Z!N{qoYzwqddgDNl{Y~C8RXl{GbF$ z%5PAEHGI-(79s%n86<5jFItf@EQGsf>nqdDqX;<@W{-&RP(NaZR?MIuL^-;>x1@c> zcp$*U1F{L;E(LLNpan+Pa>I`W+~N^B-2uH!@u@%uCYb^(wm_#91`H{HlP3cB%7{sZ zXMw4mpt6~p38d2^I!L*vEaO2$d%|x@USN~Cu)cQxP3T*J`%g_FjxW3dt}R;fl7pOP zV!eXTF|*kuV0SpuJ#f@4ZD%3Q<{d}=G}+}sT>5UUUaU2hQC7ydvfZfx;6*3EudjzDV8w4aJq`Rea0Ed?DmJkG_lx`WirCYi?M;fF- zq`Rg2+q`zuAhE4{&#ow3ubth*ns+sP`#S6_m`SnI2c24J?}S>?S3-{b?&bEQ&$~ z5I+IhG{R+K|3}QU=`fIN29R_Exm7s@u(2*nE@QwQ@i8IqF@xpt$^a~RpovZpQjr?X z_MvO`?igfTiW&La60AER3mdaz-=_v=0+G!>{@dd+H?RLLz9ehV*eoY>>v_TA#u=xO zM(!T04I0^w2`;eECiw8nou0>T&L6O!fO&Cyw^0DZ9ZHewEo!;Dy^~&}Gl~N-=y>Fp zpQu?c25Dfrvbw)l5=4(yKrBZ%JGYrcV10s%gs8&b(7}P?>XUvC1QRJ^^_r-yW;`!b zuk}i{saEW$q2dzt^_H={f!z{?DGYK9w6KpG81bI2u3nd90&^rZE_%_V%N*3X!N!sl z5RmMyC~Cs(%AwZf7GXKPS;&gJ85>{xHUQ%5ZUzOmTp+Q|9i3=9Kxi4pXVa1FrU16aF9fZr5D?e{Yd zG9LbZ2cM0)nPdl&<~a*$)N5$?9@y>r9pnEB*I*H}fA=gJ#SMJtir9x=WOpwX-Rvwp z-8fu$Tg%hpCpI@WjPI_`+_o}<40&Yk$!cYn|GRg&Lk>RA+(;oo6Uf4=2g8hZaWQ4 z^XPn2RyN$Y#(^iaq1@NK_9AnWtWodTf>zF%8ET+THhmLUhB1zD3=EqldRP3k1 z*NbX@U>nK3e<%1&IcKME*Hpp`mh;-8)p-NAW_yP0>r@AvbKG-QE_2xN`1tcKhgUY8kS;Zm1;6{lG3eD0%Ot{cN0vN zi@L?h2W(DNaTAQL9fU>?G;5h8i?&)+@Kbb7`fiH)h8_0P?9knq4cHLOO}2b!l?l8e zS3hQXR;S4#2F{nHqdWwWDf;GBFC@S{fs1(^9oOH zd{o3CFM#$m`ofGD(b?I_kT)>hN*l0KPqA-AiHnQFPQwIMS69pSV+2vJwCd3U9CUz% zj45(=3c({F_-vM2=Lk;LIX1o4FOgk{(lNO}n>qNJaO;SB$BX|L-wOEm8d`gP!)0hvwY7&%0MWerZh+Iva0OYFp}MB%4xEhhTygayH` zLe^pjc%O|C;UyY}^c6Pa%_do|KxmsFA_;SjG)d{pl_F8RPbf4&6d8!2Bxb88B&&hg zsi7i54n^>nZJh1Dah8^G+bQ~ed3SwLqXO~Pb6NE&7<7Wn5et%KpC!ELH*%}RZ)>b> zTRW*XIe}Of3ev_(ykV;>87`P}F|{byrxL2^&M(npfX_AQFPfMp3Nus>&lhR!{Q&|= z$KV$xNd!2xj39}YwIxzONAZ3M#@(aP;eP8M3ecuOevFc{9HW|;n2>z`OX z!DYVZOyj_kt;3xzoTW($heX84i8;39fMe|#Vx@32oR|l|2xSX-wMsUQoJXD5OLwSC z4v+anLqb4)YbA7JECw((^X^@iPliY5si^l7&rqDrA*G)(UaK9AX*_~G5Ra4Y0V+g zh>Tf8-2B8O$_jy2@*Gd_tr$x+;=cS=RFgw5)3sRR(9+h3DRGIDQPI?zRAA+xe40OHgG5j}zbKT+@li!D#efqV1q?}3>%pEi|N z;3tZXiOHVNZvvXXN9j`-HnsE;K%bRycCH%TuyDiECOHOXk+a@{m7dp|QnD3aUCwOy z=5R!ye<1-S73qKQUVp#B`5$tPoNZZ}>-MQq`U*mk3j|ghqX6zzVcG|^Px}CnDBX4n z^J!cXQh5>Enw-7!aa9%~HT2`n~90VzJmbyRe$-~6=n=j8A`f=ps7 zpKdy?$sU(YK0h*y!GWQtOglcOTdI$SAC}hE&3qL_IBO@W~@EG3_nE%|EqYEAnNrw?-ON$C$P6_-x7Y+pa*xw?6-%a zF2xE~@>Zt7PjNqa#{)0&yn}%t+WPH}-r^|5oQ=H1BZCvuw==C5T*6Jk@UW7e6|zt@JML8r4_ka z!_{?Pk3+4vbLk{z9{KsnYf2yj8<}0m?O#|N>%S+0tyUxf9LMZ{Geei(uR{_NMSVo# zS@wT?>q>rfSOZ9`yu+doo{!ogXl-T#vD?9?T|@Q?s=nO#h=Ma{pHhv*yPcL({{jty ze5x2oDKkN$_nAqLvj{w_G<}$PxaC>2!J0Hhc_rRuwT9H?j_iontM&&CxS{)U$jg~A zjOGdC`rArJZqwYAq@pzK#GTI&+Ih}U5z!QAsGJ|Jf3C-Z-Av;_+tNurNHS)Up%^!T zcD}X9R2Q*WokK{y>c-T$uwQA289Yn!e)?CyD;t+e{>g7oK{WZB9mWcH{rCsq%=>KY zWbAW_xLALMo3ogSr)Cx=CfTO10I_-(KYSAa5#X;%8&78(~9@R)7~ z)Ifk!QGHJ7*iuJm^_?5{G2gAK8UMqjVSCQ`Dal`<+Sc~4sOR5~w=v|beg_O%mnl{AIreLo8tA6$y+pJFRP|(#iN7 zK#z>Y<5`Q0CmjOJ(XH&1atC5?`ZlG2kzN4KCXt3@X|@cwYuCMx@p zrq-`WcKJ!YM@-Hp@oa~!6GJxvB_~nxWMJduq&*(d&<4%8{}*nI70A8@ z9<0HW(cf&8(Nc(0e2zZiuzDf{=5=$}FEX)o3ZOag1!&LC%i{o&dWsQd8ha~$wCy)^ z`41NWL}MTpN5uA9AWh3GScC-L5)~XLqACZb1kf2Oub$86C%isEt2cGX*a`VLl=HTM z1fc`C%Nlh>UfE>ywvq@OJXC7Hw%#i(gUQ6jLF*is+CTk|^I_JH=Lz^$*6)66QZb-9GXMoOrHqY3L%ez&ri@y7DZ2{qadY{cB9^6pshlRpUFQ0pEr@f#$Oj zqNcxg3Bm~fmdW1{bzLYhg%;ufR*-dfkKB9m3a%ApE5QKLZ*(yzkM702;n5;8WlVU4 zgsa>68NEmpo|Lw#HZ?l5RB>j+C5;axx@=YjmNi*%96Oqt41$x!rz#DTgT<3!{nno$ zR5Mwxie**Ok(z~$+Ire6SY(GOH3$;ZkrkEU$e0mOzMr(;^B5}Ns^G#b)^bUG=k3Jc zDB~irp6{Z7oZ!Uz?lH^HhJpev9Z^scR~&8&0`kbMD{(>B7l%>( z{qhcE^b@%`IbX}mu@2iFMEVB?sP*vC5#i~S)5C4bS_lA=&Zh*utU`_qph7RZJ#d zwkCqZ{I=Gf2*p$qK0}Ne^#CXbtNl!6l0v{`@n{_Us80lZf{@REN}eZ0>33?afdMbP z<_H;52r`~`f0UV-QP>-IMLbshT46>vQ0l3crDm~aA@0gVf9iXTn)?Svc#K}FFgXg$ z*!Lg@@Vynjs!}RNA^i?N-c+^8mjtQ}De!(; z_0^--?R+y5dmuhMY6Wm^px!}5>mN|D9xzbis#hi!v5GOoHUBduIEe0{7^jesJsv1?<)6Q`NE}R zYis3y?E|F6zLSV&i10uxnd|->{@Ho8&`5Sx7TlxdJrGC~R$0jbSoLB8dSBHD+*iP# z`i*28hmApE0ArFZ_)z7&SFUc7Lr+}jtx)$Zv#i7S>e>a*Yxcih+V8(Yon&nU$w6PU zmvXESn-FR2Dy;_bkROct>h9(O)*r`2JKxva4_pO7Z{M}x0}R=~MGAm#X{OCbh7q!s zD(u4N-E^7dt1yb2x?=KtnRq~fiq$NOlca+oI-bN#51WMVmj;@r?s)En7(Rwr3ueI) zNL|0Z)VO;^iWD<-%@>XbFs{y_o7k;3HJ8-R@Th2y6%q^uH#ufaQ4bn8TT@7|w6(nhpg|xl{Cf^OUEb_qNU!9v*l7?AB8bOfCvJf(rH~gwfkPpL; znP3JTv5&84`n7^&`qRupd9r}KoHpBV+mvTOS(0jL7Z3z_=t78GrCEU}X3d7*y9zq( zx#s9FvsEzbdY|PRc?gj|9ymaW)&+Ru0niwmsj2B!+UtZz_-qZT@CA_Uv9{g5x%?2A zuw34y?W^aTWIe9G39RWG0d^!>mh#+37aU7*hRu+9g30Cybh-wZ|VY5O8 z%jM<9pHA3l;wF(8L#UM0CG&I;^Z1y!tos1u>?{ zAyfHyfdKtW7K!K3M!L8OLe!ua0qkdSo#B_cUqWSFUCFmlUU@AO3oaw%>k3IT^3%Gk zR5~oEykvWUB1Ht)X_tyL=EAIbOeQgTA2d3#n_Fz{wn%1RoaGEZp{LCyjMwP@#PNd+0}ZyDvS; z{%etGHq+nK zP4S;q>#%dNV^3yzG)?*wCJ<6l&tkanGccX}KDX?)K={G=l83vlZ1PLeXfayM0t4&K zZTmwiLh{OG^I&=&6bZ+jk`y~wv4$u@poi$UfE}|mqTi1}x5Jy!^K|vxCbsj>ZxN1Z z+6%lEUzEl?-|Az0ZOLwwlc?{bZxG5bzrxCo&kn6Hql(q+6@)lBTEY+kHs85^*kV*g zhwb4nIsknuV+U7@Lxd2iJ&w`+BJ#l;#>1?`R0psuD)&~wxyK`H9%}6Ua_}v>&H9P{*~E6jNA#diTV75 zti3pvzfE43jps*#rO2@YlLl+x34Ch*ZK~ThF?4#y6Owh--A|nMw@YqONQ|G~p7b7t z<{1$65wCT6B1v!h*LIzH=W84POGjVO#@H6_ zfsh0glADoL61~r0Q#Tv)MUbny%3Tna`E&oEN<1bcdlWC~#fF#!e6kREjp`S>s^$Jq z@Q#|^BIc$R)U&qnrfxedFOEo-91IV9pIn|5s3s<*JxkeJL;<9;BSI(W8-q!HX@Vc5 zxm=mUNw`tVTCW*_K$3t)4?vR>w5juNcM0%T(k0lp1ov z*K-+VrCdDV)HFSd!m}B~rOfIuFLOjTE;2P&k&Z|}n&H1WN>0%;dJ21=Qs?@FIp&!L zr{34o>Wyj04vC{ zH;qZ4eZB#VH5?XPrk8;-DNxz0Y2NLTYy0RX&XzJHu2<1O{4T_mY72FtP+{bAXw8QQ zyuUbH^S`tbq~#|bU*p4nIXJr{)F66CCjq=T|4EXR7#3Dm*fZXrzCh8E8To{bpB=jj z0x>cs+B@?Yqr+jCEyTE8o+9Q@#UHeuz)6obwd+k@E~H}Qeo9Yo4T;H0brK30#J2#x z{xSKJhL7T*M8;R*_Mq_V8w_p!;n@_O#E3Txv0q|KgQF#n-nbVMFby@vqRtd>+`S(q zmto-Jo@RKD5>r7U?IgeW+2QR}=$yOZ(osgcwK9RufPlbg$BC$QCPQjniI1u?=gvZ= z?IA)owkQQV9NNk6FPrZfZ;HcT5GFUCzypM+#Pp;P+H7f~_fC~GfvbFg%@`^`hHP28 z@DWN9a_6`QfE$G!5m$|`gE{x%KPb>n7d8H@lNauPja?q;yWTTIqZ!SsDOc$?k=!X& zm6bSXge-tuIzR;=lnsIvx)Abl(YwC>Jd{a#xf*0fe0xR68Ewg1h%A5QTCUUiM!|Et z#~(WZr=gHTqkazzkSiB|XxO1UUWvW6eP?N4EQ*Fl9p0?=@vt$yrLgw^mqpHf%isNa zz6s8#$FN)V`7ro=|#c(&A`#b=5Pl_HJ@0g`U;qgDq< zJy7?zc>WxinLYX<_*YU0=_`aPYgkb9l8O8cTimky7s8EUYoXj-vb7p$Wmjg}?RnyC z`ElasPu*}*UX~q4fEDb0lCt;}&_x#jwFV2YI$zs|KJbp1lT`I!l`ZMW42w zZaS=xim5AfNVZCldydN8+`>V4#i^8cJ48`cn^}1E_Ia_*nURH@?0W&o zH8rhsf#R0p^zAJXT-jY_qjAh^(}gO ze?}}9PML*Lj?SFc0s{U{jgz6vAt8>0$;;Om3X0t$GLhXgv3PQdfN9mER~O(s!GxWr zT+IxS6#**=@rLg|f+gYu?URaGN7H;H|Efg)A8D)V{LwFIEgd=B=AElU>1l7 zIK$%gGyBdK7JjesKWOvbbnSZ8?@gML5NV*t{hH=#0wF=(ODG-2fSo5Gt`@BMHi{Wd z&G|-$o4AO4dS^#W$%LuDIAzS}A#)Q4slen@3nKof(zCsx1EWb8_tCY)Dkcf1phLG! zKUhq(338Z{!zirYlRvDWfewTwPUG7b&n-c*1V+Pgdt{NT%u3zDW5Zv_9wx9(OuDyN zp52)A5BmoW3fYK5N`3IeAuLpWWo2fwsf4Cx4BqdG<(G&8^41#ru64qtb-CTxHZVyL za7i20S5L0WJ+GV|MSM$qELkTJvB2mLm;tE0xv0n%r@n@Xy}P95_`~g?(g_!C0sVa@ z*fQ5GISRhr@Zj=%R~i?)Ih;m%MpRl_>b4v}NaHdNdBfIjj@zH_DUy1A6HwV>+HO*p zhDkl}pIwjalj7epfPe|AxJQ-e=YLXXoTTjr*pu;TYQU`8Fq~ zpjRdB?HE==_)}k$$4xO`k(nd;dv6plZ2k)LBY>NyZ=Y$XwVelG!-fUS=_S?G@j*+z zHBZ!~2`fE$qRXA>#rXgLF7W-cAlW^O;AnUsW1&coU^p0=D6=fTuJVuAZqGxxy@AWBUasNfYh!3Wm{X@ zaP}xgzemAxCnDOuYPmL=`dCK}rC;Z5z{bU|kC-e8XvLakfq*{Mveg0Lr8DbPBR^Il zAYY`YQk1y*Z&tFpy;1)9If5T=+e-iGK>oW&jX)->jqI1%`Tbks*)M3~^AwYC#v^Wl z$*Ihn^wd}yhQoucFSgom*=U~E=?ZWF0tQK*vP-`oQVo>PH4kwMY*zt6i;W(i##r!b z+z_94VR9P@7d;m4pqiF!FjI`_PYVp?VRd6*j!AU((2A#*dBe8&(nG3ZP$ebfilCIT4Os zx80|p8lw}RCj{1+`cq_TS44m)9!`rWjIM8zc)hK(^WKj#2= z@4uu^9wMUtC}OVZZ$1;uX2J&Alcu&O6Cq0hr+2qD3S`;=&7BsIHKOl%EXB7r+rVB4 zOmBn$WYq!b{>w(OKcns}2Qt9{^W7)u!%zSA%>I9$5U`(EFu^J>262bvLkAQdw%oaO zZ-m(P*TqI4nNy<`Cj|`I`VMt=+L{`%S2)asvyo~iqLWMqKAD>noE~3ZUp{dz_jp#n zkQOG?_6(iK%?)F}nW8k6LO)#w&GYED(A=^N)21I1*&Ltf95DuYx&+#$1QH+Du|AiR z$iy*uH6qP>B)-_|dDR_ETc+J7SVzosY((a=?P@YO!^-l#e7{gEYzS-fgq&U1yEmmu zFZXTmEw_E{u2EB*fBZ&uMt$8Y zRjzI)35Bq?G_FnPC=4$#eBN3cV-R$f9J$@M%4AqD6KoZSgs~2%M#uUt~9V~)!Cqwpk5a}-}$iv2ROH^AgOof{UjNHHzCbo;MdT)lS=AXKc4m)0c z%a-_YUwoC#PBZYtL6de}I#iiAyKrcH-H|vjfc*uov;_wG zl-hf>eZLWP>X0NZF6@gt+n0mAm#NM>BDfrNA>?Dd2>Qz(swTQI$tRnU*6%S=&p&+q zyemdL{VDsNC-z$J$S;Uc2;=6hV|^jMO$sC6`BXxD^5%zQ1@&|41&qW6)$a-qvsdWV z4g9xfcZ|)g#i}cC&!o}J^=}ZMoC0;Nrf#`m3ARd10|yAF0r@$4EH74%o8=;G*JXP{ z`NB9y$qLtEVTE#FDaEhCOdpuf!@OGnPl7FqY_i?QEAxRk0gYZq$Nw6rK3B(oyoc>R z@{}>)mwx=zP1GVV(9l3Vdt7!v0rF@KPZXioR^tpPQBkvSL9SZG0IGA{7Mq#&7wrzN zdh)l|M$Vc>?rKHG{5ms16Klsq+8gYVl!|f< zYyvla?1>#n(|b0sZDk7a`99Ww`^D$)db4*USL&uQ{1$$kF-x~`-`A}_GaQYo_?j^W zN0j>(`=c8MjGqwWN~fZ0I{0}j-Goybv_9};DYtRlt?+xb&#-ShFZ`0~81KVCWFS!N#RIzz(nUF{}#JxhGE}|DQ z>ykBjU#AwCF5AWqAW}By(v6m9TEf6F-^M4+eVEOtd^sYc>u(-z(yd_0NGkBQ zwWJ8zEU{^3)v@pbyb=TlpFV;5~1teJm)j&L_jCw z!=hJCM*xvk@MQKZ1&l8S?EOv*-V^-!97mnHF!k@~asA(dH|12Hb#}Le0h3&BF=rEOyF&ntjjALRaG(R zH*%5DF?Beyv@4-*d2!kG0f#k!yEB;&RJ$gm6%*8+%z+Re`+|-C#?Ru}QoFAO94p(> zlcP>&BKVbFOR0mse3hDgIWB^hSK)f^i=GWklXrBX1-*DRR>I@eUA=MDkp!BW&o!dz z9V{m@b1;nU_>`et`2^H+&trSSy;2h?pSmPa*RbAh(pLBMrdUGT5}ui7a2VX3gN_tP zH$TeSfsp;_35S=M{Y9!+N=nz;Ceq{IwH|6*FE?fT$O5⪚-3TJ}!u6($ZTen_ww_9ZmC0}l-POKoC8sFI~jUg=>c zd)!&9uYK)0gt?A!3K{?xx+0(?1QHIktE=R(!oZ*zqheM3v;{fkWa<8Y%sEp2d0{B8 z@mgL7hiW?hoT0G_F`J)@jKlzfo26gUBic6~+P@1*K|>jG^n+GhW_4t~vU$>dVtvU^ zZa`kr+ceK~boI&F&C{AgeF}CMG`$-zvMF&t(ZptYo8>!dDrjadW)Jtep$DNh+YC-S z<@ec#jYZc+WTVwNFi-*-5>eW8?z3q_RT}QzEx~uzwf6WeKHR({Z+3n8+xa=Wf#3D9 zKA!@5`P6$ark~&1LG?qaVfTbO$7T}3=Lxk-lIntd5vAHK-sFoJ*078GxqwElAndM6 z=I;Y+CJv3nvvPDfg5lp~xjK!ue-?3e7>lLMNAd6mxv~a9T=Zin-5s)eBZTSa9h>J$ zn@DZXzse=LZnwzp^5Tds2@`n9O`7JbQ1CQCJn)K7_ZW3%<10|WR&AHEVAZrgZ8&N2 zP;A#p_3ui-JL?D{Gnqqy640P!_c3Mi?JG3HN}81k%_zXB25xg1mc1M5IHK;J$RQ+W z7g&DuF!Cz}22)MFddN6vkf}3Ws9b~3FoZ`WWlNk{a(JbQ{Nj@-KLL+F?W`uxmAM4e zjCcBgcagTw9G(;>M(lgV43Tl97$4anHaxrGQ2<-K*}#<7VlwfN;@y4X_CZl=o&^`R z!fpD+F89=Xmq`fsf-rT%;)z;=?|B3^m(W2FlhewgnS%AnsDln@1{AI+S@E!id`?S| z25&T9>y@o~8XR8&<#F0BxJhM!ozIsw0I=^qhgg&zQWs#@zrBPKvHG(VRn3++7{`j zeKY3^RMRyt>K1dfs^`4S@h$>D^o%=HufW-a&qQV5a3h!X$Hd zxIi>{4k1V1bw|!cBhooaz8*deD()00WbuQyQGf~ui9*Zpfh~Tr`Nu#i?7jU%%{t-A zaBh73JV$frXmuB@T>U{#%u&_d4SUjU*5D&K@u%y&omQo(99=dDRHD~J01Q|&8ofq& zWAVq56e`au=yToZ|Mcisod1G}RWY)zovAY+h8CS%)rBxa18NCRvwye%*#o60eb?6> z^@AM#Z$^7cYY;(qP=Blht;!M>iaLG1Y483yF8h&4Makn)1=vxOW~2#~F^kYG)Zbl% zg21iiCA+(ll8JG=;ZP?UG%2-lQ0Yb0xOZa6wxY{tq|l#uwE5jQQJqEO6?@Q+jt)1X zCQelB5hkfm+C1+01g^X4txR66q0=1A{3M#=4OFeV>;68h<(s+sIe5QETYs(RI?hb1 ztr8u?h8>bw=tYL~R%UEMB+^6}ck6kiX=*mj01lCf_)Tad#9`awP@OhEKA^aLzkTxyytU7Jc5w%B*rXfMvn1nuVlx{ zS6rpW&A%oCh(5f?P}PsTeb1?*{AH92GbUJN<6?EMh_QL<7X~GJ+$B7wkT39S1QEkT zR>L`$E^e?<13(~(OGLX}QdZF*3OrOwO)m~zHty%O z*i2zef)Q9B;R7#5>*+H^bPCA4=#2(1qBPazO5Dkk%YbY`bO3ubH8eKOigzT@l3Zff z?1g0L_%7Fyi&0NATuGwl*LW$qRm)wpOpBMFTchRB!@_;x3_ zBkCIA!J3JC2A(&Jeq~lLp!#b7mG|F^f@7Ys;{uoXd^Tw|VsxJ%Kf%t@@_WH_>zb0A z925&3F~BQhk&jTJsDZ)eRRzVx0Mhl5pWTq(bz|7Y;+~- zZ(iUbMmIPqLmYZuT6;Jh2|9X;h}XtAiQVD5qqNVG3fD|S?wl%_zi0;F6F%S}8C+?i zyBw;UG#__RdH}fzyVI{ERoU(y?!%eGv-FG$fPlnTz}dtYSsN9EH8e7;QNH&28v9_6SA(dKj3~ zZ2OcZ{b_F!pM0<4*`=%^O`UCdm0W7+#d4g!1tbk|hK`SoJpmyjzS3d2TeErk) z^)sv}VhZMOAG;MPUM-l^n~ZyVZfhQr(&Qt2{k7YJFD0dApz`%wo7MRef4`YCoY>jz z+30VUn$_Y5tDtTieA=^UtP~Ct0w@G89fwFLU8rQ{2wsg#m$F-ALL~6r-8JRh4QEr3 za3y8ns-`~{+SqYWmQu3sM9YFeRrn8uVytY8pnZLq`UC#PsgyY09QHrn zs=JC~W#DivGx)uR>S=kOPcLB(cU1JsOp-StcGchTA|0P8zv^C@6S|qU?Q~N@ml44i z-#^huX#8OiG>L;kq>UwY!H=y-kgBD0^ixpS?I>V1aNGJ}qw1n_cLd3|TV(S4@#Yum zv^_Ab??EB^0A#*+#KUyuV9$_|R*BIeamqzNsZ>sO{F)#s#~d0{MnAB^O^U?KNj-GK zTkK%W!IjpnQtRsSftqZ5>V>|lPUsswo_y`pLS1=ayW?Ghslo1)zRAr()%4R~5r7B< zM9cXDJWVq$AXyU$0wVP>w}0 zFhWS1ue}i~cdqu5KtfYi!GnS2ExM04Ev2K4qkK`ie;UV^M0R+vd^{S*xTI6R>kX~p zSbs`|=UKuF$IljSLZR;-?y+23MZcW$!}(h3lfk~B8aY_G#(#fa9JahgPe1Cadg-q) zOux9*U6w9t|9!1_FYrNwmi}uhh1r1Q)NvCtCxuJWdjjq7-eQ%YJ$clgCc%ocUnGFm76H0R2GHw1e^Z_z+%Ve+K8E@;v8r~2fvRVth zsj;ac4`;Zv2xmo+R>GNaHfafF1I^riUt}oKYvsIwd_&=L>j*O$gJ@|5&&}xo5ii2= zj?6aQWv>U(Y5tjkR{cwJt%Bk@aShOu$w!5t& zpLE>G)QcC~aoNU!?8$GkLgnwH!wVGUQeN^Vq;eSa5}C4??>9$ixg0DwG~HRZ#f(vR_+XsM4f9IvEqW1Ys;9N_ZG z=2vP$pIoilL8iq=HR&rS`6ip&;RSs7lNvGMH&RBYe68q(m=BB9eRG!?kUkmNOY&8Y?q`Zx8QIqb(!;x(92cDCsHukB7~U7L7$= z5&3RhKq4jBNx&}zze*sGtP6zK+k-xQe}7-SDs(mhacHU$9WX<=ywBfRa<1ssNfql) zS$6C#Uyl&EJq-Yd2O4*ZptOr;VCFydL;h~%Ju+r0@SVExjK5ehuk>lEB7Hxl<7c(v zVfzSrbrRLD)xmEIiSjTaDfaAARsVnJ^9vulSb zBQvFv*=aye$uZ;c2(uk2qbq*R&xcLxe+1~=wz40EKq{J=`63peYds@1X?T8u#Nn(> zYxMBEZ?ykAv=ih0fi4mQ*bLVY&b>O#a_)$#TZp43M@NO;R19l92a;Ax?dj;~8~`R6 zsu^!OFA~%4Z3wec>qj&Umw=-*yZssG!TLa*ih+QtlM~eg@Ucak#4J{5&uC`|*hil~ zbc6Y6O!o_pCQ8FEiLrR5S>H4{e&XE~CZt~1@T)JQu#d-#?8LUK=n7HnPA&TBz4N4y z@ROOi*Z(yg75Ry+^}H|OWxv8ho3tb5Xq`3A9aHv8p*`_mj=aqhA%57;I3z@O4GMXsIhCC(Xf#<_T~-LaL!qjw0T zDySj(^|4jGwM;&g-P2ZA%?t%oMo%UcZk3dj;MK~k%c*_NFc!Yau;N^TI8nLa{}}@t z=e_=GUuCR86}535zck^J$KI)^lC#10JgHTG$P`OtLtIPVR25LyG+CY9#AMte!2eX* z4&-2Mt#S)y71|Nz!(VSR77~wMWad*Ni0FqGT560jwO2a z*k4R7Z5*w4opqwWn4!#CNv70lV5gfWrQWL5OcAGH?L38}<$JgA;rRR;MRu`*pfb{1 z*inRmk8jhrx53xHeftvMbp1q^P{<zbrFw!(h3ez+7^= z0nv=aLG}CO=&F>-VY6wz0Y_^Y+NSQIaYhBPjeMMBAxbCx!%y?I7;4r`JMkLg&!C&{ zY_;&_+;6X&+e?6^vzxe!lx{Y48xnJF zrKqUE3`Sp}534qNO`Ap@#7ACYe1`ZB|2LZUzf&bRHaC2j_>1te8~VnX(=lo)?EUNB z&$5|~3lkImy}i;hb{BiIet>;_(R?M%a#Kdhr;)Vlz{`1=UdR2Gq56khpnfemb#ri+ zLjeyB_>~xFVyI9=j@J12NH*{75EvK_u5n5A39MF)R6l(-xu^ItDN)wcD!HW3DluI{ zFJ;_w2rP0kzKgo_)A^ti8uJZLdYTijqmEo8xDLbX^w3d;ZuN2mhCxbW(UoLjl1wX0;DW{Tx&b;9HlitW$}|J5;K0vtyXSQ56WnZ&vr?bL(hMtH z*lGRS(l~3X=rhbZn&s2qPBmZ}oQ@Hn`;*wRu5d#Rc#YRr;+Rp#Z(J_(23E=r_U`f9 z1FJ~>M$sn{{M$Xs&sgpVM4Fgo_D;Mt4J!;8Kiw@wQAeH!1hR(xi7_!T^}q(kjUq^{iGnsNq zPc*d}K~n1qlXl|>O2UeyG5UeBbjEKG6>0M`2lx2vdh?lsRZ*A{d>I7lX>()rMdYv zmx}m;&xw-->_geLyLoz78MTqY?Q3p{{YH9vX^G^d+t@qn&KcNM>Xt=sqN#_8TwQ|? zmrsg|pHVqUqbbqb^}tgL4VQik3=2B}bhTe=YPi>JCU7G{iFXdHTD?pkns|AAOv-WV zng5d1qxt{g>Y3APfSr)DW;C7Hm)3r$SQ#WXQbuJB~42w*5jNUh_+s( z@DC?20!8W7YfX;gZPLgk18--n2v|>4WQ=kf32E6ikLhe2hk^9_7-9Gj1B0SL8nZJ0Q75+~dfn55R5zUU4q^*sFzP-@vNzHlqx5@ zSr+^P>%($Zg@90;50`2u5y0|d0Yrk70!TL!j7BeI8{Y0>Su4--#7v)J6s4ox8FBVB~>Q{xaKfv%~s zxgsJ8=gHrRY_PQAg^E`nzH*$n$}Xcplox+aLsNjGjvedKmxL$5!Ifm*0?t)csjbw#tK%YOus?(7`tD`R$6bic29B&I&vJm`MhuZiqM1}!YCG=96PNb+|jy)R}UWJ9ks#y5DFFIgmb03CX7LQ&DB(6OE zDgY$~h|(k?Cr4B;*Ku#rfBn7|Q*ov6$>y#^Khz%r_oM_FaXGz+*SH^c7ipQj#foPn7zoDxKjL7_3wdeL&Y3`l<^)Yao+zFS&ZVb>0roI{H9kyh_r zbObNDvGf0XDgLdknT+n}3l_<$2W@o(^LIa(9ZDCuJmZZyI=de)XVx{IAq?wb$R%w`PbF#PPNm*iD?)_OG`)Ay8?<^{o_tp@%1~8-0&9XJ&~1LXM08v z1#H}`lqv4LoMR~Y_3T+$8n2tQDt1UD?%r1+?{lEM>PcOXt?fOJ*Ua~()3(2!E)h~( znfDS)jMAJQH4oJh3Dil-rRJ~k9^7%Qqrj@&+{&*X?u@O{7#|X_FB2LR$tDBy+kD?B zDdh%}+Dz9SL|Yfl#O_a`o;$v&tqU=lJ}>E)A7mPB&0*)_@_*;KN}2}~!!$t$D%`8W(J39Z{w866||4k6kPuHpJHQs@Trv%eL9DSHf!5@!@?$s}U9vS0x zw-D6eAea&>2$82^qi69*xvGz@i?>XNOz(B>mpd9==Iw3~IpFUhW!4*3G-VPkRK6+shKZ#PauN_v_a}BZoq%f6N90B{Z z*fJ5AA>@vb`F&5Tj&qpE`(#t&=Yt}evEx3Oo7YwSZ_bB+n0P&q7%LerQ9z1@eV|Up zYb<+LyV%zKspARQ2bzTv1hd8{Jgulc$+0FP zyUjGZ6zeH~+JRuf(fRped)5%VUF)?K!se>PhTCx}O`o@aCj$)u|27~2-TCY0y2jW2 zr{_6E7QZ-7+_q0wxb!#9OzD;@#{gEoMp#R$_ulcv%8(dgFYT+3RXkYj+%+{{VtCt? z<$5WiVC>{!h3n*U;_1v?W{zFL3*77I`_H?#(1IdnQ<=(wVzOVnPO9W_JU!*jzhYKK zCQibV%y)cSw~=RL2PPVLVeUX;>;U)PYDgz`b8_WM_`-xQr)5ar#|H%aNOx4D%p&Ph z$U<$8$c`Pd{EI$nrBq@??R!8Ecl}BuMV8xev#H!lGmUao-_<+;B(KVF)Hczx z%e;MqgYGN4-7zfnU4Zyl}@gB)ma2Ha@Nse!u4w#BR@xMM}O+#_e{36(nf!LAhf* ztBK^FTA63`(|@N#BzMebH>Np#_o1kMI=KiCS)W;833lpIQl)Q0gJkn86Vsu#9%atn zt~w33hnLx(MOt4brWX`ZFQa?#Q!E-Rgm=gx%GGcNr1G=VNZ?XSJS~R|7CM!ubH%!8 z>Z2AIzU|Pp-0pu$4v{B6)qx@eME6kOEHBwH*O!|F7G6qE_ja(0{U+=%zzuj`FX7&n zv+e$Cg0w>@DBvfpaPf}jGFa#j0i)Y`ravRnc1@A*F7MMpys7~XUNNwom_Yw1|LCaL z+Al6W;1t5&IaN8q)`*$>n$XL?m3ut39bc?LX+bsrERKwFOSOOJ5pv#r)WA=EDyQmm zL7o)PHxUsdyu6>&NN@Z>wJrLwiKW;;Q5U8>umW;)!k4a!G(q?X2xMq|wOC4sja_6n zy24y`Il(@Yj=%xNpAOq~xsA?tmdy_w_UferP|p$a_9gRXU9F@FenC$ESv z*krFbUpJ82{}V&CdZTyBU(e9C=+Rh(qm`-XW^bnk{PzbhJ;N>|NUmDgfj21pkN@tA zAtTl3S?swU#fNZK{KQuZykMvJa?I$vj|RqvHj-eMa!VRgKl zH1UKtsiZI2#M;DvDgI>PH&d(l=URxlR^KJ5ws4|$n?4(R$UHek2P#Dz4nw4e-kqGB z@byg)Ju!wk@Wq<2Bbf}Wi?zdKf2`N+IiOluTlxzqEZ-<5G5GuT65N_!IEI=<4M#lC z+(%(bmmQ>SwEWMgsS)XIr;M-ZW)3RcdW!HOXa5wM+<6)c>ScBjURdgc$V$XW#`$wK z^ZW%`+Pwd3vFze_{bWGCa@fv z$4n)w0*Y;wmOkv`O(P*%tVtqBx%!nWBJgbb8(C+uxVY4Gl}7!y751MP%*9BHuQR;a zXIMalwXx*T^`zwV8tgwBp*ccz__X3wDeWc3q6PbT>RbGWvUj$};7 zXi@9)w6dfl-2v5e(*E7#A5-BNl4{*Vt!1r?Pfm|hKk$UFhlqxH#vGr3FEZn{Ecqgn z<*gwjA|lbS=bRzJ3oGBriHU6z*79lj_gGGDT-Jh7rhGR)>Usjp&Y$w~kRPH^-oIwr z$oBdj1z`N%m4eAGmVc@4usTYboQ%vel`QO1kXw_g9az|##9RJ=1`Mg@bUs!W3dK(E|1$j z^*SNPlFsg8*dI|eacTV9)872cPaf(l7gt!$N2!0p!^1Yv*9dma0gYMQV^DE+cW9N5 z2{|bs4OV+Nb`GN#4@(nF4Kuj5OV>H*Bbpul%zv$*<@`vt7XxXp$J5OEWxr?1aKALI z&)pCxFLUWSle@kSbC#yKI3&U^L1bGr?r6Y0&xX`Y$wPnw4Yi_Oh)2|pgQWA}>OE{W zA9+)$h#fuotm+_cgYhlyF>@a6I`YR-d&N@O^JPX`rTKUA{0^M|_gwDc_?LMD{Cc&W z^uB=kvsF*M{xhvXne%mZ{2uKHHS(FWi;Mi`W=bG)ZgY3{wV$8p`Tl$iAblt*D@W&>0=BmZ7ju8AAh1DP<9B1z zH;|oe9iCn?&-3UDKNaB}oF7~Xd#9lU$=|+osn>2NnjuJve3hHHWZ2jUQigYHk{?97 zFjl9q5@l_4W%NDs0;5fMEegf#!YeWAo*zHZAALabmyk@EJxFBfM>^McEFe_U_ zy0>yNzM+ML*sA{ALu3*Y56!^I`T>_i;m`q`gi~tx64Zp~K}G^@P=dtu*Ss8T3?Xc; zuIP7#aw+;PnU+#?j5~4$|32(d|2^!jH5+u+`_){7ddj6n@K){a>he4JipTBTw|LK| zK{5`&an03!>sq2$j{~fN%E-w@g&4{_Y@!C;`%7PSbv*&v%P4>{fD?4PLW93t#nF?m zD)xIOy5G*$S?$#a8~xcyCl~44!5r#XXV=;qQ{inAePcgLU1AIDmujADS<9fL(Q%3@ zP+SsNzc`sN5nIj&1B_vtUXW>PpsexUb&s43$FmjQ7To(5duQ^V-t)i@ed$Mq?)^mG zb1L6Y_(2y(BG77%JG*bJohzzhEv>}m`$CpP+~QZJ`p#REOP)7lLhqS)l+2mO=<-_> z({wGoid@DxH#(9JaBsC0zrfqd3BZybb`oVr4rNA zT299ll<(AQWtVK&Bvb2Ht3=LjkUx2RB9|tFsF#!)hFwFdRaJrH(BC)0B25AqA|R0{ z8Yj_UzVow{1MbY2Dk-Nvvs@e}{}+));$GO&E2bpy{=IIWor7;SR)*}Y#JYm*}QNozU;CmqNA#fp1`s5 zXb>mQW};1!s3UN{x^KgE3A$}N3i=a71d&>3A_E4l{ACG^6@fJr>2X6cv^o2wbP)$F zHNQWN-lvAwjcNRy;b#8NG6e+seuTMWr6#0`6ss0*@EdNEG!9b>lozZ~>5eW@_o(!r z=g*5XrQG;SJdko4R^mm0j54ZNHc=vC;w3wy8;Y`~Z8rb=liVJFqKAx>d<3fV@>~wT zIsv!A)Ppy};&Hkft9)X(x}im>h}ps050=<{x=_W$T-XIXbLMsL+>_I)5f))$R@)za ztJ|z}qx{9mM=k@r63-QbiqYSN;fi=-m74~3>b{T*UN8#vuxkqs85}k?S|RDmOxwFr z9>t@eA?x1Y`r3^cT{mwc`rLPvgBRF(2Rf%F=h-d(3fL6NZv~?jHi|5QOZa~%mwuEC z^PR@1Z9CajZmUZ@B-+vLQQgsrR_P3vkrOnAsqk&_kp_bo9PPiL9kgH6H0>oZKn>NB zCeo>6MU`WJ)$u}m(K=FLUdBWog_99_0o!NR3(aPrLEcRr;Q(K@-!1d^3Aq1-ID#R2H`mdkI z{O?x`Kj&w+>ng5p@#+0ZR?(1b?~2RET@9zKI%!9^e-3dkkJH<+>uFz}#5EtZ zQ5xMYla5#60-v^|Kum)y%H`XfBW>(*hJwP5LaTX<-1e^JI#($>Hs54MKAz02nncLv zFDsWvi>q|@jPU7{8pN3p^7L!dXz)BtJ3X1tCcw;KlX_%7Kr4m&%{L>c|Ga$1=g_3j zR}I$l?JFUj!^VHUmqvCAybAp4fW2_FAPurGM0UK?eo8XFu9HI;2AI*jEwzLU=NA&J z2fR^>?358<>Hg2$`bb&ekCV*##7oueKgOCG&}w)xlcGB_h&^@4tV?g#hi+pPv(GRH zyUHu-SZ`r*pk@es&zzedABjY?4u6&5lIxhZus~c-;{l!=JP*8{qP_mo(nyzs(dwe2 zj|WE|f3D6(hae-JDk&Q4fs-qCj+cBnFi7dgvwAMWBGk`z?aYPjMr|2KPMu#d{VUTd z2p@Ub{5@=9KhoCbHpIs8pPJ$jh!09rD2yf-U~{k6F9pTmV7#gQ^a%;D7t%_MEYq6UfG4*F=#M#s_!RcOrF;on7`(o{iClpRCBGDWSlu_<#YM(x}`_AyvG#X|B z{rItR_Y3=rdS8LxGdBwEXViEz`;sETPPJ5By=N$Z6_5zd%^_v-;%K4rEq{F4J_eOF zdG}7-9q5-ZGT);QbkKm`3rl08lE`vNPjM6T{ z^H!y@jISzNA%|<-6zpwkFlpbev|eOk#1XHR`{y~?DAOm2{2HRL-(z;&$}-j>66ZFU zN_?{Us(@REp@{(ls6rKtI08e%VB|cA!yANbXyfpeOd{Rw;M>-wfaPN$EBSTnl>h%+ z;gAV$7LV^8Bj%&M(19vztf~9eIhGs2PqsQp#0;HZe+4o}BLIX0UJNOBj+9a3t2B!T z(B%UI8;O=G!74@k%rHn2B3n~SW08(#m2)A`Gp!3bb)K1dxT*({Qwg+3T=P9Hj+LJ$yt%#>fh};norkO4pHsHWXuZjAVjtc^ z0MGSM4-eom9#0oEba3c4*C%W&E-u=YaTE-N@z;)5jMt6Q@|Vs?daa`ChDVH7y_^f1 zMNR9lxMnp?sI1fY9RxdqX>v=GEglRwkp5*1l>JL*;ZbPB(R(AbvK@$2(70!_tu|5? zuwP(nOU*47EJ;#>Zo!=E&-;+{mJjqYgVv2!{{B>1f({*J2F+tt)?)FAy>bqm5@=O< zl2nNPCRRJGoU02Kj!Y{TKD~?zl2}HR_vTQskHhj{6y^*zF@a20c_oEjjCnV##6s~1 zp5jr{+&}|mq{wbF(C>1k6K!qnn2rvSB^KJud5rxGmN(vp^CJ9X&^YNgMqRULfp(B9 z0sJWPK5sE_gD9hoN|jh$C_$=bv0`zQO~IUnEnHfL4XZAeR{VzIF=c{M7EK(Bxk`^cIo zXm3nEg+or;NQ=4a>IeEDwrNJ)M+Pcts;>T?1g!2L(Hb%f)!elkX69oauT(hpP?rI5CHm_KvUcv5XGx6PfCut0*-=%(7d16*0S!%{Ta%PzGE( z-^R7KI4mJ0EbB{a%f-CGf{64|{H*<~8}_#^VAIJLJqxkG+_q+70w zmEyqn%oR5^{a!F}+<+zfsG*W1c~$U}nlEL40g40a{|$v5;~!~zd`8PNhT=^W<&4KU zx~N=N@wbxbVPzeaD7)qWOTkk$HiW_7jdjI0g1rHNWwX~xrd7^&U`;KC%iz2qXa60# zN`2ijq|t3~GJd7caBo|xCp7Kb@)?QoUU<-W>D|`?RQV+DES&+PnqKP_z)9_p0$r{% zbnRmr9_OXRXB(S52muxg!qVDs!}f}ziF>7=7n-VzV$P*9yQsama&&HNL649I45L4W zxjU|Q9A9}2KaY(+2Sk&XpYUY51-=#<#y2&>^DDl}gN(vsl`{I3rRP^`VDYdjB@&8i z(b`GmZ<^k=oR_L^J5GxVzrZDOBp{8qHMW_oL;Uhhtri?YjkZZ;A9=#}f^NOA&+W+l zUZrD^YG}bFhsf#puR!uQ&K%*Bq9P6RQMJP0?hGXWq)U;IUs;ZehKA~FZjElRvSRG% zrl*IGnMu-4xY?a8AX-VQ7P*#4Py%InHE*6{K?e8bIYW=j#o>#jXZA(N;jjqRA2D+xoTJI={xp{RQeL zZ9JLlAJ0h;F0t+kwNS{-E57lCxaY;>Ht|!MvkeTa!75*fe=pqgUP;YeIgBW`c45Fs zpPZnx7PN5q9DJvpokR}|$A`{66<_CXpGOP3z017ijowNZ`9&V=$U$B|Op9vd2O{{M ztEYRYX~itXb7NBq@B2d3^J;+>=Nh%LbP?T_DMVXTHO#|I1HFs0?3rTu7x#(uz+a~W zA88Z+Zh&QU|91gQ>@2UK0Od_Qm0V`)N~#418%Gzpg~eCQCl%Gr zl%mbe<9ANyr=O;Fx(gW@!|URtrM=5E{P(a(41%vwC^^a*7(-qxUDNsn#C$KUZB4o+fRzRwijfH#14GU5nOpyz^QOu# z^X;IFfmxAA!szb9!}~js^-=S8AXOU3278E|TOZ1fX=)M~o1D!5`V}3>rw8Clio%ay zfv98wFV};q8JM8t0ZFXDV)rXBIN3!^4V#;&W~sJ?OP@zA0ZX=+(z=93V z=cNAOKM{!UKM{xr8w61zT~udQ79iz&R+Xu99nnFL+UoR>_Llf_?6BG}5xp9B2GcyN$r0hX&0b9Sgd zfc~tnHCg!f{%6^z3X&bk`vd1jf2R7hRAQD!`eH)IG@&o!9>S$nAemlP9eHI-HsPms zj*m>KVz5;LXY@py-pqt5<^#6~vZ|!~rkIM7)kZY=9{gkbNitH@_l@x{*k;&+gHCk( zJWql?p%?9js_tS0tI8FI`5<6SqNyaAR$jqQ$*{vGD>EWVIoF)ZX*ypja?qb9?TW~3 zOo+lEt-S{efA*87j&5oL0%#O2OjKxrXQQ+|61zo92}&kuUBWFz%E6&CeXau zbbb8j?a(gn{Eb#voErB*m3iR%f^K%J;kV7b8z*^y_W$(h)2RlReBIw8BOic}3w$8i zJY~siJd~@1R>LBu15b@XmdIsQP7fLaetNP6xq1AE43yP^UVvlx^!ECiti* zEHrm!tS!eNC$c)-%y3k@4@peNnP`}Zim*=z(B&TXHmMVORD%kq+5$uaPxEQ=Dl2*N z&ymxy)&eB~U2b4-xCbbXpSz7BF+USe3RMy0UtEGQVKc+oppo4bYd`S44Y=Hu6w#Gp zqA3rL6at^Lx4-UhSi+&?{&8uqtg)SG?sm*bK=l0U4>v>WV8W!9Q~q>lc&&g39k_pa z%))ECT7+CpUKxpu>HxnkCVD52itc4FLuII!dKHL~m0U|rh9&4p2(k<25)fr3aeGJ% z_1#W|@~61l*+8IJXjMQ_)U>M%p2ldC%x@U83SncO()W&bNL||Y)Nz@nMpDfJ)TW>xiX)=IvVZ;U2k#^IvVg^by z4?k5o3=$$z(Sun~M$Pqb_|KZ<^6YHu-5tU{uI61{{~f&rDF=tr6$##grY4GqL;@fS zSC$IEOyY_iBIS55W4vyxeV66mc^TN<++gWVJw#Jl6`OkPV0K&cHUS#g`XMf_hB5uw zKOk(p#{Xm|j&%|HXY;WtHIF$qykxTFWtx!`e@*7ts#`Uk7TkJ@8L<5B(QgkF4?M5V zwUBY$pKm5zxIeG2^t*8E7m+dKUcdB5Z_;Nu^-bLH%>TCX>f4&shn|p6vz*bGVf^OO zIkRyOH_~fxFe8?^sui_?m4?{XcIaEv(?6Ky$FO5BFlWEFV6t45_7$s{GpElMwi&iEo!>-vmXq5(#7Ov$LNp9e!~h*Pk?1Iqe9wZgyijW$M!qV z+n%6XG|%0synQSM9x*j{G8*4-=g~zv?~LO$%9D#QH%1$SQ5|eJyFX0IwjHG%r=aZ3 zKR4?CDYyeAo_r)6*-{5t(iiZ1#F``YApv_Q7iMlFCVBQivaOCza&>(@>4QpG=Qtnj zE#^37w0^QQ_DhX}mE*MuTONdQ`W-R$a$lp{k#~$wa9=NT5T;ehz28gEnBX`XOa)6; zHa`tH&S;LOu={uB@UCvPer)jgab|WQBfRhsXnusrwc0J=zY++;5#5ChCzwS^IBLPX zoaJ<)so3&zweiqEMP<9<;Z5Ky-rTf)tukzqlFqGYb@?+Uq5Wq$Z~_ngAE1RnCjv-s%S&&*@KT z@7>Ct!|VfpG-NH;w8Pt6ed-)d zKCjJP&L<3GI`c>9YF*;Tj%_!jz;>Q|LZtKEyZm04Nd+@})nJ|z*D^(=?J>g-76D&3 zRJFb)z!wI)?hxmQwy;X_;taY1Z}S+|v(8qMHEmdcVgp;qT~Fm%eLW?^#$1b-U2kUG zFj>qnDLe@rAa1$$3^A40?|thn9dbSMkuH9#akRcRGV!&UQ*2&f`mi+y;7Fo_k#=3_;Pr0G1h~Xv+a7k+|=6o?Ns`P=So$R$eiyl zIc;5iY`HWyHvYj)tgweKMi&TU{epBUDdwJrgsb5vj9F;`c@dU{0^cRl=~bXo<_IQ* zM*kSwMjstKUQW_88g*>a-KiDs-mwTSymLhl%U;IL` z^Rx5M$^G6Xy~8~Ky7}f@ADT%AEDS4dOC-xHD1fPpw_w2602tiAXuIs@#%y;(HNd|$ z9}48Z3P%R{#3-MYN6*>5OIvHt`}=fnMf_*Ox>KB05KZP6)hBE_-{p{n6 z$etr@1+0$Bj3(|yZbSj;og`5@*Nb+!0h+c|H#r{&v?J}Hb6c~T;fJ85c0QOe7xH$T zm(PTYU+GEVR!U9UaIH&$G^j`kXfn7O<_sNd6dANuQy4U~nP8<#R00;JdV93;Kd^@I zm)Xg`<^4p*q4p;S6tzT8s=VgXVTMr~`==hy6fKI?M`J&GJ3b9ysRHwYp9(s3vvo9& z>gsHk^OePovku&HCQ~!r!S`pD1C~GOGKht@?>6AxEco^PJTEzRwf|b87<4_wzgl49 z#x;~OBN}@Iv?8H<2}1m2?FHF!tX9wZrp8hS>~w0MVa6E2teu>^e)ZST_w(Kl|GARX zZg777;580SUcu?*nbSI#a6B-IE_lA@Wh?l4)qTSq@m%$9z(*HH#D7JuFi(T!YeA`N z@R$Vwy@w_G;|lhvkosV8+sxTL1b5&O)*X6tJ!vDK{mYB)G0Fao?%&E~wh?!5!n2ETPw_+@!Bz zAGQ$65cEw@tB2TeXz zs=CGFOW#B6``>Ez$P`Zgx@8Ky=pUwFfDf;AFjG=EztTu;U4`bY?^iyKjza#|1H?q1p=7A@G0N6fA>sfz& z5~bq*C_(HPU0%NCESz4A>LOjx)X4Z-Q(iZ>ouEaw@EJNL!Sa9o#Q&`M!qh)Fk+2HN zGRXnK>yB(Xqh%-uS&OWl+m@iO?X-Z~WDp`iekKZZo)77e07S1G@*NGyQ3nw=K7P4- zd&M$ZdXcG+XG6RamqSgpw)&obN9 zDN~9n(H@BqW<9rsr~h~k69E9>UpuYNkjE6oY-}+lGBl?&13UV*s(s19h~C5RMt5jt z$4)|bEY?M*Im&;=2EH^Tdf-mXp>u z6Zb*3Wfgv2GHU}Z(wr>^*7ADy2U6au_eXm)KYj5hXoY zMd`-_a)Wj^ctyy~KtC@Z4e8x@&DB&<=&H+j!h}*w^Ypch3X3v_yQn>KJtA*5%&%)}++#T@zd|*5UX?REqvAPD2fOb$i((89tkRpW6zES>Kg} z=0nYzc0XGH(ZnTXIEK?#t1Qz55KA7W6&Ep|U9x5U>Dy~Jm%d-c9Q(g*-^7y|_ogyy zOk<>_7$p6QPR=3G$(>QJoJpzCZ3NCDC0EBc zq@V=%i&e#jF*06$D#v|kD!;?+zl3!;a77Qk& zprmxUJT!@Q;VE@)p4YB-eD?54lo+-DUivzy1IRAa0jH{S&Ye%U4|>SRsJR@Z{Ev>_Nd=O`$?sgDxb00Q4*z z+Qvd2#lirkw&DJIXJmT1Fij3gP+e<a4wS5#Ew*@Zk$?(;im``GT zE{e9z=8rykx+gbr+q5&(#*u0EE-H#y6)~^CtJk`j+cn{Yy{ub|%$H;>m!VDK8v0dr z6KrNK8c6ajyNZ?$@=?#AjAIIIU7pnS%FJfi8WJ=jNjrr&ICc5?D@eAs%5pWXbfU?Y zBQBoIFBq2!@3NHB;B9s0#{+aQ1I!}18=KChH4AZx@cf8{Z&~Gcmbd)^aU&%7iKHMXa?@UFHpTmZ8KyywM#_smk(z#s2;#~Q+19tf<5tM|2Z(Sao zwQUWtiXKM1Zb`Wi6902pTCGinC&~NWcdmURm8@lVHuktkE+jo&t7OZu!)_k&U3WrJ zl^NH4nO|C5_mFs45?%{~`xsop-T^G9m)Tt4@}tH6MU}`dW02(Sk(Qt33mu`+5()k# zn>v*R*e>Ev4SV+;$=>IYO`n&iSaGzdeexz44if;~k`MRbNd# zbe5DG(F2@_mD(YEduM#eC&OReCx5zEoEJFwdB8oOq{$tMOTpo&-saP{3bewy(qO=~ zjkTcJZpdbKIe33(I{|a`F9Sf<%)^fknbwCm#HX|EhilxW|Gq^;|605+ z(O+Qr&513a)u7Z{B2p>~-~Ewo`d(FBn9ph57W!k64`DvgI+ z?X`UcY@;`XMGs$Cy4yymJxbO#eF{GN%7|M9884*DUd30I7{rPm6((uaca|eC?LF~o zxbo0%SW@0YVjhmXYs#Ma0U+v1%Ey3YA_1s@ndp*5rj@sDt(NCudeWU1DMPYVxN~7| z;&YdCoQc*BZ|n$(sSjSBcic^)lKc*;OBXAjXLJFXJa@+1QajvI#9>zUjmsykEKjlF zmG8o}wRODXJWXU<<_1?lXUuI&mwrZhm1S>9=~jEY~s?4h{FDYn3DZwEdC5!Nmr} z1AZ&@^|d?^Nt(6qwDPxsDVKLFr&mZwJct)~n0Xe~=m+kepMy-L94HfdjvnGp2Za{8 zRD!O-CEAsAaaskc8X92_+0a6B&W|Aw2oi$?`JehP@$u}8eK_4#*t0@dYj3Z%(g zmD?Hq!p;?O|9deX-E!XltR&aEK&r^m5{Sv@e*>52RUO|F$@Zjwr`yF4?iD&>(ShEew)kZWA0LC8V)LlSo+NS;Dr0+qcn zHKDX-y+_s^U>h?k_R%_G9!wcSwmWB6FkTjr#VOUgdXlrW;(eQK^eN!*>!EGu2p)x~ z*UGyK34K4r9;m=GZjWc&kU4#XJmG^J0Ry5GkqOn)#P3+PZ%n$rzN%`u#mqBzcO~%n zfTWuQ*2KZC%WE%3DX@4t$CCy?Z3RM-eQ{}z)z>uV9a9o-&(_!8du`8xZ1 zlhG%l&sAY3^oPBljWcbhN&QaCc6|IUH8&yJ7|#_GU#$HrdT~*a^V(;bsp*+$D;yfc zTh~5&+Dei$fl2+4=KZDzJ-|+uyA}Y813^QGvq_@_VCI1Q*3vUg@cSSGFiKssoxSsf zIBIXidDG30f&a=osQ>abm+3=lXpAY9Pg$T_@;AC$fP8xT)Koo3z5YSD{``4twEh^7 z*oc8W5O6&sQu_F~i7M}qV$xF=#90=?h&G!6QW07)rz z`3F+ffQmt}x#e*cA#_o_N+gjVp;*uDqKvt;e*9d7peMdsdk~C?7kuWlYv=rl*zdOw)xm)u z$x_8t%_kXZ+zAa06APQdinIa6>sUFVcyOML>_OL)b9cM8-UClFU_E+;`vcS(@R|l% z*|F!yS%TO~%E}NLF(grg9%g{o7bk5Hzq;L_c`~jWGo54Q_S(0ku(UfD0;#y$R6VP9 zaCIeExcPnYb7m$Q@Y3mB-n#VxjLbveeMPV0Lk%}dr|x*x+F!wK&!_bBm0Yu4yyd_5H5+{Ep1deIuvaZaqIzvTQH19-O&o&KCVNlnl6$wPH@ zArlmkr18$BYfsI+TFfZVgYz?!_x*i^EC!)6SX>n#wV9Oaq<39bwoHS>qZfl+4yej6 zT_1rHGd*>(V3LE3%YN@$v z5@YrC+!cSPvjgL#UhSOIxZyME6(Q_1s$K?*f!oeH&aCi=GdnFrB&hR<-f5|~r!780 zX#Ty|!f#tPVTAw*eI26&(R9wvt%3q)Ru@=>vQwFaS;_Jj`&_zkomtX&Dty?YM0*(y za{cVj9HX0GM;;avhNPVsmOBMSJI>ovlcOPTB=IJV4Rkfb+YKroRdLYI3uqye4SB%q z%24&W^sCJ=+FC510>^FMZ)sfdP|^K{$9W&m(q(twnQzE3XMahPVGKv>!}&bO=lFG4 zF-IqT^^tDwKY*g;{73()dkN?Shn{t2y!#6SX4*AEoOK!=X*W36;bRWK3O2y!7I{XE zv^cwPFNkOyXlnHF0ks$P9j{le4c^;)1m3KQ>SBdRuZb<8B3ETq7led{0UVPpsu&(A zui@>2E77c0YR3e6szyLEItfvf-g)OLA8X>u8_L-n7_EgP!K!ccDhR(!|Au((Ug%;O zQft(`AsL9v7DF+1XSQV0a{8SRwxKR|dmEIT;e9%G!umlj8YkJ^S5a(3@li_-?QNS> zZ3!SMSN4PulxuO?9eC3mX{U%XOA(dMb$q`I+RgUz*B{Tk2(pUyEl)GoOX6&#H0wbL z`S6l9G%1uJG&B@N@cFcm0zp;(KGQ+gE>l*hz1%@4!xuckmuWaIFS-|z1i6e?9CfP3 zIdobR`1e|Z1_oL;=KS`vMSsO|eA&3UiWP^8Z_Is83Tpd-*rmTnu8_&ao@!j~R*oVjR^74l_3xB9JI;g*_ zl;H)cx?)T3zaM-{@5yUj<(&BQpI(GVfi~|i$13gH_j9EK|A|^<8bt)*i@jO8pz!Y_ z&l_YO;`;Qn#0BD7E|+7x*HX1=Tw$|uJ9f5XX$%>g#wh2o9fzh3j@wHnxyr;=!!Kghx z-^$#ey~Ucxv2D4%!u~!iGOA5y%ja?tHvE0>m)EX$z6F}>a)XGBNr)TuJWaA3TqEru z^a8R24uAY(c$DV;A})dc$tN~Ga52^sgiGDd7k=$FD*_KMO!laic>Y>O7Vqc)^AWIq zeeLXMV+upr$gLXYXN(pqG7)@CltV;Lg!96%WbDSDW24PIVPdaBEe(ylmw2@@1o&U6 z;>IaBO}}XWta-ik)4#2e{P~hZ^VcFwVUmqrvK4(yNTnS^n+Q-<9o*lcqtjXGXp%@& zdvgAocRcZyfvRIIE?+`x`28L4eD(Q*+Q#lXu(%h?n)jtZB_w+*syaGR592!)mY>hg z9y>|~8u&jl8IK@=^?zq247R%v&Pe-b)!x!$yIvgZPNo z17AU~y=>MRm)H7P6+SL@A4XkO2CWw|zHUW}fCiOS!dQwh@)Bzi(A)@Jqt0Q&%b-m% z>$G^+tq#u1A8TIp+|6U|w~UP%+IlC-rA&CoW(Qm8_Cw@&*jq#N>(LBk#NEmx6s1gE!oL0z1H*ku;kC8x#ClC~heQbq#q};;yoHjJ-7mpn#V#M`TPqqR zIhQk@yryL2FD>CORi*OM!Bs;p3yKXOHIlM7(SQf zMd}QcG?a9crQCLDboTM6WgSu^Qywbqs1=#b_Np&~jz8^_ zz^};$Qsz~`RQAzzr}S5}#Pc~^LrYm?2>Rxr&^PC|L@UU5zI-qAE3VBNu0J;~o_)zG z(}*4Pn0z^>bTBxfWlxhC;}_`LIt_{7W%7K4UkR2paNX8*A=Yn5z{D&nn5dSZS+}xM z@Yu7$>A#Sr+aDrA&rxd*>mQA>XZUS(+#BtbUvoVz_xccmUDQ~`d!qVI+hTj?%yRM8 zgQg4OL6frW)@rCP6x6n7CEX$%w>%b0!k-0QI)-*Ojw|fF!7vS~@E;p{Py5qXs%)=Lwl3QLi0`-m zxo_xk>PEy-9-Wm385H^P)IaXwMIDX`0f!j4ownO zA<3+16?wWA`PPC6)EHKQk<}`^R;9B#HtP)v4Nw|hg3sRLN6dK2y;(UkUliB7Cnqhr zeyiTazaLu&PT|8HXY8+WJ$TDJbDfnE&?y$1h%rx=oufmWEnbVODl2KWoEfpY`Q-i3 zh$<1R;CX*Od}0seH%B#H*i85iR;`iX!sKo1Qm|Cj58hpQt(&y(kiRmjc3X4LUvZt8 zxvlWDhcSH~-{bnxv~YLBW|GRv`LI}UT$WS!NawJ8Yq?GZl8#~diohF+l^AgRgqZXb zB_3tPmsD7&N07yJcb;%|Te}s+J50#YI*Bw=G6{ddN?d#vdf4G;z>Tw~yZX+CN3%c$EKRaihsu8kkBYykJznDTtN7$xX|wsMoHVcE9#4Y3{t=Yt1@+N; zUewnm*&`=Cjh?3DX4e9X$Itr7-|1@?8;~Pe(>x2qdTHY;0ttDA^zElJ=_6#CmfzS& zO_BLqL5eLT2yVL9?+olRi5(|Xt z@iBeA5JR&6`t_x%Y&eOTnp;di-UM%9rS5kT*+{qB<3XVj-Y*ANJEqvV`qii&VPWB) zh9*pB`}4>s+mp}kTu+KLHqWk{OWFVnHM*U>hj@KeZ&jjLo*iFeU3U&z9=pVh*Q8hTt?lAiib`fdw zy6O^s&}wt?Yl6zd+x6wl=;-Nh`PCW~ElR(I2|sMy-AktZg(IcpA6ur5_S$ZIKybnz z*;kGQ*F?I|nSztw$fToxZroO5XKv@_{G`}6NG2Y=XTo%Q{o1TLNPX#?-@W(8k2j8v zVVaK5s8QcASh!*jb#Ct2MWqhpEjNjx)R%?f|MJJBpvnTrg+ zFn?UGhG%Sq)YM4P!T6>r_CZ;x(o|kysX!Et68y%>b?9ie{&&ZSVL+}X>f-u%aV4x} z?pT+7BYX)e>g*%Zv@YlZv9d>gEjvVWE(ev>UE?iI4)4~V> zc{Z@G#a3W#g>KG$PZs5U&$0gLte59r{r8nxUh%FWH{R=wXKzNp2&CsP(XH16@ECZ{O+g+0^Qk&;j?OWUlMI7g7MCKsclu=5(-E`Yx=?b>jXqCl48{R%QD&NA) zS}RI8mftC=|E!UdhC~l%H1r6eyaLBQkDnj;^(c1{Kp&J~uZ6eT7A#e!%MU14ezKvU z2@rR^1)Y1izrB-auqPMP(&&CxJeX$siZ9Pkmn=OiCw{oZ2)A4zNdFWtZ7(MT-RAH4 zRGF4SS#*L6#=nY5#LbH77&JQP z)j>S*yIG&h+`>XQnxAdA5EW^Qt5Y(L&{;xB!#*;m4+WwACnZ77g{M-U^oMyRpC-x0 zVu}&Z1x${rb|#&$$$BdqC_vk|zNz^`4X^<4@mX_{rknZkW(k-3-5ASyG??2*#0}kdhV~l&;;Q^@;8GB00&ct3)hpYn5f?9gN`?bifk&!86{hE7?f;3a547gx1E@mOl;qyb0GNXE`iA1Lc)F&3Q3dBZ%NScpgJ-^^&e~f*U5;RtU#*$kUk)%8+AhFc$ z>a!a7)^Y8~;Bu&XT0AvYVzXojFhzQsJHIb0DNR@O&%Yy2f7B}ms1}F`1DUEobTyY2 zJdJJk!%+JJ>SWMZlkNgPp)>p^@mvIqmUl<7|JDFO|JDEt5`#fZ}d24)Owqp7tVm{L5{7F-7|`en*l zSlE%$DJhlqwLrVa{H3T7`9zG%=^wFx)kTNm*t>^S$~;DP6~LacQ*<(k(av>)U0SbR z6|OY{@cb8VjMmq1vIWo}?lU-920csb?uxbYc=h;%Y#zbSi*T}AVD-rQ&~qsOE3&fq zy3eVmwn;gZxTI&jbSoRK(w98=_%3ia(z3) zZx5gEZQlu6K6b%gxc%DRmfD&yu873%WDKs%fxT>mYF(fYe&y_6>gW2iZnD+ zIaYp=?7QY_GbF_<^g4{Mm50W$s`yAv8l3C*PVEyp6qp3Us#A(aK79oCIkSAhi{zuR zk0fVP^u11PGWJoyI4saZO>g}<#`;$~@o|!G=2YN{9O*3Rdt^fVsf`?wp~7jYXPwR4`=^eD>Ko`rw^F-mUS5OqNJ{_H=-D=xY_{H*%5mZVQi>7D86R*d zco`jOnYi(3)gLX@8v{@$r{Cf2FB(DQvmwb4_MdAoQ{U?F(IQCxPO7TW{=XXQi%{I* zn8X|*$Q-Qmx(hoNG8`>)WHs}t7XnmV=I0KN-T)mOVDir$M83)!tVmp34n9*VtPX1X289F<*rED)n8qm^57(-Z^Xw@m9;A^<5z6L}n*3u4eV} zE^Yn(Uekb)t{ZddbnBIb6!aCy4&lRv#9~DE-}hND>r&$zpYP4ZrWS8;h67nx=(sfM zB}#)>I-%V%rFB2b@;GLN590!4E@_5?xz8O*d#%e?X=Ze_6gLi+eh%D3U>nJ7F>*V1 zYDaOE^n~di9T8#)m?z>97%LiPwOql?Wgn)0KwHWXP77`mc<}fGC_g=o6op^}T5Z#h zS7q&)kY5+Rk?T_b^zvF7Vn)5%?nFoW5^lBp^W#AS0G-4nCnxWsDCp})KQmEp&VW(4 zvLz*4IF;BnyM8B5?F6Bsuw;1L z{TMlgzAFvt9*}y@A5OrlH{}HUVKF55w7S(38|lDua>vvhT757_$-n*6ClxhC4MOPa zIy1XDGpkmEjt&D_TwFW_Si;1akB8?%hfWID+SO zF3xhq#%35wq3sgGn)uiUQ5)=+CE`!BI#CWhT2m=C1R)JLd6wmJ%siZzb-tf*`{eEV zlzH2NJV~43Kd;_;bJU&G;ex9jwhgy}<)JC5PXyX!ck;uZ2i#i1H{;kmgVOH;gHx>Q09lQ5a6qk(Q5Es3?HYgZAmhBBC%iZ6?U| zp1TO*EkNc|V;+6A^%6we-`}yrWh?69(S%Exb!senZQ=ygpY3Z znQV7)ea)LLWCSpslp1?@c?!8>DfrMmlm4AWV1obcLMSNK-x8eu`S#kiX=+X@IvjlH z8&Q$=+t%J5D=#l^7LnrFg&QnQ-DQX-C-a@061GCKTseO;;~VMltA>i~7j`bLIi6l5 zK*kJVPtH zkfhP&IyN?#aeu{!vuic+ZslxE5|)m<$t!g)af*ZJX7pNVzS?qN*&`W*jXhkH0zW>M za(jD}t6_w6yP2EjRX4_NypR{yvN2?eCAQXx#!GYLbKQ?qaXs4XLGB6V{rm!wrk8`= zPA0fmEg@x{v3It9{)+QE)sUgt4biXN^g(`QeU-pkJUllb)BwcF#~1N@Y@WRt((Frm z!U?3e^v1Xu`8GfH!OPt{{zWT=|Emdte!aQbr(MPYO)7)sC#UAV>?U~Mt`dQfE%^vj;O1?hdfMUaMZOSd>&urPt8#EcMoTgP+f_qrPoJy zbz&Ln_eqdb-rYZlT}l(gu;cTTq)!}P3xyvl7ujfe&+Yiz-JVo@&p+~qmIsp#P$YOOAu^Pk6O=NAP9gLoG;SyR)ulT%Y{*mz%?`Jwpyv8i?VzMo&Tr4OM0&ZMe}X?Mx1Lr2iD7#QE!y8wZa^tjSA&vDVFkcf}u|al}my%PhA5Pa3xm ziLqj3Yyh->z9^2d5R1nbgiy;qRT9C2$FC|o8#Sg8A8BC1K2`%32CrX7Z}e}pOU^K$q88L4 zZZl$WjKs$*ev*|{x|~7a+EH0f2Jo*?V;f{hl;@foEK@*$R(d$wvd`1)5BA)p^hp1F zy!gh(2K&wzEt8WkK!jvueL2wrVe(#^ILJMaMxAHwF<=b?0`X^j;iml7Yh7=!bg?z? zkK;diKKg&)2_1=BOx}mxH1M7^<);M%33EHU@|j6lM$IZw`s;}3FgBiaERUKVv4CYg~>cr2Af3 z?9E3b{|R-liMTjaiks07`hCZspx{HQqi8u+=s1NDE6ETSX)d9P5&URz^l5y*>YU&W zLwy&gund*S1U>(!(%pTN2~JIwNHDKzHcjANSd}XG>W%*_&?xdusJAUQETvUY0=*?V?jH2nh!4HUd{a|uWrmsgk~o3~odWy%gjXW#8v z3yc_<@s(+{XyEX`tj9=@e$)U^RCrW;3*nt41|&gL%E)G={dKbr)HBb&(4(Eif4e=e zp|dWevpr?s{cv(_F+7fBP@+L+>T6szp)o$(RBp!6(UDwYR1hk`8z80Fr=9GB=&nvtmP(?-L=X|8Eb?lDRnODn$EIaf!|a#e#R>(^dh;n?n> z%`f$uDJr=&cxf4*T4}J5Zfmc;!N1~YFNnA8h1)S>bY~)`O+xshD6jnr(_2Sufxa-$ zQH7KE_Oa@ePWClRdZ|LzYPT{fhgf34ayOL+F{}ob{zFZ9x@{Dxw;p{nz)|4j>D)>B zZux%p*LF!UtYhQL%%u&jmpn>h5rVJz!&=QpC7sE%+DHhPG}dWHZLm2?e+-X^eG-C^ zLl;eZl!zwn>FD^-wPziUHagFyj%7)4=ITB)n+wQry`UeZUhMcZ zRY|M$R8%L03yX{UZq&f2d4Jz(MDq;~rJo}Mr^XfM&$Ff#H+kpxv+)T=09O{{>dN2o z78{ZjVqbR+H+q#JX@M@TlYxdiqZd*2cJ6z_)ysyJy>Y$(oue2T1TC3ZVsplnx$#9$ zrF}h}MjftK)-!Oq>B2)b zwkR?pIXLPWc=9PNqGCWjfLH(32%s2HKpE9>j$nB8JB3)M)~%9m)P{iLNJCMp2ss`2 z2lrP;-Oa0)Wr0S7K@-3V!e?=WuYNRaAj|Vq2E+Wr?u8ux-$2%Z^6A%SthsiC^)Qn@ zxlebCKNrJ<_w4;BNaFclV)MX!ud7qT;h_c53HeTB=j9GeAGP$OT}Lvb z`E_;O0JVCK-v?pqO5=&Q`afG#$^2=Uv{MrU0w4j+*iDD|`p%arZ_!X*v2)S(YKIpy z(#vGLwo2GP-zkMlN=TYDB9hUr_d5Af2KWp%iNy8%)VQr7R3kh4qLxr9YCKd7@~!*; z0(>KmcU!rR$*R#P3aa5nRo`j)7tCgJ+G&Mm6eZ7e6mjbs)#; zaL>zw^ocoL4wSo5d-YNgLs@9HScqE8&y3tkmeZzaEsAcerBO4ueRPVJR8#>Q<P9Myh;XmYg#bTx zNnXV&EfsaM;^q}lE**#sRb;f)RhXd`twI=lcN=$>x0{H!z^ILK8>1XO&|Xem6O&*c zHUIquA>Es++%0nU0%3Vw)G66~_tKLAJiJ5_#?yw%V!Tf#W*-_1!Mqw--7;-A4 z^rv~!^lfE|lJ|?8@SV!#?-){IvH3?Fi-P3$(&In6BG8LTL=P;mi1>jL@CdB8h-fV2 z-Z5R7Y=-j7p`)!QRp>hyiX#AsWxAt~GTu&UwfR{`mWa|+*rXBwBP`y$*B!z`>r76v$)6#KpOw+Y}ktbJHYr*;Tsmiia!E#2ccMkZ%YBYCa#p6 z!OWo5;n4Agm6gb;0{NW${N9P8svxH<&^l&NM~hyoQ7|x4>h&NL@%9ne&k?o_b-cLo zB1}r^uwV@};NFySY}V<&aQm8>5d6D@5fBeAyWUjb);o;IemjX~$H#-yq#9v}4$WnI zKTNv|7Szi*wWJA5;ZGJXFlXJBSPKP4GUX;8MJpmm15il$qmuq`J9x=xN!ys^+uQE% zSp~7-?-=Usp%jv!1l3&QJh6qkKB~aWPiZKM);YQFvoD2Z1Y>+b&fLaUd-0=+9w-|P z-yj&6%FROaX)vheU zhAVm6+6uny`t78)kS8!Lup^Tw3c^ozcO|)lmrhNyE5zDOHV`so&v5_t^5DRK5lPMA zNVm=PfQB}_4u9ZG^Ldx5ri$5_)@q@YV*Y}b4hxjdg|oDUK9>O|K;QJ3F%{GeANLW*2F^U>#5NO1P6FYcpf>x;kd zS>T5gegY26^h{p7UIJlTNPp`3$x191eiBk))^jXRb~@%7p*Qq7df_$6Eq4nwhaQ8yf@L5DOBmuYf8AnU8ku}GG$mrj}ppDnMZF9hn&9<3ThAQ#*e z?N#?vL+Nwbp%u9Iu8jks$|LW^IiGBSUZMvaEKCVK13MY2@#4^awUDU00Et)IeAFCq z>?x5kj>vnLgMrvd)kcSjY)Kyb8S}WFow&<^cM+;T?S-SqLQamBzpxpSLAxT*mTTSF ze@{-m7EexP?fuHqzyl0nQ|-}m#_4>HY5vfpJc9Qq{#q{+!6W|*4U%9yB~JIu{!yua z`>u<7bnx1=tQ^VA(2!h$fsDrqX{p|>KKZS%w)QKRqs6><)TybMt+Ss5uSif*JVK~K z(K#V$s1nAzLRq z%)}I7Y+=))MXcI27=@Bj1kBPR3^GrNz5xwt z`pnFZ%s5A+IU1!O$fv@Z0D*=&*Lk(k5+|&>Dos3N>KCe!y}Ej$to-{<0|ok5?c?7} z>hd{w{=T=P|6O?rIR2ks`F>cA`bdMVULeNcdVJGj;*>Fc6=~-M3#gS7j9(EG+Yd3- z8wk72w`MoYtJ#F!R|v)%iM)iDEv|ev>R`^5XVUa|-?Fgf|Bxg7O%0t$QIgS9S?WwVBdT^=opj3jSsqC%_cZSJ^ z{Y(D>DhysHca#;ei7BtvmskR-BAZFASc-T)B-a4d?!-736|sf$XALj(}?7 z%C!`weT^la-=5;Vt=tVewg=m-;om)!4ENt2N=vPD4uvi6I{`bV@#jXYF|-v=4d+iN z#UZlSIsgip4xvrgNyD>=(KHQ&)?!UquH%*rLeg#fw9{?%GNt8o$OU z<2!#M=Fj$kd%Q7WQ+4z=~PEvN>

n+6tcEJ-gDvw3N$)^N|3 zYgJX-I*biqwuNEs+}y6VTHs%iyRZezmuiRHWxpw4AP3=^m`QDk0@4<5en%0yC7jFh zlfKyQLX>}le$n`LJYfDE{&i#`%qPT&B4k&^XdPF0fIit)?~YKuiB(;j=j9?4;Hf|o zWCr`&tKdDmr`VtM5I}zq0eFQf9s(j_rEwod8jrJ7*tQWG*X$hS+%8|0y^iHbUFj7Y ziQs&FXzZz*2paU}QCF7`Yq|6ml||HLK`M(9c4xCzjX{3@z^anObU~Q(SB&7WQ31VN z?%KLWv|3_)Cl>YHj zh=@OVA85JB41HErg$k12DAcymlmT``2*+ot+WnNDlOqz9_$Dh>aq+K|5e)P1=5+LB z<%@2@z8l+1lE!a3lyZR{YM0zGr}y_cccY$}*jB5}t*u1^x`Uq%tqXcA0y+Q)4-cOJ zxI%m{^oPAEUjO;RwSC`It}kK zPUB73rlLXs(H?1l@nbL^Lxt%^m!($cVRje!Z!!TdLhU;4Kg=^k8(O&#f~v0LIIn0w ziU%i@e=T9y(f)&}5pTFjEkX8twbdHD4<%Mdq&9M#okyx7=a5H*_c|D)Sp>NS(CVG^ zf-h;kDiMQmVaWMuwNxMJ%;N!tN>sE%b~~B5xJ0dk+Md!cre!o+4fN;{?3J`|K_OZ|38c z+2m+ZS2rec3S z@b-GaYJmySj7lj!eKLXBA48zAj^llMMUN*kY9ROp!w zQ?+Ln+c`xex8B$*UU&?&Wi16|qegJp(N^6A0jpl;BZ0l)QKS9}T1vCI>-~{#?|S|m zQ~aaMH+%6P-x8Z}9$FaoiACtAyisAjW{ty6*Gt&G=8zqzw61jpqy(49u-8a#o>xZ6=tuviWb zJ4*r%)k6#0UgN%~kItz@MW>ZB#bXm;W{7zU3;j5gbH{*e4hn@v^=9yU;`8%+Xq{~u zh)>QD_z5Otcl^D~&;pd^{^GjWgr{(bZQQRNA>7#Oo7a<`N%!JbCB}?MCQ!TkMBjj% zDX7SJ54I?w{8rt%Mey+`&*WUlpVfNIJWb7A057v3CkMv@Bw1WjlkXhtI6z{8qP~Lf zCR%sE0#!jkS`ljpN$y|-q@)~E7C_&?{N*ouhRPx(`IJ1Qn2|>ped5p*i*qzl@U{ew zc<7fCd)u_q*Vk39adzVRg6rH6#F`e*HIQILaQ*S`X39ylB&LL*6-cg}agutX?p|MUUcu*U5+r*ShN{|D7tykCFNF znjIBZM`5QBnv9I(8yb)dz@#C3-J{LV@77X@y|z$~dHq@-B0npOuDKxp*LaN-;@&BY z04&xv$!7s)siN}bo6n$niI-p)3yl8x-2uKNPKmfM>Vkror*XgkwZ4mXBc01MZ(Kb5I4Ih zG`MhPfW?B6Nx|G}e~BiE?3oQX>m06xe?4{A1G+I@P8;7;(b3$BvTR{`!N;2FBUXKn zy|;xr&@n~Vw3j81Ic^U6C@=nwjo7gq{^e3*w*{96{RzDm?D3VC?enT?9x4095fxuN zl_FG6W@mC`pl`;KG8z1BlXwFphlcju&;UfBqOuO;6}#!;uaU_Fi#UcAlGRp*h1{3d z)#r%Jr?Tf%AmkO>jZ;ZZDE|N-I`QVP? zzvoV!Si~GGF%%)z$1YOL3@!F{UcTT|ltQ(hm~;nypmHu9GJPsf@p&IeX}^1l+Xt)c z>Tcy7nW(CyQmSs?EH8g&&Y?Oh2jcfGxU}T%+yCvbHKr^qSTJC3LEW8B6v@7DHpcbd zkP&Nq@PL5 z3fx~dTNyZz!;>nekI^wEJRds~u#&uDAwyQ@5=v|kkyTWLVrpvIKQQ1ochCbQGu++X zjnB>oXJt`LmGJWNj6=^i?9@yBJ&Qai@)X8ZCIs31K6SNufE2v<5<&F@A5<2n@ji&+ z)Kaf+P4`Hg^Nd6Zwx*=sLq3Tq9fpb*xOgE5<0z#M#ZokIj<_n6B=k8}m-?sxUOX2> zAmu6bQn_!05U6L?%bA!!zJOWcbH?7Bj$`Cj(x;`mtmbBI1{R{RfDjtN2@S%Cs~xKU zEo+j<*MAinA%x<4sP4P_rXS8O#*UX~ELY5!zPNbyR#Fzj@>VymI|kXPe@jRR2J|~d z=i4J1RVK*zOj>~el4U}8y^3pLVbM|dY3Z~B7IS?#ncd^D14L?R(IJt*SedSD4B!eg zZlhpQJ{Orq_44oAM!3_u%()KlF~UOA)ck8JoB0Za=Q+6f-y16bP`5P6Z)76L%(7S5 z@6E;-NbL5M|af$yB^i0rcAyDLGApx85G(esR^z=d?VX#OgI+D!_0_jOetOtfZ=YPeO6L!c+}ipvGB&rL zb{uah_6|-m_qD+X@oP=>(2TvzGWtLzEmx|dI#Tr&Yt3k3T^)y;qF&!zR z(%IsKdhhr2U9zbBqinXVyk$)gcZo{n>sUrh`Hbq%-(~4p7??Af$Zt6TC)=dmKU*G+{QGrF0O*S34Sjt!))SP043Z&A0{^t#U`%6R7Kn`Oo^_*rlwhJM%*F!#; zvc~)kLF;rXeftr@G)YTT>rx{I>k~SaG6|@)_pB~l*{@*Ocl$`Lu2IIkN}D&4BO3OH8Huo8I|uO#UMMADVqedMAX zArO3ks|L*Z{GZMsr7cx8xZ&YpqXSyPY0w?d>&=?eEp!6oo9QO!A1nfh1E||rwt(mG zaAx$U$VdIRN$T?cF2C#x-C9hRpw~xTE1tXZK7dW2QfRXij3Qq&Dm=@({^{21##iVXw?( zi6!LbqAfW1SM=bE8G-1ovF{h>>ARH-0%Y@OxL}bq%(tR9g(|@T~P5@XDh&np5`}TMLA#1;-w$*DRF;%<2>FIRRd+Fp(?+M_HE>7Pq z?G+fBryMJ9ivECH_l&3|MB$tS3N+Uz*^pA{VK^44BuhLPgP>DItGjSp2wAa|E)g<% zAErA8-JC+?MjDBoUFaiI&X!ZJevC4UP^z?0+zDydY>Pi(Exih(0AIT;OOhwe3K(Iw;SxG3piw`g5)MJ6=S;%@JoQ8Dp2KX!!Z{a%>;*^5M8VhXkQN8^RGRC6cQJ)klZOvb!9pF;<=IZG*2M9d%PkTu$gcN=UpnySf7?cShXwHQ7+%WC13P%_o3byXqRXoF<>i?YD!LX_+`T zy}s|*puW454BQ+oUUwW%ish+}Tzu7gPWZv!j`o*hXCgyT`V}Ih8T{ca-h0x3ziV^V3K_~q3=WNbMe{2zK+)M!!_f*Mh68}h=rnG> zGXn(%0u}wxDpfM!;p_gqcA^FYTa$!rfUhZi&LAqOY_513H)kv7SzM-`kFe!CR3RsfLBWgP`}2TnohMv&1q?$-BcPYt>hQcd)Zv>Tj~$l7)Us>lk#~H;&h!L(cFko zaEPa;xv+wYy@GD+KciQ5AFFu#WnFf=9nMS#{#zKltC9FC-6Q#BeWOLVjw!d3whS2< z)=u_z`~HJ&zcReSX-|po_E+o_y@SBh4YXk&kodhZH+A8B$N$?EN&ey*+I)YtVXse? zcAQ1m8gXx@^;01#o`*GU_oOdoRj+jLXyoT6!xR6eeFPYsV>_DEPxn~b$h+mf<*d=j zfOk;)QXHL5A(=37Y3|kQY}-UHer`35?)YZji-OoBpr)b6J(#UdCyH-u3craIM(?zD)(^J0kdZd464KA%d`n@m#JPF zX)ELSxUPTbdQ+gRlV&*JMmigb*FB`l`;GN}A@SXPZ5=>AyME0Vib_v^+SbHl(y+3<9_wVm6WI;J2l<_=Qor6cM#=vfrYohR z;Cf3&o_xsWyxPHCHsN@1;H0_`mlOT63RRJSFVY{_p@D6J1*DNM>k$DEXk}P2bTL^n zFJjZdUEy0hNcXV-1bV#^i4+o$azkf2t6HL>-`YA<-T264=_MNv<}Z7f5xF$QU5s-$ znzsPIZ=W!rM=myBS?N=l29=d<8mULU=jEN?WBne_;NVcL^KOGl;6NT$b1gf0`g@9A2u+j-Z%it zqtk9o=yN{X`1sf9gl!k-qFA`SqADJtFQAouSV?(5@4StcVPg}h?{?Z;oC8a9cYk(< z$Doj!X~(-`0!%*6LIBqgamn||G3}uEozF53EW%EXy^Yjb0UVhNy2v7rCRYniO66aQ z5&Wi&?VbEXa#AuEV2M5ozj{5UF%6+Vp0K33(ZX(T-(OC^o3;`*XT|*>;fhllanY=DoOa@2J->y_!Hk-i$sKFx1?;5#Hl z?$AI{sXXm|;%v(b{T-QrVIJ*#|2D+k*ln49-uKHRb|?D}nO)RQ?ibTB!25Z#a^e&6 z?c2Aw@+06=-^_h}R6ks8U7A))PYg*-U=qD>oqA};RtOsAzYQimn0Qt}d*me9?P z?cUTBsq+fq6h}7*T~_tI4Ohwr4*IZ{n0A`;~~t{6env zNBq(#sf4O~EAGda?J9JO(*^Coe9ZF8l;H z3=7lvLxM&rS5~;`4tq3G;)5>n@TNFFXO4xC9WDk{e)v$#0PucwQ@MbL&wFu}E%jM? zs3U2q2Z-SHpMEC-V8BOOIWsfrSzy%Sd@#EK1Pa1n4ft1>kCC=K{2p?9y4{&rTeBmc z`zjC^d_kcCUv=8%2d}{w!@Fm^VQ?+)!TQfw@2oE5-;q052J0BH1?dkBNK9_#mw}wP zwXJIWmC5D$hx{jll_M9Zgy0=^QBjdntqQ1Pwbk?NIiv7dt=%Q;AqqMLpm>joH#$nH z@QFhn&G+uln`njSVQZSs#_rP$2|LB;nUOTA90uC@_STSMO8RS8emQtqyp^0B3tS~x zvtO!NCIg;M1T;xs>(l^(s9SA>f58lCh}xbhP4k#p*X6kKrpJoqQKtfmRE4zo<%cIFz@q_!eP0TFy*R z*ieY*4UIea{UlK3q@96Sw?Dp2+I6`mvVh6m%?9S@&>`k#v}b3i4DTz=*#5?b@1Q?5 z5X#j?13#r-Cc%kwTV0-jC7Jnbi4XwqPuBx>Q){c$h`d_bOnnSJqP=k}#g*l+NKMpB z8j|Lu{_d!ad!Fy%)Oh!k`(^Qw17ORvqGfX;mQ9VJ4Jt?Y{ zOeflqRvoY8IcsN@zUWM^7oCv8wERV5SB&xbwP<60eyv7Ub{qmG9d0Jadl8BUw`*G` zl)d_?W!q)M5$n=Yw~JlHLR&ycNS8bWh+2RGuHpW;xe{+!<*$s7ecs0ZQ!j!*tm^_8I`Mlfp;V088 zQhcH>w2FM3;!CC-P7Z0?UAdHb`2Om{p3{hB9AD3GzhMEA zf$^zQGgH$I;6Gt3e{@hjT5BhJ_9%ZoP1v1pO{kU*dfuMzKsRsCV=TQuBs&!CmG7sZ zog)lt2C9JHGmi^en}LEg@8VLp-N|ZXG^2JfpcorGyNWGbNsRRNCj5P0+mxLWzA->A zq@fh%L`Fq$fPTz_p6Zc@WTT2{UH`o(L+n7-+qkl^ah2977*@dIO#$_T*iX3}4Z@Gw z#f!zthrD2w9p$SDhq&jrcc$O==f+lI#g zKfMGSsX0f!VycY7i37Fo;xrG>;}^z3p6`mg7o$R1)u#4Xh-3R^jV%{WI(+E1av1CN z_t(13f>drYcPS^$lacek%BD7ALtJDtHUC zoVo8lY!uPxoECKICKNvH06(5Buvnd(i>L@Q26U!D1Fu%NPZXF&D zwnyAtKQX;))k~V}>All#!S#dbwfAucKbcNZPvhZBjQ}1aK9{rFZtMNnaKaR-aOcE? zu+@^1S8vr1%{a-kj!tb!ix+R3N%zTp>z6mQE~v>czb5Z1@PBf@m2e#ZM(d*)tG6C`dr4yRyK2ND$5G&_Nkq9()8zjpPuK+qQ}QX=S9ZjMOcnp z*b1{Q!k{J--p{jSK}Op9x#c$s&?n6+{ettQ$#63wR>z~@=YOpaL=I?^jOjk80;OZ+B*vViJH8kRld-S`O4&Cv#;z!C@#Lr|qd)G!8Q@mqn^+DPc2p z>oLf5s^CZiL~P_G5ZkKFF|{PbNdQE+?;(NQsfnM6wxsnZxu@8@RFndKEGT|6i`sx% zt6WtRDXZ71=4>B|1aJ_YUtR5@-JtcMbgm2>%Kv~>8J%o+Wa=Ge(4mSSb4s7?rG=Ld zm{NP|;Xv9uk*{8>6}=Sx_I;|&rNI6Dh%hS$N~SWFAheWbrrbc`5915a7)P#k`bQ@; zOei|Vic5Z9fa~mZuGgwLG4ZL6agK_syDWNHS+Vr(a`hLioq3PnRBcbchb;C_5*H_d z>%GDV9{<;tr86QX=}&FD*7qwzaG(;cT9jzPCvN7p8>2!Wa~H0Rv4aXic#I1D0x!tl zw=?43$_42K*X95e^qFbqe7=#VnP1?re?pn6Nr!pa`+7xrk!$$m8tRyNPx9=$-*u8G z77mz75vZtbIs$dmA3b}RGJs&ADBk-EUbcsuLFgMygVToa!&GnNkKuus#nGs!&3n(Q zbrxCK^)!aQ;@Pf1_49G8U}~pWX~Rn~drx*4Gbd*8JYmR7j7CKD!y%#q(jt$L7ll*? zS~J$4HD_Q+6V-WCvwrZhY;XTsq@9t=UYsy4nipe5sja-uyG70QdA%a5B)H{`*SFeeM6F2socyz3=%Gw{cSd0w} zKs){q4_*KVslC&APM2mzFm*16uYedWxq(RALtJDYNXlcKWT1i(WEH-a-;T-YIm zB1)rZc%V}d5a7(JQx6K?ZGwy^8$ zBF3^glwxaR7f**&PIBHHtYk~@=`H16Jg;?}NEz)XZgKms^|? zp9l$Fuhsd2Vmb@;`z6%dDI0b!EKVd*$35+?6=UQ1mDRHNDSlENJ?+#<@HLPQU5|(% zIp-y2NheV0a+HRXOcM?STF3T9Ll>SSP9LUXw=OpUI*PrebFEsv`;!-+^8+_Rj(!9f zz_H32Hc^%xhL{>Q!x$<|2ENgGFVHITkz)GXbdwo*dFc#wbinWd^$5UyXUyoIxqEl2 zFSpe7ca%tk{x6>g4n&Ta6(X_mB;f0>GKv$UX5zPH(F=+)+hzU+2wfk}1^=Aq?(FXE zbpj=8Sa%4f^yN@^_}SUkP)scK;Tku(fBtLIMAVbw;_k^V;fIZW>?1#RP#TbNS?_w% zdwF@;VDaSDCk>vMqlrf)u*Ihm^9~Zn{_=%MiARMw=>pd%CurT0A#ib8L^abFi@5th zu3K~*5rl-;n=?8yKj{AJn`Kdf{Y#P`)}v+R00S6N6}hO#{d{895e+oXJ|1Pzff>yu zYt0p97M7r4IL#GGDZIEi9HCR9;S^&PNT*kV%H;~NCz0!s4@VlX_tt{9w~ySZ%5k(7 zffe>2_XKVhhp9;$ahb^8C!YtSH37@ff53zQx*o2qZ3A_JVHMQWdFccsn zJgcFBaBFL;AMi5Xhcv9%{x8r#Lf|*{bB+-R%ZTJNtyPy`y6%_53Ph6K%dGXvTsaxw z$cXFdbN$N&0Df)x^e>Cj9|ZagRHao`Xd}O9M4S^hw7->?o;E%eE5;J7%JyGK?c71GknxLIOPUi$bK3f)wm} z53a0)X)qDVqoUlvjaLHiq|;P7U+xFiM`$xx3{O)<ms!0OhKBz-+H?H1N| zZA0gm0rGDMQ7kU46LpcxX-1~Ubd;L;(@`>AWYwaK%&AV5x!|Q~xzI8g-tDaagwwO0 z5sYmGj9+wGxJ}P%F)^Wt%`Tl}D3;Eqe_;oioYd2!K@D=>Kl~1GEL>cvi-0SZ{ki*& z;Zciw0+dTd&B$hinD2B}8;MAu-AjP%>UahCkk?vKEOc~2va;yUQ{6kj$P?h57ps?N ze8b^jU_kv}HuI?;=J(Q4bP($y#=3k^0YuyGwT?miAMFPhuSuN07hE;Uoj&Y8okG@z z@J)eXgFrN{xh1Y{IfGi8n!iIo=fCiw(c^eZ8(*R8E)RFe?NMhay zO-0E>Bi5JdMZO2FU1$vDDSUv|l3y7!2cSQIGN>D=S{9l{FUHy4TrrkS>~t~ZlwxDS#gHoPU1%^dDo1@33Ks;oc&m4er)I6_`XIZn*uKv z;v#4Gn*Ok?HoaPzL_3X!*NxXxeoxrk#x`%gP{I&I{a`%rehO&~YOFBqsr@EkmF_<~ zc>W3?dOEY>oa}TyG0G|nYX|JItCOT_zaq{Z`zl>j9Ajtyf;t=kb_C~ZQH^1ALse<()y5jyPlUFQd;s;l;MxD(-E5*{h0a|ZG z&G^Rzg#>&hgKmTjngKHr@*u|h|3}qZhGn_6&%>ywba%&1cQ;7NO^0+zcQ?{0-Q6JF zUD72jE!`>I?f>Et_wRj=V}JF-UfkDObI!~;vvBea<<|#xXb{K;>3D)TyHQU=wXZ(R zLcio!3=lvWJ|AXubo-c{{AH}kFoZQm?Cko{4St5}I>Uaf6=z7?+M^8!JVRjl;1k&{8)}q?@6?i%q0D?vOX+c_zv#nuW!SmT@l@}oL>67iH_8T zArHL!1<(=u;~@8rkNcnhUy6&V^TtTPjh1@~_5)Pl=0r62S6wt9u?;qR5h0t!{qMZ) z_YddtDbd7u&R<$xu2u!VyId4Tc`Ee1DV&KblTP)ZPZImNdx1`I2x262Ej*Ys1!3k= z3ea>?j{MLHwcY3pN1SB9zA8}#IU*{PM|y)}&ep9sNpfOR$jMx$^|v>Cuj9**(~akU zhgEccjxsSEG@tEk*E9K5hNs5<=k=xm8g@GMV(ckS@+rg!*4DY@MF`T8J91l}@0=zE z_`zweVy?!XeB$_0Pes^oqFw@}JSmH{0GPF8hla-4SifCxS+euidh%7LjY2nVOJy6o zV96dX1Q}l)&w@wQ=rP-xbl)6l)=?LWSm;W?5NNg&2sB?PEH;^;vyUeG`NqXDK|hTG ztodoASI<_WPK34l2JY_f-=S^@5Wrs@yY1<+0@kACe;Qx9Dfd1(aH+q0A14e(@U$KfYpv7hb=$WmZ-xJ9ln;_Pa z?XLzF`IEsFWm=(#GU;8ZY-|!>!FQjp_a+PXj{5j$RB|ZUl(1BmmgqET^skx*Id!+1 zMGJ-OK7A-gQIs|mYZRdH(@jo=7(Z3GO2TqN!p-ttr)u3%^@)$cBv_bEnXWV(}!O~24? z-VzJw@8T1P&HhAc4hkCIIi;*P$|kObhs)Bp`FV02L_73csPTMxKF4YT|Jruy_wBRb z0EDOjUEg>RtMLZ74=yMjb^2}K7bGYqnDaLU)fef8SKIYBLt{2hhi~wAnGz2y!lwE7 z`VpgU=eG0o!W|$ae&y+KNn`Iv}lTf93Mj)q9G+!(7$`)(X)P_#Fddi~kl=Cua zoDak^xh5sv7u7)6QMfxbYFxa81wp>y)$jyK%FlLKXVytZ`Ge|}S3~}U;)3pa|D`z; zoj~~ZYLM7B6n#?`;m>vR0ariZWE~K0-G4dl$4%6Wqm<+6&yCC7V0TZVqZe*X>|lVq z5|u0Ze20gVbgc7#ax;3bs3@ip zI;~?`M0uePyR#Z*OGoZs??6J7 zh$=Q?eE7K&h-%j59yq}~h2=4)ZjWqc!)rs!Qzy5#ziZ_?c8tD_pj7R+(9e*4bwQk$ z{@Ho`?EH9KQ>2svw;HY#j6MHjuwP8Of2K67^hA%5Asjb1u?M0>6fK>FZ~WF%E4@-> zyXo!QACfW=du&+VJBau~N&rl!c-3e>OU-m|w57}7bD9Db-&|E3~@$vQ5p!{Jqayhilu0@ND{n{Q1}aHg zAb2_C&)YL6Xlws$={&u~#>SQ(83(#xpPO3wtum_(xwvln$t2emOh|;Xsh}|ZP9>{r zPEX!qem1l!XSDit-2cR4?B5orHq@<2M@cyiDj?zDO6GDy$XY0v6!(6;&!73=fqgJW zW&6mu8>#MZR;hk7QMbIRMLgl`*OUfJr{-vw;=mCW?fH{?bViT0grY&p+*EjZ#!_XcgxyqsxeCu zJSt^f91M*RHJasA>beHBKL)!v*eyQT`8Kau>gW)*0W*I0$l(|cGkS{7|+8A@Sl|AeG&NKqSK#rGUz9P>_E^dv&APD50mh$? z^_JZ{Y-~bQcAsn0PBs!XeWg>Fw@-(Gi(0F?CO`ijBHsnlCZ(6_=fnBB#=ZR18~XS9 z2NYFmR4+HK7V-E?QV5nE%Q7eQYMts>3tgV54c>DEUz&{ZC;RUJM+->$h;j8JdY!E$ z%ESZWcfCR;Dey z^Jle#+{u)eBy*XQrL<+^PidW-h1d@S>AAU^jF~lzLX$*3MY75J{Sw5G$Eg&Q2f=|q9$6uO?$sE9i2;gwZe@9{m4Kk=HQ^e!}8qd>JO+VIkn)-#Kc^C z8#&H|gru((8DHp+G+HofwLKnMlai4I95;Jj z9n7gjc*Vc4cn<&Sd?9sVge_uGgfRrD)3qdcxVW&LmtBDqbZ~TBtLi5}y(_1q>rJbz z4Mt6gj^Ic#9u`vMnK8(qEkOO_yu@umOO0};2tPQp@1IUm{rXH1IpkGQA(V`t2RHm? zuI^ooX@Ic}zZKprqMxUSP+Uu3b{K9iL#U5I9~m#Hq+>|G5O`Xy3xzQzu+KM2AmeDz z2UN6D?RXVJmKo22-5q-TNTJ>=L*)VOL~-;qj2NA+4OPY#Monf)#IH{*K-yeCHx+wP zt!Cu8r!JuHQqZiv+hVlVl{BKWuoP}A@Py@gG>2YLuu-y;0h=1&iHH0xrwMyyt{I(Y z|93z;ABwlM{m!}oeJfhY`T0noENsHo=4w8fq<`CUWH7)0d^O8BIIwWPEYU%~!_pVf zsxb;*GJyK`@Mj;>{w0Q>6s>yAzhG5zD4*jyIdvD{&_6r$#KY|f8vzRYHBhrA(ZWdw zpPEa#!C~od^ljsnDjmiq83pW4{;)bmXDg%hoPwoqj9`nbu^jJNwL(-Rd6AT(r%a=0 zlK@4dCwRdcqFt7Zmig$yz|(9Wjf*sMw!w!UlBeU&q8;lS;%>BWIK-6emXgEYV{<>M_U}Lj#J|k>yK~*;3V`Zsyu)N)y z1Ym~3d|q<0YE&|IY*Xr@)dK)UwcGEm839ex@AquCu7cgYMegiICxEzIjQ)6D*nau; zI(KXz7ngl?RH?*h_`De~o(?rV=DmOa{uC(c5aAnZyRCX1ji)Q*3~^qN@2Ww zxKcd--G9VY5KNMe1mgQ>^FT)x5Wy*%!5a*yu9TJ~y}lX=^yq_YZ@TuTdEr}I zyYQ%*B)f<4(LyzY)jv?F!G`xRqhv~i#F~!z*t)9g%7mY6Zhx9FtwbzPYe)8+D{!}{ zBJ%}zCWrqV5~$f&cMF#ZJ!m|_d()Jf5toa1>%Ptn@Mzo`& z833Vxgp!5Yz~g+>^X0e|bDGzwMN4JQhv~{hP_T2@?epI+RzxJ~CAyMGh@|t0+8cEv zy`X1$Fd- zYrVIYV4#BrETt%>47Rc>k|6>BN-{-;ew+1<3AN%Ee1B=*eG$sc4{V+N!7>ASu)`=# zl~c?5yBl!xh|-bvyFC@#wQyFMGHO@3Efq?xfuG@m%$>8Gy(Kw!82STB_|5ChQ1_sd zp!*AZ3yg|?Ko*YU^pT6|2a^h-rFSpRW+Zn!Z5!2Il<33){zP3<8JVxh(QAOVJ9%d3 zU<;Nn7zqrTsraZIch58?GXL(~$p+t-lb}I~r7vbO>NssRwxs+G4pav$wYAm>lfh$V z62JIQdr(h4-iAUxUwQORn<#BGOL|qj+)wB)fvc0@$+upkFUL6Ci0ySL8Rf~k>>9!C z*1;)gyW|Mu^FQ?jqq>}raKzVl8+D_f??g(Ph>?)O_v`Qb=SNeX4KmNadmry4aYdqQ z{qYsq$a}KZfg!0iebHZn(WxP|Q~8{4CIeBjxYq^>IJ!ZC)8@7uT|z?*$n7dxK_ehh zjOa@LQ(J$|Q6W6z6#D@Co{b`~T34OhJ&*sFa?UH~wHx%`NB(48t){Mf*x-3ZEZ}IN z7*Vs3L*-%z$alBIZJ<@~G6aKV-mO{#FXu{KD2C|uEo;Z`>y1Rf-WRq|c0s0E=5q4= zTrMtweRQsX!&9vfcw=207TDbf<8|JPWsdJ8(D&wIYWX+q?J3rF4Q#Bh>uuU^&6Jds zoB||~7~fboq5xc~>df`iT#YdU)*qM`yU-rwOFat|2`%3b*H<4NUA9*z(;#f-3=@HK z3&7O&rX7;Fk7=@xP9r+XHU_a6$NXeX-Ehz$G$>Cqw;R>#t_$z#x%FG8vXMGfmqO3# zWD3cG8P!*=Pq3!hfb*yD(lV6J*+uOs6mu!=no1(BxXY;Fp6DlMb!95$D@RU- zboKwnbf_Vfli$b?0t91t@X&7t`%O(vRlln;Yz$-J;B=W+wC2|yV!+ZT^KjJugzNN& zmagH_1L%{!%c}!o+pRjlrIfJTs*tgIZY%e?FGH&l*udM!~X<^yw$8 zU|+Fj0SX8>x9RJ&k>u>?>UFk$T2^>}!^Vw49ES*Hd%O=J!cxwT*L75cv+Vfq^oy}n z*{!>G?~`aOhfvGDvZ80|DrC-^hiiDJFh%>wK#Yp8*}fYt71`lQY2~WWsx`T2Wf6Os z=~C~W;uxC=H})SMn8tXPPVXLn*b8eTa$*Ir%h^ma~X9hWLXI11%+|lvUDvUm^Kj*Q8t+%q(;N25#W+CniJ3 z{5OMqMNqS0%sxfD0;sxFygH~|hp5Hq=^k&=2m1>adduuF(K2$qGJC|`%=-N?GsmHS zLL+By^cYEdPZuZjrcnit<{lmvt|=sP(PPd;D2lbYZ$e$Mvcq_A(5d;t?hG?wGo5oS z&jk}60L6D^X8t{V5T%1d-TJ8<`iiTVPNQNVh)gviidVMG%_+W`EakDbZ7soz`2@$D-o!XalcbC z);b2NN=(vBv>00U#%hV)DnaDl`1?;1oy;Go6mbuBViPo(6&DL88!gI|l~Z8l9Bp%? z(8z#5+E0m)@N|9eTJ;8}x5ZUN=}>12OC=8`@DO7=;7DnuhqeQ`GGYp;w0N}|vB7&YH zzHckVPD3fg&RaD!Xf7=2>1V*DH36N`$Pd}oD1WT4t!ghq$rdJ2P*2CqXV=Yt&k%R7 zCFP*^A?|E$5z~MldFlbn-6!*jzG$1{)@w7x^afxjD6KUi{eS+Vby~mw4vPulNBira z=vN}}j|s@x>4}M$r>X#j8OeVqZfeYl2T;CA%0evEf&dqQ6OMm&>n~yqT=S}>56gMQ zJ!p`iPl5x4s5>gxduWpxi?-4eu`82`O&Q4$)A0pchI;;BIn=wr=74%SuAr8TBsn&e zl=U6*cS4Fap644#5fl{pFl3@jep(?E7JIyT7X{7CYj)qT>4z>JG4xMOS!X_Z2gYY@ zGqdLWj#xAFC+*C0=S4+HuLB&4%SHLVEa@_7I-gj#Z?D+d*QaF#(C=n2G1jlpY5I6~ z9Jb{oVF6MF*J)}N_E;PGxpC%ZjV$rAv|#5aI)L@X>U>s3lhO1nD>OaNsl+EheL z5RgwS41Urr1Jzwq2^_&e#jF)nt8Z)LkRJ%?_n3)MCHzYa!2IC6Z&>JBy0Fkb+cd&PY~LST8K0u8}-@_WD`7!O~kzd zBypMOD5=Bz#=73-otp67p{5C_V16bb0;;QR53jlK_by#d97NxGHdzw_%xr)@@VU0N z>Aq=GReqPa#4kz{ro)bb4jsHctK)@F+rv#+9b?Zf!X}sVih{;L4nKKpX!QqniWw|t8Bx*n9MjiZ_K_&=wKL<(6M#n zCQxlasJD&lOt)f$_=1Cbx;s6?1S6vxNnfSyu1{d# zyKH<~4cO0Ou+rdrW-NjAYuKF0ge2eLIrERWAwL!0<`Ut%y7s{Kt$x;aIa?1a@@1{A zt~08RF{jb@vk&f46ew`>GBOb@Ak~i`vY$2&uAV+oPw}+1q|Wxwv(b!|nkEdgSu|A< z-7(2QJ&AyWo|UQOB2sN;5|{Oa57Za>Dw|tXg_IRtYMY}C5w-s5T09jRN zjg$C$T{$I{;Oj*1&^Yo2Tmc4#pdiV{?Pg6En@2ZJi+Ze52e+U6jNX|CbABrXykC8g zt9ZZ21B~NxBXR@1PDD@5ZgN=sWr|0`ireoprV;xE%LZu6zF&^|+GsB$q-EBhjTa&_ z#|R5smTUYTsRM?TYlS#eK?}67$oZzMmWnP-<7#g(_7%u*iA_)aUJPLlFEZ%9TF%!r_AAhvT z+;uD#?#78aj4vn$qj;Cxo#v;rfi9MhchjDpmf8OKPW)?)R<}6gL-;$W=^4?)H--Xf z&;wn&y2svo?w|K}GQ7G)&wjt3zb?30W=fBz`f~y?DGZY zgW`2W?rgLdea8L9&Id zv`&iwEgfrDBVVu-hLREEzm!sI-nnibf6tm0xHptXT^(Z!mQ50u-jW^RPw%`S!mOK$ zFH=HDK3<@TK-W)2nS_;P`Oc3xza%ZO5Zww9<#Jod&|9LzalHt4Kk~MSamFCcP8Q0R z*9M4fq-Mj`$HLkVASI@XTF2XxnjJtortz4t2Nq;)&V$?$apPOrqI1T-(G>W0r72{4 zq%1JFaGxqW*2(SPRL8^=P9|DaUr?d@%t!-Omo&QSmS@te_3LA>9)a`U5c?gnV( z@&yX~FoU&OKQ<&9&U_WQKGF?QClsP@ZSQJ+A2#q|N~@g`mzs3Q2fNO%rhwjXVTI&p zaNiiVPsq?yqVgklWe$4SVf|3?X#eVY{L^OR=B$DI{GE)g-Mz?b?|v4j;8*8oiBul= zts|UscAvB&x5;G86xN;K)+cw>9cL0Qa(tI$QISJa6(%mWK@z`pAgH zf^N;)gzI@uO83jK1n2w*TA7A`_m~$gFR$04>@;NdxIZEH<7sy~kNnC44W1-GmG2ZQ z-OTib1G)x#vJX^0%t-sCzOFd=UFN8OGFRuU7?DZ24^LaPa`L&6`I*a;kQLB-NSASRV zPs**`q@TmbQZ~eVYUqpw_xBrZi{%LoB_(S+6G5q=q0t5nL0H7=#&EJKpRy8YNUfql z?xvS!v_FQ!_S83`QPb0JIwSC13i97oZ}T-!GayE4xihhkr1Rvrlll+Zh3_r`d)i6c zYSjk8KNCQvMFT}IUnrc6jV&Dp`lO0 zDva_`XcDTOR-ZzpUO9%AQq`f1zo{R{kF8}IsreaKI!(^&Xey)R{kk}6>TnYKyH!>h zgGLFauh^EUt1Hg;3^Xye^rIs5`GMOVs0roPHaEn;Sw_?-F>}_a%Jq9uyn+_YwS*qm zx*Yo+4mfY!Ltn|Lgl`Ez=n0R{^;J8TGGx$G%V%1C^jmB@i%tKSEcp>W3@)5JPP##@ zLU-QH^K5e$mje#|0S82QXtMI>agK&6*oF7a$-QupTyNe98H97WdcgGUEt96{0~05+ z?+UOqM&Wd9L-|YB~V^@NJ^SDTukd<>gvc?OMJ^TM$p%&dpz>HD4g_;Yywd^g$& zTN3tAWrqlI?!$UWP3I@f0R3Y^cjyB32CH!xU=v+eCK5 zqI`jD32}ghhn2IH{YWk@csc*BNLsf{iUJ%^XLEi|CB;&_!0*#vKz^hU$^gmW*y~ti zAL6T`MHqL_ij*P6Amn##HB~_{S+0&((Au^{oq&CL$2*uZBtb8vwny#=8GBk#Cj0pp zPvI!^*L4;+`C!?aP2(`sEX81DhYW12q?~w>kD2{`>1mYJ|I_XT)=#Z7IDMSWdmS#e z*Y(_uI(?JMn3i|33HlTPB1q-_I(KXXIby`F>0|^R*Jid@Nk0CGjHKWbTHMWMtZW}^ zg1&);tM<@{twC8c6(Qlh6yEilL5)qKeL6A$Nn^pc_0L9!kCWjO`hDrUy-DV zXJen5Q6wZhdE%K{s{ofj@8)RhhiGRQsoO}By|~RR613#`{+{}jVYIC@c4#V71M*{;d<0Zv1# z$mz#3GcY<73`s2S)xcn4vBCpOi=L89PwI;@8rq&i8s#2`@KeCSQ2>MtE!D%n*HHJ@ zR}OvqhtZ3_t-%x(!_ZiElqok3+Cp6%vg3;4N!* z7A#Wsd9yc#WEBmWET5|mEbg6{MNS3wnHH872smz-8ry`nCS(kcUNW((Ur#Z?R=A(}%M(3|Q$@3Erm0NCTu^6pq z6f88|>L$oo1o$~Gs)HXw72L(Lp>t3pi9sfiLabAg6q3mU9-=oX@#RP0IVM&}9gxnK z{HSX)bEZwjcDxGUCr6t|)ALo{tfl4j_nY^tJ4Y3qeE5i^8t+pLjUI1+naic39ARal z4gX_P94`b&wXD%jm5 zbXEd+S?N8Jhu=Qp!$_|_)@ktRfb3yiuI%TCPN}{dwon=!8kWGT?Cf2F4$%7PZRO=A zIFIfX@?pswFgsvwZJpTovc9NKOx+V<;eb;;5>cQ>Qc0=n@pXsqu$23CPN>aej%ej* z2c$VKOAZy-ny_2DaNe#V1|<4~tMr08YW@E`2gocBShob;2sIm$ffN2$&%TA}hwBxu z_Me^&}Gd!z1GBLb!zlqnNoiAobh#*Rz=j<%IYzOlV(kbjiKIQrd! zuDzkajqlAXGojQL=sL@faZW;KwBN>7c&XK!jI*RVKXsBXCyEW*#eBjxscidt$42t0 zmBUDmUD@(Sib%nTQP2##1cU;fDW~-~x_-FyrJ@XiwWLX-ZaSc@Rs&Ph`+;#RGzp8Fwf#dBUm%}6F54d&=02HlW9h#~ zCGsHr56^zZZrCWZf{0AUAG_p=`fX2n2spB9%_ZIi{x8L;)+Bnu3K%-75ELu8b9b-Z z{tm4aa5+x#+;V%@ur~|h zE<^canP!5`LEj?wtK?j6iM~ehZ4PQ?^nk2Z@GmSD3@&bEpOk(wZl9Z_0(%gUb+EI~ zXe!e%8=4uHm>U`^^*l6{>r^bT*m5f_O$R)4va^wdK{|>kj!N1Do{g?7^r-?~Vn@Q< zS|&~{0Zw2rc*;I){VM-0MBgv)2Fr^olKii<9*QJ?SZJ&Q;!`rd4pU)5#pV5@%kQ!V zk_?R)ko#$<4%%I#+*wi7$QRYMXSFr>?LKLg;u z;Vo*c;>)37|9=k6qR)x&4FNNc=cru%PtT2Tj+~S~cfTt>%E&}a@Gs7X9C0o)Feu~w z?{idjYsv<}*89a&-aEXF`2I&L?bj{oMFSz5II9_mLZ#a2lT3)Ij40e$mqJul+Ks>M zgkn=U*lbcfCXia=etQjbHFi2Cm21e#n~o_!1C@fyaTdD4Dc7+`AJW#OR$EITD4BEX z3Br2~xk}1R&sP!2f4(VkOp77S>)RS>wk0KFH_s5%WTesSshe|58UGZC@gMn!vXJKz zaN?4KzAT-2aOR=H<9o(%UL|GdcjelRjGMR5qf@@*QvdW{l?l+*O}VYOZ42|>Mp`Wd zUjN?jV5J(hhlM%m9!agrF8pD@$}|Vn#YgF39_kSn8Pv|`jHYrR zDwnVoa{;l%^8HG#QJ_5}i1ynT3x^*0f1`X75~wl=g5AQQ)Php-Hi;<^Q^%dDxT&IP z8z=kG*8UtznbV{2c+aPQM{&L;Wb_RPT4?SQxkPd-p+JygkT%lx>3!ho-c`R+Rbg~m z?$<6V$}KeP!i5S&(v;Wsh0qcv6ETb5anzusLlkMib$I4n-YN)B%Dbswp4vO2^JQN_ ze~H?kf$erIGJhYYkSLg~p>gi~u+=-Z-is*^O8T+hMuiP21NpiH&L#)2V1H|27KZ6f zn-coQIc=9$Fwf7%$zgYjUG~75O8Om&t>pu2g-Njc5m287ac6+dM=*v}&cXB}Y%M(n zC;K=B$#gWaq_|S!9G0Ae{-0XK_Zb4vuhz#c7b;ckz5ZcjuhU-DL8Z4u>wXd0#A_>D zo&rbWTy~pK51!NJ%zX$w1}__eBAWj_B1uSAeZSctG8nm?jy_cmj% zwuiL+n4F>T;@+|NOi|n#ravo=kc|ehBqJ9+{O-$=PCGus;XRo_{*xRJnKc=V@(P(| zH*FJ))yRJH<(A9zJ(cZU z^q5OA*tQJF5qGu=W3s#oF_(^XhB4>uhA3Qk9hMTd7kc6nbYCZqpEU8{CX+*YxtvIvww)b#h(O_nc-W^buUdQn;zoUMj9PJClmCzw_Re)ohVyR$w|yahW<&3 zr~ggJfmyrBG@xsqd)>hL^SjlBmF6y?#WuZO5jyLx(;?<% zU?b?d-nxJM%4scWNw3o}6l1L=m0efct$6@Wgx99ILB)hY`#a}8SH1PhD92WGbo6y! z9pyi@{{KFBMt(nMUX)+6VG)+Qn3H1dz=8zvkX?_xv9U3%FE-m=c;N)@`fq%DVa8uJ+_?V^e@YNFe!v(Om!3 zYP~$Q7oOhI{=4Z-v<*gc%65nPB;?{ zj5n66nZ+l5oz*Cg>;bi*{XvB5dBxOA?XO?~4{@t>>i+h4d_H%Up!T%47; zxnR-l0Ya|B(sMTjwr^#}L|+SBY*4(LC#N^UrxTG!@@bPQOb_ zOAGOgo3U}(-)(F_R)W+%*S*WYReX8_v1>6Oc~?xg*o1OKN7LO^N~=n@|L5+yo>1A|QBeNy`pgitYWU{n&^d|kJ)=b0*$#*t)ctjkR0D#X=9=#7#Oe;M!5_*u+6{6U z9DH1oe3?ZI@#9|xWkyhECikqMi5VTcNu@ke;9ztqNWn5DRLft9d@E*vU4btU(GR34|NjsxHGc1~zO>{vPsI(;&ix_phLA;h{UW zJk~RupZB%r=eyoBnwguwrP{BYW8|TuBR3EKc#~EF38s|9?K#HnTeJLw;3+U92_!q` z99RIeCgrB*>dLI`>tTV{HZifXfgxlTT;u()AGFN?5Y^C5&cJe8U6<1IYKaR%cts8~ zW91xj`F3;cWMCb!3s%LQz%cWX?f{&;-yFwgGbRGeH+)Gy!Z>vwp#dTP z7~6#`Y=UA_*ZBTD1|=4d%Bg=_MEZ&BL|-`xUTigLs>U*q%ccT*pgG?)#d-f~ad)Oo zI);uan4XpT@3jRy@jORXF5_#A)~ZHQZRZ|tC)xAd>bpW^Qb*n;4xvxq%xa^0Wrn;= zggtX_{<)j0R>g7K7gUuMQX>cW$9*6rOlUEhPjl6 zHf=l)x+Yy_OJD5@Xd!}2RK<&D?7!j-?rfVJbOnTEtMx0+jq3vaYD5qG{%|r1hF9^4 zwke7Yn8u$ynTkw_Si-N`Hn&Vx(~2jzT+Dtu%Pr8yk%|Z@kSlAQ!_qE4;H%QI%cvGl z2DP!n{-|PnEW~0-KC3;4Id~Ka%_7T^^u7FA# z9oUv2ppy2?PLSmP)VZ`;$39=;Ohg7{rL~VO&KqG1bpP=Fvjl3u9sY+O(>Zzp^XdyrF9%)KC+J8XSiVv;wE2 zZy?+DIiiuW%&gXuz}V7#kKg_UMj>JOakR3CuWujPRl=Cy%&rdLdWRU=;o5Zy z9Zql|?k3*9a2;X)aUD!l&m$Jm66}XU0dDgipWkjhgmTt@!=2%ucD$b6KVQjDkN2m; zEMu!7H02*eMFZ?IK;WCR6t+qFWHdVSv-1GvFbafL@6I+B2ngqED!lotMw=(Hb1})8 zvtb!&^!cN5b%>lzG|?<=3A4#GGrdWJOc`x=nEv6xnb+FKNZO0{sGrgvKB!hqAN5pA zBjz5k2z<<85l&|LN~yvImi|g2FI65Qq>_5@$*|nXdc5NmL=lxX9REPuAR#i6w!N&&@J5mmDTI=H2XhM25l*<|4l}WxvES*!?A1#5Jxd+yEGL zLPlrVOh?CPRkJ_~t)2oI^9{1%{J`eXvq6&47$^Sr=w)CCjpRr1r-Lw{AY1#B@podN z`rpJrqRh!=7$Arl#LcYP{oeZ`ol#US$B z|HOL)h#M$B(3L?yL0Ntj)*&RAtA{r~Kez2(@BJb9TFVaMpBF$T<11PJ+lDe#pOkWX zxOZ3cxChpqK8JcSECW{kkLI&oM&p=Pw!bWX$Vdp?cNC&IIv0~E1ymOa2KU{7K*N)1 zn#>cQ+|4Fa!(`>&-5Y#&U2S)au|Jx?t$fI__E9_h>|>vNCivM0N?c}37D9?Gz4-eS z1$So|{Jj3!6$<>KzC`s+_f4EXr08haO`z?=CPJE`U6Tz0L-?(uS#0sVNC68mSPd2R zPj_0Jp)_)L0Ztria4V0cj6Sfz=UPt2RRZjMn^OLQs07^V2 zSyOe^eSfAv;1A1NZHb#P*G^dW<_$S%0S6Zt+}KbG=kz8RI_${$YTABG)ak3gIdQ{m zfpa5fMz)No-D@Bk`wU-i>>u==;5v%nO zdYca|72BWoyA};d%H)5eQeqmaP>V}_z?r^>y!j$E9#^haN`)w523Iv7k;+-^J>XV2>FB15=v$ia8qKP}d@gB13&u_AS1;L=Ar0cAoYx5K?nXsDEaq1Gt6bN|xZjQce-ik%0-@HwcPSfh%k37#iLW3}qXU}M(F zqSrRu%=XSkADJZM&{oRSeTvEGz)*KP5cKk=xbOo-gN~NA9rH7qeh3Rg%FUMij&Q}= znasg0CeFjml+6{wKSH&4hm=HfLLs0chlUg9e~4?*|333UO;uxHP@}T)!0N|hnp7-h z9MRi}^v+0ZP_Pa(5sV7I8g)KbZ>uPqIV8p0&4qau1Dl%EEg1#qGhoukc^&+%{)oHQ zF;hg_tturBzWig8faf%|XS=M)LaCEq&Bg1eS2koJhGy^iayS{AwQHdz_2*3EAi^E4 zPN?mx4GNI42j(i(OHYP8A$}g>a$$dWUH4b;#eo1Mb|1i>uQ5IC(oinL>1=PyRIXk5 zxjGSx4NwPM+Nx0s+}s@cF$|2>%K>nZ8KcJ-lSE~5t#-IB!GL?ZSCF}0RFHvkM~gAk zo#ZKK`!Wfp{U@&H`y<0WWRvs_iAq_)Fxh|ulhbMMs=NcB(tb;d|@xw zYP1o99$UX~;H`IM;XmB%07j=_Y1#hu1B=OT6p>B>lY-8u)n^H?rXTrRi|W;Wu~KA4 zZ1xB5>?y`Vbf?~DqD$0nk7@^P?RZHi^V}$!*I8J0xV;)k_L&qF3S) zNGsRf%Yu&9a^NrZf*ewb=;N2d@T?fw`mOVu#9)*O&ADB>NOI~H3a;@vz`yorJk=V8 z&yGu<&Vl$vHnWeWKLUEE{I6sxwSSjmD3Wjr+$%R4((n&b4~sk&?Cw^33Yxsm^dM8} zOLivgZy<7*Lm+Qp(*BE^o6U;Hb!YeEqkh<9UUv3cE3^jD%MjD>e>aFkBkD22kEpgV zrWE)@i|#Ftw=Ru_WWZ$-)zR~(?vf?2H9XwK;kWX`_G%}#(!>nl;Ys_>t65`1th~7` z2I6`}^pVv4{e23YWb;{`SlvXdto^>^bV{N}yi^2!sRtrOlLwcj6U89?or)@4Z=kBW zicY<M}JRKqeCgTF0P=HhGv%Wgsd|C7$jc`PY(7C6`j-lhVJQRT<^kzz=PtsI;ZKyq?{jjqN3K z`O>PLo|P)TTwETgqr7#UcfOt7T!T7>&kf?uAp^EL8%k-*-|7OxN?W_f{Vtzr##-@r z-iQ0`kzbmcc(d0ZdJrsgYT{|eh9`jvQ?I)MudX7+f}11umZhhk{&W#9MlJLIj9Q9) zmM(@RkXJezfNsBF<9KYr>uw|}(p6*m4tmUFz>YiMO3tf97py{d_+x;fuJmwMl?}Nl z-Y*RjeLH{>p>vgBw`YdB%HVMD60sv*0m&qoSxHu|&unl~sK!dhE+i+8N4CXk-Qqhxq@*0wN#f>ncg#d66!VI* z8>d3XD7SV*_JB54NTg!ky%pJ1_rtq8r^|#kY;;;;E5=y zXu|>g%I*!3OisUnb5kexd|7uC;T6g=e-R<5$e_>K5jxzsylpK(iL?v0z@b^#jdexD zDIdsK`Kc&)-4LQ>+{?woXnpEsB-x zgVBb#gF0J|;#G2*DJ@m<8R6QSk%9FeHr4jUzR6V}8qvkrx}lBnN0d&HlZgE9zvq2l zKV0_{c5f&OR5a0JK8J)LXt;Zpcs16cd-1xf{?h0Ce^h;CSd`xv?af_cXxMpb6?co|K2;F_<)a`GiR^8_S)46bnaKWtx0K@ zgz@lyDAS18v1L5I>5O>hv>G8Hr>5o)*fcQpm%M{>Egr5Dv~O)@HqAG+^IsDB`{nKa z_rEWa$Gnor8nfPi=OBi94-vPj?X{N=lovY@3lfC%%^u)KI+#;XW0b%5K<|^7iwWS^i=-oWJ>6W^LAE>F$hL26Q3*%8?kbPek0M6w) zZlF~OAv`nhUi5obdppW$k8sNIF5x=Zm?ohOsB`&gj*p-0Mu`LA;so+*&zIC(`H{uN zqw4=lrzX^4uXqWCp|DZ``^U9txjq0bXOI2gK%=gAMC->6hMviZQ6Hdi&H-&f`2Hv? z%`fyrq`j_z!O8)>z1P2->g@lO!)+h?M0J2b0qM7OyBRqD@RqF#>luyD#u*0j_IXiK z005=w%;A~G*k`tkAM2mzGTno8EOOR9!c4&}ZhXG)=yWNGCeOQ4n|J~$^sf3oNcDSX zoqb#Jmc~0y_A-}}<4AUi$lRUl`nHjK0hP65m;Z#mtoS&(IOj-acz_p}gjJWiBJC1w%OSV~^!a-I^{8tGaC~sIbi7L>P zJ}m&v1vxPytYkc`_CG|5OSYYU56VLbDHNv%xc)49JFg@{Ld`f1#8co6d1)6RgG z6-_qc9r(rN9i=iNd=jFM-13v8MndV~(EeXC&SV)h&iZN-wzv$MILtdXJRC)*Ni)$^ zBp1d-c%yMI!xu5#8`(6PW4w^M$IZ+p*!?d|Y&`hBFg{l~GjvSjM+P1b#z2)|5%Dgs zv$N>c^!EB)T(rjX-GS_V;v9+bEZrc&tNI|7KFVYv=hoHUBLexZX&YM3^e%cuFS0_` zxoEmFSAi5X?Y72F)beD$j50dOX6o40GR>Ed%1E!IbmE}HJL!!pLA(S9>OfNLKY+;<&Vtq~-b8 zY0l@=1~W^-80H!}5aL~KhSi^AN~`pZ-%0``6NG@21NjGgvPsVTRm_j{NerZO7`l+y z)S&DQgq&R&nep8jk`H|aNnAnFzu{plD8*lnu$m|3d^HT!HLJOgt(TrlMtuv8*ELQL zcqc1<$kY5ZiE#Kw2{kY+Nx+p$vQ6#8UHhqDl^f61z_0g_hrqtdVm9U;lg+3`l9qly zf{Q@h-Nv4~Mo!!e#1-BqQzL#;oaba&g^N zm6eV1@$giBjQnj65(_Tw21=4eKqh8p3B4Kr7N>o|{!eM5wW>raq;SQ1a}T)3(RbP_ z7Q`vFTH$xk5?1MPKUyOTuS)j^nu@Q4`66bBkdqVHVw5-l=@TE`ljF zX!KP5r{k#svSdVRBp8~V&hF#^w7F;p=-4PII?68Bz370yh+pmXd|x7J^b0NH=Vq@h zpL|?G;K<`PlJ$NvAg+rrk-^mZ?i=O#5wI@0z<0mOck{;pMsC9p<@8Fm$DnjFJSh(S z!iE*}(-Hp9ppO}F3a0=)T&2O9R377txS|~i=^ry8kE2zz9V_l2_m9lU|bg&k?iQ8Lu64&{D~Lx{3q=#XNEidvLFpZOx1EC(95F6 z=qRL%Mw9sdpPPuD01FD-jEbiUdD>B|H!kJyltwi0qun6BZ{F$7I|jEKV&-9O;5U*w zhhdts$-{e=q^o{yL0^Vus|X-_CWjn;j^^e^+t5^WT>}txlUdti&L=PuU+wo+dTGGX z;?b4d{HPD`J3w`UwF{YNEDKSO2RA1tMRM!fKU?C!yavbqV^Yk|J@4R#i3u995#pXe z8hLnUd^S)k7!vx{LDW(*Ze1G6w~Vf;2^qZ6uW?(A*&tX0)Ccd~ele$*@3GAGEHxd5U1evl^VHLeD;t=*T7?&!{hc3qBu zP9Qa2vT9MQgB8aAr1o{%lJDhT`;&3$ye`?WF?IJH*W}j_~3zM)x{)p zvqnsQB@$7PLzzOs@045_Lnc>SvvmV}MX4EJcOOOrrE;?^Z7kCJ0yS}Nr4q%L1N>5f z%o0~>MwoS!IPA&bm)-am_7*0>M8LoePb1;>7eO`K1j$F*)eydjef*2o-7^=1SA34+ z6XY>%+Nx^)Gpc$1Td?+TKoS2AFaq=d2CEh%{;>;rj8QBCf3z~bE-u5y)C1O+17M3& zxL^&@VDZ%LF1cN3s^k7k2~lZ@{ucl)M`|8!*LXCAJajcuru6PGHJ1wG0P%Jaa}}0Q z$l=SmeQ$7Jl0Cv9$gmXaRwTVNmeCsx7yWxPso~X-X@>Q~r}r9> zFZf&qD0>6-&4va@=6Sw|PBc8{C%=e^7D-sfFG?+gE%|m!+1t`3cqaktD1lphEA?sl z(HDKpsi}UP&xBo3=5rk#5=Lqu%ME}nnrAlBzenL;EV{7uuUqg-5aNuZSHua4P1k2# z{weF0vAWVPA|9{Gp=If_V?ukr#s`N*;k8n>h8V79+mWGKXqt_HChR@>OQT#R+7rd> z;nnUNVB^XLFx9K6vC+Od45=0RJE}yvd%|}52U-b-f8_`RD=&gKVnnWtU7+a5ThHz8 zaZ%FL-Cm;oZwobFfZQ%E-(3lgr5o0ZkIdM_o0z-r`Ou>aLa6Km`biE(t^jOk&W|ts zU#+Er=)NB?kwFh=jhU3!E#!~cw^>Y8DR>7IlRqB+C5b_ng=HHcDP-;JbMwm}AC|xD zdC;}9J4un$qWl}Wej)mQE}#b}zke{)vSaYx!}Z)PLZJ7w_kg$BWNdERSC2p&cpntL zWb?62p=Fqljk-*`tF%%f@8g}~3-#PUX+vwN&5MnKOSvd1iA z?U?1)XnsVI@}%)zFZ^8o91N#m6V@+3g@)J>NUQKsCm~3S?k<~InOREHUHfZ^B7FGj zN8%LL1_^B-XoA?wW-myQI=lw>intGbWl8wL(Q@shdmlV3j*l)SYaHLs`AA5Gfd zX;}aokn1U8F@PdCs*~f&A-SR1U}3l80C1xe=v4wgF+kk7Gj^WQ$LIt5#(_!FI+pqR zk#8D7p2A%vwlVdB_jcTU|CkszxJ`TGliyt=INl5JgLno8J zOFATPq`g3Rqv6G0pD`xLA;Ee{tMwlp zZ@wgT#W3i1;d|53yhcS+|KRBphjco7iYe&m&sU5EYt66kt=63t@v7~19=fU+GS}nkA^lO}U z9TdZq5~?q+58va8Gfx z^TO^!24!R>@7Q<-rQ)FJ=%_lDl0~yz6lwDEH4|S@DReQ#x53vxSg&y*Y&j`=;>=y@ zm2i(z-Ofo!r$bGx&TZe&FR3*L9blM6jnz|Ig;DhKnT?i#{-h>oem+`Zw2{$rPfx6Y zh`iK2C3=V#P>A<^XWOPI6B(gNuf%W<#nG%*g;|y=KuH+VZZ}EAs+lit_!Ti zXV%YGQ-8a#I_nd2lQRi0C@fClnkSRRrV2}AJYOk&Nx=McB|3>HIz%#uH-tquBY5%i zm}a*dG3#_*z6`e}M~aAJ!1GJHBSdv;p;U0!Y2kbx-$;tFOwsM31$wi#~tdv`!TToddo{05ZHhJ z7UXfU^j(V1CZWY^V@NBFSTql!$3JbugW#rqNo@xQ} zlV`ZNc;+Xw?p%9B={!B)4+}#=LL_?x0v=B;PT&ou1wIM5QiEp;(-9SXPfqyqSKFBc z4wBzKNlDeN$#mPZH==I%DVnN|Ce~?crk;zG&`!;%Gi8E_%%V}xtyAM~UMDl{78FF3 zUSuOgE4O87ZqOkWV!XTVmjlKtJPC#sb3Kp<38^YJd}HiXPI+CNz)>7YkZDc|T!fCa zW3C8v0vCJA_bounG_G&pK&q~ZG=|Ie3Z;5#ICT_|3EW)Myh;kw4~~Y7HOzG zQq=E9cPkw*T`JIG+0@}}0#{soqO0OWJ)R{cj*fr>dMqD)&`I~n@!=YHEB|cW=ko> zzLw2NU@=(cYsAt1c#Zm$Y{9%;gQ4b*Glbl7*b#9rp5CsKJr4XZF62{q;~<4C5MIHy zU^(lY$mQ!c9QU(>1*}VyztagonMTIuA~C|N?;8p+culV)A(T(hcP4D6lf4TvildWb zph(GgU79Y~j4$c#uUgTR93W;J7NUzgKw+P|{*uhWiOWSvLp50qtIoR@>GuwZv2&ro z-`&_^x2|^cW;6sB5rUVDzP1}4oAqB_ z>2(GLg;1GZ*zP7hVA`E$$H zp2&$Qurx*o=t?YD*M7ftuXu(aI!SHFNnL`@Cv0ju6guOY=!ebs?3zm}^vjWS$|qZP z^uhTVOwc99nuLRAI z9744a&^LgvtgBELTj?~3=C6;ELZwypt;V>Qq_pv*G*>lxC0kK7e!7MX{;guqw39y? z-Sc3wyo3|m6$w{F`)#y zYPBTf-96teNq0h#u1(%xrDyAnQ2*$A-$r zj5c)R)D)lb!4LES6yMRu+n2-A@{l|SVidDrnWgd(6Qqv`if$a?gmOr7LBrn`LZ7M@ zxM$9ByfG$|3L?&}VEdj}9G@JH&(2+|i0W4S4p=IRdsM`6tx<;BN5YgaGqgRBRhGx4 zl$Vgpo3AmptxLY)n6uNY@Q~CeVl3iPZ96N-<}|p4bA=nBzsJ*(EV$`HrpddN`I7^; z(I&CaeR9%Yl~qfwe~#CZtiIBI3w6)R2BC@C-C+rSKDSWTiG`H~Yv7f3pt53SaF>pW zy(Ht8>U^y4X69d(%#N9C$!$0Z18zO~`uYkH!hy;&g9^#V3rSCG{D%#{3zs|UV~-}s zQ7JmS^fxem^)u~8fzbU(ogV*dthF_#&-1l-7y`mpRw|*)-EW@zB(aIL0cBEV${oX|>J*LWCjAbDCc3}yY(_mQslXkRZxdL3M>QAy1c`{~Jf{ie<0k+Ls z`Ia-Ri`XSxT0Frx`{})I_v4Y_DC4I&4*9HEDpQ8lrIC5Rl{&jR6+>^nwJ^K$&rJtX z0TR<~pth2dPhq~6^Bjkeb!z~SK)>BpKfSu^c81dvbLK4vhRtxIcqp+A`O@N1SerE` zMn{`$9aLx;#KKFvT_NZ%9=Sa=o+n*ld9(n$5Y+oE-$#_B&$D!@Gi6BmO5tCNLv7Ic zCOG1=KGc)UiL%?Y?Wi{wm7F&0El;pF;D;4-g=xKvf#LS?=a4-f78c?R!yW>${?9Dt zX~>>zd1AK?igdrD@RIU9WNV-@lWZRS2-9SAk)urf88i^iS`u>^W?UR@gAj8Aeds+R z-yXr6^4RxZ$Fr8y_!+QDrShjo==-T)W|}hxJAP3v{2#veW$yOSBT_*4zb%=NY-2gG z#rgc?2zdg41tfuS6B98qZ*@Sb-!KjenO$JG?xBfEkIU*co<`EsGWp`nxI^8h+D?}w<7Zq z?p-0F_L)cEq$PX(p9Rf$O@Qz5HR~C@QZrpx#l3x#-*O&)&B>*}IhAQ^+Fk$cwQ+-m zRcXB5OO7otKwp-xjZ@QSL~5I$IldhoB6n|)G!ie@$4Iw5J&TW}7bQC|pqr6)#M{cid97G5iA=f@IbJDkgUrVa!<42ZbrqvGVeP zk<72>8`Cqz8^d%0LLT+w?c*fJQfn_F-ee)Ckpj4)+M93wJ!jJbApQ^6o6puR489oA zr|6a%DKWpG^Lz$OrMtRyzQnvh2Gsy_*Ng_*V|+0r1WhuA9L83fnx-`6qY>G3HC$hhocr=ZB^7> zb1JfC!d62}xtIHZCO`$`7xiDE z4lY~_pqFtca=T4uIg)jj`9=OW!Ksm>Vse{TP@MBUtmpSMkH%ba^m5tc-{P~HJ&%mguA4qd}o8< z*DBvgo>748o$D@jsoW65XfXSvrCS^)@@onf1}1XnR+@sKvMb9lbAXp`tUvPdUjnQH z%gLPbN)X7hoD7zbsj0|2jfb^>t)`E82h2^~UhtD=9u@A^{O7ft5PrHpPv_~sr=xI* z+4FGV%L7AfG{~M08nS5ygE}#Ii}Q0oy+at#d;X2X(j_`=CfS=YgE_pm8!rAAN5=7Kh=FYyiln?3o@7I?fxf3}c*-pV` zb2+LW`%8XRQohjaDJxefnSHym17z9PaiJ|U5dDJ~u6&fTQI$}^Os=1zFRynYv^Y9C z27$&xqh|SYzWEIT-0j?Vs`QqfvHlER3McnIGD5>(aK~Oz)TFL<$Q&^%?Pt^pxJJW@ zl>j7+!^0$Ajf~eaFBPPctjt>ym6fyhcgwV%Q5SW_2A#Rl#T^X1ZaB}ioV;reEuMV& zh&@9u3(3-~M72_j&^bPu!2PfiXyrG1%SJ;dlsYKjEss;a-n4$ZqeX^>)EF>G|L zNu|WLRHVVzOILwKS>6nfFD1eMA3gb9OzL{0(@YSCJ}Csx_H69t^~ky;Su^-8mcUAM z&@;e(W@qy#2ACQcOgpo!KWvl#Xy=V4Dt#$4mIRLv-C0oHuQJ*9?k@I+q>qKcjKxop z45mr=*^tvkG5F8w$jFxy>;{}Vvyl@0RO-UF?Qo_NRI_)LX2!*7MYMLT2KO~nV!z)Q z_cad;q{zetk*La7HXeV~s;Cg-ebuW!$UFbJx)kfy5YrMw}5(@@4aK+oYUM%Au=Id&9qoHY<~UX+m8~r8QtIMbu)G z^*v-VepM=+5wZA+clYAC`rAi<;avJhTqV~`cP-}w^20#KZ$RSE&)f8IE#SMPY9`9{ zHiQ9`>&!(xNKerpD;klSnYQ?tT+I&LO}VXdF2$LeO0z)2h#K0|(1=fFsMKBxQWb~1 z0?z`Qs-j2OJ)(;R+FtFFR$dOreSDYNq^ZBLOmVSG|73xRM_;;fAA(S zhy%qs7IwTVpjwbn5A?IyOtEu zeSaK#2I@adwuk6VRO#yNV3V&FzQ%qKJ~;DB2Fc;tntN@e?GjOt(;gronPqppdeg(ai7e~G~0XCA(bp7Db z&nnUuSUdNTZR?~uPV2E#=1)-P z@q(3V=mrPT`*O?|1E3(Ohc_=L_S%VKSz2-!6~#|eIIo%b`HKs4(2X@Tf1JlAKk010 zuK)D%Y~B39i0U01{E@G5(M2z+b@U_Kd9l_$hvWA6lfQT~$K=^K*y5gu`krOXwV3_3 zh(M~%K%_GSiuoj^3x1#l2J4RQHqL|P*^Y{V4VYEy3|YcST$)LO+ZXWBRxIxD_T0Jk zJHDxt>j(4pEoJ&IFs1mRuQ2@N%o>~M80gR(M_0t89+OqV;*}Xoowg%eFn0nQJb@l1 zr8RT7H^hMJBA*O;1EnQ17N~wL-8<5m`R#fduH>gN^&lgnK2m$Z3~@-c2IoE+@{zln zAb=pu8*fyU7KfZq#82m;!1}Qf4&%YS6UGfBPZ)>M;?|6nSSE)$h9a3Y5E_4$#+Wb2 z5zTM=s!V;|fE4t#s)T}VJ&tj@VWh= zbkHVMf}9t?6=>$F3hJbyJ;Wq8I-RnBd`zr{2e^r)DtS#VCvvJ8?AI6cOqDegvkjN* zE5vKJYn+W9=zQpDSuM@XGTSnhRpZww7Poxx;)V$Y=NNgXSt^5++tTVg9fJ?r5r_vglF^K<;2I;dXhUVQ5_KhSnwQRqn^{Zdr zD*0qW7&}FZg}b{{m45SH=F@H)s~gNWJY&;2y%U=34qQGYwPT+R6Q}iU!BgoX6N+YW z-j7jZcVU+=FawY^R|V_pjuQJnWlhIa8tYxIA60@Nc_Q&EpAqiOBylnZms|J8SQ()8 zB&f(N6Q6ybR`w`gME=feTXU=ptz3*aM-NB;GSp{ zmO8Q@`$PTPadw6IO$8=DT)vc|>#o`r^z}ZMJ1sjA1fC5kg-Jilh)WoHzmx-4Sk+bl z3>Q`K&^aqbB*PrQ1_5oeQ7d6srGPwAZtAG9t3ix0zzPI{m~TiVIe$m&&n$tR?4J3E$n$rTwfS)B8U(M2bN zUkc9FN)%Ep+IMYg8;pKp^M{406VgLxA)g%%9*yPQ52SzidRo2|ec0o)J%#%12B}DB z>_)PkVsC3>RJp4e>}9eT|5SeCxGxUUflI?sb}0K0QOS7Aftc7n6(tIvI$r;4RAruf zLuAqy%LVIKebZ%9-=%VXiW1Wf-RHb!MH1n(=Wt&2x_eSFdoIy2Fe!dbSc0Odyty+t zy-CTf>SvMM4Ig2^^Rj#v);QtK`P}INT8bg&bCv#ja{x~H)J=I~Hi7^P0K~-)cC)io zRV@*yzyb9J+JdB%*+7-M5P@PnILZ_blybZ*l8hl`prs3VLOdhW37pPJ0ED*BE4(~k zQ@^JRUHUetCBRb$SsYTSN1IQ-5dHZvq^Jh;S4&ng~MJiKD9v3E>_N$t4H3R2Aey| z*zvIO3+wV1Z129KrWg+;j>;z~3E7f>p+v1bDV@NoPElasXOZPCpR(xuQgf6H?D$xL zER4d)U0e=V6rpkpBR_zad0@G!^ObFsq2b)9pozV2Mr(1q_-<~FsGV-=8d)Nt+ICMz zom)m6X(vU%ObW)c(@wj|1JZz?M=FaK;`rAxHe-sh3Quc&`ohrsaX`Hv&fFu1TEL4g z8xS4ai$?PiZy2efY724%=c*DD#dj0++`cW&+KrEMc$k-GREq=g5C-;<69c>q;BaJM zbg`OgryGs5=$OFGQb{H(M39tgI((FigFqqR7k)}W)= zpK_-!%w)_t>g&_&`l)0PV~!<(*eWi$F*CDkh`3bG%3*E1ibbE>b3_)zvJDD0?I$fR zz4;H`nXZSRsCe0sxUyrDE89MWUd9ft>Y*lXT-Or zITt^Ir#l@k?f7L4?U@SuQ>ui{Q<|75U@ApNY$G;qfO{=_cq{dRw7t0dP1H?(!b2s# z4H*^9QY~Xv2uek_3kxVDKfL&CdXaZT04%mMN1iB|}mZX2!uHm!xQhN2ef3{ zz)5WH5KOagRL(g;wiISxJ8aAB17%)rvN(^|;iO2=oT;AkW#k)aCA5$*w-%|W3$L(a zFD5)pAV`&2;=1|q%YV1>PaLSGvusHzWi{wQz*}VVtfg597i~$LL8It56PMc*{+y~> zjK`fgM|c@81{Nb%?Ln6isvWv@g+1{l@V(Krai{H~I^M8RkQ zIJp-q`F5;~8^R6y6-$s37wg&{8)H)u=o`r=3wmH!`LeNb|MN1QC!q2EI4`Jm4OTpO zk9eHp_DoXR-bJc8J$!JN^}kx^wDKqb*^Jim6?-;?6;&Cc3^5=pr6u?*L@a)AjjxbYoPdaSfiMbL;*6CU6ZIYCLg*YY+nN6F zJ0Sh*Fsm~JLj)x}0{T*8ab4jm73xx()cW>gd^;sdXwlk`b_Fs*J6b>U6n7;(<>;WGXm)>hiAR zVFRl|B%|0cZ}iN!C1z|~9KZ3qYJuKHmE9qtcegnt5i602>2S5#*M|SHJ2zRYg$leJG>!-9`P{=^vVT=!jnAkoSh5b5@k zC$F8~)(4{DLg3AqXQUii!G@cqyn7JheYNYdv@x^ea77GueXA8FmUVmaFn-rWo9s1$ zJ$KT5ikFNHsx!&{Av2tQiAUZ2m*u`X1=+^QM-MUZq9#K|qLbPAGN^CPWEu78fg3C{ zQ#TjO=0Cg%yBiQOb{@Wr zjE~88W6AJ&Lnta98GfA8;hmbqYcREKFaAiCzVb31w>vQGX@YAyyv1NJAQB7nOnU;8 z7wPnMy_PO+SHz4h3u!Bdho3Be>WUrO*7x@UIR3hVcOU=~cle79F{pJBS}Uo7NvsXY zaq(&+b)lor3p9=iZA-deZYU*)fzuE@%z`v>4M3Mg#|{~WJKa?{EvAmlu!wCfa1d`Y z+FBefcMS(byh~)Ph@iV>j2WYau5T=lO*of^Mds^xs~MQ2UP#duHNv0LB`<{=O9g#+ z-e=g>P$SR6WGUWE(_wCyf3?6a%9D3?(0;%)j|Ia-xBug6BSi77$r1TDa>d8P9a zwN4wtFZ9Oo6=k9@6~z6ZBc!_@Op%k_#K6Mh|G~7%$b}kV=SI5N_9y6EWXDND34}WX zh@gcX+kXGwt51)6I$3AUP%eO`M+|bzx!@o~TRfW;x97Q?u1d;dtaR%l_QU245y>1K zpt(nI%cdgVP;;r(=23j8hX_OGLS{DH!Tc&l_GZz^M-#u#R25oL{M#WJW47)0rl|ZY zZ{&rL&IWm!IErNomFA(TBgU>kqUCJ7Zm7`kxeo{I`>89c7m&sHU<7d&x?jG(IjZ|5 z@uhFYD+(W6gTc(S-#prE`!cSY@C3@@EfXwBM-swjH^_^No;GOnH3N$Bm~nKNn?pND zR+aNC%v19!$;jei5x#FKis_=H*-g4)M<$E_@-zM+$)rAJ2G+041j)_W;=3U{ovyQDekHE&!iT(4Hnj+; z3a1QkS9m{VcsXu;R{;#pz9GL!bZB z_OIhU1 zCkdBBhB8kazs8Zn>erX0X6ob^H{WPjg|f#ant>>LmiIxPrLxRQle{6!lkALyV8|pZ zz{i}V1-ufyd{7Zno1pBbV#sSGUAH;|ee$ig`IFV?w#_7qg)_4TEEb6~DV z%qSW91kRvb7D*k-E`x;B4ULwld6moa-F!3SkJ(mG{yV0mK*+?r6RD;!vDYn^=dRKL zLjij}aR*1CX@}_KVdM11l5Oj;8r@=Wiho7Pll5>MvqMu0{ajcc5^kuEO|Mc{C1l>f z|9gNLU1r*`Li~uS+7oNzM7c52#9mWueuIOEVnX(`Dd_pvYqZ>$I$-oIi}?>_yX^^& zhh6C*!BzpFy=u37$(K5BGbxFEWYmL83mD-e3Wn3$3nrZ`{)|?lbz2WrFf?X3S5{v7 zXl_27aH#HO0puXs6|99U0v<9+%_-rk)<}1O@r4S1*s12fYMFEqiSEnWj zU7?PukR>?w*gTqQxKOJMNl`lH1sp^8XE5DpxUBV54sz6-JTVZ*pc zVGJpjC{rP5N!X4FzzMZzEp2+Zw~hbCu&3WF0IEr<6f6jIk{FiwT;X)Q+1guK| zD2Nu;2p>#89f?~#bJ@FoS@mr;UajI(on;gOb1W#6r~nP1m2v}eeI`RCDj**DI^C&` z>Z>ps_e3Y(3?ilWe$oy5?X=7#8God>;;SUua|e5R=m!9BzZkQ(2Xm=+k~Y-guQH7# z9o1#)XLz}76=CDF?7SLQzA zF@UrMleD9-Yp^>CP90@lzXwW8G4qC|39r%ayCLgj7FoC~ZjGfF{jJ)tNcwm+Ddooa>VN1tswwUWd)TME* z;ajaTmJ~}S^fp1^Z!f(;TN#x}uNnb5wFTX8!JU`a#r`0&mLg%GPP{H|yAJn}F3TXU>^uw+ zJpLGBz+bd83${?lS+oS%wO`-YoRHzZeiy(@Y$2|`BtWwAKF!T^ta(hJLc!V`BX_%9 z?S)gxdU#0~|Aqi2xsTzDMqQu9X{g^T*ie;kGh2hAxq7aulNkqZpT4ohLidlhW(9*9 zofTOAMr6*!u&8#+hEc)#DUtw>)3I=rE08`F(t_~&F%!xQvG5oyamsu(eFY4Mc9+K! z>nAkX+-kZ{AOq6sqLZgLELKu%PaQ8}7el>7c~%dNc0!BIybiqw^c*d7-iSVaQ=Ibu zu)i9czo_P#*lF2{+~Nk5N0ED@QgtJ@vp*5aF??*ZF>J|(>>}^dh=xgN+rFVdW~`c! zOO7DI`ik@EL_zF&Z(~XPMXR+To|PyDgYxib?fBrrxYAhmz~;M`yTQV6qlF*ekmjV1 z%?_(ts^|98ja|Gvn%^RRy?8Lxud=$PZ}9$oGXXZe9=eX&5U(@O-m6I;EIiUX${VpX z!h_9m8n~~JGbZfu@nw4eKpaZprzR&g1Ka9rX>ywtH}l@D+RYs9tSedj{Bh#6`hT6c zeR4|Ee0l8AD00A}Ilhz4%l#{z@@ui%nixTh3PEiQX0J43CHnsDGOMK=Wq#4++h`m- z%p2IwtK@p@SKpa69MDLbCDN?l#{m}hB+(C1F}24uYkSn#w!QxYp1DUZO3L`C=ZMyj zS<0B{lkJ?2p^2TD{zZ#E{%P%9(M9H-*cSQ%)>p4p?fEPKaQrx&L`s7C?t%8(z-VTi zxQ?0>g}KFJtsLjYnR-F7q*q4$SBqWdw&1txBnO8s0WCC_!(Yf5_II_;$y2%j9q{dC`dV zJE5Ay^_W_iyXGwU+ulX5kw^BgaSm*b?z8yN>~Q*|991ewq3W9$!s`Xo<}t?DU9nJMSq=M`^o^dEEf zZgUD19`R6Me;PpXzz8eUtPxXJA)-tb_6QezZj8DKfFCZELom=_#H zUUn0Jg_4>G8{f4aC1_a6r{5BO!oqLb>K{mB9-1(mnq0D8JOTtBR=_`$mjS+?W>EbV zKKBHM{{wNCYwmnFbC27 z>ZLKKc1@P{h-v8(d9F&6VM8&9&IG*yFsrKHRqSPjZU7*D+IDrZ`I(8_k(huRs%Gr< zPagsD40==p1U$+LAdl*&H4pfc$^U_$$zSczU%YW-@`RXG|HKgPmJrwUnZsP2vnnok zt1Ivw!B;4zzJWfdE#QulYK*~Wp67dVdyfb}6&k>&J3)P^FI?4?%FV)o(oEANKW-TN zG>k}rY9q)A=LnQjsU?}3GA#BhcbO!uTU{jJTN%i9e?>%NEHKK6 z*wnrae!JY6ox1pS&b1qss$NaF=Irb}>t=)YBpEnbHi>sXP@v!+H6hp$o&GzDXKviD zA}3dVYDm9I92B=P&@|^pr?y;kv=Ga!RazGG4Ki|*f1p{ty8H4r;@r-bgGnl(rryJy}-$7N%UmVxnsl+L1hen{aNUePJ5%m z6$PdpPrfL4?@C6b5Og?nrE0UhOu3eT(--dz#6@VXb(FyQsxkmyX5hgSY>)C#=_V)| zfeIAVE%oIvm7PAKh_qMqJiNtr;N|2wzH;!#H2scIn1$E=I`6Xp7OdmR5UIx>-& zqMer5qgHLa$$5~C0m4(b%l9OJBa5k9vOc{8ruwjxGjzuv}mOB-%=@d$I658|aJz{0A z2sBJ&qv-7VjzJ7{m}BWLP>toviuK>=g8n<5 z{!CHDHp8S#7=djCXdLS<^c{+w#-Qbd$EI$is@D@c%5fuWancPb(T8b)U-;uR&@rw4 z${-dh=9_qVHU`rfjWwS66qP`qbC_};!{Pc+gUIvr{#?!zl{Nr61nZ9J@fdAR|(z+jn{u{x=%Ts;P`6~HNKYZ(sw#P7F-@hET;zaEXFu!Q5P%ZRp z;bvcw5*_Rshy4g_QA#tvcmGiUM04NG%nl``F=&Uc7mP;`02#J{Fc%pe`3eJ@!1q$} z)z<|l#GBjfd9+8=9Qxe)SCKS{YIQHVTT7m_#cy1IE5g}u`);d&N9ZC~@_Sk5Ba23O z5g3CpWQEyaqkv(RvwuzC>k$`4RW0!_?%U7MHGQc9px)lVr^WK#Hxb2)#}S*}|C5-0S)f23R#=P9BC%{4JZGE6k>4RQaGdV@Vb>7s#9D-@ zJZm2j06J%IZQwNqjWIb`W-8i68-N6>(^;!qi8*;;XILEbmR;lEGN?nK; z)q@-wFVxU@g@0!}H%&XUn!IZf)#$R`aRyd+>4*NSEa>{a( zQ+{|qR9ihQ(SAlHO0Q(kM`91AUsq|ZaM_vuUtJG!$|LoMv<5f;In)K+z}^pKlWzEk zz+81Ce+ED!GtQnz{qr#M|MLtaQ(oG!x-H{12;mK&!|<_$9@Dz+qv1fAq68OG<41-}t^!cY+h3EPKNSqtDKqntySg5Mff8$-sz}aV7WAqwjvkET&Vfr&E%_5EB#5h; zul%7EpHu;H?+^F4&s|I{_#*(d5B``OqwyNpYh4#6!u5b_H2Qj%(*kwdE30`8v(Y)8 ziqdE_#^m|MiaKK69$s2nh;-m~&eYH4{=3XFr2bVD=rF}OjDB{U1R@GA`p)?9y)LfQ z&9tKOP4tD;E~~d98I}5S@-C5&ulvCJ(gW|7bx%&e%wayv*8>Q!1eqM9diG#P*?R_| zy4z~o5TFbaFuA=f-y{(3YouiEnWA>sFya!s@}{3vabQ27ZUQOK=J@gP-)U=kZ@Krk zn41)=>(5#1y6|n_!{L_;k&-;BpA^m}Fur;G^5g^mML1*z@ZpUq4buVn8*o>OAm^hA zcu|}WTK)EupK={CRbba#`n;+5E}c{JieU!PH#Y0t*0=%B?_btauZlvS{d^j`*54YL zo%=)3TVK=ciScRhyB8F#SJxM1cG!$I-=QB&EoO{ymen%n%g2rE^wyeL{9H-Iv`!Qg z5p+zV6Nl`sH}J4;iVrpye&rnf@-f~zbvfFQ2whC$wJR!4hX*IJ==b%pqwsORKEC)l z`ep80zBy2|_E;PP^o?j&IKch-qg_&NCVxAAOSIfTKri2j2CDPC+=lGBu#Az@Ji3YM zC;zy#RK(NCv+IGQEB-yy2INIRDqN(Rl|p|y7u#h2hl~l>=}OoF;d$cb<1DEQ||4uTYH^iQg9NX$Qw+;YFYEsrM9 zlDXK^AJ{M1Ch*ISy`tdESJbH?4elm4cW4Wiva=HdncZS+_N!MQ^qKR&pO5~*vWQ5{ z3SZ9Ps7Ji<<^L-iODA+8Dpc8TB5-upzrg{?%3yr{IX#C0@_*M{>9qDjrMG@zIa%T6 z`*6Lo_~6jQx9aoKEDPR%>Re(#_j-AdOuwhLp!%&wknU3C$nYKJo-%EH^>_wXKW8{5A4S-B>oQc zhwHcrB7YO<;hNHC01UM_tpRfjkDuPU5$(fb26e5j2lkENKW!y_sQIsRe9^{jU`^#| z$*R9|@ak;sp(SFM+xQmNV(bw*ea_K2@bW!aoJK1YbJFr$ja)SV&Vv>Cwr=yn;a43L zZcp$G)#uiGet^zWZ9+Hr<~oy_W4W>aR-=snv^#INOhBOIbn5qk>dg4|2DJeKKb-wp zMf%pX;oe!K9+}Zq=_!byvAEY*0> z)V#uMqfPB&Pi(=H3}y}2*x$8zb-Cz;ujjzi%Ia;8+g2TV!N1SXc{+Q2r41V^-+f_0hjazN zW$h@5f5q1tw{oG_p?}aIg;F05Ry(_=KZ>NL zegM#?{q)ru3uMZO=XAy~nSJjOcjmpgOQSP=_;-=B)4vo={-R9$8jmR1cH*9B_@C!5 ztKjk5950OZXB%s-JMDY2)wxj6HV{Et=8kpsZ1z68tQyDWZ(fs3s69|{ip)JoirT+l z_vmRM5pEM^YtPMZqc)c!G~dW`w7yZYPRl&qrF|=MC93q)xdCeT+KA$?p(mz5K;EK0 z9!j=I6Vn?i8_@)2doj@1z)6)u?DvFD zRWD`wXYVvs zubn!?`t(mB$(csOo{0Lm%$&_Cu^1aw0=V7BPG&Fu^qI6ddUL4BM!lOHc_4)mW+han zPEgjoNSp_UrH>tBz=V#eM3+dYMGc1eS9iBwXj%S|#c8-%8*8%ZtpF>4jwrsj1%FW5 zbJXk7>gwtOnHQX(U){Z~e`#I4t?P+sMi`oP)fx$M93?>cN6O#SJ1c3ud zQ@)Ct&j??bnHh2cxfL*S_{3jK!#xG1-#B9=FuXtL$VsJ?fCIk7j6KD)jNFTkWr~?g z5j#Rlu^b%1d6lRWm0{JT-`RvOLISk(BhO^(LCGE&BRx`qL2h~z?nvU<)2atw@Lx!F zTEFExAj%Twz05vn6>lrv(LNMjmQ!G@bNNz+IAZcOIur|;Hd6Q%W`(?Cr~LRQwU8fS zKl8cjloS0uU-yGFGC-P6(N#vVQ>BT@{1s|nO@j0^CbOTyO}*egPR8(TG0M1 zp}R%zSuAr%zH(#HH9XlVaa%Gd*hxNYJ7v#PeTn+#sS^A-6j%3o1qc?GT?pb+Gi!)6 zR%Y^&tz?UDTggY<8eYZ)vI8-<)9kZ5m*?!nr1-+>vB3>U@*2k=elNj z=cfLoY-4IBON!H&bPvFkI>|HL$g08#NWvJX0(m~KNt%PB+ zE>)DRL!U;lBQsdQf%_73VqMrn3gs=dEpTxg;$-4dr&e znZJHSA0RgK^uJYDydL0JuzK$CFGG#5BMg!%SsE`T+hH8Y^2DH?g#BaPnbbF z*6$Fu=pSxT$Gmsi#ST!~Iz@v8170-`G1VfO&+1n8q#Mk6 z2^wwpY$qD5jSg-^4=tEBIXs4L_B|j4+=c=fLFOr9eM{vCn;K~>q2_qFSb9CLxbeLY zxrN*gn9iC(W%J*WtXo;;vDqMxgIC|dcm)Uj7#jkTXrokgZ+HU@6!pLV_!2LW666Bb zU2pvjK)Rvz)oZ0dDUT80LRf912>Pum7xbbiMgx=Op% z@6sc>8%WgF?M1lHUeV775EUz5Ty;7;tPHxrR!j#%B#&_uO~Ta_A68zI)y$-!*J=K9 z_}&^-rGh%`o7S)OPpj7O;Y6#UJ-ITdfzbD71I_^ypT5*csQf*B*#{?*F1-6LHM(he z+*u-xd?oNq0A>1)vCGya8mMJUHu;Fwkc+YkT+>s1v0(>V|x_}u#x!P13^_^ zr?(dltTDixI71!;jMV^z++>e$IQZPEP&uD*wIjhS>#8`+)KEB#Q zb+iJdoFsk9hpj@la^5dcbiyv!il5s!<-*`SbO^lrL|ki`ea>aM%w4Qf`m%^-`+v}c zHN@?Ew{}WT;2Z&8e<}SS80miiYpPB~>;ejt6MLae;(iY^PpY|ne@9fAVocSM@>R3V zN=`lVsxxg}V;SS4jWhIvQ+ei*RPc>xET^)_P)8I?(3Wp@{{pp*-y=i0O*3?br=m_J zEM>Yk?Tb985JyVnq)wiPow7PQc3|R`%&B8?%D(rr|KR~9k!+0Pz`MNw9ssn{_~4W( zv-6j*BoIjKJiX}vd5B`hv0Ln+HDfP*)f(0P!t*YOzR5zWllJ74_9gqwW&{IAOE}3oCNyvL%v+IZOIrWeZVH!V$-luew%;+;qRN8| zf7{@C7H1R5nsE}3YMng3Qniz9*Ka|K)q<6MvLe_0?}zicvhmuPYD|90!{x22M|X$e zZYSnvNY)SWlT`tZA;3v^E~0lr_4-bsOiXAg@Nk0m(XiKuVM}1TCJ!tK_I=$N+OK$u z5t@B~h3y$o$aVkCm7RTNYBYVozI>^8)$=PtnP%!x9_clX4%D3Hk*3C`LEJ{KTGgvA zbrrWt;JXAW61^U~Z?`x&+AN*4u&kJg#bCPi9)?Kd=EB(boXTGpk-UMqmwX07TPXH5 zGjOQZ-;<+@+#GuziNLF=_H3v93qz6QdE^Qt4vvKWS^G@+{u&A1QeJ<)=~q=?CdWHj zy4aKa33b*oN~g%mO-k*zG0#NAJ!UKH}*cS^66&IswUPjWb2YXo0!!HQFzHw^ZNqc?>M* z3VwYbL<1pYECz4*_$jDopeYx9P;KW1u%!a zRcR6Oz)7BpwriX$X?V^uV~q%-WuMW*qiYvjm@k}#Um>;sD6X0LHPUMcN#+NLBclO z6#RYRFyaOn_EAUVV98=pl(*2atjOQxb%iqyPwo7ooAY%V4qm*@l=N=B6Ppq7`{gRt z*@Cb+?+E^w`wQ^5U+|x7l+u3A1^7AP4+ojLAu}Pl2j6Snp^dQ3`dsSt-30?aeEqk_ zJ!8M)cP>aGpzOyV1$APoe>>@z@=qCE-xCz$eio$j`4MU?GfQ`yJbS`hqvdE0lJ=a9 zbcoJdm9saX&k1;?4URV%AGB3pwL3V-=om!+`KkitT>$iQV>Qm=t622h8}u^s65oE~ zzzU3m?Jl6?Xn>p0fc!;0h&G*V%Z^4&f!QIQElV+W564 z-dB4qLHz)BRYycF*!tycKJ+#^EQmf+1x6hBX$~%TVPUnkZRvHw;AJzafaKNwK4fUY z@Nb<*07M>U9!NJRGeqyjh?=&07)WAOmPTp{o0%ca%M`C=`NP$5-6!5qW2EI5siof} zej(B1FvD1f`DFjRWDqHH)^!1h-j1rx7`&Ez3ajyyrw`08|IKLY=u9J0aDGUi+NeF2 zz^r%;<$|BU`O3m`zJvcF8*4wazbDUDhz(9RNKU^1kohEl6OW76KQv*Fh1RT3B}mBlj2~tS9ZJ2=a)I;4O1wo; z_CZG*zAw256(;NWsz6-z24CMoIF)rbDM|?k`R5zy`}_Mh0`b(BeNFpMafqAN*&tJ2*{*U|Ita;TuaJ~^;{weGX~RXA^&^8?wu>FGOx zs53?F&l4EVCZHGju1w?y2lm&lv48_h&S6(Fd?a?=07?444Rzg=WugAoH~$H{R610& z2vdhCoUi#-W}xEwwXV%?-=fK( zjdP&9YhEd^`Z@p`Fcb$rh~j_y(&fs3QgbU8yV`JXP6X{7{ki%xe!)=fpEEMbxwpt) zQCL80O#1AKPb)U|6QonWzqKBH);Y`(YjT3dB@Y&^UNc%LFzu5H!lu_Pjq zHYB}K6>7f;!_|O5plpSEf*??nE7W6F#%&~o(^Nr9sz^BP4ev7$=-4Do>9!8OQDgXw zHY^WY6tEf0%Daw*Q1vj9F*6jHOQ&<5mjRmg5H+N@*b$-jC1FFPNSXZedQXCZTbH3k z%gWdQG&SiVhAx_!=vgtSsvr{sADZ(x0RoxPAGk4rs+gR2w$~Ilv|QnuD&S#Og*=KN91%EB8Z*|Rht9pUu^`n$ zqdHpc1A!(K8S^79l1GT+LHElfiy%8QD#Y+fKQL1|t)wR7A08hh1{p2j3AL|BA4NEz zYScO=MtRhonLwaI72sMJP}66A_7q%zf|IuHx5CdC_Z%3uBfG=)j-52N2}K<}Cwy}#ek|7@gK|DvL@rz1O%(EoJzXMd zE1T25RTk3`37=LTN|_04nG*-Z|5+rog9f@T;~jN6g-0P(MASNy27~+Sp*RKz?$?Fo zIEw*sGb3=5VE9r=25mdkp8i)EkEAjtOGY>kKaqOLd&j+G*2%YRhk&9PzzK66dFV7J zpNWQYcI~)46O}rF=&N#lCaP^x(H&!aeN)>V4{prQc>wjL%oZ8C1rqEm+L%^BX|P#s zXD6wbmqRFsr9Y13M74T^Ta<_#XUttd7S3iR@)~;ccI(*1_+{5hOArQuoTs@PCLDMQHqPa)q#(72kf?J51j!^`X@E`uj6NH0k+K!6!16Z2 ztt(8eq26vf1o&>Vo>gPBDgp$0->1$HB>Q!my`K!eKCF<=E`|AmqCM3TYaXFn4;r?8 z)3()$rk$=wfUZ}b1M_*$x(>OC6Wvf_RqGX^f)+O-&q=kGh_8}!j>lVm z&!Q4}3Z}va5X>OZg3_6vj9Om#LC3~7eX;n7;}oI+Q54^Y>W|5o^2p1!9scOga~!M% zsERTtY1u1~Fa?qB>iDuso?XTg;?{&@_kn`6F+f#$keR7Wf&D~0%5Un2vAd(jbP>#7 z8AbMx?S0BMxnileV~MI^4}v?iU8b+PRq&kS!`F7KKdKkW@+o~c@uJ^E8=HjKDkM!b z9ykcjIem=@C>o65A zDqwMAR(9d{>(O>W@-Ms9LCDUa>IRP5<7OmV#tE#wsxk?&!75-)r2Ou4tucWODkf9; zK2I6zY7d#Bq%RqC&Dkp(btRN!Oa(7)hZ9)LDAgE=D2&Sj+dNQ>e$7gvO4jC<;aE)RXr4w_#S` zR6}-*`%PhKLHE(N4tP9ylX(CED5!W6B2yYza6tywVj{y({cpxXXIy$xSF?7mN|ngr zXHYAi{O!XlO(g8wul@rstFQR34CisxiwKm;w;I%=mx@qF<5vd6VkVB3AfRG&UMhG5_nF4{54-h96mrZ=bHRqvjf~_t31Z?&k~4OOPVi}2*Nxdng4-VRfzG0Q z^{|4Os=Lwtrd>AKSexy{LaR<9x?e}DQmf6g{cUCvpt5H;82ewo(6Ps(ZYU#kzae_f zv57;>QOh({GXByy4)rZ{?2HDU3tcWO{OJ=6Wx^j$*l@J4^{eB>d=cE7SbB-Z7dL{dx)39^BKWMh8&6O$+Xb0+&eojtR%1l#*k+J$dTw5-anHOnZ> zOmSki(0*UC2DREYiN|_YYO;Or0?me~Ggj?_9XMsRe`Omoq_OnM$i;@3m*Z!HF3ZZO z$Py6KC|L2Dcdt`&3Xtl=814(Kec<2rHB`c7GF}AF=GN;? zi5Bxi#m{a!!|d$fj_?Lg0%4F+E;lsW2~FmohPSw-zLb8{>(A05D}n5funKjwY|`raD0XX>rB8812TPfmB2JInxpYn06>NU9nwaGvTT+)?UAmT} zxQq+@L@$aRP9Np>w%m!jS+Em4%k3>5JsWubxZ-BStlWaLtwTy%x#`aE=k3Z8&tEvZ z>D;+*jy%L_=-^u{Uvl~+@N^}H_|DghQg&$MoqM^|kjywvl2&SLHoz#&aS|6{)q6Z% zHJt<2kL6(gQs83tkZ{%*!+2}alQ3noM$n>dq_?}d47XIwLcc?|>Q|o-CkeCiOGV@= z{vPNLiBat^#5%nko}hoN({s%%n;JRQMw^LL9Pl8cku1Q1x7T9qmu~ppBD;7oqvF|+ zqAt!ZL*%=$dw`1s-?UnmZH&)rvQg6@-r8BZf-Jtsyxl1A-Ew1OG*g6kt1Kt*{C2ro zVTNaqy+VMlx<{SFHK~-=S8rd#Ur!9LtK1i48yl`wxnHmB;_Nr({8hGCkUwm7yeiGV zaCH{dLC-4UhgU#5+xz=JQCB0xD%J^+JkkhaFQE7!uLj1B1j>G+CRYBdFkCdLX6kn;LXZ7Yg(X4Jn_iSSj8@ zL4Xf!j%&2uEd&CdAt4_dV`*<8i64=_mMw>dp}yi<)!hZIE4WWCkjC`uvg_Jz{>rq} z(D^cPOJuwrqgAP=x)FfllZ3mHO*{vre6)Ze13CBa_HViNhx<&|%Id1Aj-5Y3c>IIm zjH_X8S8uN*IrDUqJ8!n3okL=lB)kxd!>u7v{U&zh*;p(k1v>xzksfXtSbWZYyA2%y zF3X%j*x~xf@md5m7f0doeh67m76&0`K5@S)%YTF>pASy??e`H@m>#!uE0YIBABiJTRmlFezrjnt;9pNhKtl`EvXY>NaoH#ZX< q`ikdL`%)Rh{QrOdrz0REOy_GneK=H0{QEn`gJAa%N_lt8p8XGi=E|`E diff --git a/vendor/github.com/NYTimes/gziphandler/.gitignore b/vendor/github.com/NYTimes/gziphandler/.gitignore deleted file mode 100644 index 1377554e..00000000 --- a/vendor/github.com/NYTimes/gziphandler/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.swp diff --git a/vendor/github.com/NYTimes/gziphandler/.travis.yml b/vendor/github.com/NYTimes/gziphandler/.travis.yml deleted file mode 100644 index d2b67f69..00000000 --- a/vendor/github.com/NYTimes/gziphandler/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go - -go: - - 1.7 - - 1.8 - - tip diff --git a/vendor/github.com/NYTimes/gziphandler/CODE_OF_CONDUCT.md b/vendor/github.com/NYTimes/gziphandler/CODE_OF_CONDUCT.md deleted file mode 100644 index cdbca194..00000000 --- a/vendor/github.com/NYTimes/gziphandler/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -layout: code-of-conduct -version: v1.0 ---- - -This code of conduct outlines our expectations for participants within the **NYTimes/gziphandler** community, as well as steps to reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect our code of conduct to be honored. Anyone who violates this code of conduct may be banned from the community. - -Our open source community strives to: - -* **Be friendly and patient.** -* **Be welcoming**: We strive to be a community that welcomes and supports people of all backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability. -* **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary language. -* **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a productive one. -* **Be careful in the words that we choose**: we are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren't acceptable. -* **Try to understand why we disagree**: Disagreements, both social and technical, happen all the time. It is important that we resolve disagreements and differing views constructively. Remember that we’re different. The strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping to resolve issues and learning from mistakes. - -## Definitions - -Harassment includes, but is not limited to: - -- Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, neuro(a)typicality, physical appearance, body size, race, age, regional discrimination, political or religious affiliation -- Unwelcome comments regarding a person’s lifestyle choices and practices, including those related to food, health, parenting, drugs, and employment -- Deliberate misgendering. This includes deadnaming or persistently using a pronoun that does not correctly reflect a person's gender identity. You must address people by the name they give you when not addressing them by their username or handle -- Physical contact and simulated physical contact (eg, textual descriptions like “*hug*” or “*backrub*”) without consent or after a request to stop -- Threats of violence, both physical and psychological -- Incitement of violence towards any individual, including encouraging a person to commit suicide or to engage in self-harm -- Deliberate intimidation -- Stalking or following -- Harassing photography or recording, including logging online activity for harassment purposes -- Sustained disruption of discussion -- Unwelcome sexual attention, including gratuitous or off-topic sexual images or behaviour -- Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others -- Continued one-on-one communication after requests to cease -- Deliberate “outing” of any aspect of a person’s identity without their consent except as necessary to protect others from intentional abuse -- Publication of non-harassing private communication - -Our open source community prioritizes marginalized people’s safety over privileged people’s comfort. We will not act on complaints regarding: - -- ‘Reverse’ -isms, including ‘reverse racism,’ ‘reverse sexism,’ and ‘cisphobia’ -- Reasonable communication of boundaries, such as “leave me alone,” “go away,” or “I’m not discussing this with you” -- Refusal to explain or debate social justice concepts -- Communicating in a ‘tone’ you don’t find congenial -- Criticizing racist, sexist, cissexist, or otherwise oppressive behavior or assumptions - - -### Diversity Statement - -We encourage everyone to participate and are committed to building a community for all. Although we will fail at times, we seek to treat everyone both as fairly and equally as possible. Whenever a participant has made a mistake, we expect them to take responsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and respectfully, and do our best to right the wrong. - -Although this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression, culture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation, socioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected -characteristics above, including participants with disabilities. - -### Reporting Issues - -If you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us via **code@nytimes.com**. All reports will be handled with discretion. In your report please include: - -- Your contact information. -- Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional witnesses, please -include them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly available record (e.g. a mailing list archive or a public IRC logger), please include a link. -- Any additional information that may be helpful. - -After filing a report, a representative will contact you personally, review the incident, follow up with any additional questions, and make a decision as to how to respond. If the person who is harassing you is part of the response team, they will recuse themselves from handling your incident. If the complaint originates from a member of the response team, it will be handled by a different member of the response team. We will respect confidentiality requests for the purpose of protecting victims of abuse. - -### Attribution & Acknowledgements - -We all stand on the shoulders of giants across many open source communities. We'd like to thank the communities and projects that established code of conducts and diversity statements as our inspiration: - -* [Django](https://www.djangoproject.com/conduct/reporting/) -* [Python](https://www.python.org/community/diversity/) -* [Ubuntu](http://www.ubuntu.com/about/about-ubuntu/conduct) -* [Contributor Covenant](http://contributor-covenant.org/) -* [Geek Feminism](http://geekfeminism.org/about/code-of-conduct/) -* [Citizen Code of Conduct](http://citizencodeofconduct.org/) - -This Code of Conduct was based on https://github.com/todogroup/opencodeofconduct diff --git a/vendor/github.com/NYTimes/gziphandler/CONTRIBUTING.md b/vendor/github.com/NYTimes/gziphandler/CONTRIBUTING.md deleted file mode 100644 index b89a9eb4..00000000 --- a/vendor/github.com/NYTimes/gziphandler/CONTRIBUTING.md +++ /dev/null @@ -1,30 +0,0 @@ -# Contributing to NYTimes/gziphandler - -This is an open source project started by handful of developers at The New York Times and open to the entire Go community. - -We really appreciate your help! - -## Filing issues - -When filing an issue, make sure to answer these five questions: - -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? - -## Contributing code - -Before submitting changes, please follow these guidelines: - -1. Check the open issues and pull requests for existing discussions. -2. Open an issue to discuss a new feature. -3. Write tests. -4. Make sure code follows the ['Go Code Review Comments'](https://github.com/golang/go/wiki/CodeReviewComments). -5. Make sure your changes pass `go test`. -6. Make sure the entire test suite passes locally and on Travis CI. -7. Open a Pull Request. -8. [Squash your commits](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) after receiving feedback and add a [great commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). - -Unless otherwise noted, the gziphandler source files are distributed under the Apache 2.0-style license found in the LICENSE.md file. diff --git a/vendor/github.com/NYTimes/gziphandler/LICENSE b/vendor/github.com/NYTimes/gziphandler/LICENSE deleted file mode 100644 index df6192d3..00000000 --- a/vendor/github.com/NYTimes/gziphandler/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 2016-2017 The New York Times Company - - 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/NYTimes/gziphandler/README.md b/vendor/github.com/NYTimes/gziphandler/README.md deleted file mode 100644 index 6d724607..00000000 --- a/vendor/github.com/NYTimes/gziphandler/README.md +++ /dev/null @@ -1,52 +0,0 @@ -Gzip Handler -============ - -This is a tiny Go package which wraps HTTP handlers to transparently gzip the -response body, for clients which support it. Although it's usually simpler to -leave that to a reverse proxy (like nginx or Varnish), this package is useful -when that's undesirable. - - -## Usage - -Call `GzipHandler` with any handler (an object which implements the -`http.Handler` interface), and it'll return a new handler which gzips the -response. For example: - -```go -package main - -import ( - "io" - "net/http" - "github.com/NYTimes/gziphandler" -) - -func main() { - withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain") - io.WriteString(w, "Hello, World") - }) - - withGz := gziphandler.GzipHandler(withoutGz) - - http.Handle("/", withGz) - http.ListenAndServe("0.0.0.0:8000", nil) -} -``` - - -## Documentation - -The docs can be found at [godoc.org][docs], as usual. - - -## License - -[Apache 2.0][license]. - - - - -[docs]: https://godoc.org/github.com/nytimes/gziphandler -[license]: https://github.com/nytimes/gziphandler/blob/master/LICENSE.md diff --git a/vendor/github.com/NYTimes/gziphandler/gzip.go b/vendor/github.com/NYTimes/gziphandler/gzip.go deleted file mode 100644 index f91dcfa1..00000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip.go +++ /dev/null @@ -1,429 +0,0 @@ -package gziphandler - -import ( - "bufio" - "compress/gzip" - "fmt" - "io" - "net" - "net/http" - "strconv" - "strings" - "sync" -) - -const ( - vary = "Vary" - acceptEncoding = "Accept-Encoding" - contentEncoding = "Content-Encoding" - contentType = "Content-Type" - contentLength = "Content-Length" -) - -type codings map[string]float64 - -const ( - // DefaultQValue is the default qvalue to assign to an encoding if no explicit qvalue is set. - // This is actually kind of ambiguous in RFC 2616, so hopefully it's correct. - // The examples seem to indicate that it is. - DefaultQValue = 1.0 - - // 1500 bytes is the MTU size for the internet since that is the largest size allowed at the network layer. - // If you take a file that is 1300 bytes and compress it to 800 bytes, it’s still transmitted in that same 1500 byte packet regardless, so you’ve gained nothing. - // That being the case, you should restrict the gzip compression to files with a size greater than a single packet, 1400 bytes (1.4KB) is a safe value. - DefaultMinSize = 1400 -) - -// gzipWriterPools stores a sync.Pool for each compression level for reuse of -// gzip.Writers. Use poolIndex to covert a compression level to an index into -// gzipWriterPools. -var gzipWriterPools [gzip.BestCompression - gzip.BestSpeed + 2]*sync.Pool - -func init() { - for i := gzip.BestSpeed; i <= gzip.BestCompression; i++ { - addLevelPool(i) - } - addLevelPool(gzip.DefaultCompression) -} - -// poolIndex maps a compression level to its index into gzipWriterPools. It -// assumes that level is a valid gzip compression level. -func poolIndex(level int) int { - // gzip.DefaultCompression == -1, so we need to treat it special. - if level == gzip.DefaultCompression { - return gzip.BestCompression - gzip.BestSpeed + 1 - } - return level - gzip.BestSpeed -} - -func addLevelPool(level int) { - gzipWriterPools[poolIndex(level)] = &sync.Pool{ - New: func() interface{} { - // NewWriterLevel only returns error on a bad level, we are guaranteeing - // that this will be a valid level so it is okay to ignore the returned - // error. - w, _ := gzip.NewWriterLevel(nil, level) - return w - }, - } -} - -// GzipResponseWriter provides an http.ResponseWriter interface, which gzips -// bytes before writing them to the underlying response. This doesn't close the -// writers, so don't forget to do that. -// It can be configured to skip response smaller than minSize. -type GzipResponseWriter struct { - http.ResponseWriter - index int // Index for gzipWriterPools. - gw *gzip.Writer - - code int // Saves the WriteHeader value. - - minSize int // Specifed the minimum response size to gzip. If the response length is bigger than this value, it is compressed. - buf []byte // Holds the first part of the write before reaching the minSize or the end of the write. - - contentTypes []string // Only compress if the response is one of these content-types. All are accepted if empty. -} - -type GzipResponseWriterWithCloseNotify struct { - *GzipResponseWriter -} - -func (w GzipResponseWriterWithCloseNotify) CloseNotify() <-chan bool { - return w.ResponseWriter.(http.CloseNotifier).CloseNotify() -} - -// Write appends data to the gzip writer. -func (w *GzipResponseWriter) Write(b []byte) (int, error) { - // If content type is not set. - if _, ok := w.Header()[contentType]; !ok { - // It infer it from the uncompressed body. - w.Header().Set(contentType, http.DetectContentType(b)) - } - - // GZIP responseWriter is initialized. Use the GZIP responseWriter. - if w.gw != nil { - n, err := w.gw.Write(b) - return n, err - } - - // Save the write into a buffer for later use in GZIP responseWriter (if content is long enough) or at close with regular responseWriter. - // On the first write, w.buf changes from nil to a valid slice - w.buf = append(w.buf, b...) - - // If the global writes are bigger than the minSize and we're about to write - // a response containing a content type we want to handle, enable - // compression. - if len(w.buf) >= w.minSize && handleContentType(w.contentTypes, w) && w.Header().Get(contentEncoding) == "" { - err := w.startGzip() - if err != nil { - return 0, err - } - } - - return len(b), nil -} - -// startGzip initialize any GZIP specific informations. -func (w *GzipResponseWriter) startGzip() error { - - // Set the GZIP header. - w.Header().Set(contentEncoding, "gzip") - - // if the Content-Length is already set, then calls to Write on gzip - // will fail to set the Content-Length header since its already set - // See: https://github.com/golang/go/issues/14975. - w.Header().Del(contentLength) - - // Write the header to gzip response. - if w.code != 0 { - w.ResponseWriter.WriteHeader(w.code) - } - - // Initialize the GZIP response. - w.init() - - // Flush the buffer into the gzip response. - n, err := w.gw.Write(w.buf) - - // This should never happen (per io.Writer docs), but if the write didn't - // accept the entire buffer but returned no specific error, we have no clue - // what's going on, so abort just to be safe. - if err == nil && n < len(w.buf) { - return io.ErrShortWrite - } - - w.buf = nil - return err -} - -// WriteHeader just saves the response code until close or GZIP effective writes. -func (w *GzipResponseWriter) WriteHeader(code int) { - if w.code == 0 { - w.code = code - } -} - -// init graps a new gzip writer from the gzipWriterPool and writes the correct -// content encoding header. -func (w *GzipResponseWriter) init() { - // Bytes written during ServeHTTP are redirected to this gzip writer - // before being written to the underlying response. - gzw := gzipWriterPools[w.index].Get().(*gzip.Writer) - gzw.Reset(w.ResponseWriter) - w.gw = gzw -} - -// Close will close the gzip.Writer and will put it back in the gzipWriterPool. -func (w *GzipResponseWriter) Close() error { - if w.gw == nil { - // Gzip not trigged yet, write out regular response. - if w.code != 0 { - w.ResponseWriter.WriteHeader(w.code) - } - if w.buf != nil { - _, writeErr := w.ResponseWriter.Write(w.buf) - // Returns the error if any at write. - if writeErr != nil { - return fmt.Errorf("gziphandler: write to regular responseWriter at close gets error: %q", writeErr.Error()) - } - } - return nil - } - - err := w.gw.Close() - gzipWriterPools[w.index].Put(w.gw) - w.gw = nil - return err -} - -// Flush flushes the underlying *gzip.Writer and then the underlying -// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter -// an http.Flusher. -func (w *GzipResponseWriter) Flush() { - if w.gw == nil { - // Only flush once startGzip has been called. - // - // Flush is thus a no-op until the written body - // exceeds minSize. - return - } - - w.gw.Flush() - - if fw, ok := w.ResponseWriter.(http.Flusher); ok { - fw.Flush() - } -} - -// Hijack implements http.Hijacker. If the underlying ResponseWriter is a -// Hijacker, its Hijack method is returned. Otherwise an error is returned. -func (w *GzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if hj, ok := w.ResponseWriter.(http.Hijacker); ok { - return hj.Hijack() - } - return nil, nil, fmt.Errorf("http.Hijacker interface is not supported") -} - -// verify Hijacker interface implementation -var _ http.Hijacker = &GzipResponseWriter{} - -// MustNewGzipLevelHandler behaves just like NewGzipLevelHandler except that in -// an error case it panics rather than returning an error. -func MustNewGzipLevelHandler(level int) func(http.Handler) http.Handler { - wrap, err := NewGzipLevelHandler(level) - if err != nil { - panic(err) - } - return wrap -} - -// NewGzipLevelHandler returns a wrapper function (often known as middleware) -// which can be used to wrap an HTTP handler to transparently gzip the response -// body if the client supports it (via the Accept-Encoding header). Responses will -// be encoded at the given gzip compression level. An error will be returned only -// if an invalid gzip compression level is given, so if one can ensure the level -// is valid, the returned error can be safely ignored. -func NewGzipLevelHandler(level int) (func(http.Handler) http.Handler, error) { - return NewGzipLevelAndMinSize(level, DefaultMinSize) -} - -// NewGzipLevelAndMinSize behave as NewGzipLevelHandler except it let the caller -// specify the minimum size before compression. -func NewGzipLevelAndMinSize(level, minSize int) (func(http.Handler) http.Handler, error) { - return GzipHandlerWithOpts(CompressionLevel(level), MinSize(minSize)) -} - -func GzipHandlerWithOpts(opts ...option) (func(http.Handler) http.Handler, error) { - c := &config{ - level: gzip.DefaultCompression, - minSize: DefaultMinSize, - } - - for _, o := range opts { - o(c) - } - - if err := c.validate(); err != nil { - return nil, err - } - - return func(h http.Handler) http.Handler { - index := poolIndex(c.level) - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(vary, acceptEncoding) - if acceptsGzip(r) { - gw := &GzipResponseWriter{ - ResponseWriter: w, - index: index, - minSize: c.minSize, - contentTypes: c.contentTypes, - } - defer gw.Close() - - if _, ok := w.(http.CloseNotifier); ok { - gwcn := GzipResponseWriterWithCloseNotify{gw} - h.ServeHTTP(gwcn, r) - } else { - h.ServeHTTP(gw, r) - } - - } else { - h.ServeHTTP(w, r) - } - }) - }, nil -} - -// Used for functional configuration. -type config struct { - minSize int - level int - contentTypes []string -} - -func (c *config) validate() error { - if c.level != gzip.DefaultCompression && (c.level < gzip.BestSpeed || c.level > gzip.BestCompression) { - return fmt.Errorf("invalid compression level requested: %d", c.level) - } - - if c.minSize < 0 { - return fmt.Errorf("minimum size must be more than zero") - } - - return nil -} - -type option func(c *config) - -func MinSize(size int) option { - return func(c *config) { - c.minSize = size - } -} - -func CompressionLevel(level int) option { - return func(c *config) { - c.level = level - } -} - -func ContentTypes(types []string) option { - return func(c *config) { - c.contentTypes = []string{} - for _, v := range types { - c.contentTypes = append(c.contentTypes, strings.ToLower(v)) - } - } -} - -// GzipHandler wraps an HTTP handler, to transparently gzip the response body if -// the client supports it (via the Accept-Encoding header). This will compress at -// the default compression level. -func GzipHandler(h http.Handler) http.Handler { - wrapper, _ := NewGzipLevelHandler(gzip.DefaultCompression) - return wrapper(h) -} - -// acceptsGzip returns true if the given HTTP request indicates that it will -// accept a gzipped response. -func acceptsGzip(r *http.Request) bool { - acceptedEncodings, _ := parseEncodings(r.Header.Get(acceptEncoding)) - return acceptedEncodings["gzip"] > 0.0 -} - -// returns true if we've been configured to compress the specific content type. -func handleContentType(contentTypes []string, w http.ResponseWriter) bool { - // If contentTypes is empty we handle all content types. - if len(contentTypes) == 0 { - return true - } - - ct := strings.ToLower(w.Header().Get(contentType)) - for _, c := range contentTypes { - if c == ct { - return true - } - } - - return false -} - -// parseEncodings attempts to parse a list of codings, per RFC 2616, as might -// appear in an Accept-Encoding header. It returns a map of content-codings to -// quality values, and an error containing the errors encountered. It's probably -// safe to ignore those, because silently ignoring errors is how the internet -// works. -// -// See: http://tools.ietf.org/html/rfc2616#section-14.3. -func parseEncodings(s string) (codings, error) { - c := make(codings) - var e []string - - for _, ss := range strings.Split(s, ",") { - coding, qvalue, err := parseCoding(ss) - - if err != nil { - e = append(e, err.Error()) - } else { - c[coding] = qvalue - } - } - - // TODO (adammck): Use a proper multi-error struct, so the individual errors - // can be extracted if anyone cares. - if len(e) > 0 { - return c, fmt.Errorf("errors while parsing encodings: %s", strings.Join(e, ", ")) - } - - return c, nil -} - -// parseCoding parses a single conding (content-coding with an optional qvalue), -// as might appear in an Accept-Encoding header. It attempts to forgive minor -// formatting errors. -func parseCoding(s string) (coding string, qvalue float64, err error) { - for n, part := range strings.Split(s, ";") { - part = strings.TrimSpace(part) - qvalue = DefaultQValue - - if n == 0 { - coding = strings.ToLower(part) - } else if strings.HasPrefix(part, "q=") { - qvalue, err = strconv.ParseFloat(strings.TrimPrefix(part, "q="), 64) - - if qvalue < 0.0 { - qvalue = 0.0 - } else if qvalue > 1.0 { - qvalue = 1.0 - } - } - } - - if coding == "" { - err = fmt.Errorf("empty content-coding") - } - - return -} diff --git a/vendor/github.com/NYTimes/gziphandler/gzip_go18.go b/vendor/github.com/NYTimes/gziphandler/gzip_go18.go deleted file mode 100644 index fa9665b7..00000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip_go18.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build go1.8 - -package gziphandler - -import "net/http" - -// Push initiates an HTTP/2 server push. -// Push returns ErrNotSupported if the client has disabled push or if push -// is not supported on the underlying connection. -func (w *GzipResponseWriter) Push(target string, opts *http.PushOptions) error { - pusher, ok := w.ResponseWriter.(http.Pusher) - if ok && pusher != nil { - return pusher.Push(target, setAcceptEncodingForPushOptions(opts)) - } - return http.ErrNotSupported -} - -// setAcceptEncodingForPushOptions sets "Accept-Encoding" : "gzip" for PushOptions without overriding existing headers. -func setAcceptEncodingForPushOptions(opts *http.PushOptions) *http.PushOptions { - - if opts == nil { - opts = &http.PushOptions{ - Header: http.Header{ - acceptEncoding: []string{"gzip"}, - }, - } - return opts - } - - if opts.Header == nil { - opts.Header = http.Header{ - acceptEncoding: []string{"gzip"}, - } - return opts - } - - if encoding := opts.Header.Get(acceptEncoding); encoding == "" { - opts.Header.Add(acceptEncoding, "gzip") - return opts - } - - return opts -} diff --git a/vendor/github.com/SermoDigital/jose/.gitignore b/vendor/github.com/SermoDigital/jose/.gitignore deleted file mode 100644 index 7bae159a..00000000 --- a/vendor/github.com/SermoDigital/jose/.gitignore +++ /dev/null @@ -1,29 +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 -*.prof - -*.out -*.tmp -tags - diff --git a/vendor/github.com/SermoDigital/jose/.travis.yml b/vendor/github.com/SermoDigital/jose/.travis.yml deleted file mode 100644 index 6f70d934..00000000 --- a/vendor/github.com/SermoDigital/jose/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: - - 1.6 - - 1.7 - - tip - -sudo: false - -install: - - go get -u github.com/golang/lint/golint - -script: - - ./_test.sh diff --git a/vendor/github.com/SermoDigital/jose/LICENSE b/vendor/github.com/SermoDigital/jose/LICENSE deleted file mode 100644 index d2d35b66..00000000 --- a/vendor/github.com/SermoDigital/jose/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Sermo Digital LLC - -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/SermoDigital/jose/README.md b/vendor/github.com/SermoDigital/jose/README.md deleted file mode 100644 index 44edd54a..00000000 --- a/vendor/github.com/SermoDigital/jose/README.md +++ /dev/null @@ -1,40 +0,0 @@ -JOSE -============ -[![Build Status](https://travis-ci.org/SermoDigital/jose.svg?branch=master)](https://travis-ci.org/SermoDigital/jose) -[![GoDoc](https://godoc.org/github.com/SermoDigital/jose?status.svg)](https://godoc.org/github.com/SermoDigital/jose) - -JOSE is a comprehensive set of JWT, JWS, and JWE libraries. - -## Why - -The only other JWS/JWE/JWT implementations are specific to JWT, and none -were particularly pleasant to work with. - -These libraries should provide an easy, straightforward way to securely -create, parse, and validate JWS, JWE, and JWTs. - -## Notes: -JWE is currently unimplemented. - -## Version 0.9: - -## Documentation - -The docs can be found at [godoc.org] [docs], as usual. - -A gopkg.in mirror can be found at https://gopkg.in/jose.v1, thanks to -@zia-newversion. (For context, see #30.) - -### [JWS RFC][jws] -### [JWE RFC][jwe] -### [JWT RFC][jwt] - -## License - -[MIT] [license]. - -[docs]: https://godoc.org/github.com/SermoDigital/jose -[license]: https://github.com/SermoDigital/jose/blob/master/LICENSE.md -[jws]: https://tools.ietf.org/html/rfc7515 -[jwe]: https://tools.ietf.org/html/rfc7516 -[jwt]: https://tools.ietf.org/html/rfc7519 diff --git a/vendor/github.com/SermoDigital/jose/_test.sh b/vendor/github.com/SermoDigital/jose/_test.sh deleted file mode 100644 index a36a4709..00000000 --- a/vendor/github.com/SermoDigital/jose/_test.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -go build ./... -go test ./... -golint ./... -go vet ./... \ No newline at end of file diff --git a/vendor/github.com/SermoDigital/jose/base64.go b/vendor/github.com/SermoDigital/jose/base64.go deleted file mode 100644 index f7275fb2..00000000 --- a/vendor/github.com/SermoDigital/jose/base64.go +++ /dev/null @@ -1,44 +0,0 @@ -package jose - -import "encoding/base64" - -// Encoder is satisfied if the type can marshal itself into a valid -// structure for a JWS. -type Encoder interface { - // Base64 implies T -> JSON -> RawURLEncodingBase64 - Base64() ([]byte, error) -} - -// Base64Decode decodes a base64-encoded byte slice. -func Base64Decode(b []byte) ([]byte, error) { - buf := make([]byte, base64.RawURLEncoding.DecodedLen(len(b))) - n, err := base64.RawURLEncoding.Decode(buf, b) - return buf[:n], err -} - -// Base64Encode encodes a byte slice. -func Base64Encode(b []byte) []byte { - buf := make([]byte, base64.RawURLEncoding.EncodedLen(len(b))) - base64.RawURLEncoding.Encode(buf, b) - return buf -} - -// EncodeEscape base64-encodes a byte slice but escapes it for JSON. -// It'll return the format: `"base64"` -func EncodeEscape(b []byte) []byte { - buf := make([]byte, base64.RawURLEncoding.EncodedLen(len(b))+2) - buf[0] = '"' - base64.RawURLEncoding.Encode(buf[1:], b) - buf[len(buf)-1] = '"' - return buf -} - -// DecodeEscaped decodes a base64-encoded byte slice straight from a JSON -// structure. It assumes it's in the format: `"base64"`, but can handle -// cases where it's not. -func DecodeEscaped(b []byte) ([]byte, error) { - if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' { - b = b[1 : len(b)-1] - } - return Base64Decode(b) -} diff --git a/vendor/github.com/SermoDigital/jose/crypto/doc.go b/vendor/github.com/SermoDigital/jose/crypto/doc.go deleted file mode 100644 index 16cf476b..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package crypto implements "SigningMethods" and "EncryptionMethods"; -// that is, ways to sign and encrypt JWS and JWEs, respectively, as well -// as JWTs. -package crypto diff --git a/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go b/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go deleted file mode 100644 index 3ef12ba2..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go +++ /dev/null @@ -1,117 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "encoding/asn1" - "encoding/json" - "errors" - "math/big" -) - -// ErrECDSAVerification is missing from crypto/ecdsa compared to crypto/rsa -var ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") - -// SigningMethodECDSA implements the ECDSA family of signing methods signing -// methods -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// ECPoint is a marshalling structure for the EC points R and S. -type ECPoint struct { - R *big.Int - S *big.Int -} - -// Specific instances of EC SigningMethods. -var ( - // SigningMethodES256 implements ES256. - SigningMethodES256 = &SigningMethodECDSA{ - Name: "ES256", - Hash: crypto.SHA256, - } - - // SigningMethodES384 implements ES384. - SigningMethodES384 = &SigningMethodECDSA{ - Name: "ES384", - Hash: crypto.SHA384, - } - - // SigningMethodES512 implements ES512. - SigningMethodES512 = &SigningMethodECDSA{ - Name: "ES512", - Hash: crypto.SHA512, - } -) - -// Alg returns the name of the SigningMethodECDSA instance. -func (m *SigningMethodECDSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *ecdsa.PublicKey. -func (m *SigningMethodECDSA) Verify(raw []byte, signature Signature, key interface{}) error { - - ecdsaKey, ok := key.(*ecdsa.PublicKey) - if !ok { - return ErrInvalidKey - } - - // Unmarshal asn1 ECPoint - var ecpoint ECPoint - if _, err := asn1.Unmarshal(signature, &ecpoint); err != nil { - return err - } - - // Verify the signature - if !ecdsa.Verify(ecdsaKey, m.sum(raw), ecpoint.R, ecpoint.S) { - return ErrECDSAVerification - } - return nil -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *ecdsa.PrivateKey. -func (m *SigningMethodECDSA) Sign(data []byte, key interface{}) (Signature, error) { - - ecdsaKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - - r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, m.sum(data)) - if err != nil { - return nil, err - } - - signature, err := asn1.Marshal(ECPoint{R: r, S: s}) - if err != nil { - return nil, err - } - return Signature(signature), nil -} - -func (m *SigningMethodECDSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodECDSA) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON is in case somebody decides to place SigningMethodECDSA -// inside the Header, presumably because they (wrongly) decided it was a good -// idea to use the SigningMethod itself instead of the SigningMethod's Alg -// method. In order to keep things sane, marshalling this will simply -// return the JSON-compatible representation of m.Alg(). -func (m *SigningMethodECDSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodECDSA)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go b/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go deleted file mode 100644 index 4bd75d2e..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package crypto - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// ECDSA parsing errors. -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// ParseECPrivateKeyFromPEM will parse a PEM encoded EC Private -// Key Structure. -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - return x509.ParseECPrivateKey(block.Bytes) -} - -// ParseECPublicKeyFromPEM will parse a PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - parsedKey = cert.PublicKey - } - - pkey, ok := parsedKey.(*ecdsa.PublicKey) - if !ok { - return nil, ErrNotECPublicKey - } - return pkey, nil -} diff --git a/vendor/github.com/SermoDigital/jose/crypto/errors.go b/vendor/github.com/SermoDigital/jose/crypto/errors.go deleted file mode 100644 index 34fbd25f..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package crypto - -import "errors" - -var ( - // ErrInvalidKey means the key argument passed to SigningMethod.Verify - // was not the correct type. - ErrInvalidKey = errors.New("key is invalid") -) diff --git a/vendor/github.com/SermoDigital/jose/crypto/hmac.go b/vendor/github.com/SermoDigital/jose/crypto/hmac.go deleted file mode 100644 index 1cb7f6e0..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/hmac.go +++ /dev/null @@ -1,81 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/hmac" - "encoding/json" - "errors" -) - -// SigningMethodHMAC implements the HMAC-SHA family of SigningMethods. -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of HMAC-SHA SigningMethods. -var ( - // SigningMethodHS256 implements HS256. - SigningMethodHS256 = &SigningMethodHMAC{ - Name: "HS256", - Hash: crypto.SHA256, - } - - // SigningMethodHS384 implements HS384. - SigningMethodHS384 = &SigningMethodHMAC{ - Name: "HS384", - Hash: crypto.SHA384, - } - - // SigningMethodHS512 implements HS512. - SigningMethodHS512 = &SigningMethodHMAC{ - Name: "HS512", - Hash: crypto.SHA512, - } - - // ErrSignatureInvalid is returned when the provided signature is found - // to be invalid. - ErrSignatureInvalid = errors.New("signature is invalid") -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodHMAC) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be a []byte. -func (m *SigningMethodHMAC) Verify(raw []byte, signature Signature, key interface{}) error { - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(raw) - if hmac.Equal(signature, hasher.Sum(nil)) { - return nil - } - return ErrSignatureInvalid -} - -// Sign implements the Sign method from SigningMethod for this signing method. -// Key must be a []byte. -func (m *SigningMethodHMAC) Sign(data []byte, key interface{}) (Signature, error) { - keyBytes, ok := key.([]byte) - if !ok { - return nil, ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(data) - return Signature(hasher.Sum(nil)), nil -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodHMAC) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodHMAC) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodHMAC)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/none.go b/vendor/github.com/SermoDigital/jose/crypto/none.go deleted file mode 100644 index db3d139e..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/none.go +++ /dev/null @@ -1,72 +0,0 @@ -package crypto - -import ( - "crypto" - "encoding/json" - "hash" - "io" -) - -func init() { - crypto.RegisterHash(crypto.Hash(0), h) -} - -// h is passed to crypto.RegisterHash. -func h() hash.Hash { - return &f{Writer: nil} -} - -type f struct{ io.Writer } - -// Sum helps implement the hash.Hash interface. -func (_ *f) Sum(b []byte) []byte { return nil } - -// Reset helps implement the hash.Hash interface. -func (_ *f) Reset() {} - -// Size helps implement the hash.Hash interface. -func (_ *f) Size() int { return -1 } - -// BlockSize helps implement the hash.Hash interface. -func (_ *f) BlockSize() int { return -1 } - -// Unsecured is the default "none" algorithm. -var Unsecured = &SigningMethodNone{ - Name: "none", - Hash: crypto.Hash(0), -} - -// SigningMethodNone is the default "none" algorithm. -type SigningMethodNone struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Verify helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Verify(_ []byte, _ Signature, _ interface{}) error { - return nil -} - -// Sign helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Sign(_ []byte, _ interface{}) (Signature, error) { - return nil, nil -} - -// Alg helps implement the SigningMethod interface. -func (m *SigningMethodNone) Alg() string { - return m.Name -} - -// Hasher helps implement the SigningMethod interface. -func (m *SigningMethodNone) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodNone) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodNone)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa.go b/vendor/github.com/SermoDigital/jose/crypto/rsa.go deleted file mode 100644 index 80596df3..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa.go +++ /dev/null @@ -1,80 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSA implements the RSA family of SigningMethods. -type SigningMethodRSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of RSA SigningMethods. -var ( - // SigningMethodRS256 implements RS256. - SigningMethodRS256 = &SigningMethodRSA{ - Name: "RS256", - Hash: crypto.SHA256, - } - - // SigningMethodRS384 implements RS384. - SigningMethodRS384 = &SigningMethodRSA{ - Name: "RS384", - Hash: crypto.SHA384, - } - - // SigningMethodRS512 implements RS512. - SigningMethodRS512 = &SigningMethodRSA{ - Name: "RS512", - Hash: crypto.SHA512, - } -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodRSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be an *rsa.PublicKey. -func (m *SigningMethodRSA) Verify(raw []byte, sig Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, m.sum(raw), sig) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(data []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, m.sum(data)) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodRSA) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSA)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go b/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go deleted file mode 100644 index 3847ae2d..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build go1.4 - -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSAPSS implements the RSAPSS family of SigningMethods. -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS SigningMethods. -var ( - // SigningMethodPS256 implements PS256. - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - - // SigningMethodPS384 implements PS384. - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - - // SigningMethodPS512 implements PS512. - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } -) - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *rsa.PublicKey. -func (m *SigningMethodRSAPSS) Verify(raw []byte, signature Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPSS(rsaKey, m.Hash, m.sum(raw), signature, m.Options) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *rsa.PrivateKey. -func (m *SigningMethodRSAPSS) Sign(raw []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, m.sum(raw), m.Options) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSAPSS) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodRSAPSS) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSAPSS) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSAPSS)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go b/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go deleted file mode 100644 index 43aeff37..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go +++ /dev/null @@ -1,70 +0,0 @@ -package crypto - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// Errors specific to rsa_utils. -var ( - ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") -) - -// ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key. -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key. -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/SermoDigital/jose/crypto/signature.go b/vendor/github.com/SermoDigital/jose/crypto/signature.go deleted file mode 100644 index 37571f9d..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/signature.go +++ /dev/null @@ -1,36 +0,0 @@ -package crypto - -import ( - "encoding/json" - - "github.com/SermoDigital/jose" -) - -// Signature is a JWS signature. -type Signature []byte - -// MarshalJSON implements json.Marshaler for a signature. -func (s Signature) MarshalJSON() ([]byte, error) { - return jose.EncodeEscape(s), nil -} - -// Base64 helps implements jose.Encoder for Signature. -func (s Signature) Base64() ([]byte, error) { - return jose.Base64Encode(s), nil -} - -// UnmarshalJSON implements json.Unmarshaler for signature. -func (s *Signature) UnmarshalJSON(b []byte) error { - dec, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - *s = Signature(dec) - return nil -} - -var ( - _ json.Marshaler = (Signature)(nil) - _ json.Unmarshaler = (*Signature)(nil) - _ jose.Encoder = (Signature)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/crypto/signing_method.go b/vendor/github.com/SermoDigital/jose/crypto/signing_method.go deleted file mode 100644 index c8b8874b..00000000 --- a/vendor/github.com/SermoDigital/jose/crypto/signing_method.go +++ /dev/null @@ -1,24 +0,0 @@ -package crypto - -import "crypto" - -// SigningMethod is an interface that provides a way to sign JWS tokens. -type SigningMethod interface { - // Alg describes the signing algorithm, and is used to uniquely - // describe the specific crypto.SigningMethod. - Alg() string - - // Verify accepts the raw content, the signature, and the key used - // to sign the raw content, and returns any errors found while validating - // the signature and content. - Verify(raw []byte, sig Signature, key interface{}) error - - // Sign returns a Signature for the raw bytes, as well as any errors - // that occurred during the signing. - Sign(raw []byte, key interface{}) (Signature, error) - - // Used to cause quick panics when a crypto.SigningMethod whose form of hashing - // isn't linked in the binary when you register a crypto.SigningMethod. - // To spoof this, see "crypto.SigningMethodNone". - Hasher() crypto.Hash -} diff --git a/vendor/github.com/SermoDigital/jose/doc.go b/vendor/github.com/SermoDigital/jose/doc.go deleted file mode 100644 index 7abb7bf1..00000000 --- a/vendor/github.com/SermoDigital/jose/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package jose implements some helper functions and types for the children -// packages, jws, jwt, and jwe. -package jose diff --git a/vendor/github.com/SermoDigital/jose/header.go b/vendor/github.com/SermoDigital/jose/header.go deleted file mode 100644 index 4499a769..00000000 --- a/vendor/github.com/SermoDigital/jose/header.go +++ /dev/null @@ -1,124 +0,0 @@ -package jose - -import "encoding/json" - -// Header implements a JOSE Header with the addition of some helper -// methods, similar to net/url.Values. -type Header map[string]interface{} - -// Get retrieves the value corresponding with key from the Header. -func (h Header) Get(key string) interface{} { - if h == nil { - return nil - } - return h[key] -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (h Header) Set(key string, val interface{}) { - h[key] = val -} - -// Del removes the value that corresponds with key from the Header. -func (h Header) Del(key string) { - delete(h, key) -} - -// Has returns true if a value for the given key exists inside the Header. -func (h Header) Has(key string) bool { - _, ok := h[key] - return ok -} - -// MarshalJSON implements json.Marshaler for Header. -func (h Header) MarshalJSON() ([]byte, error) { - if len(h) == 0 { - return nil, nil - } - b, err := json.Marshal(map[string]interface{}(h)) - if err != nil { - return nil, err - } - return EncodeEscape(b), nil -} - -// Base64 implements the Encoder interface. -func (h Header) Base64() ([]byte, error) { - return h.MarshalJSON() -} - -// UnmarshalJSON implements json.Unmarshaler for Header. -func (h *Header) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - b, err := DecodeEscaped(b) - if err != nil { - return err - } - return json.Unmarshal(b, (*map[string]interface{})(h)) -} - -// Protected Headers are base64-encoded after they're marshaled into -// JSON. -type Protected Header - -// Get retrieves the value corresponding with key from the Protected Header. -func (p Protected) Get(key string) interface{} { - if p == nil { - return nil - } - return p[key] -} - -// Set sets Protected[key] = val. It'll overwrite without warning. -func (p Protected) Set(key string, val interface{}) { - p[key] = val -} - -// Del removes the value that corresponds with key from the Protected Header. -func (p Protected) Del(key string) { - delete(p, key) -} - -// Has returns true if a value for the given key exists inside the Protected -// Header. -func (p Protected) Has(key string) bool { - _, ok := p[key] - return ok -} - -// MarshalJSON implements json.Marshaler for Protected. -func (p Protected) MarshalJSON() ([]byte, error) { - b, err := json.Marshal(map[string]interface{}(p)) - if err != nil { - return nil, err - } - return EncodeEscape(b), nil -} - -// Base64 implements the Encoder interface. -func (p Protected) Base64() ([]byte, error) { - b, err := json.Marshal(map[string]interface{}(p)) - if err != nil { - return nil, err - } - return Base64Encode(b), nil -} - -// UnmarshalJSON implements json.Unmarshaler for Protected. -func (p *Protected) UnmarshalJSON(b []byte) error { - var h Header - if err := h.UnmarshalJSON(b); err != nil { - return err - } - *p = Protected(h) - return nil -} - -var ( - _ json.Marshaler = (Protected)(nil) - _ json.Unmarshaler = (*Protected)(nil) - _ json.Marshaler = (Header)(nil) - _ json.Unmarshaler = (*Header)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/claims.go b/vendor/github.com/SermoDigital/jose/jws/claims.go deleted file mode 100644 index 4cc616cf..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/claims.go +++ /dev/null @@ -1,190 +0,0 @@ -package jws - -import ( - "encoding/json" - "time" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/jwt" -) - -// Claims represents a set of JOSE Claims. -type Claims jwt.Claims - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - return jwt.Claims(c).Get(key) -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - jwt.Claims(c).Set(key, val) -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - jwt.Claims(c).Del(key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - return jwt.Claims(c).Has(key) -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - return jwt.Claims(c).MarshalJSON() -} - -// Base64 implements the Encoder interface. -func (c Claims) Base64() ([]byte, error) { - return jwt.Claims(c).Base64() -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - return jwt.Claims(c).Issuer() -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - return jwt.Claims(c).Subject() -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - return jwt.Claims(c).Audience() -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return jwt.Claims(c).Expiration() -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return jwt.Claims(c).NotBefore() -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return jwt.Claims(c).IssuedAt() -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - return jwt.Claims(c).JWTID() -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { - jwt.Claims(c).Audience() -} - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { - jwt.Claims(c).RemoveExpiration() -} - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { - jwt.Claims(c).NotBefore() -} - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { - jwt.Claims(c).IssuedAt() -} - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { - jwt.Claims(c).RemoveJWTID() -} - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - jwt.Claims(c).SetIssuer(issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - jwt.Claims(c).SetSubject(subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - jwt.Claims(c).SetAudience(audience...) -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - jwt.Claims(c).SetExpiration(expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - jwt.Claims(c).SetNotBefore(notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - jwt.Claims(c).SetIssuedAt(issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - jwt.Claims(c).SetJWTID(uniqueID) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/doc.go b/vendor/github.com/SermoDigital/jose/jws/doc.go deleted file mode 100644 index 165836d5..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jws implements JWSs per RFC 7515 -package jws diff --git a/vendor/github.com/SermoDigital/jose/jws/errors.go b/vendor/github.com/SermoDigital/jose/jws/errors.go deleted file mode 100644 index 0512a0e4..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/errors.go +++ /dev/null @@ -1,62 +0,0 @@ -package jws - -import "errors" - -var ( - - // ErrNotEnoughMethods is returned if New was called _or_ the Flat/Compact - // methods were called with 0 SigningMethods. - ErrNotEnoughMethods = errors.New("not enough methods provided") - - // ErrCouldNotUnmarshal is returned when Parse's json.Unmarshaler - // parameter returns an error. - ErrCouldNotUnmarshal = errors.New("custom unmarshal failed") - - // ErrNotCompact signals that the provided potential JWS is not - // in its compact representation. - ErrNotCompact = errors.New("not a compact JWS") - - // ErrDuplicateHeaderParameter signals that there are duplicate parameters - // in the provided Headers. - ErrDuplicateHeaderParameter = errors.New("duplicate parameters in the JOSE Header") - - // ErrTwoEmptyHeaders is returned if both Headers are empty. - ErrTwoEmptyHeaders = errors.New("both headers cannot be empty") - - // ErrNotEnoughKeys is returned when not enough keys are provided for - // the given SigningMethods. - ErrNotEnoughKeys = errors.New("not enough keys (for given methods)") - - // ErrDidNotValidate means the given JWT did not properly validate - ErrDidNotValidate = errors.New("did not validate") - - // ErrNoAlgorithm means no algorithm ("alg") was found in the Protected - // Header. - ErrNoAlgorithm = errors.New("no algorithm found") - - // ErrAlgorithmDoesntExist means the algorithm asked for cannot be - // found inside the signingMethod cache. - ErrAlgorithmDoesntExist = errors.New("algorithm doesn't exist") - - // ErrMismatchedAlgorithms means the algorithm inside the JWT was - // different than the algorithm the caller wanted to use. - ErrMismatchedAlgorithms = errors.New("mismatched algorithms") - - // ErrCannotValidate means the JWS cannot be validated for various - // reasons. For example, if there aren't any signatures/payloads/headers - // to actually validate. - ErrCannotValidate = errors.New("cannot validate") - - // ErrIsNotJWT means the given JWS is not a JWT. - ErrIsNotJWT = errors.New("JWS is not a JWT") - - // ErrHoldsJWE means the given JWS holds a JWE inside its payload. - ErrHoldsJWE = errors.New("JWS holds JWE") - - // ErrNotEnoughValidSignatures means the JWS did not meet the required - // number of signatures. - ErrNotEnoughValidSignatures = errors.New("not enough valid signatures in the JWS") - - // ErrNoTokenInRequest means there's no token present inside the *http.Request. - ErrNoTokenInRequest = errors.New("no token present in request") -) diff --git a/vendor/github.com/SermoDigital/jose/jws/jws.go b/vendor/github.com/SermoDigital/jose/jws/jws.go deleted file mode 100644 index 49e7b976..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws.go +++ /dev/null @@ -1,490 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" - "net/http" - "strings" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/crypto" -) - -// JWS implements a JWS per RFC 7515. -type JWS interface { - // Payload Returns the payload. - Payload() interface{} - - // SetPayload sets the payload with the given value. - SetPayload(p interface{}) - - // Protected returns the JWS' Protected Header. - Protected() jose.Protected - - // ProtectedAt returns the JWS' Protected Header. - // i represents the index of the Protected Header. - ProtectedAt(i int) jose.Protected - - // Header returns the JWS' unprotected Header. - Header() jose.Header - - // HeaderAt returns the JWS' unprotected Header. - // i represents the index of the unprotected Header. - HeaderAt(i int) jose.Header - - // Verify validates the current JWS' signature as-is. Refer to - // ValidateMulti for more information. - Verify(key interface{}, method crypto.SigningMethod) error - - // ValidateMulti validates the current JWS' signature as-is. Since it's - // meant to be called after parsing a stream of bytes into a JWS, it - // shouldn't do any internal parsing like the Sign, Flat, Compact, or - // General methods do. - VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error - - // VerifyCallback validates the current JWS' signature as-is. It - // accepts a callback function that can be used to access header - // parameters to lookup needed information. For example, looking - // up the "kid" parameter. - // The return slice must be a slice of keys used in the verification - // of the JWS. - VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error - - // General serializes the JWS into its "general" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.1 - General(keys ...interface{}) ([]byte, error) - - // Flat serializes the JWS to its "flattened" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.2 - Flat(key interface{}) ([]byte, error) - - // Compact serializes the JWS into its "compact" form per - // https://tools.ietf.org/html/rfc7515#section-7.1 - Compact(key interface{}) ([]byte, error) - - // IsJWT returns true if the JWS is a JWT. - IsJWT() bool -} - -// jws represents a specific jws. -type jws struct { - payload *payload - plcache rawBase64 - clean bool - - sb []sigHead - - isJWT bool -} - -// Payload returns the jws' payload. -func (j *jws) Payload() interface{} { - return j.payload.v -} - -// SetPayload sets the jws' raw, unexported payload. -func (j *jws) SetPayload(val interface{}) { - j.payload.v = val -} - -// Protected returns the JWS' Protected Header. -func (j *jws) Protected() jose.Protected { - return j.sb[0].protected -} - -// Protected returns the JWS' Protected Header. -// i represents the index of the Protected Header. -// Left empty, it defaults to 0. -func (j *jws) ProtectedAt(i int) jose.Protected { - return j.sb[i].protected -} - -// Header returns the JWS' unprotected Header. -func (j *jws) Header() jose.Header { - return j.sb[0].unprotected -} - -// HeaderAt returns the JWS' unprotected Header. -// |i| is the index of the unprotected Header. -func (j *jws) HeaderAt(i int) jose.Header { - return j.sb[i].unprotected -} - -// sigHead represents the 'signatures' member of the jws' "general" -// serialization form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// It's embedded inside the "flat" structure in order to properly -// create the "flat" jws. -type sigHead struct { - Protected rawBase64 `json:"protected,omitempty"` - Unprotected rawBase64 `json:"header,omitempty"` - Signature crypto.Signature `json:"signature"` - - protected jose.Protected - unprotected jose.Header - clean bool - - method crypto.SigningMethod -} - -func (s *sigHead) unmarshal() error { - if err := s.protected.UnmarshalJSON(s.Protected); err != nil { - return err - } - return s.unprotected.UnmarshalJSON(s.Unprotected) -} - -// New creates a JWS with the provided crypto.SigningMethods. -func New(content interface{}, methods ...crypto.SigningMethod) JWS { - sb := make([]sigHead, len(methods)) - for i := range methods { - sb[i] = sigHead{ - protected: jose.Protected{ - "alg": methods[i].Alg(), - }, - unprotected: jose.Header{}, - method: methods[i], - } - } - return &jws{ - payload: &payload{v: content}, - sb: sb, - } -} - -func (s *sigHead) assignMethod(p jose.Protected) error { - alg, ok := p.Get("alg").(string) - if !ok { - return ErrNoAlgorithm - } - - sm := GetSigningMethod(alg) - if sm == nil { - return ErrNoAlgorithm - } - s.method = sm - return nil -} - -type generic struct { - Payload rawBase64 `json:"payload"` - sigHead - Signatures []sigHead `json:"signatures,omitempty"` -} - -// Parse parses any of the three serialized jws forms into a physical -// jws per https://tools.ietf.org/html/rfc7515#section-5.2 -// -// It accepts a json.Unmarshaler in order to properly parse -// the payload. In order to keep the caller from having to do extra -// parsing of the payload, a json.Unmarshaler can be passed -// which will be then to unmarshal the payload however the caller -// wishes. Do note that if json.Unmarshal returns an error the -// original payload will be used as if no json.Unmarshaler was -// passed. -// -// Internally, Parse applies some heuristics and then calls either -// ParseGeneral, ParseFlat, or ParseCompact. -// It should only be called if, for whatever reason, you do not -// know which form the serialized JWT is in. -// -// It cannot parse a JWT. -func Parse(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - // Try and unmarshal into a generic struct that'll - // hopefully hold either of the two JSON serialization - // formats. - var g generic - - // Not valid JSON. Let's try compact. - if err := json.Unmarshal(encoded, &g); err != nil { - return ParseCompact(encoded, u...) - } - - if g.Signatures == nil { - return g.parseFlat(u...) - } - return g.parseGeneral(u...) -} - -// ParseGeneral parses a jws serialized into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseGeneral(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseGeneral(u...) -} - -func (g *generic) parseGeneral(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - for i := range g.Signatures { - if err := g.Signatures[i].unmarshal(); err != nil { - return nil, err - } - if err := checkHeaders(jose.Header(g.Signatures[i].protected), g.Signatures[i].unprotected); err != nil { - return nil, err - } - - if err := g.Signatures[i].assignMethod(g.Signatures[i].protected); err != nil { - return nil, err - } - } - - g.clean = len(g.Signatures) != 0 - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: g.Signatures, - }, nil -} - -// ParseFlat parses a jws serialized into its "flat" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseFlat(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseFlat(u...) -} - -func (g *generic) parseFlat(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - if err := g.sigHead.unmarshal(); err != nil { - return nil, err - } - g.sigHead.clean = true - - if err := checkHeaders(jose.Header(g.sigHead.protected), g.sigHead.unprotected); err != nil { - return nil, err - } - - if err := g.sigHead.assignMethod(g.sigHead.protected); err != nil { - return nil, err - } - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: []sigHead{g.sigHead}, - }, nil -} - -// ParseCompact parses a jws serialized into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseCompact(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - return parseCompact(encoded, false, u...) -} - -func parseCompact(encoded []byte, jwt bool, u ...json.Unmarshaler) (*jws, error) { - - // This section loosely follows - // https://tools.ietf.org/html/rfc7519#section-7.2 - // because it's used to parse _both_ jws and JWTs. - - parts := bytes.Split(encoded, []byte{'.'}) - if len(parts) != 3 { - return nil, ErrNotCompact - } - - var p jose.Protected - if err := p.UnmarshalJSON(parts[0]); err != nil { - return nil, err - } - - s := sigHead{ - Protected: parts[0], - protected: p, - Signature: parts[2], - clean: true, - } - - if err := s.assignMethod(p); err != nil { - return nil, err - } - - var pl payload - if len(u) > 0 { - pl.u = u[0] - } - - j := jws{ - payload: &pl, - plcache: parts[1], - sb: []sigHead{s}, - isJWT: jwt, - } - - if err := j.payload.UnmarshalJSON(parts[1]); err != nil { - return nil, err - } - - j.clean = true - - if err := j.sb[0].Signature.UnmarshalJSON(parts[2]); err != nil { - return nil, err - } - - // https://tools.ietf.org/html/rfc7519#section-7.2.8 - cty, ok := p.Get("cty").(string) - if ok && cty == "JWT" { - return &j, ErrHoldsJWE - } - return &j, nil -} - -var ( - // JWSFormKey is the form "key" which should be used inside - // ParseFromRequest if the request is a multipart.Form. - JWSFormKey = "access_token" - - // MaxMemory is maximum amount of memory which should be used - // inside ParseFromRequest while parsing the multipart.Form - // if the request is a multipart.Form. - MaxMemory int64 = 10e6 -) - -// Format specifies which "format" the JWS is in -- Flat, General, -// or compact. Additionally, constants for JWT/Unknown are added. -type Format uint8 - -const ( - // Unknown format. - Unknown Format = iota - - // Flat format. - Flat - - // General format. - General - - // Compact format. - Compact -) - -var parseJumpTable = [...]func([]byte, ...json.Unmarshaler) (JWS, error){ - Unknown: Parse, - Flat: ParseFlat, - General: ParseGeneral, - Compact: ParseCompact, - 1<<8 - 1: Parse, // Max uint8. -} - -func init() { - for i := range parseJumpTable { - if parseJumpTable[i] == nil { - parseJumpTable[i] = Parse - } - } -} - -func fromHeader(req *http.Request) ([]byte, bool) { - if ah := req.Header.Get("Authorization"); len(ah) > 7 && strings.EqualFold(ah[0:7], "BEARER ") { - return []byte(ah[7:]), true - } - return nil, false -} - -func fromForm(req *http.Request) ([]byte, bool) { - if err := req.ParseMultipartForm(MaxMemory); err != nil { - return nil, false - } - if tokStr := req.Form.Get(JWSFormKey); tokStr != "" { - return []byte(tokStr), true - } - return nil, false -} - -// ParseFromHeader tries to find the JWS in an http.Request header. -func ParseFromHeader(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromHeader(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromForm tries to find the JWS in an http.Request form request. -func ParseFromForm(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromForm(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromRequest tries to find the JWS in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseFromRequest(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - token, err := ParseFromHeader(req, format, u...) - if err == nil { - return token, nil - } - - token, err = ParseFromForm(req, format, u...) - if err == nil { - return token, nil - } - - return nil, err -} - -// IgnoreDupes should be set to true if the internal duplicate header key check -// should ignore duplicate Header keys instead of reporting an error when -// duplicate Header keys are found. -// -// Note: -// Duplicate Header keys are defined in -// https://tools.ietf.org/html/rfc7515#section-5.2 -// meaning keys that both the protected and unprotected -// Headers possess. -var IgnoreDupes bool - -// checkHeaders returns an error per the constraints described in -// IgnoreDupes' comment. -func checkHeaders(a, b jose.Header) error { - if len(a)+len(b) == 0 { - return ErrTwoEmptyHeaders - } - for key := range a { - if b.Has(key) && !IgnoreDupes { - return ErrDuplicateHeaderParameter - } - } - return nil -} - -var _ JWS = (*jws)(nil) diff --git a/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go b/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go deleted file mode 100644 index 923fdc22..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go +++ /dev/null @@ -1,132 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" -) - -// Flat serializes the JWS to its "flattened" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -func (j *jws) Flat(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - if err := j.sign(key); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - sigHead - }{ - Payload: j.plcache, - sigHead: j.sb[0], - }) -} - -// General serializes the JWS into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// If only one key is passed it's used for all the provided -// crypto.SigningMethods. Otherwise, len(keys) must equal the number -// of crypto.SigningMethods added. -func (j *jws) General(keys ...interface{}) ([]byte, error) { - if err := j.sign(keys...); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - Signatures []sigHead `json:"signatures"` - }{ - Payload: j.plcache, - Signatures: j.sb, - }) -} - -// Compact serializes the JWS into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -func (j *jws) Compact(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - - if err := j.sign(key); err != nil { - return nil, err - } - - sig, err := j.sb[0].Signature.Base64() - if err != nil { - return nil, err - } - return format( - j.sb[0].Protected, - j.plcache, - sig, - ), nil -} - -// sign signs each index of j's sb member. -func (j *jws) sign(keys ...interface{}) error { - if err := j.cache(); err != nil { - return err - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(j.sb)) - for i := range keys { - keys[i] = k - } - } - - for i := range j.sb { - if err := j.sb[i].cache(); err != nil { - return err - } - - raw := format(j.sb[i].Protected, j.plcache) - sig, err := j.sb[i].method.Sign(raw, keys[i]) - if err != nil { - return err - } - j.sb[i].Signature = sig - } - - return nil -} - -// cache marshals the payload, but only if it's changed since the last cache. -func (j *jws) cache() (err error) { - if !j.clean { - j.plcache, err = j.payload.Base64() - j.clean = err == nil - } - return err -} - -// cache marshals the protected and unprotected headers, but only if -// they've changed since their last cache. -func (s *sigHead) cache() (err error) { - if !s.clean { - s.Protected, err = s.protected.Base64() - if err != nil { - return err - } - s.Unprotected, err = s.unprotected.Base64() - if err != nil { - return err - } - } - s.clean = true - return nil -} - -// format formats a slice of bytes in the order given, joining -// them with a period. -func format(a ...[]byte) []byte { - return bytes.Join(a, []byte{'.'}) -} diff --git a/vendor/github.com/SermoDigital/jose/jws/jws_validate.go b/vendor/github.com/SermoDigital/jose/jws/jws_validate.go deleted file mode 100644 index e5e3abd1..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws_validate.go +++ /dev/null @@ -1,203 +0,0 @@ -package jws - -import ( - "fmt" - - "github.com/SermoDigital/jose/crypto" -) - -// VerifyCallback is a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -type VerifyCallback func(JWS) ([]interface{}, error) - -// VerifyCallback validates the current JWS' signature as-is. It -// accepts a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -func (j *jws) VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error { - keys, err := fn(j) - if err != nil { - return err - } - return j.VerifyMulti(keys, methods, o) -} - -// IsMultiError returns true if the given error is type *MultiError. -func IsMultiError(err error) bool { - _, ok := err.(*MultiError) - return ok -} - -// MultiError is a slice of errors. -type MultiError []error - -// Errors implements the error interface. -func (m *MultiError) Error() string { - var s string - var n int - for _, err := range *m { - if err != nil { - if n == 0 { - s = err.Error() - } - n++ - } - } - switch n { - case 0: - return "" - case 1: - return s - case 2: - return s + " and 1 other error" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} - -// Any means any of the JWS signatures need to verify. -// Refer to verifyMulti for more information. -const Any int = 0 - -// VerifyMulti verifies the current JWS as-is. Since it's meant to be -// called after parsing a stream of bytes into a JWS, it doesn't do any -// internal parsing like the Sign, Flat, Compact, or General methods do. -func (j *jws) VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error { - - // Catch a simple mistake. Parameter o is irrelevant in this scenario. - if len(keys) == 1 && - len(methods) == 1 && - len(j.sb) == 1 { - return j.Verify(keys[0], methods[0]) - } - - if len(j.sb) != len(methods) { - return ErrNotEnoughMethods - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - // TODO do this better. - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(methods)) - for i := range keys { - keys[i] = k - } - } - - var o2 SigningOpts - if o == nil { - o = new(SigningOpts) - } - - var m MultiError - for i := range j.sb { - err := j.sb[i].verify(j.plcache, keys[i], methods[i]) - if err != nil { - m = append(m, err) - } else { - o2.Inc() - if o.Needs(i) { - o.ptr++ - o2.Append(i) - } - } - } - - err := o.Validate(&o2) - if err != nil { - m = append(m, err) - } - if len(m) == 0 { - return nil - } - return &m -} - -// SigningOpts is a struct which holds options for validating -// JWS signatures. -// Number represents the cumulative which signatures need to verify -// in order for the JWS to be considered valid. -// Leave 'Number' empty or set it to the constant 'Any' if any number of -// valid signatures (greater than one) should verify the JWS. -// -// Use the indices of the signatures that need to verify in order -// for the JWS to be considered valid if specific signatures need -// to verify in order for the JWS to be considered valid. -// -// Note: -// The JWS spec requires *at least* one -// signature to verify in order for the JWS to be considered valid. -type SigningOpts struct { - // Minimum of signatures which need to verify. - Number int - - // Indices of specific signatures which need to verify. - Indices []int - ptr int - - _ struct{} -} - -// Append appends x to s' Indices member. -func (s *SigningOpts) Append(x int) { - s.Indices = append(s.Indices, x) -} - -// Needs returns true if x resides inside s' Indices member -// for the given index. It's used to match two SigningOpts Indices members. -func (s *SigningOpts) Needs(x int) bool { - return s.ptr < len(s.Indices) && s.Indices[s.ptr] == x -} - -// Inc increments s' Number member by one. -func (s *SigningOpts) Inc() { s.Number++ } - -// Validate returns any errors found while validating the -// provided SigningOpts. The receiver validates |have|. -// It'll return an error if the passed SigningOpts' Number member is less -// than s' or if the passed SigningOpts' Indices slice isn't equal to s'. -func (s *SigningOpts) Validate(have *SigningOpts) error { - if have.Number < s.Number || - (s.Indices != nil && - !eq(s.Indices, have.Indices)) { - return ErrNotEnoughValidSignatures - } - return nil -} - -func eq(a, b []int) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -// Verify verifies the current JWS as-is. Refer to verifyMulti -// for more information. -func (j *jws) Verify(key interface{}, method crypto.SigningMethod) error { - if len(j.sb) < 1 { - return ErrCannotValidate - } - return j.sb[0].verify(j.plcache, key, method) -} - -func (s *sigHead) verify(pl []byte, key interface{}, method crypto.SigningMethod) error { - if s.method.Alg() != method.Alg() || s.method.Hasher() != method.Hasher() { - return ErrMismatchedAlgorithms - } - return method.Verify(format(s.Protected, pl), s.Signature, key) -} diff --git a/vendor/github.com/SermoDigital/jose/jws/jwt.go b/vendor/github.com/SermoDigital/jose/jws/jwt.go deleted file mode 100644 index 53da1fcf..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/jwt.go +++ /dev/null @@ -1,115 +0,0 @@ -package jws - -import ( - "net/http" - "time" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/crypto" - "github.com/SermoDigital/jose/jwt" -) - -// NewJWT creates a new JWT with the given claims. -func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT { - j, ok := New(claims, method).(*jws) - if !ok { - panic("jws.NewJWT: runtime panic: New(...).(*jws) != true") - } - j.sb[0].protected.Set("typ", "JWT") - j.isJWT = true - return j -} - -// Serialize helps implements jwt.JWT. -func (j *jws) Serialize(key interface{}) ([]byte, error) { - if j.isJWT { - return j.Compact(key) - } - return nil, ErrIsNotJWT -} - -// Claims helps implements jwt.JWT. -func (j *jws) Claims() jwt.Claims { - if j.isJWT { - if c, ok := j.payload.v.(Claims); ok { - return jwt.Claims(c) - } - } - return nil -} - -// ParseJWTFromRequest tries to find the JWT in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseJWTFromRequest(req *http.Request) (jwt.JWT, error) { - if b, ok := fromHeader(req); ok { - return ParseJWT(b) - } - if b, ok := fromForm(req); ok { - return ParseJWT(b) - } - return nil, ErrNoTokenInRequest -} - -// ParseJWT parses a serialized jwt.JWT into a physical jwt.JWT. -// If its payload isn't a set of claims (or able to be coerced into -// a set of claims) it'll return an error stating the -// JWT isn't a JWT. -func ParseJWT(encoded []byte) (jwt.JWT, error) { - t, err := parseCompact(encoded, true) - if err != nil { - return nil, err - } - c, ok := t.Payload().(map[string]interface{}) - if !ok { - return nil, ErrIsNotJWT - } - t.SetPayload(Claims(c)) - return t, nil -} - -// IsJWT returns true if the JWS is a JWT. -func (j *jws) IsJWT() bool { - return j.isJWT -} - -func (j *jws) Validate(key interface{}, m crypto.SigningMethod, v ...*jwt.Validator) error { - if j.isJWT { - if err := j.Verify(key, m); err != nil { - return err - } - var v1 jwt.Validator - if len(v) > 0 { - v1 = *v[0] - } - c, ok := j.payload.v.(Claims) - if ok { - if err := v1.Validate(j); err != nil { - return err - } - return jwt.Claims(c).Validate(jose.Now(), v1.EXP, v1.NBF) - } - } - return ErrIsNotJWT -} - -// Conv converts a func(Claims) error to type jwt.ValidateFunc. -func Conv(fn func(Claims) error) jwt.ValidateFunc { - if fn == nil { - return nil - } - return func(c jwt.Claims) error { - return fn(Claims(c)) - } -} - -// NewValidator returns a jwt.Validator. -func NewValidator(c Claims, exp, nbf time.Duration, fn func(Claims) error) *jwt.Validator { - return &jwt.Validator{ - Expected: jwt.Claims(c), - EXP: exp, - NBF: nbf, - Fn: Conv(fn), - } -} - -var _ jwt.JWT = (*jws)(nil) diff --git a/vendor/github.com/SermoDigital/jose/jws/payload.go b/vendor/github.com/SermoDigital/jose/jws/payload.go deleted file mode 100644 index 58bfd066..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/payload.go +++ /dev/null @@ -1,52 +0,0 @@ -package jws - -import ( - "encoding/json" - - "github.com/SermoDigital/jose" -) - -// payload represents the payload of a JWS. -type payload struct { - v interface{} - u json.Unmarshaler - _ struct{} -} - -// MarshalJSON implements json.Marshaler for payload. -func (p *payload) MarshalJSON() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.EncodeEscape(b), nil -} - -// Base64 implements jose.Encoder. -func (p *payload) Base64() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// MarshalJSON implements json.Unmarshaler for payload. -func (p *payload) UnmarshalJSON(b []byte) error { - b2, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - if p.u != nil { - err := p.u.UnmarshalJSON(b2) - p.v = p.u - return err - } - return json.Unmarshal(b2, &p.v) -} - -var ( - _ json.Marshaler = (*payload)(nil) - _ json.Unmarshaler = (*payload)(nil) - _ jose.Encoder = (*payload)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/rawbase64.go b/vendor/github.com/SermoDigital/jose/jws/rawbase64.go deleted file mode 100644 index f2c40604..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/rawbase64.go +++ /dev/null @@ -1,28 +0,0 @@ -package jws - -import "encoding/json" - -type rawBase64 []byte - -// MarshalJSON implements json.Marshaler for rawBase64. -func (r rawBase64) MarshalJSON() ([]byte, error) { - buf := make([]byte, len(r)+2) - buf[0] = '"' - copy(buf[1:], r) - buf[len(buf)-1] = '"' - return buf, nil -} - -// MarshalJSON implements json.Unmarshaler for rawBase64. -func (r *rawBase64) UnmarshalJSON(b []byte) error { - if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' { - b = b[1 : len(b)-1] - } - *r = rawBase64(b) - return nil -} - -var ( - _ json.Marshaler = (rawBase64)(nil) - _ json.Unmarshaler = (*rawBase64)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/signing_methods.go b/vendor/github.com/SermoDigital/jose/jws/signing_methods.go deleted file mode 100644 index 525806f4..00000000 --- a/vendor/github.com/SermoDigital/jose/jws/signing_methods.go +++ /dev/null @@ -1,63 +0,0 @@ -package jws - -import ( - "sync" - - "github.com/SermoDigital/jose/crypto" -) - -var ( - mu sync.RWMutex - - signingMethods = map[string]crypto.SigningMethod{ - crypto.SigningMethodES256.Alg(): crypto.SigningMethodES256, - crypto.SigningMethodES384.Alg(): crypto.SigningMethodES384, - crypto.SigningMethodES512.Alg(): crypto.SigningMethodES512, - - crypto.SigningMethodPS256.Alg(): crypto.SigningMethodPS256, - crypto.SigningMethodPS384.Alg(): crypto.SigningMethodPS384, - crypto.SigningMethodPS512.Alg(): crypto.SigningMethodPS512, - - crypto.SigningMethodRS256.Alg(): crypto.SigningMethodRS256, - crypto.SigningMethodRS384.Alg(): crypto.SigningMethodRS384, - crypto.SigningMethodRS512.Alg(): crypto.SigningMethodRS512, - - crypto.SigningMethodHS256.Alg(): crypto.SigningMethodHS256, - crypto.SigningMethodHS384.Alg(): crypto.SigningMethodHS384, - crypto.SigningMethodHS512.Alg(): crypto.SigningMethodHS512, - - crypto.Unsecured.Alg(): crypto.Unsecured, - } -) - -// RegisterSigningMethod registers the crypto.SigningMethod in the global map. -// This is typically done inside the caller's init function. -func RegisterSigningMethod(sm crypto.SigningMethod) { - alg := sm.Alg() - if GetSigningMethod(alg) != nil { - panic("jose/jws: cannot duplicate signing methods") - } - - if !sm.Hasher().Available() { - panic("jose/jws: specific hash is unavailable") - } - - mu.Lock() - signingMethods[alg] = sm - mu.Unlock() -} - -// RemoveSigningMethod removes the crypto.SigningMethod from the global map. -func RemoveSigningMethod(sm crypto.SigningMethod) { - mu.Lock() - delete(signingMethods, sm.Alg()) - mu.Unlock() -} - -// GetSigningMethod retrieves a crypto.SigningMethod from the global map. -func GetSigningMethod(alg string) (method crypto.SigningMethod) { - mu.RLock() - method = signingMethods[alg] - mu.RUnlock() - return method -} diff --git a/vendor/github.com/SermoDigital/jose/jwt/claims.go b/vendor/github.com/SermoDigital/jose/jwt/claims.go deleted file mode 100644 index d3d93bfb..00000000 --- a/vendor/github.com/SermoDigital/jose/jwt/claims.go +++ /dev/null @@ -1,274 +0,0 @@ -package jwt - -import ( - "encoding/json" - "time" - - "github.com/SermoDigital/jose" -) - -// Claims implements a set of JOSE Claims with the addition of some helper -// methods, similar to net/url.Values. -type Claims map[string]interface{} - -// Validate validates the Claims per the claims found in -// https://tools.ietf.org/html/rfc7519#section-4.1 -func (c Claims) Validate(now time.Time, expLeeway, nbfLeeway time.Duration) error { - if exp, ok := c.Expiration(); ok { - if now.After(exp.Add(expLeeway)) { - return ErrTokenIsExpired - } - } - - if nbf, ok := c.NotBefore(); ok { - if !now.After(nbf.Add(-nbfLeeway)) { - return ErrTokenNotYetValid - } - } - return nil -} - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - if c == nil { - return nil - } - return c[key] -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - c[key] = val -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - delete(c, key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - _, ok := c[key] - return ok -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - if c == nil || len(c) == 0 { - return nil, nil - } - return json.Marshal(map[string]interface{}(c)) -} - -// Base64 implements the jose.Encoder interface. -func (c Claims) Base64() ([]byte, error) { - b, err := c.MarshalJSON() - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. (Address of unaddressable object and all that...) - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - v, ok := c.Get("iss").(string) - return v, ok -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - v, ok := c.Get("sub").(string) - return v, ok -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - // Audience claim must be stringy. That is, it may be one string - // or multiple strings but it should not be anything else. E.g. an int. - switch t := c.Get("aud").(type) { - case string: - return []string{t}, true - case []string: - return t, true - case []interface{}: - return stringify(t...) - case interface{}: - return stringify(t) - } - return nil, false -} - -func stringify(a ...interface{}) ([]string, bool) { - if len(a) == 0 { - return nil, false - } - - s := make([]string, len(a)) - for i := range a { - str, ok := a[i].(string) - if !ok { - return nil, false - } - s[i] = str - } - return s, true -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return c.GetTime("exp") -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return c.GetTime("nbf") -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return c.GetTime("iat") -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - v, ok := c.Get("jti").(string) - return v, ok -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { c.Del("iss") } - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { c.Del("sub") } - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { c.Del("aud") } - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { c.Del("exp") } - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { c.Del("nbf") } - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { c.Del("iat") } - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { c.Del("jti") } - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - c.Set("iss", issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - c.Set("sub", subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - if len(audience) == 1 { - c.Set("aud", audience[0]) - } else { - c.Set("aud", audience) - } -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - c.SetTime("exp", expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - c.SetTime("nbf", notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - c.SetTime("iat", issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - c.Set("jti", uniqueID) -} - -// GetTime returns a Unix timestamp for the given key. -// -// It converts an int, int32, int64, uint, uint32, uint64 or float64 into a Unix -// timestamp (epoch seconds). float32 does not have sufficient precision to -// store a Unix timestamp. -// -// Numeric values parsed from JSON will always be stored as float64 since -// Claims is a map[string]interface{}. However, the values may be stored directly -// in the claims as a different type. -func (c Claims) GetTime(key string) (time.Time, bool) { - switch t := c.Get(key).(type) { - case int: - return time.Unix(int64(t), 0), true - case int32: - return time.Unix(int64(t), 0), true - case int64: - return time.Unix(int64(t), 0), true - case uint: - return time.Unix(int64(t), 0), true - case uint32: - return time.Unix(int64(t), 0), true - case uint64: - return time.Unix(int64(t), 0), true - case float64: - return time.Unix(int64(t), 0), true - default: - return time.Time{}, false - } -} - -// SetTime stores a UNIX time for the given key. -func (c Claims) SetTime(key string, t time.Time) { - c.Set(key, t.Unix()) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jwt/doc.go b/vendor/github.com/SermoDigital/jose/jwt/doc.go deleted file mode 100644 index 6004d0fa..00000000 --- a/vendor/github.com/SermoDigital/jose/jwt/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jwt implements JWTs per RFC 7519 -package jwt diff --git a/vendor/github.com/SermoDigital/jose/jwt/eq.go b/vendor/github.com/SermoDigital/jose/jwt/eq.go deleted file mode 100644 index 3113269f..00000000 --- a/vendor/github.com/SermoDigital/jose/jwt/eq.go +++ /dev/null @@ -1,47 +0,0 @@ -package jwt - -func verifyPrincipals(pcpls, auds []string) bool { - // "Each principal intended to process the JWT MUST - // identify itself with a value in the audience claim." - // - https://tools.ietf.org/html/rfc7519#section-4.1.3 - - found := -1 - for i, p := range pcpls { - for _, v := range auds { - if p == v { - found++ - break - } - } - if found != i { - return false - } - } - return true -} - -// ValidAudience returns true iff: -// - a and b are strings and a == b -// - a is string, b is []string and a is in b -// - a is []string, b is []string and all of a is in b -// - a is []string, b is string and len(a) == 1 and a[0] == b -func ValidAudience(a, b interface{}) bool { - s1, ok := a.(string) - if ok { - if s2, ok := b.(string); ok { - return s1 == s2 - } - a2, ok := b.([]string) - return ok && verifyPrincipals([]string{s1}, a2) - } - - a1, ok := a.([]string) - if !ok { - return false - } - if a2, ok := b.([]string); ok { - return verifyPrincipals(a1, a2) - } - s2, ok := b.(string) - return ok && len(a1) == 1 && a1[0] == s2 -} diff --git a/vendor/github.com/SermoDigital/jose/jwt/errors.go b/vendor/github.com/SermoDigital/jose/jwt/errors.go deleted file mode 100644 index 96b240d5..00000000 --- a/vendor/github.com/SermoDigital/jose/jwt/errors.go +++ /dev/null @@ -1,28 +0,0 @@ -package jwt - -import "errors" - -var ( - // ErrTokenIsExpired is return when time.Now().Unix() is after - // the token's "exp" claim. - ErrTokenIsExpired = errors.New("token is expired") - - // ErrTokenNotYetValid is return when time.Now().Unix() is before - // the token's "nbf" claim. - ErrTokenNotYetValid = errors.New("token is not yet valid") - - // ErrInvalidISSClaim means the "iss" claim is invalid. - ErrInvalidISSClaim = errors.New("claim \"iss\" is invalid") - - // ErrInvalidSUBClaim means the "sub" claim is invalid. - ErrInvalidSUBClaim = errors.New("claim \"sub\" is invalid") - - // ErrInvalidIATClaim means the "iat" claim is invalid. - ErrInvalidIATClaim = errors.New("claim \"iat\" is invalid") - - // ErrInvalidJTIClaim means the "jti" claim is invalid. - ErrInvalidJTIClaim = errors.New("claim \"jti\" is invalid") - - // ErrInvalidAUDClaim means the "aud" claim is invalid. - ErrInvalidAUDClaim = errors.New("claim \"aud\" is invalid") -) diff --git a/vendor/github.com/SermoDigital/jose/jwt/jwt.go b/vendor/github.com/SermoDigital/jose/jwt/jwt.go deleted file mode 100644 index feb17126..00000000 --- a/vendor/github.com/SermoDigital/jose/jwt/jwt.go +++ /dev/null @@ -1,144 +0,0 @@ -package jwt - -import ( - "time" - - "github.com/SermoDigital/jose/crypto" -) - -// JWT represents a JWT per RFC 7519. -// It's described as an interface instead of a physical structure -// because both JWS and JWEs can be JWTs. So, in order to use either, -// import one of those two packages and use their "NewJWT" (and other) -// functions. -type JWT interface { - // Claims returns the set of Claims. - Claims() Claims - - // Validate returns an error describing any issues found while - // validating the JWT. For info on the fn parameter, see the - // comment on ValidateFunc. - Validate(key interface{}, method crypto.SigningMethod, v ...*Validator) error - - // Serialize serializes the JWT into its on-the-wire - // representation. - Serialize(key interface{}) ([]byte, error) -} - -// ValidateFunc is a function that provides access to the JWT -// and allows for custom validation. Keep in mind that the Verify -// methods in the JWS/JWE sibling packages call ValidateFunc *after* -// validating the JWS/JWE, but *before* any validation per the JWT -// RFC. Therefore, the ValidateFunc can be used to short-circuit -// verification, but cannot be used to circumvent the RFC. -// Custom JWT implementations are free to abuse this, but it is -// not recommended. -type ValidateFunc func(Claims) error - -// Validator represents some of the validation options. -type Validator struct { - Expected Claims // If non-nil, these are required to match. - EXP time.Duration // EXPLeeway - NBF time.Duration // NBFLeeway - Fn ValidateFunc // See ValidateFunc for more information. - - _ struct{} // Require explicitly-named struct fields. -} - -// Validate validates the JWT based on the expected claims in v. -// Note: it only validates the registered claims per -// https://tools.ietf.org/html/rfc7519#section-4.1 -// -// Custom claims should be validated using v's Fn member. -func (v *Validator) Validate(j JWT) error { - if iss, ok := v.Expected.Issuer(); ok && - j.Claims().Get("iss") != iss { - return ErrInvalidISSClaim - } - if sub, ok := v.Expected.Subject(); ok && - j.Claims().Get("sub") != sub { - return ErrInvalidSUBClaim - } - if iat, ok := v.Expected.IssuedAt(); ok { - if t, ok := j.Claims().GetTime("iat"); !t.Equal(iat) || !ok { - return ErrInvalidIATClaim - } - } - if jti, ok := v.Expected.JWTID(); ok && - j.Claims().Get("jti") != jti { - return ErrInvalidJTIClaim - } - - if aud, ok := v.Expected.Audience(); ok { - aud2, ok := j.Claims().Audience() - if !ok || !ValidAudience(aud, aud2) { - return ErrInvalidAUDClaim - } - } - - if v.Fn != nil { - return v.Fn(j.Claims()) - } - return nil -} - -// SetClaim sets the claim with the given val. -func (v *Validator) SetClaim(claim string, val interface{}) { - v.expect() - v.Expected.Set(claim, val) -} - -// SetIssuer sets the "iss" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (v *Validator) SetIssuer(iss string) { - v.expect() - v.Expected.Set("iss", iss) -} - -// SetSubject sets the "sub" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (v *Validator) SetSubject(sub string) { - v.expect() - v.Expected.Set("sub", sub) -} - -// SetAudience sets the "aud" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (v *Validator) SetAudience(aud string) { - v.expect() - v.Expected.Set("aud", aud) -} - -// SetExpiration sets the "exp" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (v *Validator) SetExpiration(exp time.Time) { - v.expect() - v.Expected.Set("exp", exp) -} - -// SetNotBefore sets the "nbf" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (v *Validator) SetNotBefore(nbf time.Time) { - v.expect() - v.Expected.Set("nbf", nbf) -} - -// SetIssuedAt sets the "iat" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (v *Validator) SetIssuedAt(iat time.Time) { - v.expect() - v.Expected.Set("iat", iat) -} - -// SetJWTID sets the "jti" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (v *Validator) SetJWTID(jti string) { - v.expect() - v.Expected.Set("jti", jti) -} - -func (v *Validator) expect() { - if v.Expected == nil { - v.Expected = make(Claims) - } -} diff --git a/vendor/github.com/SermoDigital/jose/time.go b/vendor/github.com/SermoDigital/jose/time.go deleted file mode 100644 index f366a7a6..00000000 --- a/vendor/github.com/SermoDigital/jose/time.go +++ /dev/null @@ -1,6 +0,0 @@ -package jose - -import "time" - -// Now returns the current time in UTC. -func Now() time.Time { return time.Now().UTC() } diff --git a/vendor/github.com/Venafi/vcert/.gitignore b/vendor/github.com/Venafi/vcert/.gitignore deleted file mode 100644 index 2ece3927..00000000 --- a/vendor/github.com/Venafi/vcert/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -Go/bin/* -Go/pkg/* -Go/src/* -.idea -vCert -/bin/ -aruba/tmp/ -aruba/bin/ -aruba/vcert -vcert.exe -Gemfile.lock -aruba/features/step_definitions/0.endpoints.rb -aruba/log.log -/vars -/exec diff --git a/vendor/github.com/Venafi/vcert/Dockerfile b/vendor/github.com/Venafi/vcert/Dockerfile deleted file mode 100644 index ccafd727..00000000 --- a/vendor/github.com/Venafi/vcert/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM golang:latest - -COPY . /go/src/github.com/Venafi/vcert - -WORKDIR /go/src/github.com/Venafi/vcert - diff --git a/vendor/github.com/Venafi/vcert/Jenkinsfile b/vendor/github.com/Venafi/vcert/Jenkinsfile deleted file mode 100644 index 7fb2535b..00000000 --- a/vendor/github.com/Venafi/vcert/Jenkinsfile +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env groovy -node("jnode-vcert") { - - String goPath = "/go/src/github.com/Venafi/vcert" - - stage('Checkout') { - checkout scm - } - - stage("Build") { - docker.image("golang:1.9").inside("-v ${pwd()}:${goPath} -u root") { - sh "cd ${goPath} && make build" - } - } - - stage("Run Tests") { - parallel( - test: { - docker.image("golang:1.9").inside("-v ${pwd()}:${goPath} -u root") { - sh "cd ${goPath} && go get ./... && make test" - } - }, - e2eTPP: { - docker.image("golang:1.9").inside("-v ${pwd()}:${goPath} -u root") { - sh "cd ${goPath} && go get ./... && make tpp_test" - } - }, - e2eCloud: { - docker.image("golang:1.9").inside("-v ${pwd()}:${goPath} -u root") { - sh "cd ${goPath} && go get ./... && make cloud_test" - } - }, - testCLI: { - sh "make cucumber" - } - ) - } - - stage("Deploy") { - archiveArtifacts artifacts: 'bin/**/*', fingerprint: true - } - - stage("Publish") { - cifsPublisher paramPublish: null, masterNodeName:'', alwaysPublishFromMaster: false, - continueOnError: false, - failOnError: false, - publishers: [[ - configName: 'buildsDev', - transfers: [[ - cleanRemote: true, excludes: '*/obj/,/node_modules/,/_src/,/_config/,/_sassdocs/', - flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', - remoteDirectory: env.JOB_NAME, remoteDirectorySDF: false, - removePrefix: 'bin', - sourceFiles: 'bin/' - ]], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true - ]] - } -} diff --git a/vendor/github.com/Venafi/vcert/LICENSE b/vendor/github.com/Venafi/vcert/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/vendor/github.com/Venafi/vcert/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/Venafi/vcert/Makefile b/vendor/github.com/Venafi/vcert/Makefile deleted file mode 100644 index e6f5e5d5..00000000 --- a/vendor/github.com/Venafi/vcert/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -GOFLAGS ?= $(GOFLAGS:) - -get: gofmt - go get $(GOFLAGS) ./... - -build: get - env GOOS=linux GOARCH=amd64 go build -ldflags '-s -w' -o bin/linux/vcert ./cmd/vcert - env GOOS=linux GOARCH=386 go build -ldflags '-s -w' -o bin/linux/vcert86 ./cmd/vcert - env GOOS=darwin GOARCH=amd64 go build -ldflags '-s -w' -o bin/darwin/vcert ./cmd/vcert - env GOOS=darwin GOARCH=386 go build -ldflags '-s -w' -o bin/darwin/vcert86 ./cmd/vcert - env GOOS=windows GOARCH=amd64 go build -ldflags '-s -w' -o bin/windows/vcert.exe ./cmd/vcert - env GOOS=windows GOARCH=386 go build -ldflags '-s -w' -o bin/windows/vcert86.exe ./cmd/vcert - -cucumber: - rm -rf ./aruba/bin/ - mkdir -p ./aruba/bin/ && cp ./bin/linux/vcert ./aruba/bin/vcert - docker build --tag vcert.auto aruba/ - if [ -z "$(FEATURE)" ]; then \ - cd aruba && ./cucumber.sh; \ - else \ - cd aruba && ./cucumber.sh $(FEATURE); \ - fi - -gofmt: - ! gofmt -l . | grep -v ^vendor/ | grep . - -test: get - go test -v -cover . - go test -v -cover ./pkg/certificate - go test -v -cover ./pkg/endpoint - go test -v -cover ./pkg/venafi/fake - go test -v -cover ./cmd/vcert/output - go test -v -cover ./cmd/vcert - -tpp_test: get - go test -v $(GOFLAGS) ./pkg/venafi/tpp \ - -tpp-url "${VCERT_TPP_URL}" \ - -tpp-user "${VCERT_TPP_USER}" \ - -tpp-password "${VCERT_TPP_PASSWORD}" \ - -tpp-zone "${VCERT_TPP_ZONE}" - -cloud_test: get - go test -v $(GOFLAGS) ./pkg/venafi/cloud \ - -cloud-url "${VCERT_CLOUD_URL}" \ - -cloud-api-key "${VCERT_CLOUD_APIKEY}" \ - -cloud-zone "${VCERT_CLOUD_ZONE}" - diff --git a/vendor/github.com/Venafi/vcert/README.md b/vendor/github.com/Venafi/vcert/README.md deleted file mode 100644 index ae80158c..00000000 --- a/vendor/github.com/Venafi/vcert/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# VCert - - - -VCert is a Go library, SDK, and command line utility designed to simplify key generation and enrollment of machine identities -(also known as SSL/TLS certificates and keys) that comply with enterprise security policy by using the -[Venafi Platform](https://www.venafi.com/platform/trust-protection-platform) or [Venafi Cloud](https://pki.venafi.com/venafi-cloud/). - -## Installation - -1. Configure your Go environment according to https://golang.org/doc/install. -2. Verify that GOPATH environment variable is set correctly -3. Download the source code: - -```sh -go get github.com/Venafi/vcert -``` - -or - -```sh -git clone https://github.com/Venafi/vcert.git $GOPATH/src/github.com/Venafi/vcert -``` -4. Build the command line utilities for Linux, MacOS, and Windows: - -```sh -make build -``` - -## Usage example - -For code samples of programmatic use, please review the files in [/example](/example). - -1. In your main.go file, make the following import declarations: `github.com/Venafi/vcert`, `github.com/Venafi/vcert/pkg/certificate`, and `github.com/Venafi/vcert/pkg/endpoint`. -2. Create a configuration object of type `&vcert.Config` that specifies the Venafi connection details. Solutions are typically designed to get those details from a secrets vault, .ini file, environment variables, or command line parameters. -3. Instantiate a client by calling the `NewClient` method of the vcert class with the configuration object. -4. Compose a certiticate request object of type `&certificate.Request`. -5. Generate a key pair and CSR for the certificate request by calling the `GenerateRequest` method of the client. -6. Submit the request by passing the certificate request object to the `RequestCertificate` method of the client. -7. Use the request ID to pickup the certificate using the `RetrieveCertificate` method of the client. - -Samples are in a state where you can build/execute them using the following commands (after setting the environment variables discussed later): - -```sh -go build -o cli ./example -go test -v ./example -run TestRequestCertificate -``` - -For command line examples, please see the [Knowledge Base at support.venafi.com](https://support.venafi.com/hc/en-us/articles/217991528-Introducing-VCert-API-Abstraction-for-DevOpsSec). - -## Prerequisites for using with Trust Protection Platform - -1. A user account that has been granted WebSDK Access -2. A folder (zone) where the user has been granted the following permissions: View, Read, Write, Create, Revoke (for the revoke action), and Private Key Read (for the pickup action when CSR is service generated) -3. Policy applied to the folder which specifies: - 1. CA Template that Trust Protection Platform will use to enroll certificate requests submitted by VCert - 2. Subject DN values for Organizational Unit (OU), Organization (O), City (L), State (ST) and Country (C) - 3. Management Type not locked or locked to 'Enrollment' - 4. Certificate Signing Request (CSR) Generation not locked or locked to 'Service Generated CSR' - 5. Generate Key/CSR on Application not locked or locked to 'No' - 6. (Recommended) Disable Automatic Renewal set to 'Yes' - 7. (Recommended) Key Bit Strength set to 2048 or higher - 8. (Recommended) Domain Whitelisting policy appropriately assigned - -## Testing with Trust Protection Platform and Cloud - -Unit tests: - -```sh -make test -``` - -Integration tests for Trust Protection Platform and Cloud products require endpoint connection variables: - -```sh -export VCERT_TPP_URL=https://tpp.venafi.example/vedsdk -export VCERT_TPP_USER=tpp-user -export VCERT_TPP_PASSWORD=tpp-password -export VCERT_TPP_ZONE='some\policy' - -make tpp_test -``` - -```sh -export VCERT_CLOUD_URL=https://api.venafi.cloud/v1 -export VCERT_CLOUD_APIKEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -export VCERT_CLOUD_ZONE=Default - -make cloud_test -``` - -Command line utility tests make use of [Cucumber & Aruba](https://github.com/cucumber/aruba) feature files. - -- To run tests for all features in parallel: - -```sh -make cucumber -``` - -- To run tests only for a specific feature (e.g. basic, config, enroll, format, gencsr, renew, or revoke): - -```sh -make cucumber FEATURE=./features/basic/version.feature -``` - -When run, these tests will be executed in their own Docker container using the Ruby version of Cucumber. -The completed test run will report on the number of test "scenarios" and "steps" that passed, failed, or were skipped. - -## Contributing to VCert - -1. Fork it to your account (https://github.com/Venafi/vcert/fork) -2. Clone your fork (`git clone git@github.com:youracct/vcert.git`) -3. Create a feature branch (`git checkout -b your-branch-name`) -4. Implement and test your changes -5. Commit your changes (`git commit -am 'Added some cool functionality'`) -6. Push to the branch (`git push origin your-branch-name`) -7. Create a new Pull Request (https://github.com/youracct/vcert/pull/new/working-branch) - -## Release History - -- 3.18.3.1 - - First open source release - -## License - -Copyright © Venafi, Inc. All rights reserved. - -VCert is licensed under the Apache License, Version 2.0. See `LICENSE` for the full license text. - -Please direct questions/comments to opensource@venafi.com. diff --git a/vendor/github.com/Venafi/vcert/client.go b/vendor/github.com/Venafi/vcert/client.go deleted file mode 100644 index 552d5d4a..00000000 --- a/vendor/github.com/Venafi/vcert/client.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 vcert - -import ( - "crypto/x509" - "fmt" - "github.com/Venafi/vcert/pkg/endpoint" - "github.com/Venafi/vcert/pkg/venafi/cloud" - "github.com/Venafi/vcert/pkg/venafi/fake" - "github.com/Venafi/vcert/pkg/venafi/tpp" -) - -func NewClient(cfg *Config) (endpoint.Connector, error) { - var err error - - var connectionTrustBundle *x509.CertPool - if cfg.ConnectionTrust != "" { - connectionTrustBundle = x509.NewCertPool() - if !connectionTrustBundle.AppendCertsFromPEM([]byte(cfg.ConnectionTrust)) { - return nil, fmt.Errorf("failed to parse PEM trust bundle") - } - } - - var connector endpoint.Connector - switch cfg.ConnectorType { - case endpoint.ConnectorTypeCloud: - connector = cloud.NewConnector(cfg.LogVerbose, connectionTrustBundle) - case endpoint.ConnectorTypeTPP: - connector = tpp.NewConnector(cfg.LogVerbose, connectionTrustBundle) - case endpoint.ConnectorTypeFake: - connector = fake.NewConnector(cfg.LogVerbose, connectionTrustBundle) - default: - return nil, fmt.Errorf("ConnectorType is not defined") - } - - if cfg.BaseUrl != "" { - connector.SetBaseURL(cfg.BaseUrl) - } - connector.SetZone(cfg.Zone) - - err = connector.Authenticate(cfg.Credentials) - if err != nil { - return nil, err - } - return connector, nil -} diff --git a/vendor/github.com/Venafi/vcert/config.go b/vendor/github.com/Venafi/vcert/config.go deleted file mode 100644 index e4f74ceb..00000000 --- a/vendor/github.com/Venafi/vcert/config.go +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 vcert - -import ( - "fmt" - "github.com/Venafi/vcert/pkg/endpoint" - "gopkg.in/ini.v1" - "io/ioutil" - "log" - "os/user" - "path/filepath" -) - -type Config struct { - ConnectorType endpoint.ConnectorType - BaseUrl string - Zone string - Credentials *endpoint.Authentication - ConnectionTrust string // *x509.CertPool - LogVerbose bool - ConfigFile string - ConfigSection string -} - -func (cfg *Config) LoadFromFile() error { - if cfg.ConfigSection == "" { - cfg.ConfigSection = ini.DEFAULT_SECTION - } - log.Printf("Loading configuration from %s section %s", cfg.ConfigFile, cfg.ConfigSection) - - fname, err := expand(cfg.ConfigFile) - if err != nil { - return fmt.Errorf("failed to load config: %s", err) - } - - iniFile, err := ini.Load(fname) - if err != nil { - return fmt.Errorf("failed to load config: %s", err) - } - - err = validateFile(iniFile) - if err != nil { - return fmt.Errorf("failed to load config: %s", err) - } - - ok := func() bool { - for _, section := range iniFile.Sections() { - if section.Name() == cfg.ConfigSection { - return true - } - } - return false - }() - if !ok { - return fmt.Errorf("section %s has not been found in %s", cfg.ConfigSection, cfg.ConfigFile) - } - - var m Dict = iniFile.Section(cfg.ConfigSection).KeysHash() - - var connectorType endpoint.ConnectorType - var baseUrl string - var auth = &endpoint.Authentication{} - if m.has("tpp_url") { - connectorType = endpoint.ConnectorTypeTPP - baseUrl = m["tpp_url"] - auth.User = m["tpp_user"] - auth.Password = m["tpp_password"] - if m.has("tpp_zone") { - cfg.Zone = m["tpp_zone"] - } - if m.has("cloud_zone") { - cfg.Zone = m["cloud_zone"] - } - } else if m.has("cloud_apikey") { - connectorType = endpoint.ConnectorTypeCloud - if m.has("cloud_url") { - baseUrl = m["cloud_url"] - } - auth.APIKey = m["cloud_apikey"] - if m.has("cloud_zone") { - cfg.Zone = m["cloud_zone"] - } - } else if m.has("test_mode") && m["test_mode"] == "true" { - connectorType = endpoint.ConnectorTypeFake - } else { - return fmt.Errorf("failed to load config: connector type cannot be defined") - } - - if m.has("trust_bundle") { - fname, err := expand(m["trust_bundle"]) - if err != nil { - return fmt.Errorf("failed to load trust-bundle: %s", err) - } - data, err := ioutil.ReadFile(fname) - if err != nil { - return fmt.Errorf("failed to load trust-bundle: %s", err) - } - cfg.ConnectionTrust = string(data) - } - - cfg.ConnectorType = connectorType - cfg.Credentials = auth - cfg.BaseUrl = baseUrl - - return nil -} - -func expand(path string) (string, error) { - if len(path) == 0 || path[0] != '~' { - return path, nil - } - usr, err := user.Current() - if err != nil { - return "", err - } - return filepath.Join(usr.HomeDir, path[1:]), nil -} - -type Dict map[string]string - -func (d Dict) has(key string) bool { - if _, ok := d[key]; ok { - return true - } - return false -} - -type Set map[string]bool - -func (d Set) has(key string) bool { - if _, ok := d[key]; ok { - return true - } - return false -} - -func validateSection(s *ini.Section) error { - var TPPValidKeys Set = map[string]bool{ - "tpp_url": true, - "tpp_user": true, - "tpp_password": true, - "tpp_zone": true, - "trust_bundle": true, - } - var CloudValidKeys Set = map[string]bool{ - "trust_bundle": true, - "cloud_url": true, - "cloud_apikey": true, - "cloud_zone": true, - } - - log.Printf("Validating configuration section %s", s.Name()) - var m Dict = s.KeysHash() - - if m.has("tpp_url") { - // looks like TPP config section - for k, _ := range m { - if !TPPValidKeys.has(k) { - return fmt.Errorf("illegal key '%s' in TPP section %s", k, s.Name()) - } - } - if !m.has("tpp_user") { - return fmt.Errorf("configuration issue in section %s: missing TPP user", s.Name()) - } - if !m.has("tpp_password") { - return fmt.Errorf("configuration issue in section %s: missing TPP password", s.Name()) - } - } else if m.has("cloud_apikey") { - // looks like Cloud config section - for k, _ := range m { - if !CloudValidKeys.has(k) { - return fmt.Errorf("illegal key '%s' in Cloud section %s", k, s.Name()) - } - } - } else if m.has("test_mode") { - // it's ok - } else { - return fmt.Errorf("section %s looks empty", s.Name()) - } - return nil -} - -func validateFile(f *ini.File) error { - - for _, section := range f.Sections() { - if len(section.Keys()) == 0 { - if len(f.Sections()) > 1 { - // empty section is not valid. skipping it if there are more sections in the file - log.Printf("Warning: empty section %s", section.Name()) - continue - } - } - err := validateSection(section) - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/Venafi/vcert/pkg/certificate/certificate.go b/vendor/github.com/Venafi/vcert/pkg/certificate/certificate.go deleted file mode 100644 index 025b96c9..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/certificate/certificate.go +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 certificate - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "fmt" - "net" - "strings" - "time" -) - -//EllipticCurve represents the types of supported elliptic curves -type EllipticCurve int - -func (ec *EllipticCurve) String() string { - switch *ec { - case EllipticCurveP521: - return "P521" - case EllipticCurveP384: - return "P384" - case EllipticCurveP256: - return "P256" - case EllipticCurveP224: - return "P224" - default: - return "" - } -} - -//Set the elliptic cuve value via a string -func (ec *EllipticCurve) Set(value string) error { - switch strings.ToLower(value) { - case "p521": - *ec = EllipticCurveP521 - case "p384": - *ec = EllipticCurveP384 - case "p256": - *ec = EllipticCurveP256 - case "p224": - *ec = EllipticCurveP224 - default: - *ec = EllipticCurveP521 - } - - return nil -} - -const ( - //EllipticCurveP521 represents the P521 curve - EllipticCurveP521 EllipticCurve = iota - //EllipticCurveP224 represents the P224 curve - EllipticCurveP224 - //EllipticCurveP256 represents the P256 curve - EllipticCurveP256 - //EllipticCurveP384 represents the P384 curve - EllipticCurveP384 -) - -//KeyType represents the types of supported keys -type KeyType int - -func (kt *KeyType) String() string { - switch *kt { - case KeyTypeRSA: - return "RSA" - case KeyTypeECDSA: - return "ECDSA" - default: - return "" - } -} - -//Set the key type via a string -func (kt *KeyType) Set(value string) error { - switch strings.ToLower(value) { - case "rsa": - *kt = KeyTypeRSA - case "ecdsa": - *kt = KeyTypeECDSA - default: - *kt = KeyTypeECDSA - } - - return nil -} - -const ( - //KeyTypeRSA represents a key type of RSA - KeyTypeRSA KeyType = iota - //KeyTypeECDSA represents a key type of ECDSA - KeyTypeECDSA -) - -type CSrOriginOption int - -const ( - LocalGeneratedCSR CSrOriginOption = iota // local generation is default. - ServiceGeneratedCSR - UserProvidedCSR -) - -//Request contains data needed to generate a certificate request -type Request struct { - Subject pkix.Name - DNSNames []string - EmailAddresses []string - IPAddresses []net.IP - Attributes []pkix.AttributeTypeAndValueSET - SignatureAlgorithm x509.SignatureAlgorithm - PublicKeyAlgorithm x509.PublicKeyAlgorithm - FriendlyName string - KeyType KeyType - KeyLength int - KeyCurve EllipticCurve - CSR []byte - PrivateKey interface{} - CsrOrigin CSrOriginOption - PickupID string - ChainOption ChainOption - KeyPassword string - FetchPrivateKey bool - Thumbprint string /* this one is here because *Request is used in RetrieveCertificate(), - it should be refactored so that RetrieveCertificate() uses - some abstract search object, instead of *Request{PickupID} */ - Timeout time.Duration -} - -type RevocationRequest struct { - CertificateDN string - Thumbprint string - Reason string - Comments string - Disable bool -} - -type RenewalRequest struct { - CertificateDN string // these fields are for certificate lookup on remote - Thumbprint string - CertificateRequest *Request // here CSR should be filled -} - -type ImportRequest struct { - PolicyDN string `json:",omitempty"` - ObjectName string `json:",omitempty"` - CertificateData string `json:",omitempty"` - PrivateKeyData string `json:",omitempty"` - Password string `json:",omitempty"` - Reconcile bool `json:",omitempty"` - CASpecificAttributes map[string]string `json:",omitempty"` -} - -type ImportResponse struct { - CertificateDN string `json:",omitempty"` - CertificateVaultId int `json:",omitempty"` - Guid string `json:",omitempty"` - PrivateKeyVaultId int `json:",omitempty"` -} - -//GenerateRequest generates a certificate request -func GenerateRequest(request *Request, privateKey interface{}) error { - certificateRequest := x509.CertificateRequest{} - certificateRequest.Subject = request.Subject - certificateRequest.DNSNames = request.DNSNames - certificateRequest.EmailAddresses = request.EmailAddresses - certificateRequest.IPAddresses = request.IPAddresses - certificateRequest.Attributes = request.Attributes - - csr, err := x509.CreateCertificateRequest(rand.Reader, &certificateRequest, privateKey) - if err != nil { - csr = nil - } - request.CSR = csr - - return err -} - -func publicKey(priv interface{}) interface{} { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &k.PublicKey - case *ecdsa.PrivateKey: - return &k.PublicKey - default: - return nil - } -} - -func PublicKey(priv interface{}) interface{} { - return publicKey(priv) -} - -//GetPrivateKeyPEMBock gets the private key as a PEM data block -func GetPrivateKeyPEMBock(key interface{}) (*pem.Block, error) { - switch k := key.(type) { - case *rsa.PrivateKey: - return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil - case *ecdsa.PrivateKey: - b, err := x509.MarshalECPrivateKey(k) - if err != nil { - return nil, err - } - return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil - default: - return nil, fmt.Errorf("Unable to format Key") - } -} - -//GetEncryptedPrivateKeyPEMBock gets the private key as an encrypted PEM data block -func GetEncryptedPrivateKeyPEMBock(key interface{}, password []byte) (*pem.Block, error) { - switch k := key.(type) { - case *rsa.PrivateKey: - return x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(k), password, x509.PEMCipherAES256) - case *ecdsa.PrivateKey: - b, err := x509.MarshalECPrivateKey(k) - if err != nil { - return nil, err - } - return x509.EncryptPEMBlock(rand.Reader, "EC PRIVATE KEY", b, password, x509.PEMCipherAES256) - default: - return nil, fmt.Errorf("Unable to format Key") - } -} - -//GetCertificatePEMBlock gets the certificate as a PEM data block -func GetCertificatePEMBlock(cert []byte) *pem.Block { - return &pem.Block{Type: "CERTIFICATE", Bytes: cert} -} - -//GetCertificateRequestPEMBlock gets the certificate request as a PEM data block -func GetCertificateRequestPEMBlock(request []byte) *pem.Block { - return &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: request} -} - -//GenerateECDSAPrivateKey generates a new ecdsa private key using the curve specified -func GenerateECDSAPrivateKey(curve EllipticCurve) (*ecdsa.PrivateKey, error) { - var priv *ecdsa.PrivateKey - var c elliptic.Curve - var err error - - switch curve { - case EllipticCurveP521: - c = elliptic.P521() - case EllipticCurveP384: - c = elliptic.P384() - case EllipticCurveP256: - c = elliptic.P256() - case EllipticCurveP224: - c = elliptic.P224() - } - - priv, err = ecdsa.GenerateKey(c, rand.Reader) - if err != nil { - return nil, err - } - - return priv, nil -} - -//GenerateRSAPrivateKey generates a new rsa private key using the size specified -func GenerateRSAPrivateKey(size int) (*rsa.PrivateKey, error) { - priv, err := rsa.GenerateKey(rand.Reader, size) - if err != nil { - return nil, err - } - - return priv, nil -} - -func NewRequest(cert *x509.Certificate) *Request { - req := &Request{} - // 1st fill with *cert content - - req.Subject = cert.Subject - req.DNSNames = cert.DNSNames - req.EmailAddresses = cert.EmailAddresses - req.IPAddresses = cert.IPAddresses - req.SignatureAlgorithm = cert.SignatureAlgorithm - req.PublicKeyAlgorithm = cert.PublicKeyAlgorithm - switch pub := cert.PublicKey.(type) { - case *rsa.PublicKey: - req.KeyType = KeyTypeRSA - req.KeyLength = pub.N.BitLen() - case *ecdsa.PublicKey: - req.KeyType = KeyTypeECDSA - req.KeyLength = pub.Curve.Params().BitSize - // TODO: req.KeyCurve = pub.Curve.Params().Name... - default: // case *dsa.PublicKey: - // vcert only works with RSA & ECDSA - } - return req -} diff --git a/vendor/github.com/Venafi/vcert/pkg/certificate/certificateCollection.go b/vendor/github.com/Venafi/vcert/pkg/certificate/certificateCollection.go deleted file mode 100644 index 9cdff5ac..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/certificate/certificateCollection.go +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 certificate - -import ( - "crypto/x509" - "encoding/pem" - "fmt" - "strings" -) - -//ChainOption represents the options to be used with the certificate chain -type ChainOption int - -const ( - //ChainOptionRootLast specifies the root certificate should be in the last position of the chain - ChainOptionRootLast ChainOption = iota - //ChainOptionRootFirst specifies the root certificate should be in the first position of the chain - ChainOptionRootFirst - //ChainOptionIgnore specifies the chain should be ignored - ChainOptionIgnore -) - -//ChainOptionFromString converts the string to the corresponding ChainOption -func ChainOptionFromString(order string) ChainOption { - switch strings.ToLower(order) { - case "root-first": - return ChainOptionRootFirst - case "ignore": - return ChainOptionIgnore - default: - return ChainOptionRootLast - } -} - -//PEMCollection represents a collection of PEM data -type PEMCollection struct { - Certificate string `json:",omitempty"` - PrivateKey string `json:",omitempty"` - Chain []string `json:",omitempty"` -} - -//NewPEMCollection creates a PEMCollection based on the data being passed in -func NewPEMCollection(certificate *x509.Certificate, privateKey interface{}, privateKeyPassword []byte) (*PEMCollection, error) { - collection := PEMCollection{} - if certificate != nil { - collection.Certificate = string(pem.EncodeToMemory(GetCertificatePEMBlock(certificate.Raw))) - } - if privateKey != nil { - var p *pem.Block - var err error - if privateKeyPassword != nil && len(privateKeyPassword) > 0 { - p, err = GetEncryptedPrivateKeyPEMBock(privateKey, privateKeyPassword) - } else { - p, err = GetPrivateKeyPEMBock(privateKey) - } - if err != nil { - return nil, err - } - collection.PrivateKey = string(pem.EncodeToMemory(p)) - } - return &collection, nil -} - -//PEMCollectionFromBytes creates a PEMCollection based on the data passed in -func PEMCollectionFromBytes(certBytes []byte, chainOrder ChainOption) (*PEMCollection, error) { - var ( - current []byte - remaining []byte - p *pem.Block - cert *x509.Certificate - chain []*x509.Certificate - privPEM string - err error - collection *PEMCollection - ) - current = certBytes - - for { - p, remaining = pem.Decode(current) - if p == nil { - break - } - switch p.Type { - case "CERTIFICATE": - cert, err = x509.ParseCertificate(p.Bytes) - if err != nil { - return nil, err - } - chain = append(chain, cert) - case "RSA PRIVATE KEY", "EC PRIVATE KEY": - privPEM = string(current) - } - current = remaining - } - - if len(chain) > 0 { - switch chainOrder { - case ChainOptionRootFirst: - collection, err = NewPEMCollection(chain[len(chain)-1], nil, nil) - if len(chain) > 1 && chainOrder != ChainOptionIgnore { - for _, caCert := range chain[:len(chain)-1] { - collection.AddChainElement(caCert) - } - } - default: - collection, err = NewPEMCollection(chain[0], nil, nil) - if len(chain) > 1 && chainOrder != ChainOptionIgnore { - for _, caCert := range chain[1:] { - collection.AddChainElement(caCert) - } - } - } - if err != nil { - return nil, err - } - } else { - collection = &PEMCollection{} - } - collection.PrivateKey = privPEM - - return collection, nil -} - -//AddPrivateKey adds a Private Key to the PEMCollection. Note that the collection can only contain one private key -func (col *PEMCollection) AddPrivateKey(privateKey interface{}, privateKeyPassword []byte) error { - if col.PrivateKey != "" { - return fmt.Errorf("The PEM Collection can only contain one private key") - } - var p *pem.Block - var err error - if privateKeyPassword != nil && len(privateKeyPassword) > 0 { - p, err = GetEncryptedPrivateKeyPEMBock(privateKey, privateKeyPassword) - } else { - p, err = GetPrivateKeyPEMBock(privateKey) - } - if err != nil { - return err - } - col.PrivateKey = string(pem.EncodeToMemory(p)) - return nil -} - -//AddChainElement adds a chain element to the collection -func (col *PEMCollection) AddChainElement(certificate *x509.Certificate) error { - if certificate == nil { - return fmt.Errorf("Certificate cannot be nil") - } - pemChain := col.Chain - pemChain = append(pemChain, string(pem.EncodeToMemory(GetCertificatePEMBlock(certificate.Raw)))) - col.Chain = pemChain - return nil -} diff --git a/vendor/github.com/Venafi/vcert/pkg/endpoint/endpoint.go b/vendor/github.com/Venafi/vcert/pkg/endpoint/endpoint.go deleted file mode 100644 index 763906e2..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/endpoint/endpoint.go +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 endpoint - -import ( - "crypto/x509" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "regexp" - "sort" - "strings" -) - -// ConnectorType represents the available connectors -type ConnectorType int - -const ( - ConnectorTypeUndefined ConnectorType = iota - // ConnectorTypeFake is a fake connector for tests - ConnectorTypeFake - // ConnectorTypeCloud represents the Cloud connector type - ConnectorTypeCloud - // ConnectorTypeTPP represents the TPP connector type - ConnectorTypeTPP -) - -func (t ConnectorType) String() string { - switch t { - case ConnectorTypeUndefined: - return "Undefined Endpoint" - case ConnectorTypeFake: - return "Fake Endpoint" - case ConnectorTypeCloud: - return "Venafi Cloud" - case ConnectorTypeTPP: - return "TPP" - default: - return fmt.Sprintf("unexpected connector type: %d", t) - } -} - -// Connector provides a common interface for external communications with TPP or Venafi Cloud -type Connector interface { - GetType() ConnectorType - SetBaseURL(url string) (err error) - SetZone(z string) - Ping() (err error) - Register(email string) (err error) - Authenticate(auth *Authentication) (err error) - ReadZoneConfiguration(zone string) (config *ZoneConfiguration, err error) - GenerateRequest(config *ZoneConfiguration, req *certificate.Request) (err error) - RequestCertificate(req *certificate.Request, zone string) (requestID string, err error) - RetrieveCertificate(req *certificate.Request) (certificates *certificate.PEMCollection, err error) - RevokeCertificate(req *certificate.RevocationRequest) error - RenewCertificate(req *certificate.RenewalRequest) (requestID string, err error) - ImportCertificate(req *certificate.ImportRequest) (*certificate.ImportResponse, error) -} - -// Authentication provides a data construct for authentication data -type Authentication struct { - User string - Password string - APIKey string -} - -// ErrRetrieveCertificateTimeout provides a common error structure for a timeout while retrieving a certificate -type ErrRetrieveCertificateTimeout struct { - CertificateID string -} - -func (err ErrRetrieveCertificateTimeout) Error() string { - return fmt.Sprintf("Operation timed out. You may try retrieving the certificate later using Pickup ID: %s", err.CertificateID) -} - -// ErrCertificatePending provides a common error structure for a timeout while retrieving a certificate -type ErrCertificatePending struct { - CertificateID string - Status string -} - -func (err ErrCertificatePending) Error() string { - if err.Status == "" { - return fmt.Sprintf("Issuance is pending. You may try retrieving the certificate later using Pickup ID: %s", err.CertificateID) - } - return fmt.Sprintf("Issuance is pending. You may try retrieving the certificate later using Pickup ID: %s\n\tStatus: %s", err.CertificateID, err.Status) -} - -// ZoneConfiguration provides a common structure for certificate request data provided by the remote endpoint -type ZoneConfiguration struct { - Organization string - OrganizationLocked bool - OrganizationalUnit []string - Country string - CountryLocked bool - Province string - ProvinceLocked bool - Locality string - LocalityLocked bool - - SubjectCNRegexes []string - SubjectORegexes []string - SubjectOURegexes []string - SubjectSTRegexes []string - SubjectLRegexes []string - SubjectCRegexes []string - SANRegexes []string - - AllowedKeyConfigurations []AllowedKeyConfiguration - KeySizeLocked bool - - HashAlgorithm x509.SignatureAlgorithm - - CustomAttributeValues map[string]string -} - -// AllowedKeyConfiguration contains an allowed key type with its sizes or curves -type AllowedKeyConfiguration struct { - KeyType certificate.KeyType - KeySizes []int - KeyCurves []certificate.EllipticCurve -} - -// NewZoneConfiguration creates a new zone configuration which creates the map used in the configuration -func NewZoneConfiguration() *ZoneConfiguration { - zc := ZoneConfiguration{} - zc.CustomAttributeValues = make(map[string]string) - - return &zc -} - -// ValidateCertificateRequest validates the request against the zone configuration -func (z *ZoneConfiguration) ValidateCertificateRequest(request *certificate.Request) error { - if !isComponentValid(z.SubjectCNRegexes, []string{request.Subject.CommonName}) { - return fmt.Errorf("The requested CN does not match any of the allowed CN regular expressions") - } - if !isComponentValid(z.SubjectORegexes, request.Subject.Organization) { - return fmt.Errorf("The requested Organization does not match any of the allowed Organization regular expressions") - } - if !isComponentValid(z.SubjectOURegexes, request.Subject.OrganizationalUnit) { - return fmt.Errorf("The requested Organizational Unit does not match any of the allowed Organization Unit regular expressions") - } - if !isComponentValid(z.SubjectSTRegexes, request.Subject.Province) { - return fmt.Errorf("The requested State/Province does not match any of the allowed State/Province regular expressions") - } - if !isComponentValid(z.SubjectLRegexes, request.Subject.Locality) { - return fmt.Errorf("The requested Locality does not match any of the allowed Locality regular expressions") - } - if !isComponentValid(z.SubjectCRegexes, request.Subject.Country) { - return fmt.Errorf("The requested Country does not match any of the allowed Country regular expressions") - } - if !isComponentValid(z.SANRegexes, request.DNSNames) { - return fmt.Errorf("The requested Subject Alternative Name does not match any of the allowed Country regular expressions") - } - - if z.AllowedKeyConfigurations != nil && len(z.AllowedKeyConfigurations) > 0 { - match := false - for _, keyConf := range z.AllowedKeyConfigurations { - if keyConf.KeyType == request.KeyType { - if request.KeyLength > 0 { - for _, size := range keyConf.KeySizes { - if size == request.KeyLength { - match = true - break - } - } - } else { - match = true - } - } - if match { - break - } - } - if !match { - return fmt.Errorf("The requested Key Type and Size do not match any of the allowed Key Types and Sizes") - } - } - - return nil -} - -func isComponentValid(regexes []string, component []string) bool { - if regexes != nil && len(regexes) > 0 && component != nil { - regexOk := false - for _, subReg := range regexes { - matchedAny := false - reg := regexp.MustCompile(subReg) - for _, c := range component { - if reg.FindStringIndex(c) != nil { - matchedAny = true - break - } - } - if matchedAny { - regexOk = true - break - } - } - return regexOk - } - return true -} - -// UpdateCertificateRequest updates a certificate request based on the zone configurataion retrieved from the remote endpoint -func (z *ZoneConfiguration) UpdateCertificateRequest(request *certificate.Request) { - if (request.Subject.Organization == nil || len(request.Subject.Organization) == 0) && z.Organization != "" { - request.Subject.Organization = []string{z.Organization} - } else { - if z.OrganizationLocked && !strings.EqualFold(request.Subject.Organization[0], z.Organization) { - request.Subject.Organization = []string{z.Organization} - } - } - if (request.Subject.OrganizationalUnit == nil || len(request.Subject.OrganizationalUnit) == 0) && z.OrganizationalUnit != nil { - request.Subject.OrganizationalUnit = z.OrganizationalUnit - } - - if (request.Subject.Country == nil || len(request.Subject.Country) == 0) && z.Country != "" { - request.Subject.Country = []string{z.Country} - } else { - if z.CountryLocked && !strings.EqualFold(request.Subject.Country[0], z.Country) { - request.Subject.Country = []string{z.Country} - } - } - if (request.Subject.Province == nil || len(request.Subject.Province) == 0) && z.Province != "" { - request.Subject.Province = []string{z.Province} - } else { - if z.ProvinceLocked && !strings.EqualFold(request.Subject.Province[0], z.Province) { - request.Subject.Province = []string{z.Province} - } - } - if (request.Subject.Locality == nil || len(request.Subject.Locality) == 0) && z.Locality != "" { - request.Subject.Locality = []string{z.Locality} - } else { - if z.LocalityLocked && !strings.EqualFold(request.Subject.Locality[0], z.Locality) { - request.Subject.Locality = []string{z.Locality} - } - } - if z.HashAlgorithm != 0 { - request.SignatureAlgorithm = z.HashAlgorithm - } else { - request.SignatureAlgorithm = x509.SHA256WithRSA - } - - if z.KeySizeLocked { - for _, keyConf := range z.AllowedKeyConfigurations { - if keyConf.KeyType == request.KeyType { - sort.Sort(sort.Reverse(sort.IntSlice(keyConf.KeySizes))) - request.KeyLength = keyConf.KeySizes[0] - } - } - } else if z.AllowedKeyConfigurations != nil { - foundMatch := false - for _, keyConf := range z.AllowedKeyConfigurations { - if keyConf.KeyType == request.KeyType { - foundMatch = true - switch request.KeyType { - case certificate.KeyTypeECDSA: - if z.AllowedKeyConfigurations[0].KeyCurves != nil { - request.KeyCurve = z.AllowedKeyConfigurations[0].KeyCurves[0] - } else { - request.KeyCurve = certificate.EllipticCurveP256 - } - case certificate.KeyTypeRSA: - if keyConf.KeySizes != nil { - sizeOK := false - for _, size := range keyConf.KeySizes { - if size == request.KeyLength { - sizeOK = true - } - } - if !sizeOK { - sort.Sort(sort.Reverse(sort.IntSlice(keyConf.KeySizes))) - request.KeyLength = keyConf.KeySizes[0] - } - } else { - request.KeyLength = 2048 - } - } - } - } - if !foundMatch { - request.KeyType = z.AllowedKeyConfigurations[0].KeyType - switch request.KeyType { - case certificate.KeyTypeECDSA: - if z.AllowedKeyConfigurations[0].KeyCurves != nil { - request.KeyCurve = z.AllowedKeyConfigurations[0].KeyCurves[0] - } else { - request.KeyCurve = certificate.EllipticCurveP256 - } - case certificate.KeyTypeRSA: - if z.AllowedKeyConfigurations[0].KeySizes != nil { - sort.Sort(sort.Reverse(sort.IntSlice(z.AllowedKeyConfigurations[0].KeySizes))) - request.KeyLength = z.AllowedKeyConfigurations[0].KeySizes[0] - } else { - request.KeyLength = 2048 - } - } - } - } else { - // Zone config has no key length parameters, so we just pass user's -key-size or fall to default 2048 - if request.KeyType == certificate.KeyTypeRSA && request.KeyLength == 0 { - request.KeyLength = 2048 - } - } - - return -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/certificatePolicies.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/certificatePolicies.go deleted file mode 100644 index 5c58df96..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/certificatePolicies.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import "time" - -type certificatePolicy struct { - CertificatePolicyType certificatePolicyType `json:"certificatePolicyType,omitempty"` - ID string `json:"id,omitempty"` - CompanyID string `json:"companyId,omitempty"` - Name string `json:"name,omitempty"` - SystemGenerated bool `json:"systemGeneratedate,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` - CertificateProviderID string `json:"certificateProviderId,omitempty"` - SubjectCNRegexes []string `json:"subjectCNRegexes,omitempty"` - SubjectORegexes []string `json:"subjectORegexes,omitempty"` - SubjectOURegexes []string `json:"subjectOURegexes,omitempty"` - SubjectSTRegexes []string `json:"subjectSTRegexes,omitempty"` - SubjectLRegexes []string `json:"subjectLRegexes,omitempty"` - SubjectCRegexes []string `json:"subjectCRegexes,omitempty"` - SANRegexes []string `json:"sanRegexes,omitempty"` - KeyTypes []allowedKeyType `json:"keyTypes,omitempty"` - KeyReuse bool `json:"keyReuse,omitempty"` -} - -type allowedKeyType struct { - KeyType keyType - KeyLengths []int -} - -type certificatePolicyType string - -const ( - certificatePolicyTypeIdentity certificatePolicyType = "CERTIFICATE_IDENTITY" - certificatePolicyTypeUse = "CERTIFICATE_USE" -) - -type keyType string - -const ( - keyTypeRSA keyType = "RSA" - keyTypeDSA = "DSA" - keyTypeEC = "EC" - keyTypeGost3410 = "GOST3410" - keyTypeECGost3410 = "ECGOST3410" - keyTypeReserved3 = "RESERVED3" - keyTypeUnknown = "UNKNOWN" -) - -/* -"signatureAlgorithm":{"type":"string","enum":["MD2_WITH_RSA_ENCRYPTION","MD5_WITH_RSA_ENCRYPTION","SHA1_WITH_RSA_ENCRYPTION","SHA1_WITH_RSA_ENCRYPTION2","SHA256_WITH_RSA_ENCRYPTION","SHA384_WITH_RSA_ENCRYPTION","SHA512_WITH_RSA_ENCRYPTION","ID_DSA_WITH_SHA1","dsaWithSHA1","EC_DSA_WITH_SHA1","EC_DSA_WITH_SHA224","EC_DSA_WITH_SHA256","EC_DSA_WITH_SHA384","EC_DSA_WITH_SHA512","UNKNOWN","SHA1_WITH_RSAandMGF1","GOST_R3411_94_WITH_GOST_R3410_2001","GOST_R3411_94_WITH_GOST_R3410_94"]}, -"signatureHashAlgorithm":{"type":"string","enum":["MD5","SHA1","MD2","SHA224","SHA256","SHA384","SHA512","UNKNOWN","GOSTR3411_94"]} -*/ diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/cloud.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/cloud.go deleted file mode 100644 index 2bcd1d7e..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/cloud.go +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "encoding/json" - "encoding/pem" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "net/http" - "regexp" - "strings" - "time" -) - -type apiKey struct { - Username string `json:"username,omitempty"` - APITypes []string `json:"apitypes,omitempty"` - APIVersion string `json:"apiVersion,omitempty"` - APIKeyStatus string `json:"apiKeyStatus,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` - ValidityStartDateString string `json:"validityStartDate,omitempty"` - ValidityStartDate time.Time `json:"-"` - ValidityEndDateString string `json:"validityEndDate,omitempty"` - ValidityEndDate time.Time `json:"-"` -} - -type userDetails struct { - User *user `json:"user,omitempty"` - Company *company `json:"company,omitempty"` - APIKey *apiKey `json:"apiKey,omitempty"` -} - -type certificateRequestResponse struct { - CertificateRequests []certificateRequestResponseData `json:"certificateRequests,omitempty"` -} - -type certificateRequestResponseData struct { - ID string `json:"id,omitempty"` - ZoneID string `json:"zoneId,omitempty"` - Status string `json:"status,omitempty"` - SubjectDN string `json:"subjectDN,omitempty"` - GeneratedKey bool `json:"generatedKey,omitempty"` - DefaultKeyPassword bool `json:"defaultKeyPassword,omitempty"` - CertificateInstanceIDs []string `json:"certificateInstanceIds,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` - PEM string `json:"pem,omitempty"` - DER string `json:"der,omitempty"` -} - -type certificateRequest struct { // TODO: this is actually certificate request object (sent with POST) - //CompanyID string `json:"companyId,omitempty"` - CSR string `json:"certificateSigningRequest,omitempty"` - ZoneID string `json:"zoneId,omitempty"` - ExistingManagedCertificateId string `json:"existingManagedCertificateId,omitempty"` - ReuseCSR bool `json:"reuseCSR,omitempty"` - //DownloadFormat string `json:"downloadFormat,omitempty"` -} - -type certificateStatus struct { // TODO: this is actually the same certificate request object (received with GET) - Id string `json:"Id,omitempty"` - ManagedCertificateId string `json:"managedCertificateId,omitempty"` - ZoneId string `json:"zoneId,omitempty"` - Status string `json:"status,omitempty"` - ErrorInformation CertificateStatusErrorInformation `json:"errorInformation,omitempty"` - CreationDate string `json:"creationDate,omitempty"` - ModificationDate string `json:"modificationDate,omitempty"` - CertificateSigningRequest string `json:"certificateSigningRequest,omitempty"` - SubjectDN string `json:"subjectDN,omitempty"` -} - -type CertificateStatusErrorInformation struct { - Type string `json:"type,omitempty"` - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` - Args []string `json:"args,omitempty"` -} - -//GenerateRequest generates a CertificateRequest based on the zone configuration, and returns the request along with the private key. -func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *certificate.Request) (err error) { - switch req.CsrOrigin { - case certificate.LocalGeneratedCSR: - var pk interface{} - if config == nil { - config, err = c.ReadZoneConfiguration(c.zone) - if err != nil { - return fmt.Errorf("could not read zone configuration: %s", err) - } - } - err = config.ValidateCertificateRequest(req) - if err != nil { - return err - } - config.UpdateCertificateRequest(req) - switch req.KeyType { - case certificate.KeyTypeECDSA: - pk, err = certificate.GenerateECDSAPrivateKey(req.KeyCurve) - case certificate.KeyTypeRSA: - pk, err = certificate.GenerateRSAPrivateKey(req.KeyLength) - default: - return fmt.Errorf("Unable to generate certificate request, key type %s is not supported", req.KeyType.String()) - } - if err != nil { - return err - } - req.PrivateKey = pk - err = certificate.GenerateRequest(req, pk) - if err != nil { - return err - } - req.CSR = pem.EncodeToMemory(certificate.GetCertificateRequestPEMBlock(req.CSR)) - return nil - - case certificate.UserProvidedCSR: - if req.CSR == nil || len(req.CSR) == 0 { - return fmt.Errorf("CSR was supposed to be provided by user, but it's empty") - } - return nil - - case certificate.ServiceGeneratedCSR: - req.CSR = nil - return nil - - default: - return fmt.Errorf("unrecognised req.CsrOrigin %v", req.CsrOrigin) - } -} - -//SetBaseURL allows overriding the default URL used to communicate with Venafi Cloud -func (c *Connector) SetBaseURL(url string) error { - if url == "" { - return fmt.Errorf("base URL cannot be empty") - } - modified := strings.ToLower(url) - reg := regexp.MustCompile("^http(|s)://") - if reg.FindStringIndex(modified) == nil { - modified = "https://" + modified - } else { - modified = reg.ReplaceAllString(modified, "https://") - } - reg = regexp.MustCompile("/v1(|/)$") - if reg.FindStringIndex(modified) == nil { - modified += "v1/" - } else { - modified = reg.ReplaceAllString(modified, "/v1/") - } - c.baseURL = modified - return nil -} - -func (c *Connector) getURL(resource urlResource) string { - return fmt.Sprintf("%s%s", c.baseURL, resource) -} - -func parseUserDetailsResult(expectedStatusCode int, httpStatusCode int, httpStatus string, body []byte) (*userDetails, error) { - if httpStatusCode == expectedStatusCode { - resp, err := parseUserDetailsData(body) - if err != nil { - return nil, err - } - return resp, nil - } - - switch httpStatusCode { - case http.StatusConflict, http.StatusPreconditionFailed: - respErrors, err := parseResponseErrors(body) - if err != nil { - return nil, err - } - - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud registration. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud registration. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud registration. Status: %s", httpStatus) - } -} - -func parseUserDetailsData(b []byte) (*userDetails, error) { - var data userDetails - err := json.Unmarshal(b, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -func parseZoneConfigurationResult(httpStatusCode int, httpStatus string, body []byte) (*zone, error) { - switch httpStatusCode { - case http.StatusOK: - z, err := parseZoneConfigurationData(body) - if err != nil { - return nil, err - } - return z, nil - case http.StatusBadRequest, http.StatusPreconditionFailed, http.StatusNotFound: - respErrors, err := parseResponseErrors(body) - if err != nil { - return nil, err - } - - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud zone read. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud zone read. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud zone read. Status: %s", httpStatus) - } -} - -func parseZoneConfigurationData(b []byte) (*zone, error) { - var data zone - err := json.Unmarshal(b, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -func parseCertificatePolicyResult(httpStatusCode int, httpStatus string, body []byte) (*certificatePolicy, error) { - switch httpStatusCode { - case http.StatusOK: - p, err := parseCertificatePolicyData(body) - if err != nil { - return nil, err - } - return p, nil - case http.StatusBadRequest, http.StatusPreconditionFailed, http.StatusNotFound: - respErrors, err := parseResponseErrors(body) - if err != nil { - return nil, err - } - - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud policy read. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud policy read. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud policy read. Status: %s", httpStatus) - } -} - -func parseCertificatePolicyData(b []byte) (*certificatePolicy, error) { - var data certificatePolicy - err := json.Unmarshal(b, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -func parseCertificateRequestResult(httpStatusCode int, httpStatus string, body []byte) (*certificateRequestResponse, error) { - switch httpStatusCode { - case http.StatusCreated: - z, err := parseCertificateRequestData(body) - if err != nil { - return nil, err - } - return z, nil - case http.StatusBadRequest, http.StatusPreconditionFailed: - respErrors, err := parseResponseErrors(body) - if err != nil { - return nil, err - } - - respError := fmt.Sprintf("Certificate request failed with server error. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud certificate request. Status: %s\n", httpStatus) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud certificate request. Status: %s", httpStatus) - } -} - -func parseCertificateRequestData(b []byte) (*certificateRequestResponse, error) { - var data certificateRequestResponse - err := json.Unmarshal(b, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -func newPEMCollectionFromResponse(data []byte, chainOrder certificate.ChainOption) (*certificate.PEMCollection, error) { - return certificate.PEMCollectionFromBytes(data, chainOrder) -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/company.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/company.go deleted file mode 100644 index 6f566157..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/company.go +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "time" -) - -type company struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - CompanyType string `json:"companyType,omitempty"` - Active bool `json:"active,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` - Domains []string `json:"domains,omitempty"` -} - -type zone struct { - ID string `json:"id,omitempty"` - CompanyID string `json:"companyId,omitempty"` - Tag string `json:"tag,omitempty"` - ZoneType string `json:"zoneType,omitempty"` - CertificatePolicyIDs certificatePolicyID `json:"certificatePolicyIds,omitempty"` - DefaultCertificateIdentityPolicy string `json:"defaultCertificateIdentityPolicyId,omitempty"` - DefaultCertificateUsePolicy string `json:"defaultCertificateUsePolicyId,omitempty"` - SystemGenerated bool `json:"systemGeneratedate,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` -} - -type certificatePolicyID struct { - CertificateIdentity []string `json:"CERTIFICATE_IDENTITY,omitempty"` - CertificateUse []string `json:"CERTIFICATE_USE,omitempty"` -} - -func (z *zone) GetZoneConfiguration(ud *userDetails, policy *certificatePolicy) *endpoint.ZoneConfiguration { - zoneConfig := endpoint.ZoneConfiguration{} - - if policy != nil { - if policy.KeyTypes != nil { - certKeyType := certificate.KeyTypeRSA - for _, kt := range policy.KeyTypes { - certKeyType.Set(fmt.Sprintf("%s", kt.KeyType)) - keyConfiguration := endpoint.AllowedKeyConfiguration{} - keyConfiguration.KeyType = certKeyType - for _, size := range kt.KeyLengths { - keyConfiguration.KeySizes = append(keyConfiguration.KeySizes, size) - } - zoneConfig.AllowedKeyConfigurations = append(zoneConfig.AllowedKeyConfigurations, keyConfiguration) - } - } - } - return &zoneConfig -} - -const ( - zoneKeyGeneratorDeviceKeyGeneration = "DEVICE_KEY_GENERATION" - zoneKeyGeneratorCentralKeyGeneration = "CENTRAL_KEY_GENERATION" - zoneKeyGeneratorUnknown = "UNKNOWN" -) - -const ( - zoneEncryptionTypeRSA = "RSA" - zoneEncryptionTypeDSA = "DSA" - zoneEncryptionTypeEC = "EC" - zoneEncryptionTypeGOST3410 = "GOST3410" - zoneEncryptionTypeECGOST3410 = "ECGOST3410" - zoneEncryptionTypeRESERVED3 = "RESERVED3" - zoneEncryptionTypeUnknown = "UNKNOWN" -) - -const ( - zoneHashAlgorithmMD5 = "MD5" - zoneHashAlgorithmSHA1 = "SHA1" - zoneHashAlgorithmMD2 = "MD2" - zoneHashAlgorithmSHA224 = "SHA224" - zoneHashAlgorithmSHA256 = "SHA256" - zoneHashAlgorithmSHA384 = "SHA384" - zoneHashAlgorithmSHA512 = "SHA512" - zoneHashAlgorithmUnknown = "UNKNOWN" - zoneHashAlgorithmGOSTR341194 = "GOSTR3411_94" -) - -const ( - zoneValidityPeriodLTE90 = "LTE_90_DAYS" - zoneValidityPeriodGT90 = "GT_90_DAYS" - zoneValidityPeriodOther = "OTHER" -) - -const ( - zoneCertificateAuthorityTypeCondorTest = "CONDOR_TEST_CA" - zoneCertificateAuthorityTypePublic = "PUBLIC_CA" - zoneCertificateAuthorityTypePrivate = "PRIVATE_CA" - zoneCertificateAuthorityTypeOther = "OTHER" -) diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/connector.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/connector.go deleted file mode 100644 index 0c2fa481..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/connector.go +++ /dev/null @@ -1,710 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "bytes" - "crypto/x509" - "encoding/json" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "io/ioutil" - "log" - "net/http" - "strings" - "time" -) - -const apiURL = "api.venafi.cloud/v1/" - -type urlResource string - -const ( - urlResourceUserAccounts urlResource = "useraccounts" - urlResourcePing = "ping" - urlResourceZones = "zones" - urlResourceZoneByTag = urlResourceZones + "/tag/%s" - urlResourceCertificatePolicies = "certificatepolicies" - urlResourcePoliciesByID = urlResourceCertificatePolicies + "%s" - urlResourcePoliciesForZoneByID = urlResourceCertificatePolicies + "?zoneId=%s" - urlResourceCertificateRequests = "certificaterequests" - urlResourceCertificateStatus = urlResourceCertificateRequests + "/%s" - urlResourceCertificateRetrieve = urlResourceCertificateRequests + "/%s/certificate" - urlResourceCertificateSearch = "certificatesearch" - urlResourceManagedCertificates = "managedcertificates" - urlResourceManagedCertificateById = urlResourceManagedCertificates + "/%s" -) - -type condorChainOption string - -const ( - condorChainOptionRootFirst condorChainOption = "ROOT_FIRST" - condorChainOptionRootLast = "EE_FIRST" -) - -// Connector contains the base data needed to communicate with the Venafi Cloud servers -type Connector struct { - baseURL string - apiKey string - verbose bool - user *userDetails - trust *x509.CertPool - zone string -} - -// NewConnector creates a new Venafi Cloud Connector object used to communicate with Venafi Cloud -func NewConnector(verbose bool, trust *x509.CertPool) *Connector { - c := Connector{verbose: verbose, trust: trust} - c.SetBaseURL(apiURL) - return &c -} - -func (c *Connector) SetZone(z string) { - c.zone = z -} - -func (c *Connector) GetType() endpoint.ConnectorType { - return endpoint.ConnectorTypeCloud -} - -//Ping attempts to connect to the Venafi Cloud API and returns an errror if it cannot -func (c *Connector) Ping() (err error) { - url := c.getURL(urlResourcePing) - - resp, err := http.Get(url) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - err = fmt.Errorf("Unexpected status code on Venafi Cloud ping. Status: %d %s", resp.StatusCode, resp.Status) - } - return err -} - -//Authenticate authenticates the user with Venafi Cloud using the provided API Key -func (c *Connector) Authenticate(auth *endpoint.Authentication) (err error) { - if auth == nil { - return fmt.Errorf("failed to authenticate: missing credentials") - } - c.apiKey = auth.APIKey - url := c.getURL(urlResourceUserAccounts) - b := []byte{} - reader := bytes.NewReader(b) - request, err := http.NewRequest("GET", url, reader) - if err != nil { - return err - } - request.Header.Add("tppl-api-key", c.apiKey) - resp, err := http.DefaultClient.Do(request) - if err != nil { - return err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - ud, err := parseUserDetailsResult(http.StatusOK, resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return err - } - c.user = ud - return nil -} - -//Register registers a new user with Venafi Cloud -func (c *Connector) Register(email string) (err error) { - b, err := json.Marshal(userAccount{Username: email, UserAccountType: "API"}) - - url := c.getURL(urlResourceUserAccounts) - - reader := bytes.NewReader(b) - resp, err := http.Post(url, "application/json", reader) - if err != nil { - return err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - //the user has already been registered and there is nothing to parse - if resp.StatusCode == http.StatusAccepted { - return nil - } - ud, err := parseUserDetailsResult(http.StatusCreated, resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return err - } - c.user = ud - return nil -} - -//ReadZoneConfiguration reads the Zone information needed for generating and requesting a certificate from Venafi Cloud -func (c *Connector) ReadZoneConfiguration(zone string) (config *endpoint.ZoneConfiguration, err error) { - z, err := c.getZoneByTag(zone) - if err != nil { - return nil, err - } - p, err := c.getPoliciesByID([]string{z.DefaultCertificateIdentityPolicy, z.DefaultCertificateUsePolicy}) - config = z.GetZoneConfiguration(c.user, p) - return config, nil -} - -//RequestCertificate submits the CSR to the Venafi Cloud API for processing -func (c *Connector) RequestCertificate(req *certificate.Request, zone string) (requestID string, err error) { - - if zone == "" { - zone = c.zone - } - - if req.CsrOrigin == certificate.ServiceGeneratedCSR { - return "", fmt.Errorf("service generated CSR is not supported by Saas service") - } - - url := c.getURL(urlResourceCertificateRequests) - if c.user == nil || c.user.Company == nil { - return "", fmt.Errorf("Must be autheticated to request a certificate") - } - z, err := c.getZoneByTag(zone) - if err != nil { - return "", err - } - b, _ := json.Marshal(certificateRequest{ZoneID: z.ID, CSR: string(req.CSR)}) - reader := bytes.NewReader(b) - request, err := http.NewRequest("POST", url, reader) - if err != nil { - return "", err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("content-type", "application/json") - resp, err := http.DefaultClient.Do(request) - if err != nil { - return "", err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - cr, err := parseCertificateRequestResult(resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return "", err - } - requestID = cr.CertificateRequests[0].ID - req.PickupID = requestID - return requestID, nil -} - -func (c *Connector) getCertificateStatus(requestID string) (*certificateStatus, error) { - var err error - url := c.getURL(urlResourceCertificateStatus) - if c.user == nil || c.user.Company == nil { - err = fmt.Errorf("Must be autheticated to retieve certificate") - return nil, err - } - url = fmt.Sprintf(url, requestID) - - b := []byte{} - reader := bytes.NewReader(b) - request, err := http.NewRequest("GET", url, reader) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("Accept", "application/json") - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - - switch resp.StatusCode { - case http.StatusOK: - var data = &certificateStatus{} - err = json.Unmarshal(body, data) - if err != nil { - return nil, fmt.Errorf("failed to parse certificate request status response: %s", err) - } - return data, nil - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud certificate search. Status: %d\n", resp.StatusCode) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud certificate search. Status: %d", resp.StatusCode) - } -} - -//RetrieveCertificate retrieves the certificate for the specified ID -func (c *Connector) RetrieveCertificate(req *certificate.Request) (certificates *certificate.PEMCollection, err error) { - - if req.FetchPrivateKey { - return nil, fmt.Errorf("Failed to retrieve private key from Venafi Cloud service: not supported") - } - - if req.PickupID == "" && req.Thumbprint != "" { - // search cert by Thumbprint and fill pickupID - var certificateRequestId string - searchResult, err := c.searchCertificatesByFingerprint(req.Thumbprint) - if err != nil { - return nil, fmt.Errorf("Failed to retrieve certificate: %s", err) - } - if len(searchResult.Certificates) == 0 { - return nil, fmt.Errorf("No certifiate found using fingerprint %s", req.Thumbprint) - } - - reqIds := []string{} - isOnlyOneCertificateRequestId := true - for _, c := range searchResult.Certificates { - reqIds = append(reqIds, c.CertificateRequestId) - if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId { - isOnlyOneCertificateRequestId = false - } - certificateRequestId = c.CertificateRequestId - } - if !isOnlyOneCertificateRequestId { - return nil, fmt.Errorf("More than one CertificateRequestId was found with the same Fingerprint: %s", reqIds) - } - - req.PickupID = certificateRequestId - } - - startTime := time.Now() - for { - status, err := c.getCertificateStatus(req.PickupID) - if err != nil { - return nil, fmt.Errorf("unable to retrieve: %s", err) - } - if status.Status == "ISSUED" { - break // to fetch the cert itself - } else if status.Status == "FAILED" { - return nil, fmt.Errorf("Failed to retrieve certificate. Status: %v", status) - } - // status.Status == "REQUESTED" || status.Status == "PENDING" - if req.Timeout == 0 { - return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID, Status: status.Status} - } - if time.Now().After(startTime.Add(req.Timeout)) { - return nil, endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID} - } - // fmt.Printf("pending... %s\n", status.Status) - time.Sleep(2 * time.Second) - } - - url := c.getURL(urlResourceCertificateRetrieve) - if c.user == nil || c.user.Company == nil { - return nil, fmt.Errorf("Must be autheticated to retieve certificate") - } - url = fmt.Sprintf(url, req.PickupID) - url += "?chainOrder=%s&format=PEM" - switch req.ChainOption { - case certificate.ChainOptionRootFirst: - url = fmt.Sprintf(url, condorChainOptionRootFirst) - default: - url = fmt.Sprintf(url, condorChainOptionRootLast) - } - b := []byte{} - reader := bytes.NewReader(b) - request, err := http.NewRequest("GET", url, reader) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("Accept", "text/plain") - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if resp.StatusCode == http.StatusOK { - return newPEMCollectionFromResponse(body, req.ChainOption) - } else if resp.StatusCode == http.StatusConflict { // Http Status Code 409 means the certificate has not been signed by the ca yet. - return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID} - } else { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - return nil, fmt.Errorf("Failed to retrieve certificate. StatusCode: %d -- Status: %s -- Server Data: %s", resp.StatusCode, resp.Status, body) - } -} - -// RevokeCertificate attempts to revoke the certificate -func (c *Connector) RevokeCertificate(revReq *certificate.RevocationRequest) (err error) { - return fmt.Errorf("not supported by endpoint") -} - -// RenewCertificate attempts to renew the certificate -func (c *Connector) RenewCertificate(renewReq *certificate.RenewalRequest) (requestID string, err error) { - - /* 1st step is to get CertificateRequestId which is required to lookup managedCertificateId and zoneId */ - var certificateRequestId string - - if renewReq.Thumbprint != "" { - // by Thumbprint (aka Fingerprint) - searchResult, err := c.searchCertificatesByFingerprint(renewReq.Thumbprint) - if err != nil { - return "", fmt.Errorf("Failed to create renewal request: %s", err) - } - if len(searchResult.Certificates) == 0 { - return "", fmt.Errorf("No certifiate found using fingerprint %s", renewReq.Thumbprint) - } - - reqIds := []string{} - isOnlyOneCertificateRequestId := true - for _, c := range searchResult.Certificates { - reqIds = append(reqIds, c.CertificateRequestId) - if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId { - isOnlyOneCertificateRequestId = false - } - certificateRequestId = c.CertificateRequestId - } - if !isOnlyOneCertificateRequestId { - return "", fmt.Errorf("Error: more than one CertificateRequestId was found with the same Fingerprint: %s", reqIds) - } - } else if renewReq.CertificateDN != "" { - // by CertificateDN (which is the same as CertificateRequestId for current implementation) - certificateRequestId = renewReq.CertificateDN - } else { - return "", fmt.Errorf("failed to create renewal request: CertificateDN or Thumbprint required") - } - - /* 2nd step is to get ManagedCertificateId & ZoneId by looking up certificate request record */ - previousRequest, err := c.getCertificateStatus(certificateRequestId) - if err != nil { - return "", fmt.Errorf("certificate renew failed: %s", err) - } - var zoneId = previousRequest.ZoneId - var managedCertificateId = previousRequest.ManagedCertificateId - - if managedCertificateId == "" { - return "", fmt.Errorf("failed to submit renewal request for certificate: ManagedCertificateId is empty, certificate status is %s", previousRequest.Status) - } - - if managedCertificateId == "" { - return "", fmt.Errorf("failed to submit renewal request for certificate: ZoneId is empty, certificate status is %s", previousRequest.Status) - } - - /* 3rd step is to get ManagedCertificate Object by id - and check if latestCertificateRequestId there equals to certificateRequestId from 1st step */ - managedCertificate, err := c.getManagedCertificate(managedCertificateId) - if err != nil { - return "", fmt.Errorf("failed to renew certificate: %s", err) - } - if managedCertificate.LatestCertificateRequestId != certificateRequestId { - withThumbprint := "" - if renewReq.Thumbprint != "" { - withThumbprint = fmt.Sprintf("with thumbprint %s ", renewReq.Thumbprint) - } - return "", fmt.Errorf( - "Certificate under requestId %s "+withThumbprint+ - "is not the latest under ManagedCertificateId %s. The latest request is %s. "+ - "This error may happen when revoked certificate is requested to be renewed.", - certificateRequestId, managedCertificateId, managedCertificate.LatestCertificateRequestId) - } - - /* 4th step is to send renewal request */ - url := c.getURL(urlResourceCertificateRequests) - if c.user == nil || c.user.Company == nil { - return "", fmt.Errorf("Must be autheticated to request a certificate") - } - - req := certificateRequest{ - ZoneID: zoneId, - ExistingManagedCertificateId: managedCertificateId, - } - if renewReq.CertificateRequest != nil && 0 < len(renewReq.CertificateRequest.CSR) { - req.CSR = string(renewReq.CertificateRequest.CSR) - req.ReuseCSR = false - } else { - req.ReuseCSR = true - } - b, _ := json.Marshal(req) - reader := bytes.NewReader(b) - request, err := http.NewRequest("POST", url, reader) - if err != nil { - return "", err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("content-type", "application/json") - resp, err := http.DefaultClient.Do(request) - if err != nil { - return "", err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - cr, err := parseCertificateRequestResult(resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return "", fmt.Errorf("Failed to renew certificate: %s", err) - } - return cr.CertificateRequests[0].ID, nil -} - -func (c *Connector) getZoneByTag(tag string) (*zone, error) { - url := c.getURL(urlResourceZoneByTag) - if c.user == nil { - return nil, fmt.Errorf("Must be autheticated to read the zone configuration") - } - url = fmt.Sprintf(url, tag) - b := []byte{} - reader := bytes.NewReader(b) - request, err := http.NewRequest("GET", url, reader) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - z, err := parseZoneConfigurationResult(resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return nil, err - } - return z, nil -} - -func (c *Connector) getPoliciesByID(ids []string) (*certificatePolicy, error) { - policy := new(certificatePolicy) - url := c.getURL(urlResourcePoliciesByID) - if c.user == nil { - return nil, fmt.Errorf("Must be autheticated to read the zone configuration") - } - for _, id := range ids { - url = fmt.Sprintf(url, id) - b := []byte{} - reader := bytes.NewReader(b) - request, err := http.NewRequest("GET", url, reader) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - p, err := parseCertificatePolicyResult(resp.StatusCode, resp.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - } - - return nil, err - } - switch p.CertificatePolicyType { - case certificatePolicyTypeIdentity: - policy.SubjectCNRegexes = p.SubjectCNRegexes - policy.SubjectORegexes = p.SubjectORegexes - policy.SubjectOURegexes = p.SubjectOURegexes - policy.SubjectSTRegexes = p.SubjectSTRegexes - policy.SubjectLRegexes = p.SubjectLRegexes - policy.SubjectCRegexes = p.SubjectCRegexes - policy.SANRegexes = p.SANRegexes - break - case certificatePolicyTypeUse: - policy.KeyTypes = p.KeyTypes - policy.KeyReuse = p.KeyReuse - break - } - } - return policy, nil -} - -func (c *Connector) searchCertificates(req *SearchRequest) (*CertificateSearchResponse, error) { - - var err error - - url := c.getURL(urlResourceCertificateSearch) - if c.user == nil || c.user.Company == nil { - err = fmt.Errorf("Must be autheticated") - return nil, err - } - - b, _ := json.Marshal(req) - reader := bytes.NewReader(b) - request, err := http.NewRequest("POST", url, reader) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("content-type", "application/json") - request.Header.Add("accept", "application/json") - - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if c.verbose { - fmt.Printf("REQ: %s\n", b) - fmt.Printf("RES: %s\n", body) - } - - searchResult, err := ParseCertificateSearchResponse(resp.StatusCode, body) - if err != nil { - return nil, err - } - return searchResult, nil -} - -func (c *Connector) searchCertificatesByFingerprint(fp string) (*CertificateSearchResponse, error) { - fp = strings.Replace(fp, ":", "", -1) - fp = strings.Replace(fp, ".", "", -1) - fp = strings.ToUpper(fp) - req := &SearchRequest{ - Expression: &Expression{ - Operands: []Operand{ - { - "fingerprint", - MATCH, - fp, - }, - }, - }, - } - return c.searchCertificates(req) -} - -/* - "id": "32a656d1-69b1-11e8-93d8-71014a32ec53", - "companyId": "b5ed6d60-22c4-11e7-ac27-035f0608fd2c", - "latestCertificateRequestId": "0e546560-69b1-11e8-9102-a1f1c55d36fb", - "ownerUserId": "593cdba0-2124-11e8-8219-0932652c1da0", - "certificateIds": [ - "32a656d0-69b1-11e8-93d8-71014a32ec53" - ], - "certificateName": "cn=svc6.venafi.example.com", - -*/ -type managedCertificate struct { - Id string `json:"id"` - CompanyId string `json:"companyId"` - LatestCertificateRequestId string `json:"latestCertificateRequestId"` - CertificateName string `json:"certificateName"` -} - -func (c *Connector) getManagedCertificate(managedCertId string) (*managedCertificate, error) { - var err error - url := c.getURL(urlResourceManagedCertificateById) - url = fmt.Sprintf(url, managedCertId) - if c.user == nil || c.user.Company == nil { - err = fmt.Errorf("Must be autheticated") - return nil, err - } - - request, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - request.Header.Add("tppl-api-key", c.apiKey) - request.Header.Add("accept", "application/json") - - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if c.verbose { - fmt.Printf("REQ: %s\n", url) - fmt.Printf("RES: %s\n", body) - } - - switch resp.StatusCode { - case http.StatusOK: - var res = &managedCertificate{} - err = json.Unmarshal(body, res) - if err != nil { - return nil, fmt.Errorf("Failed to parse search results: %s, body: %s", err, body) - } - return res, nil - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud certificate search. Status: %d\n", resp.StatusCode) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud certificate search. Status: %d", resp.StatusCode) - } - -} - -func (c *Connector) ImportCertificate(req *certificate.ImportRequest) (*certificate.ImportResponse, error) { - return nil, fmt.Errorf("import is not supported") -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/error.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/error.go deleted file mode 100644 index 36339f2f..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/error.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "encoding/json" - "fmt" -) - -type responseError struct { - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` - Args interface{} `json:"args,omitempty"` -} - -type jsonData struct { - Errors []responseError `json:"errors,omitempty"` -} - -func parseResponseErrors(b []byte) ([]responseError, error) { - var data jsonData - err := json.Unmarshal(b, &data) - if err != nil { - return nil, err - } - - return data.Errors, nil -} - -func parseResponseError(b []byte) (responseError, error) { - e := responseError{} - err := json.Unmarshal(b, &e) - if err != nil { - return e, err - } - - return e, nil -} - -func (re *responseError) parseResponseArgs() (string, error) { - if re.Args == nil { - return "", nil - } - return fmt.Sprintf("%v", re.Args), nil -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/search.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/search.go deleted file mode 100644 index 50028976..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/search.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "encoding/json" - "fmt" - "net/http" -) - -type SearchRequest struct { - Expression *Expression `json:"expression"` - Ordering *interface{} `json:"ordering,omitempty"` - Paging *Paging `json:"paging,omitempty"` - // ordering is not used here so far - // "ordering": {"orders": [{"direction": "ASC", "field": "subjectCN"},{"direction": "DESC", "field": "keyStrength"}]}, -} - -type Expression struct { - Operands []Operand `json:"operands,omitempty"` -} - -type Operand struct { - Field Field `json:"field"` - Operator Operator `json:"operator"` - Value interface{} `json:"value"` -} - -type Field string -type Operator string - -type Paging struct { - PageNumber int `json:"pageNumber"` - PageSize int `json:"pageSize"` -} - -const ( - EQ Operator = "EQ" - FIND = "FIND" - GT = "GT" - GTE = "GTE" - IN = "IN" - LT = "LT" - LTE = "LTE" - MATCH = "MATCH" -) - -type CertificateSearchResponse struct { - Count int `json:"count"` - Certificates []Certificate `json:"certificates"` -} - -type Certificate struct { - Id string `json:"id"` - ManagedCertificateId string `json:"managedCertificateId"` - CertificateRequestId string `json:"certificateRequestId"` - SubjectCN []string `json:"subjectCN"` - /*...and many more fields... */ -} - -func ParseCertificateSearchResponse(httpStatusCode int, body []byte) (searchResult *CertificateSearchResponse, err error) { - switch httpStatusCode { - case http.StatusOK: - var searchResult = &CertificateSearchResponse{} - err = json.Unmarshal(body, searchResult) - if err != nil { - return nil, fmt.Errorf("Failed to parse search results: %s, body: %s", err, body) - } - return searchResult, nil - default: - if body != nil { - respErrors, err := parseResponseErrors(body) - if err == nil { - respError := fmt.Sprintf("Unexpected status code on Venafi Cloud certificate search. Status: %d\n", httpStatusCode) - for _, e := range respErrors { - respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message) - } - return nil, fmt.Errorf(respError) - } - } - return nil, fmt.Errorf("Unexpected status code on Venafi Cloud certificate search. Status: %d", httpStatusCode) - } -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/user.go b/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/user.go deleted file mode 100644 index 50bff338..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/cloud/user.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 cloud - -import ( - "encoding/json" - "time" -) - -type user struct { - Username string `json:"username,omitempty"` - ID string `json:"id,omitempty"` - CompanyID string `json:"companyId,omitempty"` - EmailAddress string `json:"emailAddress,omitempty"` - UserType string `json:"userType,omitempty"` - UserAccountType string `json:"userAccountType,omitempty"` - UserStatus string `json:"userStatus,omitempty"` - CreationDateString string `json:"creationDate,omitempty"` - CreationDate time.Time `json:"-"` -} - -type userAccount struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Firstname string `json:"firstname,omitempty"` - Lastname string `json:"lastname,omitempty"` - CompanyID string `json:"companyId,omitempty"` - CompanyName string `json:"companyName,omitempty"` - UserAccountType string `json:"userAccountType,omitempty"` - GreCaptchaResponse string `json:"grecaptchaResponse,omitempty"` -} - -func (u *user) encodeToJSON() ([]byte, error) { - b, err := json.Marshal(u) - return b, err -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/ca.go b/vendor/github.com/Venafi/vcert/pkg/venafi/fake/ca.go deleted file mode 100644 index bef59639..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/ca.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 fake - -import ( - "crypto/x509" - "encoding/pem" -) - -const caCertPEM = `-----BEGIN CERTIFICATE----- -MIID1TCCAr2gAwIBAgIJAIOVTvMIMD7OMA0GCSqGSIb3DQEBCwUAMIGAMQswCQYD -VQQGEwJVUzENMAsGA1UECAwEVXRhaDEXMBUGA1UEBwwOU2FsdCBMYWtlIENpdHkx -DzANBgNVBAoMBlZlbmFmaTEbMBkGA1UECwwSTk9UIEZPUiBQUk9EVUNUSU9OMRsw -GQYDVQQDDBJWQ2VydCBUZXN0IE1vZGUgQ0EwHhcNMTgwMzI3MTAyNTI5WhcNMzgw -MzIyMTAyNTI5WjCBgDELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxFzAVBgNV -BAcMDlNhbHQgTGFrZSBDaXR5MQ8wDQYDVQQKDAZWZW5hZmkxGzAZBgNVBAsMEk5P -VCBGT1IgUFJPRFVDVElPTjEbMBkGA1UEAwwSVkNlcnQgVGVzdCBNb2RlIENBMIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0BobDKthxG5SuMfAp2heyDQN -/IL9NTEnFJUUl/CkLEQTSQT68M9US7TCxi+FOizIoev2k4Nkovgk7uM0q94aygbh -cHyTTL64uphHwcClu99ZQ6DIwzDH2gREsLWfj+KXw4bPsne+5tGxv2+0jG2at5or -p/nOQWYD1C1HB6ZQqvP3PypDjou7Uh+Y00bOfXkbYWr8GkX4XAL6UtC0jUnsBEZX -CuwO1BlIIoKNokhOV7Jcb3l/jurjzVWfem+tqwYb/Tkj6MI1YBqt6Yy2EsGsoAv1 -E5/IGcjSQnLEqDWhpY0s2fA4o+bAMzyakDFKJoQbF982QhS2fT+d87vQlnMi1QID -AQABo1AwTjAdBgNVHQ4EFgQUzqRFDvLX0mz4AjPb45tLGavm8AcwHwYDVR0jBBgw -FoAUzqRFDvLX0mz4AjPb45tLGavm8AcwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B -AQsFAAOCAQEAWbRgS1qUyGMh3ToJ060s5cdoKzyx/ji5pRPXRxrmzzSxP+dlKX7h -AKUgYOV9FU/k2f4C7TeCZSsir20x8fKRg4qs6r8vHTcWnkC6A08SNlT5kjyJl8vt -qQTEsemnyBFis8ZFUfYdmNYqZXuWSb7ZBfNkR7qMVna8A87NyEmTtlTBkZYSTOaB -NRuOli+/6akXg/OW/GfVUD11D413CtZsWNzKaxj1WH88mjBYwQx2pGRzMWHfWBka -f6ZUnA9hhqxO4CHqQWmKPHftbGscwx5yg/J6J7TfG+rYd5ZVVhrr2un2xpOTctjO -lriDCQa4FOwP9/x1OJRXEsSl5YFqBppX5A== ------END CERTIFICATE-----` - -const caKeyPEM = `-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA0BobDKthxG5SuMfAp2heyDQN/IL9NTEnFJUUl/CkLEQTSQT6 -8M9US7TCxi+FOizIoev2k4Nkovgk7uM0q94aygbhcHyTTL64uphHwcClu99ZQ6DI -wzDH2gREsLWfj+KXw4bPsne+5tGxv2+0jG2at5orp/nOQWYD1C1HB6ZQqvP3PypD -jou7Uh+Y00bOfXkbYWr8GkX4XAL6UtC0jUnsBEZXCuwO1BlIIoKNokhOV7Jcb3l/ -jurjzVWfem+tqwYb/Tkj6MI1YBqt6Yy2EsGsoAv1E5/IGcjSQnLEqDWhpY0s2fA4 -o+bAMzyakDFKJoQbF982QhS2fT+d87vQlnMi1QIDAQABAoIBACDBuzhHUeBlrUfA -yaaQWzsQVpNE2y6gShKHVPKFwpHlNVPtIML/H7m6/l3L5SC/I+W5Cts1d4XfoZCo -2wWitHzQkHPwaA9Qhit5BPKOrIfiJF7s1C1FZHAA8/8M180CUflJIzBogPg8Ucpc -fwMLzarQ7cZHIBxTPo8LgX7GwzPlYn/kSlys8w5+gfXCbPIqWHdHgJPIm52ePLZt -0XfTF3Q+HSKzKHpdP/9kJJ3eknM/uEgyOKVPHdkq6U4HeJQq9lmp85X58cyHZOYT -qeLIqgq63x+K3Rgc2EUEOHEbdoEU9aP2fsk9M4AOHf7CpPg7htwN/5m0l4dYpIb+ -tcxH+BECgYEA5u9Mtt67y37IIzwQxh80vVZ47LnZMmxKA3AOJOj3Q/fkt36TM+rM -vRFKf6dR6Yolt7JtB6bGrLyGFFbmVDtfDjt9uvseKtG4PUrwjr+ayxICsPPidPlU -hUYh2uu4+m/DK8BGV+PR6/5kwQ2cDF5pdFHECX4VY0uvBnsif1IcBDsCgYEA5rBh -HeKNiUzmfIhP345tZaVM/SFDmAWDs5GZXpCnpMoI2QBg6nU3o6ssPflLjcDjnBrK -VpDlGsTBldX+HhXuEFJzUFASbXXWPqdUyMPzcTQuJWRH+s7Pz94gu/FliNJwmYu2 -tsS/PuId4O7dA/Bkhp94sH7OW4iD451xyn4RVC8CgYBtlLu4QrSl+UEKxyPGf2RN -O80ht4aC0LPGMdPkW8+JJwYWtC8xgYcpaB0Lud+6i90d78Kg0NiRetu8pwegjJOs -czpUEXjdJKriGr9PXUgceC1ivjeE/hLHMuI5uYULASGBjzlR1z7zVsGEgeq8S8iK -c4osXvHTLkSdNKzH8bRtpQKBgQDkOZlLHKjULi1VBPKohFr8lcYOJAugacw7Kg+m -u8vvPyXzsekv69mo5Z72jR1PV4aXGPYXIHBYxFGU8Eng7+c/ZKLK0Pz6J/tWrus1 -WI8O7wW8XnLL0jFMQED4T0EZVMCrV8rjFNDz4HaY4xfrXrfFbB3V1w5HBk8dL9W0 -9HYmZwKBgQCN6xAb82gwFM0H1w4iu6MnA2LyLc/19xn8khgNynW3cUznvyKGQuQo -ZEU0fw9VRRyQVwUwjAaLbIuME4cKhGjcJUvGPLftNamTlFS/TvtE1fwauGBXYc5o -wWh1aVElz5xMF+SnGUCW7t02dvhK0i29mOfx/eG5jkSm33NvVBq/IA== ------END RSA PRIVATE KEY-----` - -var ( - caBlock, _ = pem.Decode([]byte(caCertPEM)) - caCrt, _ = x509.ParseCertificate(caBlock.Bytes) - - caKeyBlock, _ = pem.Decode([]byte(caKeyPEM)) - caKey, _ = x509.ParsePKCS1PrivateKey(caKeyBlock.Bytes) -) diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/connector.go b/vendor/github.com/Venafi/vcert/pkg/venafi/fake/connector.go deleted file mode 100644 index 966caa68..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/connector.go +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 fake - -import ( - "crypto/rand" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "math/big" - "strings" - "time" -) - -type Connector struct { - verbose bool -} - -func NewConnector(verbose bool, trust *x509.CertPool) *Connector { - c := Connector{verbose: verbose} - return &c -} - -func (c *Connector) GetType() endpoint.ConnectorType { - return endpoint.ConnectorTypeFake -} - -func (c *Connector) SetZone(z string) { - return -} - -func (c *Connector) Ping() (err error) { - return -} - -func (c *Connector) Register(email string) (err error) { - return -} - -func (c *Connector) Authenticate(auth *endpoint.Authentication) (err error) { - return -} - -type fakeRequestID struct { - Req *certificate.Request - CSR string -} - -func validateRequest(req *certificate.Request) error { - if strings.HasSuffix(req.Subject.CommonName, "venafi.com") { - return fmt.Errorf("%s certificate cannot be requested", req.Subject.CommonName) - } - return nil -} - -func (c *Connector) RequestCertificate(req *certificate.Request, zone string) (requestID string, err error) { - - err = validateRequest(req) - if err != nil { - return "", fmt.Errorf("certificate request validation fail: %s", err) - } - - var fakeRequest = fakeRequestID{} - - switch req.CsrOrigin { - case certificate.LocalGeneratedCSR, certificate.UserProvidedCSR: - // should return CSR as requestID payload - fakeRequest.CSR = base64.StdEncoding.EncodeToString(req.CSR) - - case certificate.ServiceGeneratedCSR: - // should return certificate.Request as requestID payload - fakeRequest.Req = req - - default: - return "", fmt.Errorf("Unexpected option in PrivateKeyOrigin") - } - - js, err := json.Marshal(fakeRequest) - if err != nil { - return "", fmt.Errorf("failed to json.Marshal(certificate.Request: %v)", req) - } - pickupID := base64.StdEncoding.EncodeToString(js) - req.PickupID = pickupID - return pickupID, nil -} - -func issueCertificate(csr *x509.CertificateRequest) ([]byte, error) { - limit := new(big.Int).Lsh(big.NewInt(1), 128) - serial, _ := rand.Int(rand.Reader, limit) - - if "disabled" == "CSR pre-precessing for HTTPS" { - csr.DNSNames = append(csr.DNSNames, csr.Subject.CommonName) - - nameSet := map[string]bool{} - for _, name := range csr.DNSNames { - nameSet[name] = true - } - uniqNames := []string{} - for name, _ := range nameSet { - uniqNames = append(uniqNames, name) - } - csr.DNSNames = uniqNames - } - - certRequest := x509.Certificate{ - SerialNumber: serial, - } - certRequest.Subject = csr.Subject - certRequest.DNSNames = csr.DNSNames - certRequest.EmailAddresses = csr.EmailAddresses - certRequest.IPAddresses = csr.IPAddresses - certRequest.SignatureAlgorithm = x509.SHA512WithRSA - certRequest.PublicKeyAlgorithm = csr.PublicKeyAlgorithm - certRequest.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} - certRequest.NotBefore = time.Now().Add(-24 * time.Hour) - certRequest.NotAfter = certRequest.NotBefore.AddDate(0, 0, 90) - certRequest.IsCA = false - certRequest.BasicConstraintsValid = true - // ku := x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign - - derBytes, err := x509.CreateCertificate(rand.Reader, &certRequest, caCrt, csr.PublicKey, caKey) - if err != nil { - return nil, err - } - - res := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - return res, nil -} - -func (c *Connector) RetrieveCertificate(req *certificate.Request) (pcc *certificate.PEMCollection, err error) { - - bytes, err := base64.StdEncoding.DecodeString(req.PickupID) - if err != nil { - return nil, fmt.Errorf("Test-mode: could not parse requestID as base64 encoded fakeRequestID structure") - } - - var fakeRequest = &fakeRequestID{} - err = json.Unmarshal(bytes, fakeRequest) - if err != nil { - return nil, fmt.Errorf("failed to json.Unmarshal(fakeRequestId): %s\n", err) - } - - var csrPEMbytes []byte - var pk interface{} - - if fakeRequest.CSR != "" { - csrPEMbytes, err = base64.StdEncoding.DecodeString(fakeRequest.CSR) - - } else { - req := fakeRequest.Req - - switch req.KeyType { - case certificate.KeyTypeECDSA: - req.PrivateKey, err = certificate.GenerateECDSAPrivateKey(req.KeyCurve) - case certificate.KeyTypeRSA: - req.PrivateKey, err = certificate.GenerateRSAPrivateKey(req.KeyLength) - default: - return nil, fmt.Errorf("Unable to generate certificate request, key type %s is not supported", req.KeyType.String()) - } - if err != nil { - return - } - - req.DNSNames = append(req.DNSNames, "fake-service-generated."+req.Subject.CommonName) - - err = certificate.GenerateRequest(req, req.PrivateKey) - if err != nil { - return - } - csrPEMbytes = pem.EncodeToMemory(certificate.GetCertificateRequestPEMBlock(req.CSR)) - pk = req.PrivateKey - } - - var ( - csrBlock *pem.Block - csr *x509.CertificateRequest - ) - csrBlock, _ = pem.Decode([]byte(csrPEMbytes)) - if csrBlock == nil || csrBlock.Type != "CERTIFICATE REQUEST" { - return nil, fmt.Errorf("Test-mode: could not parse requestID as base64 encoded certificate request block") - } - - csr, err = x509.ParseCertificateRequest(csrBlock.Bytes) - if err != nil { - return nil, err - } - - cert_pem, err := issueCertificate(csr) - if err != nil { - return nil, err - } - - var certBytes []byte - switch req.ChainOption { - case certificate.ChainOptionRootFirst: - certBytes = append([]byte(caCertPEM+"\n"), cert_pem...) - default: - certBytes = append(cert_pem, []byte(caCertPEM)...) - } - pcc, err = certificate.PEMCollectionFromBytes(certBytes, req.ChainOption) - - // no key password -- no key - if pk != nil && req.KeyPassword != "" { - pcc.AddPrivateKey(pk, []byte(req.KeyPassword)) - } - return -} - -// RevokeCertificate attempts to revoke the certificate -func (c *Connector) RevokeCertificate(revReq *certificate.RevocationRequest) (err error) { - return fmt.Errorf("revocation is not supported in -test-mode") -} - -func (c *Connector) ReadZoneConfiguration(zone string) (config *endpoint.ZoneConfiguration, err error) { - return endpoint.NewZoneConfiguration(), nil -} - -// RenewCertificate attempts to renew the certificate -func (c *Connector) RenewCertificate(revReq *certificate.RenewalRequest) (requestID string, err error) { - return "", fmt.Errorf("renew is not supported in -test-mode") -} - -func (c *Connector) ImportCertificate(req *certificate.ImportRequest) (*certificate.ImportResponse, error) { - return nil, fmt.Errorf("import is not supported in -test-mode") -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/fake.go b/vendor/github.com/Venafi/vcert/pkg/venafi/fake/fake.go deleted file mode 100644 index cd80a96f..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/fake/fake.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 fake - -import ( - "encoding/pem" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" -) - -func (c *Connector) SetBaseURL(url string) error { - return nil -} - -//GenerateRequest creates a new certificate request, based on the zone/policy configuration and the user data -func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *certificate.Request) (err error) { - - switch req.CsrOrigin { - case certificate.LocalGeneratedCSR: - switch req.KeyType { - case certificate.KeyTypeECDSA: - req.PrivateKey, err = certificate.GenerateECDSAPrivateKey(req.KeyCurve) - case certificate.KeyTypeRSA: - if req.KeyLength == 0 { - req.KeyLength = 2048 - } - req.PrivateKey, err = certificate.GenerateRSAPrivateKey(req.KeyLength) - default: - return fmt.Errorf("Unable to generate certificate request, key type %s is not supported", req.KeyType.String()) - } - if err != nil { - return err - } - err = certificate.GenerateRequest(req, req.PrivateKey) - if err != nil { - return err - } - req.CSR = pem.EncodeToMemory(certificate.GetCertificateRequestPEMBlock(req.CSR)) - - case certificate.UserProvidedCSR: - if req.CSR == nil { - return fmt.Errorf("CSR was supposed to be provided by user, but it's empty") - } - - case certificate.ServiceGeneratedCSR: - req.CSR = nil - - default: - return fmt.Errorf("Unexpected option in PrivateKeyOrigin") - } - - return nil -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/connector.go b/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/connector.go deleted file mode 100644 index efa99177..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/connector.go +++ /dev/null @@ -1,551 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 tpp - -import ( - "bytes" - "crypto/x509" - "encoding/json" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "io/ioutil" - "log" - "net/http" - "strconv" - "strings" - "time" -) - -// Connector contains the base data needed to communicate with a TPP Server -type Connector struct { - baseURL string - apiKey string - verbose bool - trust *x509.CertPool - zone string -} - -// NewConnector creates a new TPP Connector object used to communicate with TPP -func NewConnector(verbose bool, trust *x509.CertPool) *Connector { - c := Connector{trust: trust, verbose: verbose} - return &c -} - -func (c *Connector) SetZone(z string) { - c.zone = z -} - -func (c *Connector) GetType() endpoint.ConnectorType { - return endpoint.ConnectorTypeTPP -} - -//Ping attempts to connect to the TPP Server WebSDK API and returns an errror if it cannot -func (c *Connector) Ping() (err error) { - url, err := c.getURL("") - if err != nil { - return err - } - req, _ := http.NewRequest("GET", url, nil) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - if err != nil { - return err - } else if res.StatusCode != http.StatusOK { - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - err = fmt.Errorf("%s", string(body)) - } - return err -} - -//Register does nothing for TPP -func (c *Connector) Register(email string) (err error) { - return nil -} - -// Authenticate authenticates the user to the TPP -func (c *Connector) Authenticate(auth *endpoint.Authentication) (err error) { - if auth == nil { - return fmt.Errorf("failed to authenticate: missing credentials") - } - url, err := c.getURL(urlResourceAuthorize) - if err != nil { - return err - } - - b, _ := json.Marshal(authorizeResquest{Username: auth.User, Password: auth.Password}) - payload := bytes.NewReader(b) - req, _ := http.NewRequest("POST", url, payload) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - if err == nil { - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - key, err := parseAuthorizeResult(res.StatusCode, res.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", urlResourceAuthorize, strings.Replace(fmt.Sprintf("%s", b), auth.Password, "********", -1)) - } - return err - } - c.apiKey = key - return nil - } - return err -} - -func wrapAltNames(req *certificate.Request) (items []sanItem) { - for _, name := range req.EmailAddresses { - items = append(items, sanItem{1, name}) - } - for _, name := range req.DNSNames { - items = append(items, sanItem{2, name}) - } - for _, name := range req.IPAddresses { - items = append(items, sanItem{7, name.String()}) - } - return items -} - -func wrapKeyType(kt certificate.KeyType) string { - switch kt { - case certificate.KeyTypeRSA: - return "RSA" - case certificate.KeyTypeECDSA: - return "ECC" - default: - return kt.String() - } -} - -func prepareRequest(req *certificate.Request, zone string) (tppReq certificateRequest, err error) { - switch req.CsrOrigin { - case certificate.LocalGeneratedCSR, certificate.UserProvidedCSR: - tppReq = certificateRequest{ - PolicyDN: getPolicyDN(zone), - PKCS10: string(req.CSR), - ObjectName: req.FriendlyName, - DisableAutomaticRenewal: true} - - case certificate.ServiceGeneratedCSR: - tppReq = certificateRequest{ - PolicyDN: getPolicyDN(zone), - ObjectName: req.FriendlyName, - Subject: req.Subject.CommonName, // TODO: there is some problem because Subject is not only CN - SubjectAltNames: wrapAltNames(req), - DisableAutomaticRenewal: true} - - default: - return tppReq, fmt.Errorf("Unexpected option in PrivateKeyOrigin") - } - - switch req.KeyType { - case certificate.KeyTypeRSA: - tppReq.KeyAlgorithm = "RSA" - tppReq.KeyBitSize = req.KeyLength - case certificate.KeyTypeECDSA: - tppReq.KeyAlgorithm = "ECC" - tppReq.EllipticCurve = req.KeyCurve.String() - } - - return tppReq, err -} - -// RequestCertificate submits the CSR to TPP returning the DN of the requested Certificate -func (c *Connector) RequestCertificate(req *certificate.Request, zone string) (requestID string, err error) { - - if zone == "" { - zone = c.zone - } - - tppCertificateRequest, err := prepareRequest(req, zone) - if err != nil { - return "", err - } - - b, _ := json.Marshal(tppCertificateRequest) - - url, err := c.getURL(urlResourceCertificateRequest) - if err != nil { - return "", err - } - payload := bytes.NewReader(b) - request, _ := http.NewRequest("POST", url, payload) - request.Header.Add("x-venafi-api-key", c.apiKey) - request.Header.Add("content-type", "application/json") - request.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(request) - - if err != nil { - return "", err - } - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - requestID, err = parseRequestResult(res.StatusCode, res.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", urlResourceCertificateRequest, b) - } - return "", fmt.Errorf("%s: %s", err, string(body)) - } - req.PickupID = requestID - return requestID, nil -} - -// RetrieveCertificate attempts to retrieve the requested certificate -func (c *Connector) RetrieveCertificate(req *certificate.Request) (certificates *certificate.PEMCollection, err error) { - - includeChain := req.ChainOption != certificate.ChainOptionIgnore - rootFirstOrder := includeChain && req.ChainOption == certificate.ChainOptionRootFirst - - if req.PickupID == "" && req.Thumbprint != "" { - // search cert by Thumbprint and fill pickupID - searchResult, err := c.searchCertificatesByFingerprint(req.Thumbprint) - if err != nil { - return nil, fmt.Errorf("Failed to create renewal request: %s", err) - } - if len(searchResult.Certificates) == 0 { - return nil, fmt.Errorf("No certifiate found using fingerprint %s", req.Thumbprint) - } - if len(searchResult.Certificates) > 1 { - return nil, fmt.Errorf("Error: more than one CertificateRequestId was found with the same thumbprint") - } - req.PickupID = searchResult.Certificates[0].CertificateRequestId - } - - certReq := certificateRetrieveRequest{ - CertificateDN: req.PickupID, - Format: "base64", - RootFirstOrder: rootFirstOrder, - IncludeChain: includeChain, - } - if req.CsrOrigin == certificate.ServiceGeneratedCSR || req.FetchPrivateKey { - certReq.IncludePrivateKey = true - certReq.Password = req.KeyPassword - } - - startTime := time.Now() - for { - retrieveResponse, err := c.retrieveCertificateOnce(certReq) - if err != nil { - return nil, fmt.Errorf("unable to retrieve: %s", err) - } - if retrieveResponse.CertificateData != "" { - return newPEMCollectionFromResponse(retrieveResponse.CertificateData, req.ChainOption) - } - if req.Timeout == 0 { - return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID, Status: retrieveResponse.Status} - } - if time.Now().After(startTime.Add(req.Timeout)) { - return nil, endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID} - } - time.Sleep(2 * time.Second) - } -} - -func (c *Connector) retrieveCertificateOnce(certReq certificateRetrieveRequest) (*certificateRetrieveResponse, error) { - url, err := c.getURL(urlResourceCertificateRetrieve) - if err != nil { - return nil, err - } - - b, _ := json.Marshal(certReq) - - payload := bytes.NewReader(b) - r, _ := http.NewRequest("POST", url, payload) - r.Header.Add("x-venafi-api-key", c.apiKey) - r.Header.Add("content-type", "application/json") - r.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(r) - - if err != nil { - return nil, err - } - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - retrieveResponse, err := parseRetrieveResult(res.StatusCode, res.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", urlResourceCertificateRetrieve, b) - } - return nil, err - } - return &retrieveResponse, nil -} - -// RenewCertificate attempts to renew the certificate -func (c *Connector) RenewCertificate(renewReq *certificate.RenewalRequest) (requestID string, err error) { - - if renewReq.Thumbprint != "" && renewReq.CertificateDN == "" { - // search by Thumbprint and fill *renewReq.CertificateDN - searchResult, err := c.searchCertificatesByFingerprint(renewReq.Thumbprint) - if err != nil { - return "", fmt.Errorf("Failed to create renewal request: %s", err) - } - if len(searchResult.Certificates) == 0 { - return "", fmt.Errorf("No certifiate found using fingerprint %s", renewReq.Thumbprint) - } - if len(searchResult.Certificates) > 1 { - return "", fmt.Errorf("Error: more than one CertificateRequestId was found with the same thumbprint") - } - - renewReq.CertificateDN = searchResult.Certificates[0].CertificateRequestId - } - if renewReq.CertificateDN == "" { - return "", fmt.Errorf("failed to create renewal request: CertificateDN or Thumbprint required") - } - - url, err := c.getURL(urlResourceCertificateRenew) - if err != nil { - return "", err - } - - var r = certificateRenewRequest{} - r.CertificateDN = renewReq.CertificateDN - if renewReq.CertificateRequest != nil && len(renewReq.CertificateRequest.CSR) > 0 { - r.PKCS10 = string(renewReq.CertificateRequest.CSR) - } - - b, _ := json.Marshal(r) - payload := bytes.NewReader(b) - req, _ := http.NewRequest("POST", url, payload) - req.Header.Add("x-venafi-api-key", c.apiKey) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - - if err != nil { - return "", err - } - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - response, err := parseRenewResult(res.StatusCode, res.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", url, b) - log.Printf("Response: %s", string(body)) - } - return "", err - } - if !response.Success { - return "", fmt.Errorf("Certificate Renewal error: %s", response.Error) - } - return renewReq.CertificateDN, nil -} - -// RevokeCertificate attempts to revoke the certificate -func (c *Connector) RevokeCertificate(revReq *certificate.RevocationRequest) (err error) { - url, err := c.getURL(urlResourceCertificateRevoke) - if err != nil { - return err - } - - reason, ok := RevocationReasonsMap[revReq.Reason] - if !ok { - return fmt.Errorf("could not parse revocation reason `%s`", revReq.Reason) - } - - var r = certificateRevokeRequest{ - revReq.CertificateDN, - revReq.Thumbprint, - reason, - revReq.Comments, - revReq.Disable, - } - - b, _ := json.Marshal(r) - payload := bytes.NewReader(b) - req, _ := http.NewRequest("POST", url, payload) - req.Header.Add("x-venafi-api-key", c.apiKey) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - - if err != nil { - return err - } - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - revokeResponse, err := parseRevokeResult(res.StatusCode, res.Status, body) - if err != nil { - if c.verbose { - log.Printf("JSON sent for %s\n%s", urlResourceCertificateRevoke, b) - } - return err - } - if !revokeResponse.Success { - return fmt.Errorf("Revocation error: %s", revokeResponse.Error) - } - return -} - -//ReadZoneConfiguration reads the policy data from TPP to get locked and pre-configured values for certificate requests -func (c *Connector) ReadZoneConfiguration(zone string) (config *endpoint.ZoneConfiguration, err error) { - zoneConfig := endpoint.NewZoneConfiguration() - zoneConfig.HashAlgorithm = x509.SHA256WithRSA - policyDN := getPolicyDN(zone) - keyType := certificate.KeyTypeRSA - - url, err := c.getURL(urlResourceFindPolicy) - if err != nil { - return nil, err - } - attributes := []string{tppAttributeOrg, tppAttributeOrgUnit, tppAttributeCountry, tppAttributeState, tppAttributeLocality, tppAttributeKeyAlgorithm, tppAttributeKeySize, tppAttributeEllipticCurve, tppAttributeRequestHash, tppAttributeManagementType, tppAttributeManualCSR} - for _, attrib := range attributes { - b, _ := json.Marshal(policyRequest{ObjectDN: policyDN, Class: "X509 Certificate", AttributeName: attrib}) - payload := bytes.NewReader(b) - req, _ := http.NewRequest("POST", url, payload) - req.Header.Add("x-venafi-api-key", c.apiKey) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - - if err == nil { - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - tppData, err := parseConfigResult(res.StatusCode, res.Status, body) - if tppData.Error == "" && (err != nil || tppData.Values == nil || len(tppData.Values) == 0) { - continue - } else if tppData.Error != "" && tppData.Result == 400 { //object does not exist - return nil, fmt.Errorf(tppData.Error) - } - - switch attrib { - case tppAttributeOrg: - zoneConfig.Organization = tppData.Values[0] - zoneConfig.OrganizationLocked = tppData.Locked - case tppAttributeOrgUnit: - zoneConfig.OrganizationalUnit = tppData.Values - case tppAttributeCountry: - zoneConfig.Country = tppData.Values[0] - zoneConfig.CountryLocked = tppData.Locked - case tppAttributeState: - zoneConfig.Province = tppData.Values[0] - zoneConfig.ProvinceLocked = tppData.Locked - case tppAttributeLocality: - zoneConfig.Locality = tppData.Values[0] - zoneConfig.LocalityLocked = tppData.Locked - case tppAttributeKeyAlgorithm: - err = keyType.Set(tppData.Values[0]) - if err == nil { - zoneConfig.AllowedKeyConfigurations = []endpoint.AllowedKeyConfiguration{endpoint.AllowedKeyConfiguration{KeyType: keyType}} - } - case tppAttributeKeySize: - temp, err := strconv.Atoi(tppData.Values[0]) - if err == nil { - zoneConfig.AllowedKeyConfigurations = []endpoint.AllowedKeyConfiguration{endpoint.AllowedKeyConfiguration{KeyType: keyType, KeySizes: []int{temp}}} - zoneConfig.KeySizeLocked = tppData.Locked - } - case tppAttributeEllipticCurve: - curve := certificate.EllipticCurveP256 - err = curve.Set(tppData.Values[0]) - if err == nil { - zoneConfig.AllowedKeyConfigurations = []endpoint.AllowedKeyConfiguration{endpoint.AllowedKeyConfiguration{KeyType: certificate.KeyTypeECDSA, KeyCurves: []certificate.EllipticCurve{curve}}} - zoneConfig.KeySizeLocked = tppData.Locked - } - case tppAttributeRequestHash: - alg, err := strconv.Atoi(tppData.Values[0]) - if err == nil { - switch alg { - case pkcs10HashAlgorithmSha1: - zoneConfig.HashAlgorithm = x509.SHA1WithRSA - case pkcs10HashAlgorithmSha384: - zoneConfig.HashAlgorithm = x509.SHA384WithRSA - case pkcs10HashAlgorithmSha512: - zoneConfig.HashAlgorithm = x509.SHA512WithRSA - default: - zoneConfig.HashAlgorithm = x509.SHA256WithRSA - } - } - case tppAttributeManagementType, tppAttributeManualCSR: - if tppData.Locked { - zoneConfig.CustomAttributeValues[attrib] = tppData.Values[0] - } - } - } else { - if c.verbose { - log.Printf("JSON sent for %s\n%s", urlResourceFindPolicy, b) - } - return nil, err - } - } - - return zoneConfig, nil -} - -func (c *Connector) ImportCertificate(r *certificate.ImportRequest) (*certificate.ImportResponse, error) { - url, err := c.getURL(urlResourceCertificateImport) - if err != nil { - return nil, err - } - - if r.PolicyDN == "" { - r.PolicyDN = getPolicyDN(c.zone) - } - - b, _ := json.Marshal(r) - payload := bytes.NewReader(b) - req, _ := http.NewRequest("POST", url, payload) - req.Header.Add("x-venafi-api-key", c.apiKey) - req.Header.Add("content-type", "application/json") - req.Header.Add("cache-control", "no-cache") - - res, err := c.getHTTPClient().Do(req) - if err != nil { - return nil, err - } - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - switch res.StatusCode { - case http.StatusOK: - - var response = &certificate.ImportResponse{} - err := json.Unmarshal(body, response) - if err != nil { - return nil, fmt.Errorf("failed to decode import response message: %s", err) - } - return response, nil - - case http.StatusBadRequest: - var errorResponse = &struct{ Error string }{} - err := json.Unmarshal(body, errorResponse) - if err != nil { - return nil, fmt.Errorf("failed to decode error message: %s", err) - } - return nil, fmt.Errorf("%s", errorResponse.Error) - default: - return nil, fmt.Errorf("unexpected response status %d: %s", res.StatusCode, string(b)) - } -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/error.go b/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/error.go deleted file mode 100644 index 2f4955d5..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/error.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 tpp - -import ( - "encoding/json" - "fmt" -) - -type responseError struct { - ErrorDetails string `json:"ErrorDetails,omitempty"` -} - -func NewResponseError(b []byte) error { - if len(b) == 0 { - return fmt.Errorf("failed to parser empty error message") - } - var data = &responseError{} - err := json.Unmarshal(b, data) - if err != nil { - return fmt.Errorf("failed to parser server error: %s", err) - } - return data -} - -func (e *responseError) Error() string { - return e.ErrorDetails -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/search.go b/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/search.go deleted file mode 100644 index e9e4b13f..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/search.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 tpp - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -type SearchRequest []string - -type CertificateSearchResponse struct { - Certificates []Certificate `json:"Certificates"` - Count int `json:"TotalCount"` -} - -type Certificate struct { - //Id string `json:"DN"` - //ManagedCertificateId string `json:"DN"` - CertificateRequestId string `json:"DN"` - /*...and some more fields... */ -} - -func (c *Connector) searchCertificatesByFingerprint(fp string) (*CertificateSearchResponse, error) { - fp = strings.Replace(fp, ":", "", -1) - fp = strings.Replace(fp, ".", "", -1) - fp = strings.ToUpper(fp) - - var req SearchRequest - req = append(req, fmt.Sprintf("Thumbprint=%s", fp)) - - return c.searchCertificates(&req) -} - -func (c *Connector) searchCertificates(req *SearchRequest) (*CertificateSearchResponse, error) { - - var err error - - url, _ := c.getURL(urlResourceCertificateSearch) - - url = fmt.Sprintf("%s?%s", url, strings.Join(*req, "&")) - - request, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - request.Header.Add("x-venafi-api-key", c.apiKey) - request.Header.Add("cache-control", "no-cache") - request.Header.Add("accept", "application/json") - - resp, err := http.DefaultClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if c.verbose { - fmt.Printf("REQ: %s\n", url) - fmt.Printf("RES: %s\n", body) - } - - searchResult, err := ParseCertificateSearchResponse(resp.StatusCode, body) - if err != nil { - return nil, err - } - return searchResult, nil -} - -func ParseCertificateSearchResponse(httpStatusCode int, body []byte) (searchResult *CertificateSearchResponse, err error) { - switch httpStatusCode { - case http.StatusOK: - var searchResult = &CertificateSearchResponse{} - err = json.Unmarshal(body, searchResult) - if err != nil { - return nil, fmt.Errorf("Failed to parse search results: %s, body: %s", err, body) - } - return searchResult, nil - default: - if body != nil { - return nil, NewResponseError(body) - } else { - return nil, fmt.Errorf("Unexpected status code on certificate search. Status: %d", httpStatusCode) - } - } -} diff --git a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/tpp.go b/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/tpp.go deleted file mode 100644 index 07e774e0..00000000 --- a/vendor/github.com/Venafi/vcert/pkg/venafi/tpp/tpp.go +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 tpp - -import ( - "crypto/tls" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "github.com/Venafi/vcert/pkg/certificate" - "github.com/Venafi/vcert/pkg/endpoint" - "net/http" - "regexp" - "strings" -) - -const defaultKeySize = 2048 -const defaultSignatureAlgorithm = x509.SHA256WithRSA - -type certificateRequest struct { - PolicyDN string `json:",omitempty"` - CADN string `json:",omitempty"` - ObjectName string `json:",omitempty"` - Subject string `json:",omitempty"` - OrganizationalUnit string `json:",omitempty"` - Organization string `json:",omitempty"` - City string `json:",omitempty"` - State string `json:",omitempty"` - Country string `json:",omitempty"` - SubjectAltNames []sanItem `json:",omitempty"` - Contact string `json:",omitempty"` - CASpecificAttributes []nameValuePair `json:",omitempty"` - PKCS10 string `json:",omitempty"` - KeyAlgorithm string `json:",omitempty"` - KeyBitSize int `json:",omitempty"` - EllipticCurve string `json:",omitempty"` - DisableAutomaticRenewal bool `json:",omitempty"` -} - -type certificateRetrieveRequest struct { - CertificateDN string `json:",omitempty"` - Format string `json:",omitempty"` - Password string `json:",omitempty"` - IncludePrivateKey bool `json:",omitempty"` - IncludeChain bool `json:",omitempty"` - FriendlyName string `json:",omitempty"` - RootFirstOrder bool `json:",omitempty"` -} - -type certificateRetrieveResponse struct { - CertificateData string `json:",omitempty"` - Format string `json:",omitempty"` - Filename string `json:",omitempty"` - Status string `json:",omitempty"` - Stage int `json:",omitempty"` -} - -type RevocationReason int - -// this maps *certificate.RevocationRequest.Reason to TPP-specific webSDK codes -var RevocationReasonsMap = map[string]RevocationReason{ - "": 0, // NoReason - "none": 0, // - "key-compromise": 1, // UserKeyCompromised - "ca-compromise": 2, // CAKeyCompromised - "affiliation-changed": 3, // UserChangedAffiliation - "superseded": 4, // CertificateSuperseded - "cessation-of-operation": 5, // OriginalUseNoLongerValid -} - -type certificateRevokeRequest struct { - CertificateDN string `json:",omitempty"` - Thumbprint string `json:",omitempty"` - Reason RevocationReason `json:",omitempty"` - Comments string `json:",omitempty"` - Disable bool `json:",omitempty"` -} - -/* {Requested:true Success:true Error:} -- means requested - {Requested:false Success:true Error:} -- means already revoked */ -type certificateRevokeResponse struct { - Requested bool `json:",omitempty"` - Success bool `json:",omitempty"` - Error string `json:",omitempty"` -} - -type certificateRenewRequest struct { - CertificateDN string `json:",omitempty"` - PKCS10 string `json:",omitempty"` -} - -type certificateRenewResponse struct { - Success bool `json:",omitempty"` - Error string `json:",omitempty"` -} - -type sanItem struct { - Type int `json:",omitempty"` - Name string `json:",omitempty"` -} - -type nameValuePair struct { - Name string `json:",omitempty"` - Value string `json:",omitempty"` -} - -type certificateRequestResponse struct { - CertificateDN string `json:",omitempty"` - Error string `json:",omitempty"` -} - -type authorizeResponse struct { - APIKey string `json:",omitempty"` - ValidUntil string `json:",omitempty"` -} - -type authorizeResquest struct { - Username string `json:",omitempty"` - Password string `json:",omitempty"` -} - -type policyRequest struct { - ObjectDN string `json:",omitempty"` - Class string `json:",omitempty"` - AttributeName string `json:",omitempty"` -} - -type urlResource string - -const ( - urlResourceAuthorize urlResource = "authorize/" - urlResourceCertificateRequest = "certificates/request" - urlResourceCertificateRetrieve = "certificates/retrieve" - urlResourceFindPolicy = "config/findpolicy" - urlResourceCertificateRevoke = "certificates/revoke" - urlResourceCertificateRenew = "certificates/renew" - urlResourceCertificateSearch = "certificates/" - urlResourceCertificateImport = "certificates/import" -) - -const ( - tppAttributeOrg = "Organization" - tppAttributeOrgUnit = "Organizational Unit" - tppAttributeCountry = "Country" - tppAttributeState = "State" - tppAttributeLocality = "City" - tppAttributeKeyAlgorithm = "Key Algorithm" - tppAttributeKeySize = "Key Bit Strength" - tppAttributeEllipticCurve = "Elliptic Curve" - tppAttributeRequestHash = "PKCS10 Hash Algorithm" - tppAttributeManagementType = "Management Type" - tppAttributeManualCSR = "Manual Csr" -) - -type tppPolicyData struct { - Error string `json:",omitempty"` - Result int `json:",omitempty"` - Values []string `json:",omitempty"` - Locked bool `json:",omitempty"` -} - -type retrieveChainOption int - -const ( - retrieveChainOptionRootLast retrieveChainOption = iota - retrieveChainOptionRootFirst - retrieveChainOptionIgnore -) - -const ( - pkcs10HashAlgorithmSha1 = 0 - pkcs10HashAlgorithmSha256 = 1 - pkcs10HashAlgorithmSha384 = 2 - pkcs10HashAlgorithmSha512 = 3 -) - -func retrieveChainOptionFromString(order string) retrieveChainOption { - switch strings.ToLower(order) { - case "root-first": - return retrieveChainOptionRootFirst - case "ignore": - return retrieveChainOptionIgnore - default: - return retrieveChainOptionRootLast - } -} - -// SetBaseURL sets the base URL used to cummuncate with TPP -func (c *Connector) SetBaseURL(url string) error { - modified := strings.ToLower(url) - reg := regexp.MustCompile("^http(|s)://") - if reg.FindStringIndex(modified) == nil { - modified = "https://" + modified - } else { - modified = reg.ReplaceAllString(modified, "https://") - } - reg = regexp.MustCompile("^https://.+?/") - if reg.FindStringIndex(modified) == nil { - modified = modified + "/" - } - - reg = regexp.MustCompile("/vedsdk(|/)$") - if reg.FindStringIndex(modified) == nil { - modified += "vedsdk/" - } else { - modified = reg.ReplaceAllString(modified, "/vedsdk/") - } - - reg = regexp.MustCompile("^https://[a-z\\d]+[-a-z\\d.]+[a-z\\d][:\\d]*/vedsdk/$") - if loc := reg.FindStringIndex(modified); loc == nil { - return fmt.Errorf("The specified TPP URL is invalid. %s\nExpected TPP URL format 'https://tpp.company.com/vedsdk/'", url) - } - - c.baseURL = modified - return nil -} - -func (c *Connector) getURL(resource urlResource) (string, error) { - if c.baseURL == "" { - return "", fmt.Errorf("The Host URL has not been set") - } - return fmt.Sprintf("%s%s", c.baseURL, resource), nil -} - -func (c *Connector) getHTTPClient() *http.Client { - if c.trust != nil { - tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: c.trust}} - return &http.Client{Transport: tr} - } - - return http.DefaultClient -} - -//GenerateRequest creates a new certificate request, based on the zone/policy configuration and the user data -func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *certificate.Request) (err error) { - if config == nil { - config, err = c.ReadZoneConfiguration(c.zone) - if err != nil { - return fmt.Errorf("could not read zone configuration: %s", err) - } - } - - tppMgmtType := config.CustomAttributeValues[tppAttributeManagementType] - if tppMgmtType == "Monitoring" || tppMgmtType == "Unassigned" { - return fmt.Errorf("Unable to request certificate from TPP, current TPP configuration would not allow the request to be processed") - } - - config.UpdateCertificateRequest(req) - - switch req.CsrOrigin { - case certificate.LocalGeneratedCSR: - if config.CustomAttributeValues[tppAttributeManualCSR] == "0" { - return fmt.Errorf("Unable to request certificate by local generated CSR when zone configuration is 'Manual Csr' = 0") - } - switch req.KeyType { - case certificate.KeyTypeECDSA: - req.PrivateKey, err = certificate.GenerateECDSAPrivateKey(req.KeyCurve) - case certificate.KeyTypeRSA: - req.PrivateKey, err = certificate.GenerateRSAPrivateKey(req.KeyLength) - default: - return fmt.Errorf("Unable to generate certificate request, key type %s is not supported", req.KeyType.String()) - } - if err != nil { - return err - } - err = certificate.GenerateRequest(req, req.PrivateKey) - if err != nil { - return err - } - req.CSR = pem.EncodeToMemory(certificate.GetCertificateRequestPEMBlock(req.CSR)) - - case certificate.UserProvidedCSR: - if config.CustomAttributeValues[tppAttributeManualCSR] == "0" { - return fmt.Errorf("Unable to request certificate with user provided CSR when zone configuration is 'Manual Csr' = 0") - } - if req.CSR == nil || len(req.CSR) == 0 { - return fmt.Errorf("CSR was supposed to be provided by user, but it's empty") - } - - case certificate.ServiceGeneratedCSR: - req.CSR = nil - } - return nil -} - -func getPolicyDN(zone string) string { - modified := zone - reg := regexp.MustCompile("^\\\\VED\\\\Policy") - if reg.FindStringIndex(modified) == nil { - reg = regexp.MustCompile("^\\\\") - if reg.FindStringIndex(modified) == nil { - modified = "\\" + modified - } - modified = "\\VED\\Policy" + modified - } - return modified -} - -func parseAuthorizeResult(httpStatusCode int, httpStatus string, body []byte) (string, error) { - switch httpStatusCode { - case http.StatusOK: - auth, err := parseAuthorizeData(body) - if err != nil { - return "", err - } - return auth.APIKey, nil - default: - return "", fmt.Errorf("Unexpected status code on TPP Authorize. Status: %s", httpStatus) - } -} - -func parseAuthorizeData(b []byte) (authorizeResponse, error) { - var data authorizeResponse - err := json.Unmarshal(b, &data) - if err != nil { - return data, err - } - - return data, nil -} - -func parseConfigResult(httpStatusCode int, httpStatus string, body []byte) (tppData tppPolicyData, err error) { - tppData = tppPolicyData{} - switch httpStatusCode { - case http.StatusOK: - tppData, err := parseConfigData(body) - if err != nil { - return tppData, err - } - return tppData, nil - default: - return tppData, fmt.Errorf("Unexpected status code on TPP Config Operation. Status: %s", httpStatus) - } -} - -func parseConfigData(b []byte) (tppPolicyData, error) { - var data tppPolicyData - err := json.Unmarshal(b, &data) - if err != nil { - return data, err - } - - return data, nil -} - -func parseRequestResult(httpStatusCode int, httpStatus string, body []byte) (string, error) { - switch httpStatusCode { - case http.StatusOK, http.StatusCreated: - reqData, err := parseRequestData(body) - if err != nil { - return "", err - } - return reqData.CertificateDN, nil - default: - return "", fmt.Errorf("Unexpected status code on TPP Certificate Request. Status: %s. Body: %s", httpStatus, body) - } -} - -func parseRequestData(b []byte) (certificateRequestResponse, error) { - var data certificateRequestResponse - err := json.Unmarshal(b, &data) - if err != nil { - return data, err - } - - return data, nil -} - -func parseRetrieveResult(httpStatusCode int, httpStatus string, body []byte) (certificateRetrieveResponse, error) { - var retrieveResponse certificateRetrieveResponse - switch httpStatusCode { - case http.StatusOK, http.StatusAccepted: - retrieveResponse, err := parseRetrieveData(body) - if err != nil { - return retrieveResponse, err - } - return retrieveResponse, nil - default: - return retrieveResponse, fmt.Errorf("Unexpected status code on TPP Certificate Retrieval. Status: %s", httpStatus) - } -} - -func parseRetrieveData(b []byte) (certificateRetrieveResponse, error) { - var data certificateRetrieveResponse - err := json.Unmarshal(b, &data) - if err != nil { - return data, err - } - // fmt.Printf("\n\n%s\n\n%+v\n\n", string(b), data) - return data, nil -} - -func parseRevokeResult(httpStatusCode int, httpStatus string, body []byte) (certificateRevokeResponse, error) { - var revokeResponse certificateRevokeResponse - switch httpStatusCode { - case http.StatusOK, http.StatusAccepted: - revokeResponse, err := parseRevokeData(body) - if err != nil { - return revokeResponse, err - } - return revokeResponse, nil - default: - return revokeResponse, fmt.Errorf("Unexpected status code on TPP Certificate Revocation. Status: %s", httpStatus) - } -} - -func parseRevokeData(b []byte) (certificateRevokeResponse, error) { - var data certificateRevokeResponse - err := json.Unmarshal(b, &data) - if err != nil { - return data, err - } - return data, nil -} - -func parseRenewResult(httpStatusCode int, httpStatus string, body []byte) (resp certificateRenewResponse, err error) { - resp, err = parseRenewData(body) - if err != nil { - return resp, fmt.Errorf("failed to parse certificate renewal response. status: %s", httpStatus) - } - return resp, nil -} - -func parseRenewData(b []byte) (certificateRenewResponse, error) { - var data certificateRenewResponse - err := json.Unmarshal(b, &data) - return data, err -} - -func newPEMCollectionFromResponse(base64Response string, chainOrder certificate.ChainOption) (*certificate.PEMCollection, error) { - if base64Response != "" { - certBytes, err := base64.StdEncoding.DecodeString(base64Response) - if err != nil { - return nil, err - } - - return certificate.PEMCollectionFromBytes(certBytes, chainOrder) - } - return nil, nil -} diff --git a/vendor/github.com/Venafi/vcert/test/context.go b/vendor/github.com/Venafi/vcert/test/context.go deleted file mode 100644 index a4fc0d67..00000000 --- a/vendor/github.com/Venafi/vcert/test/context.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 test - -import ( - "flag" - "os" -) - -type Context struct { - TPPurl string - TPPuser string - TPPPassword string - TPPZone string - CloudUrl string - CloudAPIkey string - CloudZone string -} - -func GetContext() *Context { - - c := &Context{} - - flag.StringVar(&c.TPPurl, "tpp-url", "", "") - flag.StringVar(&c.TPPuser, "tpp-user", "", "") - flag.StringVar(&c.TPPPassword, "tpp-password", "", "") - flag.StringVar(&c.TPPZone, "tpp-zone", "", "") - - flag.StringVar(&c.CloudUrl, "cloud-url", "", "") - flag.StringVar(&c.CloudAPIkey, "cloud-api-key", "", "") - flag.StringVar(&c.CloudZone, "cloud-zone", "", "") - - flag.Parse() - - return c -} - -func GetEnvContext() *Context { - - c := &Context{} - - c.TPPurl = os.Getenv("VCERT_TPP_URL") - c.TPPuser = os.Getenv("VCERT_TPP_USER") - c.TPPPassword = os.Getenv("VCERT_TPP_PASSWORD") - c.TPPZone = os.Getenv("VCERT_TPP_ZONE") - - c.CloudUrl = os.Getenv("VCERT_CLOUD_URL") - c.CloudAPIkey = os.Getenv("VCERT_CLOUD_APIKEY") - c.CloudZone = os.Getenv("VCERT_CLOUD_ZONE") - - return c -} diff --git a/vendor/github.com/Venafi/vcert/test/fixtures.go b/vendor/github.com/Venafi/vcert/test/fixtures.go deleted file mode 100644 index 7179782b..00000000 --- a/vendor/github.com/Venafi/vcert/test/fixtures.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 test - -import ( - "fmt" - "math/rand" - "time" -) - -func init() { - rand.Seed(time.Now().UnixNano()) -} - -func randRunes(n int) string { - var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz") - b := make([]rune, n) - for i := range b { - b[i] = letterRunes[rand.Intn(len(letterRunes))] - } - return string(b) -} - -func RandCN() string { - return fmt.Sprintf("t%d-%s.venafi.example.com", time.Now().Unix(), randRunes(4)) -} diff --git a/vendor/github.com/Venafi/vcert/vcert.go b/vendor/github.com/Venafi/vcert/vcert.go deleted file mode 100644 index daadfaa3..00000000 --- a/vendor/github.com/Venafi/vcert/vcert.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2018 Venafi, Inc. - * - * 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 vcert - -import ( - "fmt" -) - -//ProjectName contains the friendly name of the vcert utiltity -const ProjectName string = "Venafi Certificate Utility" - -var ( - versionString string - versionBuildTimeStamp string -) - -//GetFormattedVersionString gets a friendly printable string to represent the version -func GetFormattedVersionString() string { - if versionBuildTimeStamp != "" { - versionBuildTimeStamp = fmt.Sprintf("\tBuild Timestamp: %s\n", versionBuildTimeStamp) - } - return fmt.Sprintf("%s\n\tVersion: %s\n%s", ProjectName, GetVersionString(), versionBuildTimeStamp) -} - -//GetVersionString gets a simple version string -func GetVersionString() string { - if versionString == "" { - versionString = "3.18.3.1" - } - return versionString -} diff --git a/vendor/github.com/armon/go-metrics/.gitignore b/vendor/github.com/armon/go-metrics/.gitignore deleted file mode 100644 index 8c03ec11..00000000 --- a/vendor/github.com/armon/go-metrics/.gitignore +++ /dev/null @@ -1,24 +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 - -/metrics.out diff --git a/vendor/github.com/armon/go-metrics/LICENSE b/vendor/github.com/armon/go-metrics/LICENSE deleted file mode 100644 index 106569e5..00000000 --- a/vendor/github.com/armon/go-metrics/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 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-metrics/README.md b/vendor/github.com/armon/go-metrics/README.md deleted file mode 100644 index aa73348c..00000000 --- a/vendor/github.com/armon/go-metrics/README.md +++ /dev/null @@ -1,91 +0,0 @@ -go-metrics -========== - -This library provides a `metrics` package which can be used to instrument code, -expose application metrics, and profile runtime performance in a flexible manner. - -Current API: [![GoDoc](https://godoc.org/github.com/armon/go-metrics?status.svg)](https://godoc.org/github.com/armon/go-metrics) - -Sinks ------ - -The `metrics` package makes use of a `MetricSink` interface to support delivery -to any type of backend. Currently the following sinks are provided: - -* StatsiteSink : Sinks to a [statsite](https://github.com/armon/statsite/) instance (TCP) -* StatsdSink: Sinks to a [StatsD](https://github.com/etsy/statsd/) / statsite instance (UDP) -* PrometheusSink: Sinks to a [Prometheus](http://prometheus.io/) metrics endpoint (exposed via HTTP for scrapes) -* InmemSink : Provides in-memory aggregation, can be used to export stats -* FanoutSink : Sinks to multiple sinks. Enables writing to multiple statsite instances for example. -* BlackholeSink : Sinks to nowhere - -In addition to the sinks, the `InmemSignal` can be used to catch a signal, -and dump a formatted output of recent metrics. For example, when a process gets -a SIGUSR1, it can dump to stderr recent performance metrics for debugging. - -Labels ------- - -Most metrics do have an equivalent ending with `WithLabels`, such methods -allow to push metrics with labels and use some features of underlying Sinks -(ex: translated into Prometheus labels). - -Since some of these labels may increase greatly cardinality of metrics, the -library allow to filter labels using a blacklist/whitelist filtering system -which is global to all metrics. - -* If `Config.AllowedLabels` is not nil, then only labels specified in this value will be sent to underlying Sink, otherwise, all labels are sent by default. -* If `Config.BlockedLabels` is not nil, any label specified in this value will not be sent to underlying Sinks. - -By default, both `Config.AllowedLabels` and `Config.BlockedLabels` are nil, meaning that -no tags are filetered at all, but it allow to a user to globally block some tags with high -cardinality at application level. - -Examples --------- - -Here is an example of using the package: - -```go -func SlowMethod() { - // Profiling the runtime of a method - defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now()) -} - -// Configure a statsite sink as the global metrics sink -sink, _ := metrics.NewStatsiteSink("statsite:8125") -metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink) - -// Emit a Key/Value pair -metrics.EmitKey([]string{"questions", "meaning of life"}, 42) -``` - -Here is an example of setting up a signal handler: - -```go -// Setup the inmem sink and signal handler -inm := metrics.NewInmemSink(10*time.Second, time.Minute) -sig := metrics.DefaultInmemSignal(inm) -metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm) - -// Run some code -inm.SetGauge([]string{"foo"}, 42) -inm.EmitKey([]string{"bar"}, 30) - -inm.IncrCounter([]string{"baz"}, 42) -inm.IncrCounter([]string{"baz"}, 1) -inm.IncrCounter([]string{"baz"}, 80) - -inm.AddSample([]string{"method", "wow"}, 42) -inm.AddSample([]string{"method", "wow"}, 100) -inm.AddSample([]string{"method", "wow"}, 22) - -.... -``` - -When a signal comes in, output like the following will be dumped to stderr: - - [2014-01-28 14:57:33.04 -0800 PST][G] 'foo': 42.000 - [2014-01-28 14:57:33.04 -0800 PST][P] 'bar': 30.000 - [2014-01-28 14:57:33.04 -0800 PST][C] 'baz': Count: 3 Min: 1.000 Mean: 41.000 Max: 80.000 Stddev: 39.509 - [2014-01-28 14:57:33.04 -0800 PST][S] 'method.wow': Count: 3 Min: 22.000 Mean: 54.667 Max: 100.000 Stddev: 40.513 \ No newline at end of file diff --git a/vendor/github.com/armon/go-metrics/const_unix.go b/vendor/github.com/armon/go-metrics/const_unix.go deleted file mode 100644 index 31098dd5..00000000 --- a/vendor/github.com/armon/go-metrics/const_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - DefaultSignal = syscall.SIGUSR1 -) diff --git a/vendor/github.com/armon/go-metrics/const_windows.go b/vendor/github.com/armon/go-metrics/const_windows.go deleted file mode 100644 index 38136af3..00000000 --- a/vendor/github.com/armon/go-metrics/const_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - // Windows has no SIGUSR1, use SIGBREAK - DefaultSignal = syscall.Signal(21) -) diff --git a/vendor/github.com/armon/go-metrics/inmem.go b/vendor/github.com/armon/go-metrics/inmem.go deleted file mode 100644 index 4e2d6a70..00000000 --- a/vendor/github.com/armon/go-metrics/inmem.go +++ /dev/null @@ -1,348 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "math" - "net/url" - "strings" - "sync" - "time" -) - -// InmemSink provides a MetricSink that does in-memory aggregation -// without sending metrics over a network. It can be embedded within -// an application to provide profiling information. -type InmemSink struct { - // How long is each aggregation interval - interval time.Duration - - // Retain controls how many metrics interval we keep - retain time.Duration - - // maxIntervals is the maximum length of intervals. - // It is retain / interval. - maxIntervals int - - // intervals is a slice of the retained intervals - intervals []*IntervalMetrics - intervalLock sync.RWMutex - - rateDenom float64 -} - -// IntervalMetrics stores the aggregated metrics -// for a specific interval -type IntervalMetrics struct { - sync.RWMutex - - // The start time of the interval - Interval time.Time - - // Gauges maps the key to the last set value - Gauges map[string]GaugeValue - - // Points maps the string to the list of emitted values - // from EmitKey - Points map[string][]float32 - - // Counters maps the string key to a sum of the counter - // values - Counters map[string]SampledValue - - // Samples maps the key to an AggregateSample, - // which has the rolled up view of a sample - Samples map[string]SampledValue -} - -// NewIntervalMetrics creates a new IntervalMetrics for a given interval -func NewIntervalMetrics(intv time.Time) *IntervalMetrics { - return &IntervalMetrics{ - Interval: intv, - Gauges: make(map[string]GaugeValue), - Points: make(map[string][]float32), - Counters: make(map[string]SampledValue), - Samples: make(map[string]SampledValue), - } -} - -// AggregateSample is used to hold aggregate metrics -// about a sample -type AggregateSample struct { - Count int // The count of emitted pairs - Rate float64 // The values rate per time unit (usually 1 second) - Sum float64 // The sum of values - SumSq float64 `json:"-"` // The sum of squared values - Min float64 // Minimum value - Max float64 // Maximum value - LastUpdated time.Time `json:"-"` // When value was last updated -} - -// Computes a Stddev of the values -func (a *AggregateSample) Stddev() float64 { - num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2) - div := float64(a.Count * (a.Count - 1)) - if div == 0 { - return 0 - } - return math.Sqrt(num / div) -} - -// Computes a mean of the values -func (a *AggregateSample) Mean() float64 { - if a.Count == 0 { - return 0 - } - return a.Sum / float64(a.Count) -} - -// Ingest is used to update a sample -func (a *AggregateSample) Ingest(v float64, rateDenom float64) { - a.Count++ - a.Sum += v - a.SumSq += (v * v) - if v < a.Min || a.Count == 1 { - a.Min = v - } - if v > a.Max || a.Count == 1 { - a.Max = v - } - a.Rate = float64(a.Sum) / rateDenom - a.LastUpdated = time.Now() -} - -func (a *AggregateSample) String() string { - if a.Count == 0 { - return "Count: 0" - } else if a.Stddev() == 0 { - return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated) - } else { - return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s", - a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated) - } -} - -// NewInmemSinkFromURL creates an InmemSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) { - params := u.Query() - - interval, err := time.ParseDuration(params.Get("interval")) - if err != nil { - return nil, fmt.Errorf("Bad 'interval' param: %s", err) - } - - retain, err := time.ParseDuration(params.Get("retain")) - if err != nil { - return nil, fmt.Errorf("Bad 'retain' param: %s", err) - } - - return NewInmemSink(interval, retain), nil -} - -// NewInmemSink is used to construct a new in-memory sink. -// Uses an aggregation interval and maximum retention period. -func NewInmemSink(interval, retain time.Duration) *InmemSink { - rateTimeUnit := time.Second - i := &InmemSink{ - interval: interval, - retain: retain, - maxIntervals: int(retain / interval), - rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()), - } - i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals) - return i -} - -func (i *InmemSink) SetGauge(key []string, val float32) { - i.SetGaugeWithLabels(key, val, nil) -} - -func (i *InmemSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - intv.Gauges[k] = GaugeValue{Name: name, Value: val, Labels: labels} -} - -func (i *InmemSink) EmitKey(key []string, val float32) { - k := i.flattenKey(key) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - vals := intv.Points[k] - intv.Points[k] = append(vals, val) -} - -func (i *InmemSink) IncrCounter(key []string, val float32) { - i.IncrCounterWithLabels(key, val, nil) -} - -func (i *InmemSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Counters[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Counters[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -func (i *InmemSink) AddSample(key []string, val float32) { - i.AddSampleWithLabels(key, val, nil) -} - -func (i *InmemSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Samples[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Samples[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -// Data is used to retrieve all the aggregated metrics -// Intervals may be in use, and a read lock should be acquired -func (i *InmemSink) Data() []*IntervalMetrics { - // Get the current interval, forces creation - i.getInterval() - - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - intervals := make([]*IntervalMetrics, n) - - copy(intervals[:n-1], i.intervals[:n-1]) - current := i.intervals[n-1] - - // make its own copy for current interval - intervals[n-1] = &IntervalMetrics{} - copyCurrent := intervals[n-1] - current.RLock() - *copyCurrent = *current - - copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges)) - for k, v := range current.Gauges { - copyCurrent.Gauges[k] = v - } - // saved values will be not change, just copy its link - copyCurrent.Points = make(map[string][]float32, len(current.Points)) - for k, v := range current.Points { - copyCurrent.Points[k] = v - } - copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters)) - for k, v := range current.Counters { - copyCurrent.Counters[k] = v - } - copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples)) - for k, v := range current.Samples { - copyCurrent.Samples[k] = v - } - current.RUnlock() - - return intervals -} - -func (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - return nil -} - -func (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.Lock() - defer i.intervalLock.Unlock() - - // Check for an existing interval - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - - // Add the current interval - current := NewIntervalMetrics(intv) - i.intervals = append(i.intervals, current) - n++ - - // Truncate the intervals if they are too long - if n >= i.maxIntervals { - copy(i.intervals[0:], i.intervals[n-i.maxIntervals:]) - i.intervals = i.intervals[:i.maxIntervals] - } - return current -} - -// getInterval returns the current interval to write to -func (i *InmemSink) getInterval() *IntervalMetrics { - intv := time.Now().Truncate(i.interval) - if m := i.getExistingInterval(intv); m != nil { - return m - } - return i.createInterval(intv) -} - -// Flattens the key for formatting, removes spaces -func (i *InmemSink) flattenKey(parts []string) string { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - return buf.String() -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSink) flattenKeyLabels(parts []string, labels []Label) (string, string) { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - key := buf.String() - - for _, label := range labels { - replacer.WriteString(buf, fmt.Sprintf(";%s=%s", label.Name, label.Value)) - } - - return buf.String(), key -} diff --git a/vendor/github.com/armon/go-metrics/inmem_endpoint.go b/vendor/github.com/armon/go-metrics/inmem_endpoint.go deleted file mode 100644 index 504f1b37..00000000 --- a/vendor/github.com/armon/go-metrics/inmem_endpoint.go +++ /dev/null @@ -1,118 +0,0 @@ -package metrics - -import ( - "fmt" - "net/http" - "sort" - "time" -) - -// MetricsSummary holds a roll-up of metrics info for a given interval -type MetricsSummary struct { - Timestamp string - Gauges []GaugeValue - Points []PointValue - Counters []SampledValue - Samples []SampledValue -} - -type GaugeValue struct { - Name string - Hash string `json:"-"` - Value float32 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -type PointValue struct { - Name string - Points []float32 -} - -type SampledValue struct { - Name string - Hash string `json:"-"` - *AggregateSample - Mean float64 - Stddev float64 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -// DisplayMetrics returns a summary of the metrics from the most recent finished interval. -func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - data := i.Data() - - var interval *IntervalMetrics - n := len(data) - switch { - case n == 0: - return nil, fmt.Errorf("no metric intervals have been initialized yet") - case n == 1: - // Show the current interval if it's all we have - interval = i.intervals[0] - default: - // Show the most recent finished interval if we have one - interval = i.intervals[n-2] - } - - summary := MetricsSummary{ - Timestamp: interval.Interval.Round(time.Second).UTC().String(), - Gauges: make([]GaugeValue, 0, len(interval.Gauges)), - Points: make([]PointValue, 0, len(interval.Points)), - } - - // Format and sort the output of each metric type, so it gets displayed in a - // deterministic order. - for name, points := range interval.Points { - summary.Points = append(summary.Points, PointValue{name, points}) - } - sort.Slice(summary.Points, func(i, j int) bool { - return summary.Points[i].Name < summary.Points[j].Name - }) - - for hash, value := range interval.Gauges { - value.Hash = hash - value.DisplayLabels = make(map[string]string) - for _, label := range value.Labels { - value.DisplayLabels[label.Name] = label.Value - } - value.Labels = nil - - summary.Gauges = append(summary.Gauges, value) - } - sort.Slice(summary.Gauges, func(i, j int) bool { - return summary.Gauges[i].Hash < summary.Gauges[j].Hash - }) - - summary.Counters = formatSamples(interval.Counters) - summary.Samples = formatSamples(interval.Samples) - - return summary, nil -} - -func formatSamples(source map[string]SampledValue) []SampledValue { - output := make([]SampledValue, 0, len(source)) - for hash, sample := range source { - displayLabels := make(map[string]string) - for _, label := range sample.Labels { - displayLabels[label.Name] = label.Value - } - - output = append(output, SampledValue{ - Name: sample.Name, - Hash: hash, - AggregateSample: sample.AggregateSample, - Mean: sample.AggregateSample.Mean(), - Stddev: sample.AggregateSample.Stddev(), - DisplayLabels: displayLabels, - }) - } - sort.Slice(output, func(i, j int) bool { - return output[i].Hash < output[j].Hash - }) - - return output -} diff --git a/vendor/github.com/armon/go-metrics/inmem_signal.go b/vendor/github.com/armon/go-metrics/inmem_signal.go deleted file mode 100644 index 0937f4ae..00000000 --- a/vendor/github.com/armon/go-metrics/inmem_signal.go +++ /dev/null @@ -1,117 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "io" - "os" - "os/signal" - "strings" - "sync" - "syscall" -) - -// InmemSignal is used to listen for a given signal, and when received, -// to dump the current metrics from the InmemSink to an io.Writer -type InmemSignal struct { - signal syscall.Signal - inm *InmemSink - w io.Writer - sigCh chan os.Signal - - stop bool - stopCh chan struct{} - stopLock sync.Mutex -} - -// NewInmemSignal creates a new InmemSignal which listens for a given signal, -// and dumps the current metrics out to a writer -func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal { - i := &InmemSignal{ - signal: sig, - inm: inmem, - w: w, - sigCh: make(chan os.Signal, 1), - stopCh: make(chan struct{}), - } - signal.Notify(i.sigCh, sig) - go i.run() - return i -} - -// DefaultInmemSignal returns a new InmemSignal that responds to SIGUSR1 -// and writes output to stderr. Windows uses SIGBREAK -func DefaultInmemSignal(inmem *InmemSink) *InmemSignal { - return NewInmemSignal(inmem, DefaultSignal, os.Stderr) -} - -// Stop is used to stop the InmemSignal from listening -func (i *InmemSignal) Stop() { - i.stopLock.Lock() - defer i.stopLock.Unlock() - - if i.stop { - return - } - i.stop = true - close(i.stopCh) - signal.Stop(i.sigCh) -} - -// run is a long running routine that handles signals -func (i *InmemSignal) run() { - for { - select { - case <-i.sigCh: - i.dumpStats() - case <-i.stopCh: - return - } - } -} - -// dumpStats is used to dump the data to output writer -func (i *InmemSignal) dumpStats() { - buf := bytes.NewBuffer(nil) - - data := i.inm.Data() - // Skip the last period which is still being aggregated - for j := 0; j < len(data)-1; j++ { - intv := data[j] - intv.RLock() - for _, val := range intv.Gauges { - name := i.flattenLabels(val.Name, val.Labels) - fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value) - } - for name, vals := range intv.Points { - for _, val := range vals { - fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val) - } - } - for _, agg := range intv.Counters { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - for _, agg := range intv.Samples { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - intv.RUnlock() - } - - // Write out the bytes - i.w.Write(buf.Bytes()) -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSignal) flattenLabels(name string, labels []Label) string { - buf := bytes.NewBufferString(name) - replacer := strings.NewReplacer(" ", "_", ":", "_") - - for _, label := range labels { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, label.Value) - } - - return buf.String() -} diff --git a/vendor/github.com/armon/go-metrics/metrics.go b/vendor/github.com/armon/go-metrics/metrics.go deleted file mode 100644 index cf9def74..00000000 --- a/vendor/github.com/armon/go-metrics/metrics.go +++ /dev/null @@ -1,278 +0,0 @@ -package metrics - -import ( - "runtime" - "strings" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -type Label struct { - Name string - Value string -} - -func (m *Metrics) SetGauge(key []string, val float32) { - m.SetGaugeWithLabels(key, val, nil) -} - -func (m *Metrics) SetGaugeWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" { - if m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } else if m.EnableHostname { - key = insert(0, m.HostName, key) - } - } - if m.EnableTypePrefix { - key = insert(0, "gauge", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.SetGaugeWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) EmitKey(key []string, val float32) { - if m.EnableTypePrefix { - key = insert(0, "kv", key) - } - if m.ServiceName != "" { - key = insert(0, m.ServiceName, key) - } - allowed, _ := m.allowMetric(key, nil) - if !allowed { - return - } - m.sink.EmitKey(key, val) -} - -func (m *Metrics) IncrCounter(key []string, val float32) { - m.IncrCounterWithLabels(key, val, nil) -} - -func (m *Metrics) IncrCounterWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "counter", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.IncrCounterWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) AddSample(key []string, val float32) { - m.AddSampleWithLabels(key, val, nil) -} - -func (m *Metrics) AddSampleWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "sample", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.AddSampleWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) MeasureSince(key []string, start time.Time) { - m.MeasureSinceWithLabels(key, start, nil) -} - -func (m *Metrics) MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "timer", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - now := time.Now() - elapsed := now.Sub(start) - msec := float32(elapsed.Nanoseconds()) / float32(m.TimerGranularity) - m.sink.AddSampleWithLabels(key, msec, labelsFiltered) -} - -// UpdateFilter overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilter(allow, block []string) { - m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels) -} - -// UpdateFilterAndLabels overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - m.filterLock.Lock() - defer m.filterLock.Unlock() - - m.AllowedPrefixes = allow - m.BlockedPrefixes = block - - if allowedLabels == nil { - // Having a white list means we take only elements from it - m.allowedLabels = nil - } else { - m.allowedLabels = make(map[string]bool) - for _, v := range allowedLabels { - m.allowedLabels[v] = true - } - } - m.blockedLabels = make(map[string]bool) - for _, v := range blockedLabels { - m.blockedLabels[v] = true - } - m.AllowedLabels = allowedLabels - m.BlockedLabels = blockedLabels - - m.filter = iradix.New() - for _, prefix := range m.AllowedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), true) - } - for _, prefix := range m.BlockedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), false) - } -} - -// labelIsAllowed return true if a should be included in metric -// the caller should lock m.filterLock while calling this method -func (m *Metrics) labelIsAllowed(label *Label) bool { - labelName := (*label).Name - if m.blockedLabels != nil { - _, ok := m.blockedLabels[labelName] - if ok { - // If present, let's remove this label - return false - } - } - if m.allowedLabels != nil { - _, ok := m.allowedLabels[labelName] - return ok - } - // Allow by default - return true -} - -// filterLabels return only allowed labels -// the caller should lock m.filterLock while calling this method -func (m *Metrics) filterLabels(labels []Label) []Label { - if labels == nil { - return nil - } - toReturn := labels[:0] - for _, label := range labels { - if m.labelIsAllowed(&label) { - toReturn = append(toReturn, label) - } - } - return toReturn -} - -// Returns whether the metric should be allowed based on configured prefix filters -// Also return the applicable labels -func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) { - m.filterLock.RLock() - defer m.filterLock.RUnlock() - - if m.filter == nil || m.filter.Len() == 0 { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - _, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, "."))) - if !ok { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - return allowed.(bool), m.filterLabels(labels) -} - -// Periodically collects runtime stats to publish -func (m *Metrics) collectStats() { - for { - time.Sleep(m.ProfileInterval) - m.emitRuntimeStats() - } -} - -// Emits various runtime statsitics -func (m *Metrics) emitRuntimeStats() { - // Export number of Goroutines - numRoutines := runtime.NumGoroutine() - m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines)) - - // Export memory stats - var stats runtime.MemStats - runtime.ReadMemStats(&stats) - m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc)) - m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys)) - m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs)) - m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees)) - m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects)) - m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs)) - m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC)) - - // Export info about the last few GC runs - num := stats.NumGC - - // Handle wrap around - if num < m.lastNumGC { - m.lastNumGC = 0 - } - - // Ensure we don't scan more than 256 - if num-m.lastNumGC >= 256 { - m.lastNumGC = num - 255 - } - - for i := m.lastNumGC; i < num; i++ { - pause := stats.PauseNs[i%256] - m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause)) - } - m.lastNumGC = num -} - -// Inserts a string value at an index into the slice -func insert(i int, v string, s []string) []string { - s = append(s, "") - copy(s[i+1:], s[i:]) - s[i] = v - return s -} diff --git a/vendor/github.com/armon/go-metrics/sink.go b/vendor/github.com/armon/go-metrics/sink.go deleted file mode 100644 index 0b7d6e4b..00000000 --- a/vendor/github.com/armon/go-metrics/sink.go +++ /dev/null @@ -1,115 +0,0 @@ -package metrics - -import ( - "fmt" - "net/url" -) - -// The MetricSink interface is used to transmit metrics information -// to an external system -type MetricSink interface { - // A Gauge should retain the last value it is set to - SetGauge(key []string, val float32) - SetGaugeWithLabels(key []string, val float32, labels []Label) - - // Should emit a Key/Value pair for each call - EmitKey(key []string, val float32) - - // Counters should accumulate values - IncrCounter(key []string, val float32) - IncrCounterWithLabels(key []string, val float32, labels []Label) - - // Samples are for timing information, where quantiles are used - AddSample(key []string, val float32) - AddSampleWithLabels(key []string, val float32, labels []Label) -} - -// BlackholeSink is used to just blackhole messages -type BlackholeSink struct{} - -func (*BlackholeSink) SetGauge(key []string, val float32) {} -func (*BlackholeSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) EmitKey(key []string, val float32) {} -func (*BlackholeSink) IncrCounter(key []string, val float32) {} -func (*BlackholeSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) AddSample(key []string, val float32) {} -func (*BlackholeSink) AddSampleWithLabels(key []string, val float32, labels []Label) {} - -// FanoutSink is used to sink to fanout values to multiple sinks -type FanoutSink []MetricSink - -func (fh FanoutSink) SetGauge(key []string, val float32) { - fh.SetGaugeWithLabels(key, val, nil) -} - -func (fh FanoutSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.SetGaugeWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) EmitKey(key []string, val float32) { - for _, s := range fh { - s.EmitKey(key, val) - } -} - -func (fh FanoutSink) IncrCounter(key []string, val float32) { - fh.IncrCounterWithLabels(key, val, nil) -} - -func (fh FanoutSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.IncrCounterWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) AddSample(key []string, val float32) { - fh.AddSampleWithLabels(key, val, nil) -} - -func (fh FanoutSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.AddSampleWithLabels(key, val, labels) - } -} - -// sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided -// by each sink type -type sinkURLFactoryFunc func(*url.URL) (MetricSink, error) - -// sinkRegistry supports the generic NewMetricSink function by mapping URL -// schemes to metric sink factory functions -var sinkRegistry = map[string]sinkURLFactoryFunc{ - "statsd": NewStatsdSinkFromURL, - "statsite": NewStatsiteSinkFromURL, - "inmem": NewInmemSinkFromURL, -} - -// NewMetricSinkFromURL allows a generic URL input to configure any of the -// supported sinks. The scheme of the URL identifies the type of the sink, the -// and query parameters are used to set options. -// -// "statsd://" - Initializes a StatsdSink. The host and port are passed through -// as the "addr" of the sink -// -// "statsite://" - Initializes a StatsiteSink. The host and port become the -// "addr" of the sink -// -// "inmem://" - Initializes an InmemSink. The host and port are ignored. The -// "interval" and "duration" query parameters must be specified with valid -// durations, see NewInmemSink for details. -func NewMetricSinkFromURL(urlStr string) (MetricSink, error) { - u, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - sinkURLFactoryFunc := sinkRegistry[u.Scheme] - if sinkURLFactoryFunc == nil { - return nil, fmt.Errorf( - "cannot create metric sink, unrecognized sink name: %q", u.Scheme) - } - - return sinkURLFactoryFunc(u) -} diff --git a/vendor/github.com/armon/go-metrics/start.go b/vendor/github.com/armon/go-metrics/start.go deleted file mode 100644 index 32a28c48..00000000 --- a/vendor/github.com/armon/go-metrics/start.go +++ /dev/null @@ -1,141 +0,0 @@ -package metrics - -import ( - "os" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -// Config is used to configure metrics settings -type Config struct { - ServiceName string // Prefixed with keys to separate services - HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname - EnableHostname bool // Enable prefixing gauge values with hostname - EnableHostnameLabel bool // Enable adding hostname to labels - EnableServiceLabel bool // Enable adding service to labels - EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory) - EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer") - TimerGranularity time.Duration // Granularity of timers. - ProfileInterval time.Duration // Interval to profile runtime metrics - - AllowedPrefixes []string // A list of metric prefixes to allow, with '.' as the separator - BlockedPrefixes []string // A list of metric prefixes to block, with '.' as the separator - AllowedLabels []string // A list of metric labels to allow, with '.' as the separator - BlockedLabels []string // A list of metric labels to block, with '.' as the separator - FilterDefault bool // Whether to allow metrics by default -} - -// Metrics represents an instance of a metrics sink that can -// be used to emit -type Metrics struct { - Config - lastNumGC uint32 - sink MetricSink - filter *iradix.Tree - allowedLabels map[string]bool - blockedLabels map[string]bool - filterLock sync.RWMutex // Lock filters and allowedLabels/blockedLabels access -} - -// Shared global metrics instance -var globalMetrics atomic.Value // *Metrics - -func init() { - // Initialize to a blackhole sink to avoid errors - globalMetrics.Store(&Metrics{sink: &BlackholeSink{}}) -} - -// DefaultConfig provides a sane default configuration -func DefaultConfig(serviceName string) *Config { - c := &Config{ - ServiceName: serviceName, // Use client provided service - HostName: "", - EnableHostname: true, // Enable hostname prefix - EnableRuntimeMetrics: true, // Enable runtime profiling - EnableTypePrefix: false, // Disable type prefix - TimerGranularity: time.Millisecond, // Timers are in milliseconds - ProfileInterval: time.Second, // Poll runtime every second - FilterDefault: true, // Don't filter metrics by default - } - - // Try to get the hostname - name, _ := os.Hostname() - c.HostName = name - return c -} - -// New is used to create a new instance of Metrics -func New(conf *Config, sink MetricSink) (*Metrics, error) { - met := &Metrics{} - met.Config = *conf - met.sink = sink - met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels) - - // Start the runtime collector - if conf.EnableRuntimeMetrics { - go met.collectStats() - } - return met, nil -} - -// NewGlobal is the same as New, but it assigns the metrics object to be -// used globally as well as returning it. -func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) { - metrics, err := New(conf, sink) - if err == nil { - globalMetrics.Store(metrics) - } - return metrics, err -} - -// Proxy all the methods to the globalMetrics instance -func SetGauge(key []string, val float32) { - globalMetrics.Load().(*Metrics).SetGauge(key, val) -} - -func SetGaugeWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).SetGaugeWithLabels(key, val, labels) -} - -func EmitKey(key []string, val float32) { - globalMetrics.Load().(*Metrics).EmitKey(key, val) -} - -func IncrCounter(key []string, val float32) { - globalMetrics.Load().(*Metrics).IncrCounter(key, val) -} - -func IncrCounterWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).IncrCounterWithLabels(key, val, labels) -} - -func AddSample(key []string, val float32) { - globalMetrics.Load().(*Metrics).AddSample(key, val) -} - -func AddSampleWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).AddSampleWithLabels(key, val, labels) -} - -func MeasureSince(key []string, start time.Time) { - globalMetrics.Load().(*Metrics).MeasureSince(key, start) -} - -func MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - globalMetrics.Load().(*Metrics).MeasureSinceWithLabels(key, start, labels) -} - -func UpdateFilter(allow, block []string) { - globalMetrics.Load().(*Metrics).UpdateFilter(allow, block) -} - -// UpdateFilterAndLabels set allow/block prefixes of metrics while allowedLabels -// and blockedLabels - when not nil - allow filtering of labels in order to -// block/allow globally labels (especially useful when having large number of -// values for a given label). See README.md for more information about usage. -func UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - globalMetrics.Load().(*Metrics).UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels) -} diff --git a/vendor/github.com/armon/go-metrics/statsd.go b/vendor/github.com/armon/go-metrics/statsd.go deleted file mode 100644 index 1bfffce4..00000000 --- a/vendor/github.com/armon/go-metrics/statsd.go +++ /dev/null @@ -1,184 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // statsdMaxLen is the maximum size of a packet - // to send to statsd - statsdMaxLen = 1400 -) - -// StatsdSink provides a MetricSink that can be used -// with a statsite or statsd metrics server. It uses -// only UDP packets, while StatsiteSink uses TCP. -type StatsdSink struct { - addr string - metricQueue chan string -} - -// NewStatsdSinkFromURL creates an StatsdSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsdSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsdSink(u.Host) -} - -// NewStatsdSink is used to create a new StatsdSink -func NewStatsdSink(addr string) (*StatsdSink, error) { - s := &StatsdSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsd -func (s *StatsdSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsdSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsdSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsdSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsdSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsdSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsdSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Create a buffer - buf := bytes.NewBuffer(nil) - - // Attempt to connect - sock, err = net.Dial("udp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsd! Err: %s", err) - goto WAIT - } - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Check if this would overflow the packet size - if len(metric)+buf.Len() > statsdMaxLen { - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error writing to statsd! Err: %s", err) - goto WAIT - } - } - - // Append to the buffer - buf.WriteString(metric) - - case <-ticker.C: - if buf.Len() == 0 { - continue - } - - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error flushing to statsd! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/armon/go-metrics/statsite.go b/vendor/github.com/armon/go-metrics/statsite.go deleted file mode 100644 index 6c0d284d..00000000 --- a/vendor/github.com/armon/go-metrics/statsite.go +++ /dev/null @@ -1,172 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // We force flush the statsite metrics after this period of - // inactivity. Prevents stats from getting stuck in a buffer - // forever. - flushInterval = 100 * time.Millisecond -) - -// NewStatsiteSinkFromURL creates an StatsiteSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsiteSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsiteSink(u.Host) -} - -// StatsiteSink provides a MetricSink that can be used with a -// statsite metrics server -type StatsiteSink struct { - addr string - metricQueue chan string -} - -// NewStatsiteSink is used to create a new StatsiteSink -func NewStatsiteSink(addr string) (*StatsiteSink, error) { - s := &StatsiteSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsite -func (s *StatsiteSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsiteSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsiteSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsiteSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsiteSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsiteSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - var buffered *bufio.Writer - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Attempt to connect - sock, err = net.Dial("tcp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsite! Err: %s", err) - goto WAIT - } - - // Create a buffered writer - buffered = bufio.NewWriter(sock) - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Try to send to statsite - _, err := buffered.Write([]byte(metric)) - if err != nil { - log.Printf("[ERR] Error writing to statsite! Err: %s", err) - goto WAIT - } - case <-ticker.C: - if err := buffered.Flush(); err != nil { - log.Printf("[ERR] Error flushing to statsite! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/armon/go-radix/.gitignore b/vendor/github.com/armon/go-radix/.gitignore deleted file mode 100644 index 00268614..00000000 --- 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 1a0bbea6..00000000 --- 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 a5df10e6..00000000 --- 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 26f42a28..00000000 --- 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/go.mod b/vendor/github.com/armon/go-radix/go.mod deleted file mode 100644 index 4336aa29..00000000 --- a/vendor/github.com/armon/go-radix/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/armon/go-radix 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 e2bb22eb..00000000 --- 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/elazarl/go-bindata-assetfs/LICENSE b/vendor/github.com/elazarl/go-bindata-assetfs/LICENSE deleted file mode 100644 index 5782c726..00000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2014, Elazar Leibovich -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. - -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/elazarl/go-bindata-assetfs/README.md b/vendor/github.com/elazarl/go-bindata-assetfs/README.md deleted file mode 100644 index 27ee48f0..00000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# go-bindata-assetfs - -Serve embedded files from [jteeuwen/go-bindata](https://github.com/jteeuwen/go-bindata) with `net/http`. - -[GoDoc](http://godoc.org/github.com/elazarl/go-bindata-assetfs) - -### Installation - -Install with - - $ go get github.com/jteeuwen/go-bindata/... - $ go get github.com/elazarl/go-bindata-assetfs/... - -### Creating embedded data - -Usage is identical to [jteeuwen/go-bindata](https://github.com/jteeuwen/go-bindata) usage, -instead of running `go-bindata` run `go-bindata-assetfs`. - -The tool will create a `bindata_assetfs.go` file, which contains the embedded data. - -A typical use case is - - $ go-bindata-assetfs data/... - -### Using assetFS in your code - -The generated file provides an `assetFS()` function that returns a `http.Filesystem` -wrapping the embedded files. What you usually want to do is: - - http.Handle("/", http.FileServer(assetFS())) - -This would run an HTTP server serving the embedded files. - -## Without running binary tool - -You can always just run the `go-bindata` tool, and then - -use - - import "github.com/elazarl/go-bindata-assetfs" - ... - http.Handle("/", - http.FileServer( - &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "data"})) - -to serve files embedded from the `data` directory. diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go b/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go deleted file mode 100644 index 04f6d7a3..00000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go +++ /dev/null @@ -1,167 +0,0 @@ -package assetfs - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "net/http" - "os" - "path" - "path/filepath" - "strings" - "time" -) - -var ( - defaultFileTimestamp = time.Now() -) - -// FakeFile implements os.FileInfo interface for a given path and size -type FakeFile struct { - // Path is the path of this file - Path string - // Dir marks of the path is a directory - Dir bool - // Len is the length of the fake file, zero if it is a directory - Len int64 - // Timestamp is the ModTime of this file - Timestamp time.Time -} - -func (f *FakeFile) Name() string { - _, name := filepath.Split(f.Path) - return name -} - -func (f *FakeFile) Mode() os.FileMode { - mode := os.FileMode(0644) - if f.Dir { - return mode | os.ModeDir - } - return mode -} - -func (f *FakeFile) ModTime() time.Time { - return f.Timestamp -} - -func (f *FakeFile) Size() int64 { - return f.Len -} - -func (f *FakeFile) IsDir() bool { - return f.Mode().IsDir() -} - -func (f *FakeFile) Sys() interface{} { - return nil -} - -// AssetFile implements http.File interface for a no-directory file with content -type AssetFile struct { - *bytes.Reader - io.Closer - FakeFile -} - -func NewAssetFile(name string, content []byte, timestamp time.Time) *AssetFile { - if timestamp.IsZero() { - timestamp = defaultFileTimestamp - } - return &AssetFile{ - bytes.NewReader(content), - ioutil.NopCloser(nil), - FakeFile{name, false, int64(len(content)), timestamp}} -} - -func (f *AssetFile) Readdir(count int) ([]os.FileInfo, error) { - return nil, errors.New("not a directory") -} - -func (f *AssetFile) Size() int64 { - return f.FakeFile.Size() -} - -func (f *AssetFile) Stat() (os.FileInfo, error) { - return f, nil -} - -// AssetDirectory implements http.File interface for a directory -type AssetDirectory struct { - AssetFile - ChildrenRead int - Children []os.FileInfo -} - -func NewAssetDirectory(name string, children []string, fs *AssetFS) *AssetDirectory { - fileinfos := make([]os.FileInfo, 0, len(children)) - for _, child := range children { - _, err := fs.AssetDir(filepath.Join(name, child)) - fileinfos = append(fileinfos, &FakeFile{child, err == nil, 0, time.Time{}}) - } - return &AssetDirectory{ - AssetFile{ - bytes.NewReader(nil), - ioutil.NopCloser(nil), - FakeFile{name, true, 0, time.Time{}}, - }, - 0, - fileinfos} -} - -func (f *AssetDirectory) Readdir(count int) ([]os.FileInfo, error) { - if count <= 0 { - return f.Children, nil - } - if f.ChildrenRead+count > len(f.Children) { - count = len(f.Children) - f.ChildrenRead - } - rv := f.Children[f.ChildrenRead : f.ChildrenRead+count] - f.ChildrenRead += count - return rv, nil -} - -func (f *AssetDirectory) Stat() (os.FileInfo, error) { - return f, nil -} - -// AssetFS implements http.FileSystem, allowing -// embedded files to be served from net/http package. -type AssetFS struct { - // Asset should return content of file in path if exists - Asset func(path string) ([]byte, error) - // AssetDir should return list of files in the path - AssetDir func(path string) ([]string, error) - // AssetInfo should return the info of file in path if exists - AssetInfo func(path string) (os.FileInfo, error) - // Prefix would be prepended to http requests - Prefix string -} - -func (fs *AssetFS) Open(name string) (http.File, error) { - name = path.Join(fs.Prefix, name) - if len(name) > 0 && name[0] == '/' { - name = name[1:] - } - if b, err := fs.Asset(name); err == nil { - timestamp := defaultFileTimestamp - if fs.AssetInfo != nil { - if info, err := fs.AssetInfo(name); err == nil { - timestamp = info.ModTime() - } - } - return NewAssetFile(name, b, timestamp), nil - } - if children, err := fs.AssetDir(name); err == nil { - return NewAssetDirectory(name, children, fs), nil - } else { - // If the error is not found, return an error that will - // result in a 404 error. Otherwise the server returns - // a 500 error for files not found. - if strings.Contains(err.Error(), "not found") { - return nil, os.ErrNotExist - } - return nil, err - } -} diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/doc.go b/vendor/github.com/elazarl/go-bindata-assetfs/doc.go deleted file mode 100644 index a664249f..00000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/doc.go +++ /dev/null @@ -1,13 +0,0 @@ -// assetfs allows packages to serve static content embedded -// with the go-bindata tool with the standard net/http package. -// -// See https://github.com/jteeuwen/go-bindata for more information -// about embedding binary data with go-bindata. -// -// Usage example, after running -// $ go-bindata data/... -// use: -// http.Handle("/", -// http.FileServer( -// &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "data"})) -package assetfs diff --git a/vendor/github.com/go-sql-driver/mysql/.gitignore b/vendor/github.com/go-sql-driver/mysql/.gitignore deleted file mode 100644 index 2de28da1..00000000 --- a/vendor/github.com/go-sql-driver/mysql/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -Icon? -ehthumbs.db -Thumbs.db -.idea diff --git a/vendor/github.com/go-sql-driver/mysql/.travis.yml b/vendor/github.com/go-sql-driver/mysql/.travis.yml deleted file mode 100644 index cc1268c3..00000000 --- a/vendor/github.com/go-sql-driver/mysql/.travis.yml +++ /dev/null @@ -1,107 +0,0 @@ -sudo: false -language: go -go: - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - master - -before_install: - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - -before_script: - - echo -e "[server]\ninnodb_log_file_size=256MB\ninnodb_buffer_pool_size=512MB\nmax_allowed_packet=16MB" | sudo tee -a /etc/mysql/my.cnf - - sudo service mysql restart - - .travis/wait_mysql.sh - - mysql -e 'create database gotest;' - -matrix: - include: - - env: DB=MYSQL8 - sudo: required - dist: trusty - go: 1.10.x - services: - - docker - before_install: - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - docker pull mysql:8.0 - - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret - mysql:8.0 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB --local-infile=1 - - cp .travis/docker.cnf ~/.my.cnf - - .travis/wait_mysql.sh - before_script: - - export MYSQL_TEST_USER=gotest - - export MYSQL_TEST_PASS=secret - - export MYSQL_TEST_ADDR=127.0.0.1:3307 - - export MYSQL_TEST_CONCURRENT=1 - - - env: DB=MYSQL57 - sudo: required - dist: trusty - go: 1.10.x - services: - - docker - before_install: - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - docker pull mysql:5.7 - - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret - mysql:5.7 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB --local-infile=1 - - cp .travis/docker.cnf ~/.my.cnf - - .travis/wait_mysql.sh - before_script: - - export MYSQL_TEST_USER=gotest - - export MYSQL_TEST_PASS=secret - - export MYSQL_TEST_ADDR=127.0.0.1:3307 - - export MYSQL_TEST_CONCURRENT=1 - - - env: DB=MARIA55 - sudo: required - dist: trusty - go: 1.10.x - services: - - docker - before_install: - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - docker pull mariadb:5.5 - - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret - mariadb:5.5 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB --local-infile=1 - - cp .travis/docker.cnf ~/.my.cnf - - .travis/wait_mysql.sh - before_script: - - export MYSQL_TEST_USER=gotest - - export MYSQL_TEST_PASS=secret - - export MYSQL_TEST_ADDR=127.0.0.1:3307 - - export MYSQL_TEST_CONCURRENT=1 - - - env: DB=MARIA10_1 - sudo: required - dist: trusty - go: 1.10.x - services: - - docker - before_install: - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - docker pull mariadb:10.1 - - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret - mariadb:10.1 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB --local-infile=1 - - cp .travis/docker.cnf ~/.my.cnf - - .travis/wait_mysql.sh - before_script: - - export MYSQL_TEST_USER=gotest - - export MYSQL_TEST_PASS=secret - - export MYSQL_TEST_ADDR=127.0.0.1:3307 - - export MYSQL_TEST_CONCURRENT=1 - -script: - - go test -v -covermode=count -coverprofile=coverage.out - - go vet ./... - - .travis/gofmt.sh -after_script: - - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci diff --git a/vendor/github.com/go-sql-driver/mysql/AUTHORS b/vendor/github.com/go-sql-driver/mysql/AUTHORS deleted file mode 100644 index 73ff68fb..00000000 --- a/vendor/github.com/go-sql-driver/mysql/AUTHORS +++ /dev/null @@ -1,89 +0,0 @@ -# This is the official list of Go-MySQL-Driver authors for copyright purposes. - -# If you are submitting a patch, please add your name or the name of the -# organization which holds the copyright to this list in alphabetical order. - -# Names should be added to this file as -# Name -# The email address is not required for organizations. -# Please keep the list sorted. - - -# Individual Persons - -Aaron Hopkins -Achille Roussel -Alexey Palazhchenko -Andrew Reid -Arne Hormann -Asta Xie -Bulat Gaifullin -Carlos Nieto -Chris Moos -Craig Wilson -Daniel Montoya -Daniel Nichter -Daniël van Eeden -Dave Protasowski -DisposaBoy -Egor Smolyakov -Evan Shaw -Frederick Mayle -Gustavo Kristic -Hajime Nakagami -Hanno Braun -Henri Yandell -Hirotaka Yamamoto -ICHINOSE Shogo -INADA Naoki -Jacek Szwec -James Harr -Jeff Hodges -Jeffrey Charles -Jian Zhen -Joshua Prunier -Julien Lefevre -Julien Schmidt -Justin Li -Justin Nuß -Kamil Dziedzic -Kevin Malachowski -Kieron Woodhouse -Lennart Rudolph -Leonardo YongUk Kim -Linh Tran Tuan -Lion Yang -Luca Looz -Lucas Liu -Luke Scott -Maciej Zimnoch -Michael Woolnough -Nicola Peduzzi -Olivier Mengué -oscarzhao -Paul Bonser -Peter Schultz -Rebecca Chin -Reed Allman -Richard Wilkes -Robert Russell -Runrioter Wung -Shuode Li -Soroush Pour -Stan Putrya -Stanley Gunawan -Xiangyu Hu -Xiaobing Jiang -Xiuming Chen -Zhenye Xie - -# Organizations - -Barracuda Networks, Inc. -Counting Ltd. -Google Inc. -InfoSum Ltd. -Keybase Inc. -Percona LLC -Pivotal Inc. -Stripe Inc. diff --git a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md b/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md deleted file mode 100644 index ce1b5330..00000000 --- a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md +++ /dev/null @@ -1,178 +0,0 @@ -## Version 1.4.1 (2018-11-14) - -Bugfixes: - - - Fix TIME format for binary columns (#818) - - Fix handling of empty auth plugin names (#835) - - Fix caching_sha2_password with empty password (#826) - - Fix canceled context broke mysqlConn (#862) - - Fix OldAuthSwitchRequest support (#870) - - Fix Auth Response packet for cleartext password (#887) - -## Version 1.4 (2018-06-03) - -Changes: - - - Documentation fixes (#530, #535, #567) - - Refactoring (#575, #579, #580, #581, #603, #615, #704) - - Cache column names (#444) - - Sort the DSN parameters in DSNs generated from a config (#637) - - Allow native password authentication by default (#644) - - Use the default port if it is missing in the DSN (#668) - - Removed the `strict` mode (#676) - - Do not query `max_allowed_packet` by default (#680) - - Dropped support Go 1.6 and lower (#696) - - Updated `ConvertValue()` to match the database/sql/driver implementation (#760) - - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783) - - Improved the compatibility of the authentication system (#807) - -New Features: - - - Multi-Results support (#537) - - `rejectReadOnly` DSN option (#604) - - `context.Context` support (#608, #612, #627, #761) - - Transaction isolation level support (#619, #744) - - Read-Only transactions support (#618, #634) - - `NewConfig` function which initializes a config with default values (#679) - - Implemented the `ColumnType` interfaces (#667, #724) - - Support for custom string types in `ConvertValue` (#623) - - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710) - - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802) - - Implemented `driver.SessionResetter` (#779) - - `sha256_password` authentication plugin support (#808) - -Bugfixes: - - - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718) - - Fixed LOAD LOCAL DATA INFILE for empty files (#590) - - Removed columns definition cache since it sometimes cached invalid data (#592) - - Don't mutate registered TLS configs (#600) - - Make RegisterTLSConfig concurrency-safe (#613) - - Handle missing auth data in the handshake packet correctly (#646) - - Do not retry queries when data was written to avoid data corruption (#302, #736) - - Cache the connection pointer for error handling before invalidating it (#678) - - Fixed imports for appengine/cloudsql (#700) - - Fix sending STMT_LONG_DATA for 0 byte data (#734) - - Set correct capacity for []bytes read from length-encoded strings (#766) - - Make RegisterDial concurrency-safe (#773) - - -## Version 1.3 (2016-12-01) - -Changes: - - - Go 1.1 is no longer supported - - Use decimals fields in MySQL to format time types (#249) - - Buffer optimizations (#269) - - TLS ServerName defaults to the host (#283) - - Refactoring (#400, #410, #437) - - Adjusted documentation for second generation CloudSQL (#485) - - Documented DSN system var quoting rules (#502) - - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512) - -New Features: - - - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) - - Support for returning table alias on Columns() (#289, #359, #382) - - Placeholder interpolation, can be actived with the DSN parameter `interpolateParams=true` (#309, #318, #490) - - Support for uint64 parameters with high bit set (#332, #345) - - Cleartext authentication plugin support (#327) - - Exported ParseDSN function and the Config struct (#403, #419, #429) - - Read / Write timeouts (#401) - - Support for JSON field type (#414) - - Support for multi-statements and multi-results (#411, #431) - - DSN parameter to set the driver-side max_allowed_packet value manually (#489) - - Native password authentication plugin support (#494, #524) - -Bugfixes: - - - Fixed handling of queries without columns and rows (#255) - - Fixed a panic when SetKeepAlive() failed (#298) - - Handle ERR packets while reading rows (#321) - - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349) - - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356) - - Actually zero out bytes in handshake response (#378) - - Fixed race condition in registering LOAD DATA INFILE handler (#383) - - Fixed tests with MySQL 5.7.9+ (#380) - - QueryUnescape TLS config names (#397) - - Fixed "broken pipe" error by writing to closed socket (#390) - - Fixed LOAD LOCAL DATA INFILE buffering (#424) - - Fixed parsing of floats into float64 when placeholders are used (#434) - - Fixed DSN tests with Go 1.7+ (#459) - - Handle ERR packets while waiting for EOF (#473) - - Invalidate connection on error while discarding additional results (#513) - - Allow terminating packets of length 0 (#516) - - -## Version 1.2 (2014-06-03) - -Changes: - - - We switched back to a "rolling release". `go get` installs the current master branch again - - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver - - Exported errors to allow easy checking from application code - - Enabled TCP Keepalives on TCP connections - - Optimized INFILE handling (better buffer size calculation, lazy init, ...) - - The DSN parser also checks for a missing separating slash - - Faster binary date / datetime to string formatting - - Also exported the MySQLWarning type - - mysqlConn.Close returns the first error encountered instead of ignoring all errors - - writePacket() automatically writes the packet size to the header - - readPacket() uses an iterative approach instead of the recursive approach to merge splitted packets - -New Features: - - - `RegisterDial` allows the usage of a custom dial function to establish the network connection - - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter - - Logging of critical errors is configurable with `SetLogger` - - Google CloudSQL support - -Bugfixes: - - - Allow more than 32 parameters in prepared statements - - Various old_password fixes - - Fixed TestConcurrent test to pass Go's race detection - - Fixed appendLengthEncodedInteger for large numbers - - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo) - - -## Version 1.1 (2013-11-02) - -Changes: - - - Go-MySQL-Driver now requires Go 1.1 - - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore - - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors - - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")` - - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'. - - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries - - Optimized the buffer for reading - - stmt.Query now caches column metadata - - New Logo - - Changed the copyright header to include all contributors - - Improved the LOAD INFILE documentation - - The driver struct is now exported to make the driver directly accessible - - Refactored the driver tests - - Added more benchmarks and moved all to a separate file - - Other small refactoring - -New Features: - - - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure - - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs - - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used - -Bugfixes: - - - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification - - Convert to DB timezone when inserting `time.Time` - - Splitted packets (more than 16MB) are now merged correctly - - Fixed false positive `io.EOF` errors when the data was fully read - - Avoid panics on reuse of closed connections - - Fixed empty string producing false nil values - - Fixed sign byte for positive TIME fields - - -## Version 1.0 (2013-05-14) - -Initial Release diff --git a/vendor/github.com/go-sql-driver/mysql/CONTRIBUTING.md b/vendor/github.com/go-sql-driver/mysql/CONTRIBUTING.md deleted file mode 100644 index 8fe16bcb..00000000 --- a/vendor/github.com/go-sql-driver/mysql/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -# Contributing Guidelines - -## Reporting Issues - -Before creating a new Issue, please check first if a similar Issue [already exists](https://github.com/go-sql-driver/mysql/issues?state=open) or was [recently closed](https://github.com/go-sql-driver/mysql/issues?direction=desc&page=1&sort=updated&state=closed). - -## Contributing Code - -By contributing to this project, you share your code under the Mozilla Public License 2, as specified in the LICENSE file. -Don't forget to add yourself to the AUTHORS file. - -### Code Review - -Everyone is invited to review and comment on pull requests. -If it looks fine to you, comment with "LGTM" (Looks good to me). - -If changes are required, notice the reviewers with "PTAL" (Please take another look) after committing the fixes. - -Before merging the Pull Request, at least one [team member](https://github.com/go-sql-driver?tab=members) must have commented with "LGTM". - -## Development Ideas - -If you are looking for ideas for code contributions, please check our [Development Ideas](https://github.com/go-sql-driver/mysql/wiki/Development-Ideas) Wiki page. diff --git a/vendor/github.com/go-sql-driver/mysql/LICENSE b/vendor/github.com/go-sql-driver/mysql/LICENSE deleted file mode 100644 index 14e2f777..00000000 --- a/vendor/github.com/go-sql-driver/mysql/LICENSE +++ /dev/null @@ -1,373 +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/go-sql-driver/mysql/README.md b/vendor/github.com/go-sql-driver/mysql/README.md deleted file mode 100644 index 2e9b07ee..00000000 --- a/vendor/github.com/go-sql-driver/mysql/README.md +++ /dev/null @@ -1,490 +0,0 @@ -# Go-MySQL-Driver - -A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package - -![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin") - ---------------------------------------- - * [Features](#features) - * [Requirements](#requirements) - * [Installation](#installation) - * [Usage](#usage) - * [DSN (Data Source Name)](#dsn-data-source-name) - * [Password](#password) - * [Protocol](#protocol) - * [Address](#address) - * [Parameters](#parameters) - * [Examples](#examples) - * [Connection pool and timeouts](#connection-pool-and-timeouts) - * [context.Context Support](#contextcontext-support) - * [ColumnType Support](#columntype-support) - * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support) - * [time.Time support](#timetime-support) - * [Unicode support](#unicode-support) - * [Testing / Development](#testing--development) - * [License](#license) - ---------------------------------------- - -## Features - * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance") - * Native Go implementation. No C-bindings, just pure Go - * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc) - * Automatic handling of broken connections - * Automatic Connection Pooling *(by database/sql package)* - * Supports queries larger than 16MB - * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support. - * Intelligent `LONG DATA` handling in prepared statements - * Secure `LOAD DATA LOCAL INFILE` support with file Whitelisting and `io.Reader` support - * Optional `time.Time` parsing - * Optional placeholder interpolation - -## Requirements - * Go 1.7 or higher. We aim to support the 3 latest versions of Go. - * MySQL (4.1+), MariaDB, Percona Server, Google CloudSQL or Sphinx (2.2.3+) - ---------------------------------------- - -## Installation -Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell: -```bash -$ go get -u github.com/go-sql-driver/mysql -``` -Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`. - -## Usage -_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then. - -Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name) as `dataSourceName`: -```go -import "database/sql" -import _ "github.com/go-sql-driver/mysql" - -db, err := sql.Open("mysql", "user:password@/dbname") -``` - -[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples "Go-MySQL-Driver Examples"). - - -### DSN (Data Source Name) - -The Data Source Name has a common format, like e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) uses it, but without type-prefix (optional parts marked by squared brackets): -``` -[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] -``` - -A DSN in its fullest form: -``` -username:password@protocol(address)/dbname?param=value -``` - -Except for the databasename, all values are optional. So the minimal DSN is: -``` -/dbname -``` - -If you do not want to preselect a database, leave `dbname` empty: -``` -/ -``` -This has the same effect as an empty DSN string: -``` - -``` - -Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct. - -#### Password -Passwords can consist of any character. Escaping is **not** necessary. - -#### Protocol -See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available. -In general you should use an Unix domain socket if available and TCP otherwise for best performance. - -#### Address -For TCP and UDP networks, addresses have the form `host[:port]`. -If `port` is omitted, the default port will be used. -If `host` is a literal IPv6 address, it must be enclosed in square brackets. -The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form. - -For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`. - -#### Parameters -*Parameters are case-sensitive!* - -Notice that any of `true`, `TRUE`, `True` or `1` is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: `false`, `FALSE`, `False` or `0`. - -##### `allowAllFiles` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowAllFiles=true` disables the file Whitelist for `LOAD DATA LOCAL INFILE` and allows *all* files. -[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) - -##### `allowCleartextPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowCleartextPasswords=true` allows using the [cleartext client side plugin](http://dev.mysql.com/doc/en/cleartext-authentication-plugin.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network. - -##### `allowNativePasswords` - -``` -Type: bool -Valid Values: true, false -Default: true -``` -`allowNativePasswords=false` disallows the usage of MySQL native password method. - -##### `allowOldPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` -`allowOldPasswords=true` allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also [the old_passwords wiki page](https://github.com/go-sql-driver/mysql/wiki/old_passwords). - -##### `charset` - -``` -Type: string -Valid Values: -Default: none -``` - -Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset failes. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). - -Usage of the `charset` parameter is discouraged because it issues additional queries to the server. -Unless you need the fallback behavior, please use `collation` instead. - -##### `collation` - -``` -Type: string -Valid Values: -Default: utf8_general_ci -``` - -Sets the collation used for client-server interaction on connection. In contrast to `charset`, `collation` does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail. - -A list of valid charsets for a server is retrievable with `SHOW COLLATION`. - -##### `clientFoundRows` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed. - -##### `columnsWithAlias` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -When `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example: - -``` -SELECT u.id FROM users as u -``` - -will return `u.id` instead of just `id` if `columnsWithAlias=true`. - -##### `interpolateParams` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -If `interpolateParams` is true, placeholders (`?`) in calls to `db.Query()` and `db.Exec()` are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with `interpolateParams=false`. - -*This can not be used together with the multibyte encodings BIG5, CP932, GB2312, GBK or SJIS. These are blacklisted as they may [introduce a SQL injection vulnerability](http://stackoverflow.com/a/12118602/3430118)!* - -##### `loc` - -``` -Type: string -Valid Values: -Default: UTC -``` - -Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details. - -Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter. - -Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. - -##### `maxAllowedPacket` -``` -Type: decimal number -Default: 4194304 -``` - -Max packet size allowed in bytes. The default value is 4 MiB and should be adjusted to match the server settings. `maxAllowedPacket=0` can be used to automatically fetch the `max_allowed_packet` variable from server *on every connection*. - -##### `multiStatements` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -Allow multiple statements in one query. While this allows batch queries, it also greatly increases the risk of SQL injections. Only the result of the first query is returned, all other results are silently discarded. - -When `multiStatements` is used, `?` parameters must only be used in the first statement. - -##### `parseTime` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string` -The date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`. - - -##### `readTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - -##### `rejectReadOnly` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - - -`rejectReadOnly=true` causes the driver to reject read-only connections. This -is for a possible race condition during an automatic failover, where the mysql -client gets connected to a read-only replica after the failover. - -Note that this should be a fairly rare case, as an automatic failover normally -happens when the primary is down, and the race condition shouldn't happen -unless it comes back up online as soon as the failover is kicked off. On the -other hand, when this happens, a MySQL application can get stuck on a -read-only connection until restarted. It is however fairly easy to reproduce, -for example, using a manual failover on AWS Aurora's MySQL-compatible cluster. - -If you are not relying on read-only transactions to reject writes that aren't -supposed to happen, setting this on some MySQL providers (such as AWS Aurora) -is safer for failovers. - -Note that ERROR 1290 can be returned for a `read-only` server and this option will -cause a retry for that error. However the same error number is used for some -other cases. You should ensure your application will never cause an ERROR 1290 -except for `read-only` mode when enabling this option. - - -##### `serverPubKey` - -``` -Type: string -Valid Values: -Default: none -``` - -Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN. -Public keys are used to transmit encrypted data, e.g. for authentication. -If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required. - - -##### `timeout` - -``` -Type: duration -Default: OS default -``` - -Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### `tls` - -``` -Type: bool / string -Valid Values: true, false, skip-verify, -Default: false -``` - -`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side). Use a custom value registered with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig). - - -##### `writeTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### System Variables - -Any other parameters are interpreted as system variables: - * `=`: `SET =` - * `=`: `SET =` - * `=%27%27`: `SET =''` - -Rules: -* The values for string variables must be quoted with `'`. -* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed! - (which implies values of string variables must be wrapped with `%27`). - -Examples: - * `autocommit=1`: `SET autocommit=1` - * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'` - * [`tx_isolation=%27REPEATABLE-READ%27`](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_tx_isolation): `SET tx_isolation='REPEATABLE-READ'` - - -#### Examples -``` -user@unix(/path/to/socket)/dbname -``` - -``` -root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local -``` - -``` -user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true -``` - -Treat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html): -``` -user:password@/dbname?sql_mode=TRADITIONAL -``` - -TCP via IPv6: -``` -user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci -``` - -TCP on a remote host, e.g. Amazon RDS: -``` -id:password@tcp(your-amazonaws-uri.com:3306)/dbname -``` - -Google Cloud SQL on App Engine (First Generation MySQL Server): -``` -user@cloudsql(project-id:instance-name)/dbname -``` - -Google Cloud SQL on App Engine (Second Generation MySQL Server): -``` -user@cloudsql(project-id:regionname:instance-name)/dbname -``` - -TCP using default port (3306) on localhost: -``` -user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped -``` - -Use the default protocol (tcp) and host (localhost:3306): -``` -user:password@/dbname -``` - -No Database preselected: -``` -user:password@/ -``` - - -### Connection pool and timeouts -The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively. - -## `ColumnType` Support -This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. - -## `context.Context` Support -Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts. -See [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details. - - -### `LOAD DATA LOCAL INFILE` support -For this feature you need direct access to the package. Therefore you must change the import path (no `_`): -```go -import "github.com/go-sql-driver/mysql" -``` - -Files must be whitelisted by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the Whitelist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)). - -To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore. - -See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details. - - -### `time.Time` support -The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your program. - -However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical opposite in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter. - -**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes). - -Alternatively you can use the [`NullTime`](https://godoc.org/github.com/go-sql-driver/mysql#NullTime) type as the scan destination, which works with both `time.Time` and `string` / `[]byte`. - - -### Unicode support -Since version 1.1 Go-MySQL-Driver automatically uses the collation `utf8_general_ci` by default. - -Other collations / charsets can be set using the [`collation`](#collation) DSN parameter. - -Version 1.0 of the driver recommended adding `&charset=utf8` (alias for `SET NAMES utf8`) to the DSN to enable proper UTF-8 support. This is not necessary anymore. The [`collation`](#collation) parameter should be preferred to set another collation / charset than the default. - -See http://dev.mysql.com/doc/refman/5.7/en/charset-unicode.html for more details on MySQL's Unicode support. - -## Testing / Development -To run the driver tests you may need to adjust the configuration. See the [Testing Wiki-Page](https://github.com/go-sql-driver/mysql/wiki/Testing "Testing") for details. - -Go-MySQL-Driver is not feature-complete yet. Your help is very appreciated. -If you want to contribute, you can work on an [open issue](https://github.com/go-sql-driver/mysql/issues?state=open) or review a [pull request](https://github.com/go-sql-driver/mysql/pulls). - -See the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/CONTRIBUTING.md) for details. - ---------------------------------------- - -## License -Go-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE) - -Mozilla summarizes the license scope as follows: -> MPL: The copyleft applies to any files containing MPLed code. - - -That means: - * You can **use** the **unchanged** source code both in private and commercially. - * When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0). - * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**. - -Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license. - -You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE). - -![Go Gopher and MySQL Dolphin](https://raw.github.com/wiki/go-sql-driver/mysql/go-mysql-driver_m.jpg "Golang Gopher transporting the MySQL Dolphin in a wheelbarrow") - diff --git a/vendor/github.com/go-sql-driver/mysql/appengine.go b/vendor/github.com/go-sql-driver/mysql/appengine.go deleted file mode 100644 index be41f2ee..00000000 --- a/vendor/github.com/go-sql-driver/mysql/appengine.go +++ /dev/null @@ -1,19 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -// +build appengine - -package mysql - -import ( - "google.golang.org/appengine/cloudsql" -) - -func init() { - RegisterDial("cloudsql", cloudsql.Dial) -} diff --git a/vendor/github.com/go-sql-driver/mysql/auth.go b/vendor/github.com/go-sql-driver/mysql/auth.go deleted file mode 100644 index 14f678a8..00000000 --- a/vendor/github.com/go-sql-driver/mysql/auth.go +++ /dev/null @@ -1,420 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "encoding/pem" - "sync" -) - -// server pub keys registry -var ( - serverPubKeyLock sync.RWMutex - serverPubKeyRegistry map[string]*rsa.PublicKey -) - -// RegisterServerPubKey registers a server RSA public key which can be used to -// send data in a secure manner to the server without receiving the public key -// in a potentially insecure way from the server first. -// Registered keys can afterwards be used adding serverPubKey= to the DSN. -// -// Note: The provided rsa.PublicKey instance is exclusively owned by the driver -// after registering it and may not be modified. -// -// data, err := ioutil.ReadFile("mykey.pem") -// if err != nil { -// log.Fatal(err) -// } -// -// block, _ := pem.Decode(data) -// if block == nil || block.Type != "PUBLIC KEY" { -// log.Fatal("failed to decode PEM block containing public key") -// } -// -// pub, err := x509.ParsePKIXPublicKey(block.Bytes) -// if err != nil { -// log.Fatal(err) -// } -// -// if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { -// mysql.RegisterServerPubKey("mykey", rsaPubKey) -// } else { -// log.Fatal("not a RSA public key") -// } -// -func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry == nil { - serverPubKeyRegistry = make(map[string]*rsa.PublicKey) - } - - serverPubKeyRegistry[name] = pubKey - serverPubKeyLock.Unlock() -} - -// DeregisterServerPubKey removes the public key registered with the given name. -func DeregisterServerPubKey(name string) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry != nil { - delete(serverPubKeyRegistry, name) - } - serverPubKeyLock.Unlock() -} - -func getServerPubKey(name string) (pubKey *rsa.PublicKey) { - serverPubKeyLock.RLock() - if v, ok := serverPubKeyRegistry[name]; ok { - pubKey = v - } - serverPubKeyLock.RUnlock() - return -} - -// Hash password using pre 4.1 (old password) method -// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c -type myRnd struct { - seed1, seed2 uint32 -} - -const myRndMaxVal = 0x3FFFFFFF - -// Pseudo random number generator -func newMyRnd(seed1, seed2 uint32) *myRnd { - return &myRnd{ - seed1: seed1 % myRndMaxVal, - seed2: seed2 % myRndMaxVal, - } -} - -// Tested to be equivalent to MariaDB's floating point variant -// http://play.golang.org/p/QHvhd4qved -// http://play.golang.org/p/RG0q4ElWDx -func (r *myRnd) NextByte() byte { - r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal - r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal - - return byte(uint64(r.seed1) * 31 / myRndMaxVal) -} - -// Generate binary hash from byte string using insecure pre 4.1 method -func pwHash(password []byte) (result [2]uint32) { - var add uint32 = 7 - var tmp uint32 - - result[0] = 1345345333 - result[1] = 0x12345671 - - for _, c := range password { - // skip spaces and tabs in password - if c == ' ' || c == '\t' { - continue - } - - tmp = uint32(c) - result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) - result[1] += (result[1] << 8) ^ result[0] - add += tmp - } - - // Remove sign bit (1<<31)-1) - result[0] &= 0x7FFFFFFF - result[1] &= 0x7FFFFFFF - - return -} - -// Hash password using insecure pre 4.1 method -func scrambleOldPassword(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - scramble = scramble[:8] - - hashPw := pwHash([]byte(password)) - hashSc := pwHash(scramble) - - r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) - - var out [8]byte - for i := range out { - out[i] = r.NextByte() + 64 - } - - mask := r.NextByte() - for i := range out { - out[i] ^= mask - } - - return out[:] -} - -// Hash password using 4.1+ method (SHA1) -func scramblePassword(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // stage1Hash = SHA1(password) - crypt := sha1.New() - crypt.Write([]byte(password)) - stage1 := crypt.Sum(nil) - - // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) - // inner Hash - crypt.Reset() - crypt.Write(stage1) - hash := crypt.Sum(nil) - - // outer Hash - crypt.Reset() - crypt.Write(scramble) - crypt.Write(hash) - scramble = crypt.Sum(nil) - - // token = scrambleHash XOR stage1Hash - for i := range scramble { - scramble[i] ^= stage1[i] - } - return scramble -} - -// Hash password using MySQL 8+ method (SHA256) -func scrambleSHA256Password(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) - - crypt := sha256.New() - crypt.Write([]byte(password)) - message1 := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1) - message1Hash := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1Hash) - crypt.Write(scramble) - message2 := crypt.Sum(nil) - - for i := range message1 { - message1[i] ^= message2[i] - } - - return message1 -} - -func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { - plain := make([]byte, len(password)+1) - copy(plain, password) - for i := range plain { - j := i % len(seed) - plain[i] ^= seed[j] - } - sha1 := sha1.New() - return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) -} - -func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { - enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) - if err != nil { - return err - } - return mc.writeAuthSwitchPacket(enc) -} - -func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { - switch plugin { - case "caching_sha2_password": - authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) - return authResp, nil - - case "mysql_old_password": - if !mc.cfg.AllowOldPasswords { - return nil, ErrOldPassword - } - // Note: there are edge cases where this should work but doesn't; - // this is currently "wontfix": - // https://github.com/go-sql-driver/mysql/issues/184 - authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) - return authResp, nil - - case "mysql_clear_password": - if !mc.cfg.AllowCleartextPasswords { - return nil, ErrCleartextPassword - } - // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html - // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html - return append([]byte(mc.cfg.Passwd), 0), nil - - case "mysql_native_password": - if !mc.cfg.AllowNativePasswords { - return nil, ErrNativePassword - } - // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html - // Native password authentication only need and will need 20-byte challenge. - authResp := scramblePassword(authData[:20], mc.cfg.Passwd) - return authResp, nil - - case "sha256_password": - if len(mc.cfg.Passwd) == 0 { - return []byte{0}, nil - } - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - return append([]byte(mc.cfg.Passwd), 0), nil - } - - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - return []byte{1}, nil - } - - // encrypted password - enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) - return enc, err - - default: - errLog.Print("unknown auth plugin:", plugin) - return nil, ErrUnknownPlugin - } -} - -func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { - // Read Result Packet - authData, newPlugin, err := mc.readAuthResult() - if err != nil { - return err - } - - // handle auth plugin switch, if requested - if newPlugin != "" { - // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is - // sent and we have to keep using the cipher sent in the init packet. - if authData == nil { - authData = oldAuthData - } else { - // copy data from read buffer to owned slice - copy(oldAuthData, authData) - } - - plugin = newPlugin - - authResp, err := mc.auth(authData, plugin) - if err != nil { - return err - } - if err = mc.writeAuthSwitchPacket(authResp); err != nil { - return err - } - - // Read Result Packet - authData, newPlugin, err = mc.readAuthResult() - if err != nil { - return err - } - - // Do not allow to change the auth plugin more than once - if newPlugin != "" { - return ErrMalformPkt - } - } - - switch plugin { - - // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ - case "caching_sha2_password": - switch len(authData) { - case 0: - return nil // auth successful - case 1: - switch authData[0] { - case cachingSha2PasswordFastAuthSuccess: - if err = mc.readResultOK(); err == nil { - return nil // auth successful - } - - case cachingSha2PasswordPerformFullAuthentication: - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) - if err != nil { - return err - } - } else { - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - data := mc.buf.takeSmallBuffer(4 + 1) - data[4] = cachingSha2PasswordRequestPublicKey - mc.writePacket(data) - - // parse public key - data, err := mc.readPacket() - if err != nil { - return err - } - - block, _ := pem.Decode(data[1:]) - pkix, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - pubKey = pkix.(*rsa.PublicKey) - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pubKey) - if err != nil { - return err - } - } - return mc.readResultOK() - - default: - return ErrMalformPkt - } - default: - return ErrMalformPkt - } - - case "sha256_password": - switch len(authData) { - case 0: - return nil // auth successful - default: - block, _ := pem.Decode(authData) - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) - if err != nil { - return err - } - return mc.readResultOK() - } - - default: - return nil // auth successful - } - - return err -} diff --git a/vendor/github.com/go-sql-driver/mysql/buffer.go b/vendor/github.com/go-sql-driver/mysql/buffer.go deleted file mode 100644 index eb4748bf..00000000 --- a/vendor/github.com/go-sql-driver/mysql/buffer.go +++ /dev/null @@ -1,147 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "io" - "net" - "time" -) - -const defaultBufSize = 4096 - -// A buffer which is used for both reading and writing. -// This is possible since communication on each connection is synchronous. -// In other words, we can't write and read simultaneously on the same connection. -// The buffer is similar to bufio.Reader / Writer but zero-copy-ish -// Also highly optimized for this particular use case. -type buffer struct { - buf []byte - nc net.Conn - idx int - length int - timeout time.Duration -} - -func newBuffer(nc net.Conn) buffer { - var b [defaultBufSize]byte - return buffer{ - buf: b[:], - nc: nc, - } -} - -// fill reads into the buffer until at least _need_ bytes are in it -func (b *buffer) fill(need int) error { - n := b.length - - // move existing data to the beginning - if n > 0 && b.idx > 0 { - copy(b.buf[0:n], b.buf[b.idx:]) - } - - // grow buffer if necessary - // TODO: let the buffer shrink again at some point - // Maybe keep the org buf slice and swap back? - if need > len(b.buf) { - // Round up to the next multiple of the default size - newBuf := make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) - copy(newBuf, b.buf) - b.buf = newBuf - } - - b.idx = 0 - - for { - if b.timeout > 0 { - if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { - return err - } - } - - nn, err := b.nc.Read(b.buf[n:]) - n += nn - - switch err { - case nil: - if n < need { - continue - } - b.length = n - return nil - - case io.EOF: - if n >= need { - b.length = n - return nil - } - return io.ErrUnexpectedEOF - - default: - return err - } - } -} - -// returns next N bytes from buffer. -// The returned slice is only guaranteed to be valid until the next read -func (b *buffer) readNext(need int) ([]byte, error) { - if b.length < need { - // refill - if err := b.fill(need); err != nil { - return nil, err - } - } - - offset := b.idx - b.idx += need - b.length -= need - return b.buf[offset:b.idx], nil -} - -// returns a buffer with the requested size. -// If possible, a slice from the existing buffer is returned. -// Otherwise a bigger buffer is made. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeBuffer(length int) []byte { - if b.length > 0 { - return nil - } - - // test (cheap) general case first - if length <= defaultBufSize || length <= cap(b.buf) { - return b.buf[:length] - } - - if length < maxPacketSize { - b.buf = make([]byte, length) - return b.buf - } - return make([]byte, length) -} - -// shortcut which can be used if the requested buffer is guaranteed to be -// smaller than defaultBufSize -// Only one buffer (total) can be used at a time. -func (b *buffer) takeSmallBuffer(length int) []byte { - if b.length > 0 { - return nil - } - return b.buf[:length] -} - -// takeCompleteBuffer returns the complete existing buffer. -// This can be used if the necessary buffer size is unknown. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeCompleteBuffer() []byte { - if b.length > 0 { - return nil - } - return b.buf -} diff --git a/vendor/github.com/go-sql-driver/mysql/collations.go b/vendor/github.com/go-sql-driver/mysql/collations.go deleted file mode 100644 index 136c9e4d..00000000 --- a/vendor/github.com/go-sql-driver/mysql/collations.go +++ /dev/null @@ -1,251 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -const defaultCollation = "utf8_general_ci" -const binaryCollation = "binary" - -// A list of available collations mapped to the internal ID. -// To update this map use the following MySQL query: -// SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS -var collations = map[string]byte{ - "big5_chinese_ci": 1, - "latin2_czech_cs": 2, - "dec8_swedish_ci": 3, - "cp850_general_ci": 4, - "latin1_german1_ci": 5, - "hp8_english_ci": 6, - "koi8r_general_ci": 7, - "latin1_swedish_ci": 8, - "latin2_general_ci": 9, - "swe7_swedish_ci": 10, - "ascii_general_ci": 11, - "ujis_japanese_ci": 12, - "sjis_japanese_ci": 13, - "cp1251_bulgarian_ci": 14, - "latin1_danish_ci": 15, - "hebrew_general_ci": 16, - "tis620_thai_ci": 18, - "euckr_korean_ci": 19, - "latin7_estonian_cs": 20, - "latin2_hungarian_ci": 21, - "koi8u_general_ci": 22, - "cp1251_ukrainian_ci": 23, - "gb2312_chinese_ci": 24, - "greek_general_ci": 25, - "cp1250_general_ci": 26, - "latin2_croatian_ci": 27, - "gbk_chinese_ci": 28, - "cp1257_lithuanian_ci": 29, - "latin5_turkish_ci": 30, - "latin1_german2_ci": 31, - "armscii8_general_ci": 32, - "utf8_general_ci": 33, - "cp1250_czech_cs": 34, - "ucs2_general_ci": 35, - "cp866_general_ci": 36, - "keybcs2_general_ci": 37, - "macce_general_ci": 38, - "macroman_general_ci": 39, - "cp852_general_ci": 40, - "latin7_general_ci": 41, - "latin7_general_cs": 42, - "macce_bin": 43, - "cp1250_croatian_ci": 44, - "utf8mb4_general_ci": 45, - "utf8mb4_bin": 46, - "latin1_bin": 47, - "latin1_general_ci": 48, - "latin1_general_cs": 49, - "cp1251_bin": 50, - "cp1251_general_ci": 51, - "cp1251_general_cs": 52, - "macroman_bin": 53, - "utf16_general_ci": 54, - "utf16_bin": 55, - "utf16le_general_ci": 56, - "cp1256_general_ci": 57, - "cp1257_bin": 58, - "cp1257_general_ci": 59, - "utf32_general_ci": 60, - "utf32_bin": 61, - "utf16le_bin": 62, - "binary": 63, - "armscii8_bin": 64, - "ascii_bin": 65, - "cp1250_bin": 66, - "cp1256_bin": 67, - "cp866_bin": 68, - "dec8_bin": 69, - "greek_bin": 70, - "hebrew_bin": 71, - "hp8_bin": 72, - "keybcs2_bin": 73, - "koi8r_bin": 74, - "koi8u_bin": 75, - "latin2_bin": 77, - "latin5_bin": 78, - "latin7_bin": 79, - "cp850_bin": 80, - "cp852_bin": 81, - "swe7_bin": 82, - "utf8_bin": 83, - "big5_bin": 84, - "euckr_bin": 85, - "gb2312_bin": 86, - "gbk_bin": 87, - "sjis_bin": 88, - "tis620_bin": 89, - "ucs2_bin": 90, - "ujis_bin": 91, - "geostd8_general_ci": 92, - "geostd8_bin": 93, - "latin1_spanish_ci": 94, - "cp932_japanese_ci": 95, - "cp932_bin": 96, - "eucjpms_japanese_ci": 97, - "eucjpms_bin": 98, - "cp1250_polish_ci": 99, - "utf16_unicode_ci": 101, - "utf16_icelandic_ci": 102, - "utf16_latvian_ci": 103, - "utf16_romanian_ci": 104, - "utf16_slovenian_ci": 105, - "utf16_polish_ci": 106, - "utf16_estonian_ci": 107, - "utf16_spanish_ci": 108, - "utf16_swedish_ci": 109, - "utf16_turkish_ci": 110, - "utf16_czech_ci": 111, - "utf16_danish_ci": 112, - "utf16_lithuanian_ci": 113, - "utf16_slovak_ci": 114, - "utf16_spanish2_ci": 115, - "utf16_roman_ci": 116, - "utf16_persian_ci": 117, - "utf16_esperanto_ci": 118, - "utf16_hungarian_ci": 119, - "utf16_sinhala_ci": 120, - "utf16_german2_ci": 121, - "utf16_croatian_ci": 122, - "utf16_unicode_520_ci": 123, - "utf16_vietnamese_ci": 124, - "ucs2_unicode_ci": 128, - "ucs2_icelandic_ci": 129, - "ucs2_latvian_ci": 130, - "ucs2_romanian_ci": 131, - "ucs2_slovenian_ci": 132, - "ucs2_polish_ci": 133, - "ucs2_estonian_ci": 134, - "ucs2_spanish_ci": 135, - "ucs2_swedish_ci": 136, - "ucs2_turkish_ci": 137, - "ucs2_czech_ci": 138, - "ucs2_danish_ci": 139, - "ucs2_lithuanian_ci": 140, - "ucs2_slovak_ci": 141, - "ucs2_spanish2_ci": 142, - "ucs2_roman_ci": 143, - "ucs2_persian_ci": 144, - "ucs2_esperanto_ci": 145, - "ucs2_hungarian_ci": 146, - "ucs2_sinhala_ci": 147, - "ucs2_german2_ci": 148, - "ucs2_croatian_ci": 149, - "ucs2_unicode_520_ci": 150, - "ucs2_vietnamese_ci": 151, - "ucs2_general_mysql500_ci": 159, - "utf32_unicode_ci": 160, - "utf32_icelandic_ci": 161, - "utf32_latvian_ci": 162, - "utf32_romanian_ci": 163, - "utf32_slovenian_ci": 164, - "utf32_polish_ci": 165, - "utf32_estonian_ci": 166, - "utf32_spanish_ci": 167, - "utf32_swedish_ci": 168, - "utf32_turkish_ci": 169, - "utf32_czech_ci": 170, - "utf32_danish_ci": 171, - "utf32_lithuanian_ci": 172, - "utf32_slovak_ci": 173, - "utf32_spanish2_ci": 174, - "utf32_roman_ci": 175, - "utf32_persian_ci": 176, - "utf32_esperanto_ci": 177, - "utf32_hungarian_ci": 178, - "utf32_sinhala_ci": 179, - "utf32_german2_ci": 180, - "utf32_croatian_ci": 181, - "utf32_unicode_520_ci": 182, - "utf32_vietnamese_ci": 183, - "utf8_unicode_ci": 192, - "utf8_icelandic_ci": 193, - "utf8_latvian_ci": 194, - "utf8_romanian_ci": 195, - "utf8_slovenian_ci": 196, - "utf8_polish_ci": 197, - "utf8_estonian_ci": 198, - "utf8_spanish_ci": 199, - "utf8_swedish_ci": 200, - "utf8_turkish_ci": 201, - "utf8_czech_ci": 202, - "utf8_danish_ci": 203, - "utf8_lithuanian_ci": 204, - "utf8_slovak_ci": 205, - "utf8_spanish2_ci": 206, - "utf8_roman_ci": 207, - "utf8_persian_ci": 208, - "utf8_esperanto_ci": 209, - "utf8_hungarian_ci": 210, - "utf8_sinhala_ci": 211, - "utf8_german2_ci": 212, - "utf8_croatian_ci": 213, - "utf8_unicode_520_ci": 214, - "utf8_vietnamese_ci": 215, - "utf8_general_mysql500_ci": 223, - "utf8mb4_unicode_ci": 224, - "utf8mb4_icelandic_ci": 225, - "utf8mb4_latvian_ci": 226, - "utf8mb4_romanian_ci": 227, - "utf8mb4_slovenian_ci": 228, - "utf8mb4_polish_ci": 229, - "utf8mb4_estonian_ci": 230, - "utf8mb4_spanish_ci": 231, - "utf8mb4_swedish_ci": 232, - "utf8mb4_turkish_ci": 233, - "utf8mb4_czech_ci": 234, - "utf8mb4_danish_ci": 235, - "utf8mb4_lithuanian_ci": 236, - "utf8mb4_slovak_ci": 237, - "utf8mb4_spanish2_ci": 238, - "utf8mb4_roman_ci": 239, - "utf8mb4_persian_ci": 240, - "utf8mb4_esperanto_ci": 241, - "utf8mb4_hungarian_ci": 242, - "utf8mb4_sinhala_ci": 243, - "utf8mb4_german2_ci": 244, - "utf8mb4_croatian_ci": 245, - "utf8mb4_unicode_520_ci": 246, - "utf8mb4_vietnamese_ci": 247, -} - -// A blacklist of collations which is unsafe to interpolate parameters. -// These multibyte encodings may contains 0x5c (`\`) in their trailing bytes. -var unsafeCollations = map[string]bool{ - "big5_chinese_ci": true, - "sjis_japanese_ci": true, - "gbk_chinese_ci": true, - "big5_bin": true, - "gb2312_bin": true, - "gbk_bin": true, - "sjis_bin": true, - "cp932_japanese_ci": true, - "cp932_bin": true, -} diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go deleted file mode 100644 index e5706141..00000000 --- a/vendor/github.com/go-sql-driver/mysql/connection.go +++ /dev/null @@ -1,461 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "database/sql/driver" - "io" - "net" - "strconv" - "strings" - "time" -) - -// a copy of context.Context for Go 1.7 and earlier -type mysqlContext interface { - Done() <-chan struct{} - Err() error - - // defined in context.Context, but not used in this driver: - // Deadline() (deadline time.Time, ok bool) - // Value(key interface{}) interface{} -} - -type mysqlConn struct { - buf buffer - netConn net.Conn - affectedRows uint64 - insertId uint64 - cfg *Config - maxAllowedPacket int - maxWriteSize int - writeTimeout time.Duration - flags clientFlag - status statusFlag - sequence uint8 - parseTime bool - - // for context support (Go 1.8+) - watching bool - watcher chan<- mysqlContext - closech chan struct{} - finished chan<- struct{} - canceled atomicError // set non-nil if conn is canceled - closed atomicBool // set when conn is closed, before closech is closed -} - -// Handles parameters set in DSN after the connection is established -func (mc *mysqlConn) handleParams() (err error) { - for param, val := range mc.cfg.Params { - switch param { - // Charset - case "charset": - charsets := strings.Split(val, ",") - for i := range charsets { - // ignore errors here - a charset may not exist - err = mc.exec("SET NAMES " + charsets[i]) - if err == nil { - break - } - } - if err != nil { - return - } - - // System Vars - default: - err = mc.exec("SET " + param + "=" + val + "") - if err != nil { - return - } - } - } - - return -} - -func (mc *mysqlConn) markBadConn(err error) error { - if mc == nil { - return err - } - if err != errBadConnNoWrite { - return err - } - return driver.ErrBadConn -} - -func (mc *mysqlConn) Begin() (driver.Tx, error) { - return mc.begin(false) -} - -func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - var q string - if readOnly { - q = "START TRANSACTION READ ONLY" - } else { - q = "START TRANSACTION" - } - err := mc.exec(q) - if err == nil { - return &mysqlTx{mc}, err - } - return nil, mc.markBadConn(err) -} - -func (mc *mysqlConn) Close() (err error) { - // Makes Close idempotent - if !mc.closed.IsSet() { - err = mc.writeCommandPacket(comQuit) - } - - mc.cleanup() - - return -} - -// Closes the network connection and unsets internal variables. Do not call this -// function after successfully authentication, call Close instead. This function -// is called before auth or on auth failure because MySQL will have already -// closed the network connection. -func (mc *mysqlConn) cleanup() { - if !mc.closed.TrySet(true) { - return - } - - // Makes cleanup idempotent - close(mc.closech) - if mc.netConn == nil { - return - } - if err := mc.netConn.Close(); err != nil { - errLog.Print(err) - } -} - -func (mc *mysqlConn) error() error { - if mc.closed.IsSet() { - if err := mc.canceled.Value(); err != nil { - return err - } - return ErrInvalidConn - } - return nil -} - -func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := mc.writeCommandPacketStr(comStmtPrepare, query) - if err != nil { - return nil, mc.markBadConn(err) - } - - stmt := &mysqlStmt{ - mc: mc, - } - - // Read Result - columnCount, err := stmt.readPrepareResultPacket() - if err == nil { - if stmt.paramCount > 0 { - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if columnCount > 0 { - err = mc.readUntilEOF() - } - } - - return stmt, err -} - -func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) { - // Number of ? should be same to len(args) - if strings.Count(query, "?") != len(args) { - return "", driver.ErrSkip - } - - buf := mc.buf.takeCompleteBuffer() - if buf == nil { - // can not take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return "", ErrInvalidConn - } - buf = buf[:0] - argPos := 0 - - for i := 0; i < len(query); i++ { - q := strings.IndexByte(query[i:], '?') - if q == -1 { - buf = append(buf, query[i:]...) - break - } - buf = append(buf, query[i:i+q]...) - i += q - - arg := args[argPos] - argPos++ - - if arg == nil { - buf = append(buf, "NULL"...) - continue - } - - switch v := arg.(type) { - case int64: - buf = strconv.AppendInt(buf, v, 10) - case float64: - buf = strconv.AppendFloat(buf, v, 'g', -1, 64) - case bool: - if v { - buf = append(buf, '1') - } else { - buf = append(buf, '0') - } - case time.Time: - if v.IsZero() { - buf = append(buf, "'0000-00-00'"...) - } else { - v := v.In(mc.cfg.Loc) - v = v.Add(time.Nanosecond * 500) // To round under microsecond - year := v.Year() - year100 := year / 100 - year1 := year % 100 - month := v.Month() - day := v.Day() - hour := v.Hour() - minute := v.Minute() - second := v.Second() - micro := v.Nanosecond() / 1000 - - buf = append(buf, []byte{ - '\'', - digits10[year100], digits01[year100], - digits10[year1], digits01[year1], - '-', - digits10[month], digits01[month], - '-', - digits10[day], digits01[day], - ' ', - digits10[hour], digits01[hour], - ':', - digits10[minute], digits01[minute], - ':', - digits10[second], digits01[second], - }...) - - if micro != 0 { - micro10000 := micro / 10000 - micro100 := micro / 100 % 100 - micro1 := micro % 100 - buf = append(buf, []byte{ - '.', - digits10[micro10000], digits01[micro10000], - digits10[micro100], digits01[micro100], - digits10[micro1], digits01[micro1], - }...) - } - buf = append(buf, '\'') - } - case []byte: - if v == nil { - buf = append(buf, "NULL"...) - } else { - buf = append(buf, "_binary'"...) - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeBytesBackslash(buf, v) - } else { - buf = escapeBytesQuotes(buf, v) - } - buf = append(buf, '\'') - } - case string: - buf = append(buf, '\'') - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeStringBackslash(buf, v) - } else { - buf = escapeStringQuotes(buf, v) - } - buf = append(buf, '\'') - default: - return "", driver.ErrSkip - } - - if len(buf)+4 > mc.maxAllowedPacket { - return "", driver.ErrSkip - } - } - if argPos != len(args) { - return "", driver.ErrSkip - } - return string(buf), nil -} - -func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - mc.affectedRows = 0 - mc.insertId = 0 - - err := mc.exec(query) - if err == nil { - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, err - } - return nil, mc.markBadConn(err) -} - -// Internal function to execute commands -func (mc *mysqlConn) exec(query string) error { - // Send command - if err := mc.writeCommandPacketStr(comQuery, query); err != nil { - return mc.markBadConn(err) - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - - return mc.discardResults() -} - -func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { - return mc.query(query, args) -} - -func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try client-side prepare to reduce roundtrip - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - // Send command - err := mc.writeCommandPacketStr(comQuery, query) - if err == nil { - // Read Result - var resLen int - resLen, err = mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - - if resLen == 0 { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - // Columns - rows.rs.columns, err = mc.readColumns(resLen) - return rows, err - } - } - return nil, mc.markBadConn(err) -} - -// Gets the value of the given MySQL System Variable -// The returned byte slice is only valid until the next read -func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { - // Send command - if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { - return nil, err - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}} - - if resLen > 0 { - // Columns - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - dest := make([]driver.Value, resLen) - if err = rows.readRow(dest); err == nil { - return dest[0].([]byte), mc.readUntilEOF() - } - } - return nil, err -} - -// finish is called when the query has canceled. -func (mc *mysqlConn) cancel(err error) { - mc.canceled.Set(err) - mc.cleanup() -} - -// finish is called when the query has succeeded. -func (mc *mysqlConn) finish() { - if !mc.watching || mc.finished == nil { - return - } - select { - case mc.finished <- struct{}{}: - mc.watching = false - case <-mc.closech: - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/connection_go18.go b/vendor/github.com/go-sql-driver/mysql/connection_go18.go deleted file mode 100644 index ce52c7d1..00000000 --- a/vendor/github.com/go-sql-driver/mysql/connection_go18.go +++ /dev/null @@ -1,207 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -// +build go1.8 - -package mysql - -import ( - "context" - "database/sql" - "database/sql/driver" -) - -// Ping implements driver.Pinger interface -func (mc *mysqlConn) Ping(ctx context.Context) (err error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - if err = mc.watchCancel(ctx); err != nil { - return - } - defer mc.finish() - - if err = mc.writeCommandPacket(comPing); err != nil { - return - } - - return mc.readResultOK() -} - -// BeginTx implements driver.ConnBeginTx interface -func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault { - level, err := mapIsolationLevel(opts.Isolation) - if err != nil { - return nil, err - } - err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level) - if err != nil { - return nil, err - } - } - - return mc.begin(opts.ReadOnly) -} - -func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := mc.query(query, dargs) - if err != nil { - mc.finish() - return nil, err - } - rows.finish = mc.finish - return rows, err -} - -func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - return mc.Exec(query, dargs) -} - -func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - stmt, err := mc.Prepare(query) - mc.finish() - if err != nil { - return nil, err - } - - select { - default: - case <-ctx.Done(): - stmt.Close() - return nil, ctx.Err() - } - return stmt, nil -} - -func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := stmt.query(dargs) - if err != nil { - stmt.mc.finish() - return nil, err - } - rows.finish = stmt.mc.finish - return rows, err -} - -func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - defer stmt.mc.finish() - - return stmt.Exec(dargs) -} - -func (mc *mysqlConn) watchCancel(ctx context.Context) error { - if mc.watching { - // Reach here if canceled, - // so the connection is already invalid - mc.cleanup() - return nil - } - // When ctx is already cancelled, don't watch it. - if err := ctx.Err(); err != nil { - return err - } - // When ctx is not cancellable, don't watch it. - if ctx.Done() == nil { - return nil - } - // When watcher is not alive, can't watch it. - if mc.watcher == nil { - return nil - } - - mc.watching = true - mc.watcher <- ctx - return nil -} - -func (mc *mysqlConn) startWatcher() { - watcher := make(chan mysqlContext, 1) - mc.watcher = watcher - finished := make(chan struct{}) - mc.finished = finished - go func() { - for { - var ctx mysqlContext - select { - case ctx = <-watcher: - case <-mc.closech: - return - } - - select { - case <-ctx.Done(): - mc.cancel(ctx.Err()) - case <-finished: - case <-mc.closech: - return - } - } - }() -} - -func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) { - nv.Value, err = converter{}.ConvertValue(nv.Value) - return -} - -// ResetSession implements driver.SessionResetter. -// (From Go 1.10) -func (mc *mysqlConn) ResetSession(ctx context.Context) error { - if mc.closed.IsSet() { - return driver.ErrBadConn - } - return nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/const.go b/vendor/github.com/go-sql-driver/mysql/const.go deleted file mode 100644 index b1e6b85e..00000000 --- a/vendor/github.com/go-sql-driver/mysql/const.go +++ /dev/null @@ -1,174 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -const ( - defaultAuthPlugin = "mysql_native_password" - defaultMaxAllowedPacket = 4 << 20 // 4 MiB - minProtocolVersion = 10 - maxPacketSize = 1<<24 - 1 - timeFormat = "2006-01-02 15:04:05.999999" -) - -// MySQL constants documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -const ( - iOK byte = 0x00 - iAuthMoreData byte = 0x01 - iLocalInFile byte = 0xfb - iEOF byte = 0xfe - iERR byte = 0xff -) - -// https://dev.mysql.com/doc/internals/en/capability-flags.html#packet-Protocol::CapabilityFlags -type clientFlag uint32 - -const ( - clientLongPassword clientFlag = 1 << iota - clientFoundRows - clientLongFlag - clientConnectWithDB - clientNoSchema - clientCompress - clientODBC - clientLocalFiles - clientIgnoreSpace - clientProtocol41 - clientInteractive - clientSSL - clientIgnoreSIGPIPE - clientTransactions - clientReserved - clientSecureConn - clientMultiStatements - clientMultiResults - clientPSMultiResults - clientPluginAuth - clientConnectAttrs - clientPluginAuthLenEncClientData - clientCanHandleExpiredPasswords - clientSessionTrack - clientDeprecateEOF -) - -const ( - comQuit byte = iota + 1 - comInitDB - comQuery - comFieldList - comCreateDB - comDropDB - comRefresh - comShutdown - comStatistics - comProcessInfo - comConnect - comProcessKill - comDebug - comPing - comTime - comDelayedInsert - comChangeUser - comBinlogDump - comTableDump - comConnectOut - comRegisterSlave - comStmtPrepare - comStmtExecute - comStmtSendLongData - comStmtClose - comStmtReset - comSetOption - comStmtFetch -) - -// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType -type fieldType byte - -const ( - fieldTypeDecimal fieldType = iota - fieldTypeTiny - fieldTypeShort - fieldTypeLong - fieldTypeFloat - fieldTypeDouble - fieldTypeNULL - fieldTypeTimestamp - fieldTypeLongLong - fieldTypeInt24 - fieldTypeDate - fieldTypeTime - fieldTypeDateTime - fieldTypeYear - fieldTypeNewDate - fieldTypeVarChar - fieldTypeBit -) -const ( - fieldTypeJSON fieldType = iota + 0xf5 - fieldTypeNewDecimal - fieldTypeEnum - fieldTypeSet - fieldTypeTinyBLOB - fieldTypeMediumBLOB - fieldTypeLongBLOB - fieldTypeBLOB - fieldTypeVarString - fieldTypeString - fieldTypeGeometry -) - -type fieldFlag uint16 - -const ( - flagNotNULL fieldFlag = 1 << iota - flagPriKey - flagUniqueKey - flagMultipleKey - flagBLOB - flagUnsigned - flagZeroFill - flagBinary - flagEnum - flagAutoIncrement - flagTimestamp - flagSet - flagUnknown1 - flagUnknown2 - flagUnknown3 - flagUnknown4 -) - -// http://dev.mysql.com/doc/internals/en/status-flags.html -type statusFlag uint16 - -const ( - statusInTrans statusFlag = 1 << iota - statusInAutocommit - statusReserved // Not in documentation - statusMoreResultsExists - statusNoGoodIndexUsed - statusNoIndexUsed - statusCursorExists - statusLastRowSent - statusDbDropped - statusNoBackslashEscapes - statusMetadataChanged - statusQueryWasSlow - statusPsOutParams - statusInTransReadonly - statusSessionStateChanged -) - -const ( - cachingSha2PasswordRequestPublicKey = 2 - cachingSha2PasswordFastAuthSuccess = 3 - cachingSha2PasswordPerformFullAuthentication = 4 -) diff --git a/vendor/github.com/go-sql-driver/mysql/driver.go b/vendor/github.com/go-sql-driver/mysql/driver.go deleted file mode 100644 index e9ede2c8..00000000 --- a/vendor/github.com/go-sql-driver/mysql/driver.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -// Package mysql provides a MySQL driver for Go's database/sql package. -// -// The driver should be used via the database/sql package: -// -// import "database/sql" -// import _ "github.com/go-sql-driver/mysql" -// -// db, err := sql.Open("mysql", "user:password@/dbname") -// -// See https://github.com/go-sql-driver/mysql#usage for details -package mysql - -import ( - "database/sql" - "database/sql/driver" - "net" - "sync" -) - -// watcher interface is used for context support (From Go 1.8) -type watcher interface { - startWatcher() -} - -// MySQLDriver is exported to make the driver directly accessible. -// In general the driver is used via the database/sql package. -type MySQLDriver struct{} - -// DialFunc is a function which can be used to establish the network connection. -// Custom dial functions must be registered with RegisterDial -type DialFunc func(addr string) (net.Conn, error) - -var ( - dialsLock sync.RWMutex - dials map[string]DialFunc -) - -// RegisterDial registers a custom dial function. It can then be used by the -// network address mynet(addr), where mynet is the registered new network. -// addr is passed as a parameter to the dial function. -func RegisterDial(net string, dial DialFunc) { - dialsLock.Lock() - defer dialsLock.Unlock() - if dials == nil { - dials = make(map[string]DialFunc) - } - dials[net] = dial -} - -// Open new Connection. -// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how -// the DSN string is formated -func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { - var err error - - // New mysqlConn - mc := &mysqlConn{ - maxAllowedPacket: maxPacketSize, - maxWriteSize: maxPacketSize - 1, - closech: make(chan struct{}), - } - mc.cfg, err = ParseDSN(dsn) - if err != nil { - return nil, err - } - mc.parseTime = mc.cfg.ParseTime - - // Connect to Server - dialsLock.RLock() - dial, ok := dials[mc.cfg.Net] - dialsLock.RUnlock() - if ok { - mc.netConn, err = dial(mc.cfg.Addr) - } else { - nd := net.Dialer{Timeout: mc.cfg.Timeout} - mc.netConn, err = nd.Dial(mc.cfg.Net, mc.cfg.Addr) - } - if err != nil { - return nil, err - } - - // Enable TCP Keepalives on TCP connections - if tc, ok := mc.netConn.(*net.TCPConn); ok { - if err := tc.SetKeepAlive(true); err != nil { - // Don't send COM_QUIT before handshake. - mc.netConn.Close() - mc.netConn = nil - return nil, err - } - } - - // Call startWatcher for context support (From Go 1.8) - if s, ok := interface{}(mc).(watcher); ok { - s.startWatcher() - } - - mc.buf = newBuffer(mc.netConn) - - // Set I/O timeouts - mc.buf.timeout = mc.cfg.ReadTimeout - mc.writeTimeout = mc.cfg.WriteTimeout - - // Reading Handshake Initialization Packet - authData, plugin, err := mc.readHandshakePacket() - if err != nil { - mc.cleanup() - return nil, err - } - if plugin == "" { - plugin = defaultAuthPlugin - } - - // Send Client Authentication Packet - authResp, err := mc.auth(authData, plugin) - if err != nil { - // try the default auth plugin, if using the requested plugin failed - errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) - plugin = defaultAuthPlugin - authResp, err = mc.auth(authData, plugin) - if err != nil { - mc.cleanup() - return nil, err - } - } - if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil { - mc.cleanup() - return nil, err - } - - // Handle response to auth packet, switch methods if possible - if err = mc.handleAuthResult(authData, plugin); err != nil { - // Authentication failed and MySQL has already closed the connection - // (https://dev.mysql.com/doc/internals/en/authentication-fails.html). - // Do not send COM_QUIT, just cleanup and return the error. - mc.cleanup() - return nil, err - } - - if mc.cfg.MaxAllowedPacket > 0 { - mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket - } else { - // Get max allowed packet size - maxap, err := mc.getSystemVar("max_allowed_packet") - if err != nil { - mc.Close() - return nil, err - } - mc.maxAllowedPacket = stringToInt(maxap) - 1 - } - if mc.maxAllowedPacket < maxPacketSize { - mc.maxWriteSize = mc.maxAllowedPacket - } - - // Handle DSN Params - err = mc.handleParams() - if err != nil { - mc.Close() - return nil, err - } - - return mc, nil -} - -func init() { - sql.Register("mysql", &MySQLDriver{}) -} diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go deleted file mode 100644 index be014bab..00000000 --- a/vendor/github.com/go-sql-driver/mysql/dsn.go +++ /dev/null @@ -1,611 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "crypto/rsa" - "crypto/tls" - "errors" - "fmt" - "net" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -var ( - errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") - errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") - errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") - errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations") -) - -// Config is a configuration parsed from a DSN string. -// If a new Config is created instead of being parsed from a DSN string, -// the NewConfig function should be used, which sets default values. -type Config struct { - User string // Username - Passwd string // Password (requires User) - Net string // Network type - Addr string // Network address (requires Net) - DBName string // Database name - Params map[string]string // Connection parameters - Collation string // Connection collation - Loc *time.Location // Location for time.Time values - MaxAllowedPacket int // Max packet size allowed - ServerPubKey string // Server public key name - pubKey *rsa.PublicKey // Server public key - TLSConfig string // TLS configuration name - tls *tls.Config // TLS configuration - Timeout time.Duration // Dial timeout - ReadTimeout time.Duration // I/O read timeout - WriteTimeout time.Duration // I/O write timeout - - AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE - AllowCleartextPasswords bool // Allows the cleartext client side plugin - AllowNativePasswords bool // Allows the native password authentication method - AllowOldPasswords bool // Allows the old insecure password method - ClientFoundRows bool // Return number of matching rows instead of rows changed - ColumnsWithAlias bool // Prepend table alias to column names - InterpolateParams bool // Interpolate placeholders into query string - MultiStatements bool // Allow multiple statements in one query - ParseTime bool // Parse time values to time.Time - RejectReadOnly bool // Reject read-only connections -} - -// NewConfig creates a new Config and sets default values. -func NewConfig() *Config { - return &Config{ - Collation: defaultCollation, - Loc: time.UTC, - MaxAllowedPacket: defaultMaxAllowedPacket, - AllowNativePasswords: true, - } -} - -func (cfg *Config) normalize() error { - if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { - return errInvalidDSNUnsafeCollation - } - - // Set default network if empty - if cfg.Net == "" { - cfg.Net = "tcp" - } - - // Set default address if empty - if cfg.Addr == "" { - switch cfg.Net { - case "tcp": - cfg.Addr = "127.0.0.1:3306" - case "unix": - cfg.Addr = "/tmp/mysql.sock" - default: - return errors.New("default addr for network '" + cfg.Net + "' unknown") - } - - } else if cfg.Net == "tcp" { - cfg.Addr = ensureHavePort(cfg.Addr) - } - - if cfg.tls != nil { - if cfg.tls.ServerName == "" && !cfg.tls.InsecureSkipVerify { - host, _, err := net.SplitHostPort(cfg.Addr) - if err == nil { - cfg.tls.ServerName = host - } - } - } - - return nil -} - -// FormatDSN formats the given Config into a DSN string which can be passed to -// the driver. -func (cfg *Config) FormatDSN() string { - var buf bytes.Buffer - - // [username[:password]@] - if len(cfg.User) > 0 { - buf.WriteString(cfg.User) - if len(cfg.Passwd) > 0 { - buf.WriteByte(':') - buf.WriteString(cfg.Passwd) - } - buf.WriteByte('@') - } - - // [protocol[(address)]] - if len(cfg.Net) > 0 { - buf.WriteString(cfg.Net) - if len(cfg.Addr) > 0 { - buf.WriteByte('(') - buf.WriteString(cfg.Addr) - buf.WriteByte(')') - } - } - - // /dbname - buf.WriteByte('/') - buf.WriteString(cfg.DBName) - - // [?param1=value1&...¶mN=valueN] - hasParam := false - - if cfg.AllowAllFiles { - hasParam = true - buf.WriteString("?allowAllFiles=true") - } - - if cfg.AllowCleartextPasswords { - if hasParam { - buf.WriteString("&allowCleartextPasswords=true") - } else { - hasParam = true - buf.WriteString("?allowCleartextPasswords=true") - } - } - - if !cfg.AllowNativePasswords { - if hasParam { - buf.WriteString("&allowNativePasswords=false") - } else { - hasParam = true - buf.WriteString("?allowNativePasswords=false") - } - } - - if cfg.AllowOldPasswords { - if hasParam { - buf.WriteString("&allowOldPasswords=true") - } else { - hasParam = true - buf.WriteString("?allowOldPasswords=true") - } - } - - if cfg.ClientFoundRows { - if hasParam { - buf.WriteString("&clientFoundRows=true") - } else { - hasParam = true - buf.WriteString("?clientFoundRows=true") - } - } - - if col := cfg.Collation; col != defaultCollation && len(col) > 0 { - if hasParam { - buf.WriteString("&collation=") - } else { - hasParam = true - buf.WriteString("?collation=") - } - buf.WriteString(col) - } - - if cfg.ColumnsWithAlias { - if hasParam { - buf.WriteString("&columnsWithAlias=true") - } else { - hasParam = true - buf.WriteString("?columnsWithAlias=true") - } - } - - if cfg.InterpolateParams { - if hasParam { - buf.WriteString("&interpolateParams=true") - } else { - hasParam = true - buf.WriteString("?interpolateParams=true") - } - } - - if cfg.Loc != time.UTC && cfg.Loc != nil { - if hasParam { - buf.WriteString("&loc=") - } else { - hasParam = true - buf.WriteString("?loc=") - } - buf.WriteString(url.QueryEscape(cfg.Loc.String())) - } - - if cfg.MultiStatements { - if hasParam { - buf.WriteString("&multiStatements=true") - } else { - hasParam = true - buf.WriteString("?multiStatements=true") - } - } - - if cfg.ParseTime { - if hasParam { - buf.WriteString("&parseTime=true") - } else { - hasParam = true - buf.WriteString("?parseTime=true") - } - } - - if cfg.ReadTimeout > 0 { - if hasParam { - buf.WriteString("&readTimeout=") - } else { - hasParam = true - buf.WriteString("?readTimeout=") - } - buf.WriteString(cfg.ReadTimeout.String()) - } - - if cfg.RejectReadOnly { - if hasParam { - buf.WriteString("&rejectReadOnly=true") - } else { - hasParam = true - buf.WriteString("?rejectReadOnly=true") - } - } - - if len(cfg.ServerPubKey) > 0 { - if hasParam { - buf.WriteString("&serverPubKey=") - } else { - hasParam = true - buf.WriteString("?serverPubKey=") - } - buf.WriteString(url.QueryEscape(cfg.ServerPubKey)) - } - - if cfg.Timeout > 0 { - if hasParam { - buf.WriteString("&timeout=") - } else { - hasParam = true - buf.WriteString("?timeout=") - } - buf.WriteString(cfg.Timeout.String()) - } - - if len(cfg.TLSConfig) > 0 { - if hasParam { - buf.WriteString("&tls=") - } else { - hasParam = true - buf.WriteString("?tls=") - } - buf.WriteString(url.QueryEscape(cfg.TLSConfig)) - } - - if cfg.WriteTimeout > 0 { - if hasParam { - buf.WriteString("&writeTimeout=") - } else { - hasParam = true - buf.WriteString("?writeTimeout=") - } - buf.WriteString(cfg.WriteTimeout.String()) - } - - if cfg.MaxAllowedPacket != defaultMaxAllowedPacket { - if hasParam { - buf.WriteString("&maxAllowedPacket=") - } else { - hasParam = true - buf.WriteString("?maxAllowedPacket=") - } - buf.WriteString(strconv.Itoa(cfg.MaxAllowedPacket)) - - } - - // other params - if cfg.Params != nil { - var params []string - for param := range cfg.Params { - params = append(params, param) - } - sort.Strings(params) - for _, param := range params { - if hasParam { - buf.WriteByte('&') - } else { - hasParam = true - buf.WriteByte('?') - } - - buf.WriteString(param) - buf.WriteByte('=') - buf.WriteString(url.QueryEscape(cfg.Params[param])) - } - } - - return buf.String() -} - -// ParseDSN parses the DSN string to a Config -func ParseDSN(dsn string) (cfg *Config, err error) { - // New config with some default values - cfg = NewConfig() - - // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] - // Find the last '/' (since the password or the net addr might contain a '/') - foundSlash := false - for i := len(dsn) - 1; i >= 0; i-- { - if dsn[i] == '/' { - foundSlash = true - var j, k int - - // left part is empty if i <= 0 - if i > 0 { - // [username[:password]@][protocol[(address)]] - // Find the last '@' in dsn[:i] - for j = i; j >= 0; j-- { - if dsn[j] == '@' { - // username[:password] - // Find the first ':' in dsn[:j] - for k = 0; k < j; k++ { - if dsn[k] == ':' { - cfg.Passwd = dsn[k+1 : j] - break - } - } - cfg.User = dsn[:k] - - break - } - } - - // [protocol[(address)]] - // Find the first '(' in dsn[j+1:i] - for k = j + 1; k < i; k++ { - if dsn[k] == '(' { - // dsn[i-1] must be == ')' if an address is specified - if dsn[i-1] != ')' { - if strings.ContainsRune(dsn[k+1:i], ')') { - return nil, errInvalidDSNUnescaped - } - return nil, errInvalidDSNAddr - } - cfg.Addr = dsn[k+1 : i-1] - break - } - } - cfg.Net = dsn[j+1 : k] - } - - // dbname[?param1=value1&...¶mN=valueN] - // Find the first '?' in dsn[i+1:] - for j = i + 1; j < len(dsn); j++ { - if dsn[j] == '?' { - if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { - return - } - break - } - } - cfg.DBName = dsn[i+1 : j] - - break - } - } - - if !foundSlash && len(dsn) > 0 { - return nil, errInvalidDSNNoSlash - } - - if err = cfg.normalize(); err != nil { - return nil, err - } - return -} - -// parseDSNParams parses the DSN "query string" -// Values must be url.QueryEscape'ed -func parseDSNParams(cfg *Config, params string) (err error) { - for _, v := range strings.Split(params, "&") { - param := strings.SplitN(v, "=", 2) - if len(param) != 2 { - continue - } - - // cfg params - switch value := param[1]; param[0] { - // Disable INFILE whitelist / enable all files - case "allowAllFiles": - var isBool bool - cfg.AllowAllFiles, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use cleartext authentication mode (MySQL 5.5.10+) - case "allowCleartextPasswords": - var isBool bool - cfg.AllowCleartextPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use native password authentication - case "allowNativePasswords": - var isBool bool - cfg.AllowNativePasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use old authentication mode (pre MySQL 4.1) - case "allowOldPasswords": - var isBool bool - cfg.AllowOldPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Switch "rowsAffected" mode - case "clientFoundRows": - var isBool bool - cfg.ClientFoundRows, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Collation - case "collation": - cfg.Collation = value - break - - case "columnsWithAlias": - var isBool bool - cfg.ColumnsWithAlias, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Compression - case "compress": - return errors.New("compression not implemented yet") - - // Enable client side placeholder substitution - case "interpolateParams": - var isBool bool - cfg.InterpolateParams, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Time Location - case "loc": - if value, err = url.QueryUnescape(value); err != nil { - return - } - cfg.Loc, err = time.LoadLocation(value) - if err != nil { - return - } - - // multiple statements in one query - case "multiStatements": - var isBool bool - cfg.MultiStatements, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // time.Time parsing - case "parseTime": - var isBool bool - cfg.ParseTime, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // I/O read Timeout - case "readTimeout": - cfg.ReadTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // Reject read-only connections - case "rejectReadOnly": - var isBool bool - cfg.RejectReadOnly, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Server public key - case "serverPubKey": - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for server pub key name: %v", err) - } - - if pubKey := getServerPubKey(name); pubKey != nil { - cfg.ServerPubKey = name - cfg.pubKey = pubKey - } else { - return errors.New("invalid value / unknown server pub key name: " + name) - } - - // Strict mode - case "strict": - panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode") - - // Dial Timeout - case "timeout": - cfg.Timeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // TLS-Encryption - case "tls": - boolValue, isBool := readBool(value) - if isBool { - if boolValue { - cfg.TLSConfig = "true" - cfg.tls = &tls.Config{} - } else { - cfg.TLSConfig = "false" - } - } else if vl := strings.ToLower(value); vl == "skip-verify" { - cfg.TLSConfig = vl - cfg.tls = &tls.Config{InsecureSkipVerify: true} - } else { - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for TLS config name: %v", err) - } - - if tlsConfig := getTLSConfigClone(name); tlsConfig != nil { - cfg.TLSConfig = name - cfg.tls = tlsConfig - } else { - return errors.New("invalid value / unknown config name: " + name) - } - } - - // I/O write Timeout - case "writeTimeout": - cfg.WriteTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - case "maxAllowedPacket": - cfg.MaxAllowedPacket, err = strconv.Atoi(value) - if err != nil { - return - } - default: - // lazy init - if cfg.Params == nil { - cfg.Params = make(map[string]string) - } - - if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { - return - } - } - } - - return -} - -func ensureHavePort(addr string) string { - if _, _, err := net.SplitHostPort(addr); err != nil { - return net.JoinHostPort(addr, "3306") - } - return addr -} diff --git a/vendor/github.com/go-sql-driver/mysql/errors.go b/vendor/github.com/go-sql-driver/mysql/errors.go deleted file mode 100644 index 760782ff..00000000 --- a/vendor/github.com/go-sql-driver/mysql/errors.go +++ /dev/null @@ -1,65 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "errors" - "fmt" - "log" - "os" -) - -// Various errors the driver might return. Can change between driver versions. -var ( - ErrInvalidConn = errors.New("invalid connection") - ErrMalformPkt = errors.New("malformed packet") - ErrNoTLS = errors.New("TLS requested but server does not support TLS") - ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") - ErrNativePassword = errors.New("this user requires mysql native password authentication.") - ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") - ErrUnknownPlugin = errors.New("this authentication plugin is not supported") - ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") - ErrPktSync = errors.New("commands out of sync. You can't run this command now") - ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") - ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") - ErrBusyBuffer = errors.New("busy buffer") - - // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. - // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn - // to trigger a resend. - // See https://github.com/go-sql-driver/mysql/pull/302 - errBadConnNoWrite = errors.New("bad connection") -) - -var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) - -// Logger is used to log critical error messages. -type Logger interface { - Print(v ...interface{}) -} - -// SetLogger is used to set the logger for critical errors. -// The initial logger is os.Stderr. -func SetLogger(logger Logger) error { - if logger == nil { - return errors.New("logger is nil") - } - errLog = logger - return nil -} - -// MySQLError is an error type which represents a single MySQL error -type MySQLError struct { - Number uint16 - Message string -} - -func (me *MySQLError) Error() string { - return fmt.Sprintf("Error %d: %s", me.Number, me.Message) -} diff --git a/vendor/github.com/go-sql-driver/mysql/fields.go b/vendor/github.com/go-sql-driver/mysql/fields.go deleted file mode 100644 index e1e2ece4..00000000 --- a/vendor/github.com/go-sql-driver/mysql/fields.go +++ /dev/null @@ -1,194 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "database/sql" - "reflect" -) - -func (mf *mysqlField) typeDatabaseName() string { - switch mf.fieldType { - case fieldTypeBit: - return "BIT" - case fieldTypeBLOB: - if mf.charSet != collations[binaryCollation] { - return "TEXT" - } - return "BLOB" - case fieldTypeDate: - return "DATE" - case fieldTypeDateTime: - return "DATETIME" - case fieldTypeDecimal: - return "DECIMAL" - case fieldTypeDouble: - return "DOUBLE" - case fieldTypeEnum: - return "ENUM" - case fieldTypeFloat: - return "FLOAT" - case fieldTypeGeometry: - return "GEOMETRY" - case fieldTypeInt24: - return "MEDIUMINT" - case fieldTypeJSON: - return "JSON" - case fieldTypeLong: - return "INT" - case fieldTypeLongBLOB: - if mf.charSet != collations[binaryCollation] { - return "LONGTEXT" - } - return "LONGBLOB" - case fieldTypeLongLong: - return "BIGINT" - case fieldTypeMediumBLOB: - if mf.charSet != collations[binaryCollation] { - return "MEDIUMTEXT" - } - return "MEDIUMBLOB" - case fieldTypeNewDate: - return "DATE" - case fieldTypeNewDecimal: - return "DECIMAL" - case fieldTypeNULL: - return "NULL" - case fieldTypeSet: - return "SET" - case fieldTypeShort: - return "SMALLINT" - case fieldTypeString: - if mf.charSet == collations[binaryCollation] { - return "BINARY" - } - return "CHAR" - case fieldTypeTime: - return "TIME" - case fieldTypeTimestamp: - return "TIMESTAMP" - case fieldTypeTiny: - return "TINYINT" - case fieldTypeTinyBLOB: - if mf.charSet != collations[binaryCollation] { - return "TINYTEXT" - } - return "TINYBLOB" - case fieldTypeVarChar: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeVarString: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeYear: - return "YEAR" - default: - return "" - } -} - -var ( - scanTypeFloat32 = reflect.TypeOf(float32(0)) - scanTypeFloat64 = reflect.TypeOf(float64(0)) - scanTypeInt8 = reflect.TypeOf(int8(0)) - scanTypeInt16 = reflect.TypeOf(int16(0)) - scanTypeInt32 = reflect.TypeOf(int32(0)) - scanTypeInt64 = reflect.TypeOf(int64(0)) - scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) - scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) - scanTypeNullTime = reflect.TypeOf(NullTime{}) - scanTypeUint8 = reflect.TypeOf(uint8(0)) - scanTypeUint16 = reflect.TypeOf(uint16(0)) - scanTypeUint32 = reflect.TypeOf(uint32(0)) - scanTypeUint64 = reflect.TypeOf(uint64(0)) - scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) - scanTypeUnknown = reflect.TypeOf(new(interface{})) -) - -type mysqlField struct { - tableName string - name string - length uint32 - flags fieldFlag - fieldType fieldType - decimals byte - charSet uint8 -} - -func (mf *mysqlField) scanType() reflect.Type { - switch mf.fieldType { - case fieldTypeTiny: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint8 - } - return scanTypeInt8 - } - return scanTypeNullInt - - case fieldTypeShort, fieldTypeYear: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint16 - } - return scanTypeInt16 - } - return scanTypeNullInt - - case fieldTypeInt24, fieldTypeLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint32 - } - return scanTypeInt32 - } - return scanTypeNullInt - - case fieldTypeLongLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint64 - } - return scanTypeInt64 - } - return scanTypeNullInt - - case fieldTypeFloat: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat32 - } - return scanTypeNullFloat - - case fieldTypeDouble: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat64 - } - return scanTypeNullFloat - - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, - fieldTypeTime: - return scanTypeRawBytes - - case fieldTypeDate, fieldTypeNewDate, - fieldTypeTimestamp, fieldTypeDateTime: - // NullTime is always returned for more consistent behavior as it can - // handle both cases of parseTime regardless if the field is nullable. - return scanTypeNullTime - - default: - return scanTypeUnknown - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/infile.go b/vendor/github.com/go-sql-driver/mysql/infile.go deleted file mode 100644 index 273cb0ba..00000000 --- a/vendor/github.com/go-sql-driver/mysql/infile.go +++ /dev/null @@ -1,182 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "fmt" - "io" - "os" - "strings" - "sync" -) - -var ( - fileRegister map[string]bool - fileRegisterLock sync.RWMutex - readerRegister map[string]func() io.Reader - readerRegisterLock sync.RWMutex -) - -// RegisterLocalFile adds the given file to the file whitelist, -// so that it can be used by "LOAD DATA LOCAL INFILE ". -// Alternatively you can allow the use of all local files with -// the DSN parameter 'allowAllFiles=true' -// -// filePath := "/home/gopher/data.csv" -// mysql.RegisterLocalFile(filePath) -// err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterLocalFile(filePath string) { - fileRegisterLock.Lock() - // lazy map init - if fileRegister == nil { - fileRegister = make(map[string]bool) - } - - fileRegister[strings.Trim(filePath, `"`)] = true - fileRegisterLock.Unlock() -} - -// DeregisterLocalFile removes the given filepath from the whitelist. -func DeregisterLocalFile(filePath string) { - fileRegisterLock.Lock() - delete(fileRegister, strings.Trim(filePath, `"`)) - fileRegisterLock.Unlock() -} - -// RegisterReaderHandler registers a handler function which is used -// to receive a io.Reader. -// The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". -// If the handler returns a io.ReadCloser Close() is called when the -// request is finished. -// -// mysql.RegisterReaderHandler("data", func() io.Reader { -// var csvReader io.Reader // Some Reader that returns CSV data -// ... // Open Reader here -// return csvReader -// }) -// err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterReaderHandler(name string, handler func() io.Reader) { - readerRegisterLock.Lock() - // lazy map init - if readerRegister == nil { - readerRegister = make(map[string]func() io.Reader) - } - - readerRegister[name] = handler - readerRegisterLock.Unlock() -} - -// DeregisterReaderHandler removes the ReaderHandler function with -// the given name from the registry. -func DeregisterReaderHandler(name string) { - readerRegisterLock.Lock() - delete(readerRegister, name) - readerRegisterLock.Unlock() -} - -func deferredClose(err *error, closer io.Closer) { - closeErr := closer.Close() - if *err == nil { - *err = closeErr - } -} - -func (mc *mysqlConn) handleInFileRequest(name string) (err error) { - var rdr io.Reader - var data []byte - packetSize := 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP - if mc.maxWriteSize < packetSize { - packetSize = mc.maxWriteSize - } - - if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader - // The server might return an an absolute path. See issue #355. - name = name[idx+8:] - - readerRegisterLock.RLock() - handler, inMap := readerRegister[name] - readerRegisterLock.RUnlock() - - if inMap { - rdr = handler() - if rdr != nil { - if cl, ok := rdr.(io.Closer); ok { - defer deferredClose(&err, cl) - } - } else { - err = fmt.Errorf("Reader '%s' is ", name) - } - } else { - err = fmt.Errorf("Reader '%s' is not registered", name) - } - } else { // File - name = strings.Trim(name, `"`) - fileRegisterLock.RLock() - fr := fileRegister[name] - fileRegisterLock.RUnlock() - if mc.cfg.AllowAllFiles || fr { - var file *os.File - var fi os.FileInfo - - if file, err = os.Open(name); err == nil { - defer deferredClose(&err, file) - - // get file size - if fi, err = file.Stat(); err == nil { - rdr = file - if fileSize := int(fi.Size()); fileSize < packetSize { - packetSize = fileSize - } - } - } - } else { - err = fmt.Errorf("local file '%s' is not registered", name) - } - } - - // send content packets - // if packetSize == 0, the Reader contains no data - if err == nil && packetSize > 0 { - data := make([]byte, 4+packetSize) - var n int - for err == nil { - n, err = rdr.Read(data[4:]) - if n > 0 { - if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { - return ioErr - } - } - } - if err == io.EOF { - err = nil - } - } - - // send empty packet (termination) - if data == nil { - data = make([]byte, 4) - } - if ioErr := mc.writePacket(data[:4]); ioErr != nil { - return ioErr - } - - // read OK packet - if err == nil { - return mc.readResultOK() - } - - mc.readPacket() - return err -} diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go deleted file mode 100644 index 9ed64085..00000000 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ /dev/null @@ -1,1286 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "crypto/tls" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "time" -) - -// Packets documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -// Read packet to buffer 'data' -func (mc *mysqlConn) readPacket() ([]byte, error) { - var prevData []byte - for { - // read packet header - data, err := mc.buf.readNext(4) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // packet length [24 bit] - pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16) - - // check packet sync [8 bit] - if data[3] != mc.sequence { - if data[3] > mc.sequence { - return nil, ErrPktSyncMul - } - return nil, ErrPktSync - } - mc.sequence++ - - // packets with length 0 terminate a previous packet which is a - // multiple of (2^24)−1 bytes long - if pktLen == 0 { - // there was no previous packet - if prevData == nil { - errLog.Print(ErrMalformPkt) - mc.Close() - return nil, ErrInvalidConn - } - - return prevData, nil - } - - // read packet body [pktLen bytes] - data, err = mc.buf.readNext(pktLen) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // return data if this was the last packet - if pktLen < maxPacketSize { - // zero allocations for non-split packets - if prevData == nil { - return data, nil - } - - return append(prevData, data...), nil - } - - prevData = append(prevData, data...) - } -} - -// Write packet buffer 'data' -func (mc *mysqlConn) writePacket(data []byte) error { - pktLen := len(data) - 4 - - if pktLen > mc.maxAllowedPacket { - return ErrPktTooLarge - } - - for { - var size int - if pktLen >= maxPacketSize { - data[0] = 0xff - data[1] = 0xff - data[2] = 0xff - size = maxPacketSize - } else { - data[0] = byte(pktLen) - data[1] = byte(pktLen >> 8) - data[2] = byte(pktLen >> 16) - size = pktLen - } - data[3] = mc.sequence - - // Write packet - if mc.writeTimeout > 0 { - if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil { - return err - } - } - - n, err := mc.netConn.Write(data[:4+size]) - if err == nil && n == 4+size { - mc.sequence++ - if size != maxPacketSize { - return nil - } - pktLen -= size - data = data[size:] - continue - } - - // Handle error - if err == nil { // n != len(data) - mc.cleanup() - errLog.Print(ErrMalformPkt) - } else { - if cerr := mc.canceled.Value(); cerr != nil { - return cerr - } - if n == 0 && pktLen == len(data)-4 { - // only for the first loop iteration when nothing was written yet - return errBadConnNoWrite - } - mc.cleanup() - errLog.Print(err) - } - return ErrInvalidConn - } -} - -/****************************************************************************** -* Initialization Process * -******************************************************************************/ - -// Handshake Initialization Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake -func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) { - data, err = mc.readPacket() - if err != nil { - // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since - // in connection initialization we don't risk retrying non-idempotent actions. - if err == ErrInvalidConn { - return nil, "", driver.ErrBadConn - } - return - } - - if data[0] == iERR { - return nil, "", mc.handleErrorPacket(data) - } - - // protocol version [1 byte] - if data[0] < minProtocolVersion { - return nil, "", fmt.Errorf( - "unsupported protocol version %d. Version %d or higher is required", - data[0], - minProtocolVersion, - ) - } - - // server version [null terminated string] - // connection id [4 bytes] - pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4 - - // first part of the password cipher [8 bytes] - authData := data[pos : pos+8] - - // (filler) always 0x00 [1 byte] - pos += 8 + 1 - - // capability flags (lower 2 bytes) [2 bytes] - mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - if mc.flags&clientProtocol41 == 0 { - return nil, "", ErrOldProtocol - } - if mc.flags&clientSSL == 0 && mc.cfg.tls != nil { - return nil, "", ErrNoTLS - } - pos += 2 - - if len(data) > pos { - // character set [1 byte] - // status flags [2 bytes] - // capability flags (upper 2 bytes) [2 bytes] - // length of auth-plugin-data [1 byte] - // reserved (all [00]) [10 bytes] - pos += 1 + 2 + 2 + 1 + 10 - - // second part of the password cipher [mininum 13 bytes], - // where len=MAX(13, length of auth-plugin-data - 8) - // - // The web documentation is ambiguous about the length. However, - // according to mysql-5.7/sql/auth/sql_authentication.cc line 538, - // the 13th byte is "\0 byte, terminating the second part of - // a scramble". So the second part of the password cipher is - // a NULL terminated string that's at least 13 bytes with the - // last byte being NULL. - // - // The official Python library uses the fixed length 12 - // which seems to work but technically could have a hidden bug. - authData = append(authData, data[pos:pos+12]...) - pos += 13 - - // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) - // \NUL otherwise - if end := bytes.IndexByte(data[pos:], 0x00); end != -1 { - plugin = string(data[pos : pos+end]) - } else { - plugin = string(data[pos:]) - } - - // make a memory safe copy of the cipher slice - var b [20]byte - copy(b[:], authData) - return b[:], plugin, nil - } - - // make a memory safe copy of the cipher slice - var b [8]byte - copy(b[:], authData) - return b[:], plugin, nil -} - -// Client Authentication Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse -func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error { - // Adjust client flags based on server support - clientFlags := clientProtocol41 | - clientSecureConn | - clientLongPassword | - clientTransactions | - clientLocalFiles | - clientPluginAuth | - clientMultiResults | - mc.flags&clientLongFlag - - if mc.cfg.ClientFoundRows { - clientFlags |= clientFoundRows - } - - // To enable TLS / SSL - if mc.cfg.tls != nil { - clientFlags |= clientSSL - } - - if mc.cfg.MultiStatements { - clientFlags |= clientMultiStatements - } - - // encode length of the auth plugin data - var authRespLEIBuf [9]byte - authRespLen := len(authResp) - authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen)) - if len(authRespLEI) > 1 { - // if the length can not be written in 1 byte, it must be written as a - // length encoded integer - clientFlags |= clientPluginAuthLenEncClientData - } - - pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1 - - // To specify a db name - if n := len(mc.cfg.DBName); n > 0 { - clientFlags |= clientConnectWithDB - pktLen += n + 1 - } - - // Calculate packet length and get buffer with that size - data := mc.buf.takeSmallBuffer(pktLen + 4) - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // ClientFlags [32 bit] - data[4] = byte(clientFlags) - data[5] = byte(clientFlags >> 8) - data[6] = byte(clientFlags >> 16) - data[7] = byte(clientFlags >> 24) - - // MaxPacketSize [32 bit] (none) - data[8] = 0x00 - data[9] = 0x00 - data[10] = 0x00 - data[11] = 0x00 - - // Charset [1 byte] - var found bool - data[12], found = collations[mc.cfg.Collation] - if !found { - // Note possibility for false negatives: - // could be triggered although the collation is valid if the - // collations map does not contain entries the server supports. - return errors.New("unknown collation") - } - - // SSL Connection Request Packet - // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest - if mc.cfg.tls != nil { - // Send TLS / SSL request packet - if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil { - return err - } - - // Switch to TLS - tlsConn := tls.Client(mc.netConn, mc.cfg.tls) - if err := tlsConn.Handshake(); err != nil { - return err - } - mc.netConn = tlsConn - mc.buf.nc = tlsConn - } - - // Filler [23 bytes] (all 0x00) - pos := 13 - for ; pos < 13+23; pos++ { - data[pos] = 0 - } - - // User [null terminated string] - if len(mc.cfg.User) > 0 { - pos += copy(data[pos:], mc.cfg.User) - } - data[pos] = 0x00 - pos++ - - // Auth Data [length encoded integer] - pos += copy(data[pos:], authRespLEI) - pos += copy(data[pos:], authResp) - - // Databasename [null terminated string] - if len(mc.cfg.DBName) > 0 { - pos += copy(data[pos:], mc.cfg.DBName) - data[pos] = 0x00 - pos++ - } - - pos += copy(data[pos:], plugin) - data[pos] = 0x00 - pos++ - - // Send Auth packet - return mc.writePacket(data[:pos]) -} - -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse -func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { - pktLen := 4 + len(authData) - data := mc.buf.takeSmallBuffer(pktLen) - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // Add the auth data [EOF] - copy(data[4:], authData) - return mc.writePacket(data) -} - -/****************************************************************************** -* Command Packets * -******************************************************************************/ - -func (mc *mysqlConn) writeCommandPacket(command byte) error { - // Reset Packet Sequence - mc.sequence = 0 - - data := mc.buf.takeSmallBuffer(4 + 1) - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { - // Reset Packet Sequence - mc.sequence = 0 - - pktLen := 1 + len(arg) - data := mc.buf.takeBuffer(pktLen + 4) - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg - copy(data[5:], arg) - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { - // Reset Packet Sequence - mc.sequence = 0 - - data := mc.buf.takeSmallBuffer(4 + 1 + 4) - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg [32 bit] - data[5] = byte(arg) - data[6] = byte(arg >> 8) - data[7] = byte(arg >> 16) - data[8] = byte(arg >> 24) - - // Send CMD packet - return mc.writePacket(data) -} - -/****************************************************************************** -* Result Packets * -******************************************************************************/ - -func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { - data, err := mc.readPacket() - if err != nil { - return nil, "", err - } - - // packet indicator - switch data[0] { - - case iOK: - return nil, "", mc.handleOkPacket(data) - - case iAuthMoreData: - return data[1:], "", err - - case iEOF: - if len(data) == 1 { - // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest - return nil, "mysql_old_password", nil - } - pluginEndIndex := bytes.IndexByte(data, 0x00) - if pluginEndIndex < 0 { - return nil, "", ErrMalformPkt - } - plugin := string(data[1:pluginEndIndex]) - authData := data[pluginEndIndex+1:] - return authData, plugin, nil - - default: // Error otherwise - return nil, "", mc.handleErrorPacket(data) - } -} - -// Returns error if Packet is not an 'Result OK'-Packet -func (mc *mysqlConn) readResultOK() error { - data, err := mc.readPacket() - if err != nil { - return err - } - - if data[0] == iOK { - return mc.handleOkPacket(data) - } - return mc.handleErrorPacket(data) -} - -// Result Set Header Packet -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset -func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { - data, err := mc.readPacket() - if err == nil { - switch data[0] { - - case iOK: - return 0, mc.handleOkPacket(data) - - case iERR: - return 0, mc.handleErrorPacket(data) - - case iLocalInFile: - return 0, mc.handleInFileRequest(string(data[1:])) - } - - // column count - num, _, n := readLengthEncodedInteger(data) - if n-len(data) == 0 { - return int(num), nil - } - - return 0, ErrMalformPkt - } - return 0, err -} - -// Error Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet -func (mc *mysqlConn) handleErrorPacket(data []byte) error { - if data[0] != iERR { - return ErrMalformPkt - } - - // 0xff [1 byte] - - // Error Number [16 bit uint] - errno := binary.LittleEndian.Uint16(data[1:3]) - - // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION - // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover) - if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly { - // Oops; we are connected to a read-only connection, and won't be able - // to issue any write statements. Since RejectReadOnly is configured, - // we throw away this connection hoping this one would have write - // permission. This is specifically for a possible race condition - // during failover (e.g. on AWS Aurora). See README.md for more. - // - // We explicitly close the connection before returning - // driver.ErrBadConn to ensure that `database/sql` purges this - // connection and initiates a new one for next statement next time. - mc.Close() - return driver.ErrBadConn - } - - pos := 3 - - // SQL State [optional: # + 5bytes string] - if data[3] == 0x23 { - //sqlstate := string(data[4 : 4+5]) - pos = 9 - } - - // Error Message [string] - return &MySQLError{ - Number: errno, - Message: string(data[pos:]), - } -} - -func readStatus(b []byte) statusFlag { - return statusFlag(b[0]) | statusFlag(b[1])<<8 -} - -// Ok Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet -func (mc *mysqlConn) handleOkPacket(data []byte) error { - var n, m int - - // 0x00 [1 byte] - - // Affected rows [Length Coded Binary] - mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) - - // Insert id [Length Coded Binary] - mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) - - // server_status [2 bytes] - mc.status = readStatus(data[1+n+m : 1+n+m+2]) - if mc.status&statusMoreResultsExists != 0 { - return nil - } - - // warning count [2 bytes] - - return nil -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41 -func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { - columns := make([]mysqlField, count) - - for i := 0; ; i++ { - data, err := mc.readPacket() - if err != nil { - return nil, err - } - - // EOF Packet - if data[0] == iEOF && (len(data) == 5 || len(data) == 1) { - if i == count { - return columns, nil - } - return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns)) - } - - // Catalog - pos, err := skipLengthEncodedString(data) - if err != nil { - return nil, err - } - - // Database [len coded string] - n, err := skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Table [len coded string] - if mc.cfg.ColumnsWithAlias { - tableName, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - columns[i].tableName = string(tableName) - } else { - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - } - - // Original table [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Name [len coded string] - name, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - columns[i].name = string(name) - pos += n - - // Original name [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Filler [uint8] - pos++ - - // Charset [charset, collation uint8] - columns[i].charSet = data[pos] - pos += 2 - - // Length [uint32] - columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4]) - pos += 4 - - // Field type [uint8] - columns[i].fieldType = fieldType(data[pos]) - pos++ - - // Flags [uint16] - columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - pos += 2 - - // Decimals [uint8] - columns[i].decimals = data[pos] - //pos++ - - // Default value [len coded binary] - //if pos < len(data) { - // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:]) - //} - } -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow -func (rows *textRows) readRow(dest []driver.Value) error { - mc := rows.mc - - if rows.rs.done { - return io.EOF - } - - data, err := mc.readPacket() - if err != nil { - return err - } - - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - // server_status [2 bytes] - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - if data[0] == iERR { - rows.mc = nil - return mc.handleErrorPacket(data) - } - - // RowSet Packet - var n int - var isNull bool - pos := 0 - - for i := range dest { - // Read bytes and convert to string - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - if !mc.parseTime { - continue - } else { - switch rows.rs.columns[i].fieldType { - case fieldTypeTimestamp, fieldTypeDateTime, - fieldTypeDate, fieldTypeNewDate: - dest[i], err = parseDateTime( - string(dest[i].([]byte)), - mc.cfg.Loc, - ) - if err == nil { - continue - } - default: - continue - } - } - - } else { - dest[i] = nil - continue - } - } - return err // err != nil - } - - return nil -} - -// Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read -func (mc *mysqlConn) readUntilEOF() error { - for { - data, err := mc.readPacket() - if err != nil { - return err - } - - switch data[0] { - case iERR: - return mc.handleErrorPacket(data) - case iEOF: - if len(data) == 5 { - mc.status = readStatus(data[3:]) - } - return nil - } - } -} - -/****************************************************************************** -* Prepared Statements * -******************************************************************************/ - -// Prepare Result Packets -// http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html -func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { - data, err := stmt.mc.readPacket() - if err == nil { - // packet indicator [1 byte] - if data[0] != iOK { - return 0, stmt.mc.handleErrorPacket(data) - } - - // statement id [4 bytes] - stmt.id = binary.LittleEndian.Uint32(data[1:5]) - - // Column count [16 bit uint] - columnCount := binary.LittleEndian.Uint16(data[5:7]) - - // Param count [16 bit uint] - stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9])) - - // Reserved [8 bit] - - // Warning count [16 bit uint] - - return columnCount, nil - } - return 0, err -} - -// http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html -func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error { - maxLen := stmt.mc.maxAllowedPacket - 1 - pktLen := maxLen - - // After the header (bytes 0-3) follows before the data: - // 1 byte command - // 4 bytes stmtID - // 2 bytes paramID - const dataOffset = 1 + 4 + 2 - - // Cannot use the write buffer since - // a) the buffer is too small - // b) it is in use - data := make([]byte, 4+1+4+2+len(arg)) - - copy(data[4+dataOffset:], arg) - - for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset { - if dataOffset+argLen < maxLen { - pktLen = dataOffset + argLen - } - - stmt.mc.sequence = 0 - // Add command byte [1 byte] - data[4] = comStmtSendLongData - - // Add stmtID [32 bit] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // Add paramID [16 bit] - data[9] = byte(paramID) - data[10] = byte(paramID >> 8) - - // Send CMD packet - err := stmt.mc.writePacket(data[:4+pktLen]) - if err == nil { - data = data[pktLen-dataOffset:] - continue - } - return err - - } - - // Reset Packet Sequence - stmt.mc.sequence = 0 - return nil -} - -// Execute Prepared Statement -// http://dev.mysql.com/doc/internals/en/com-stmt-execute.html -func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { - if len(args) != stmt.paramCount { - return fmt.Errorf( - "argument count mismatch (got: %d; has: %d)", - len(args), - stmt.paramCount, - ) - } - - const minPktLen = 4 + 1 + 4 + 1 + 4 - mc := stmt.mc - - // Determine threshould dynamically to avoid packet size shortage. - longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1) - if longDataSize < 64 { - longDataSize = 64 - } - - // Reset packet-sequence - mc.sequence = 0 - - var data []byte - - if len(args) == 0 { - data = mc.buf.takeBuffer(minPktLen) - } else { - data = mc.buf.takeCompleteBuffer() - } - if data == nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(ErrBusyBuffer) - return errBadConnNoWrite - } - - // command [1 byte] - data[4] = comStmtExecute - - // statement_id [4 bytes] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte] - data[9] = 0x00 - - // iteration_count (uint32(1)) [4 bytes] - data[10] = 0x01 - data[11] = 0x00 - data[12] = 0x00 - data[13] = 0x00 - - if len(args) > 0 { - pos := minPktLen - - var nullMask []byte - if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= len(data) { - // buffer has to be extended but we don't know by how much so - // we depend on append after all data with known sizes fit. - // We stop at that because we deal with a lot of columns here - // which makes the required allocation size hard to guess. - tmp := make([]byte, pos+maskLen+typesLen) - copy(tmp[:pos], data[:pos]) - data = tmp - nullMask = data[pos : pos+maskLen] - pos += maskLen - } else { - nullMask = data[pos : pos+maskLen] - for i := 0; i < maskLen; i++ { - nullMask[i] = 0 - } - pos += maskLen - } - - // newParameterBoundFlag 1 [1 byte] - data[pos] = 0x01 - pos++ - - // type of each parameter [len(args)*2 bytes] - paramTypes := data[pos:] - pos += len(args) * 2 - - // value of each parameter [n bytes] - paramValues := data[pos:pos] - valuesCap := cap(paramValues) - - for i, arg := range args { - // build NULL-bitmap - if arg == nil { - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - continue - } - - // cache types and values - switch v := arg.(type) { - case int64: - paramTypes[i+i] = byte(fieldTypeLongLong) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - uint64(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(uint64(v))..., - ) - } - - case float64: - paramTypes[i+i] = byte(fieldTypeDouble) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - math.Float64bits(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(math.Float64bits(v))..., - ) - } - - case bool: - paramTypes[i+i] = byte(fieldTypeTiny) - paramTypes[i+i+1] = 0x00 - - if v { - paramValues = append(paramValues, 0x01) - } else { - paramValues = append(paramValues, 0x00) - } - - case []byte: - // Common case (non-nil value) first - if v != nil { - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, v); err != nil { - return err - } - } - continue - } - - // Handle []byte(nil) as a NULL value - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - - case string: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, []byte(v)); err != nil { - return err - } - } - - case time.Time: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - var a [64]byte - var b = a[:0] - - if v.IsZero() { - b = append(b, "0000-00-00"...) - } else { - b = v.In(mc.cfg.Loc).AppendFormat(b, timeFormat) - } - - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(b)), - ) - paramValues = append(paramValues, b...) - - default: - return fmt.Errorf("cannot convert type: %T", arg) - } - } - - // Check if param values exceeded the available buffer - // In that case we must build the data packet with the new values buffer - if valuesCap != cap(paramValues) { - data = append(data[:pos], paramValues...) - mc.buf.buf = data - } - - pos += len(paramValues) - data = data[:pos] - } - - return mc.writePacket(data) -} - -func (mc *mysqlConn) discardResults() error { - for mc.status&statusMoreResultsExists != 0 { - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - } - return nil -} - -// http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html -func (rows *binaryRows) readRow(dest []driver.Value) error { - data, err := rows.mc.readPacket() - if err != nil { - return err - } - - // packet indicator [1 byte] - if data[0] != iOK { - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - mc := rows.mc - rows.mc = nil - - // Error otherwise - return mc.handleErrorPacket(data) - } - - // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes] - pos := 1 + (len(dest)+7+2)>>3 - nullMask := data[1:pos] - - for i := range dest { - // Field is NULL - // (byte >> bit-pos) % 2 == 1 - if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 { - dest[i] = nil - continue - } - - // Convert to byte-coded string - switch rows.rs.columns[i].fieldType { - case fieldTypeNULL: - dest[i] = nil - continue - - // Numeric Types - case fieldTypeTiny: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(data[pos]) - } else { - dest[i] = int64(int8(data[pos])) - } - pos++ - continue - - case fieldTypeShort, fieldTypeYear: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2])) - } else { - dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2]))) - } - pos += 2 - continue - - case fieldTypeInt24, fieldTypeLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4])) - } else { - dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4]))) - } - pos += 4 - continue - - case fieldTypeLongLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - val := binary.LittleEndian.Uint64(data[pos : pos+8]) - if val > math.MaxInt64 { - dest[i] = uint64ToString(val) - } else { - dest[i] = int64(val) - } - } else { - dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8])) - } - pos += 8 - continue - - case fieldTypeFloat: - dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])) - pos += 4 - continue - - case fieldTypeDouble: - dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8])) - pos += 8 - continue - - // Length coded Binary Strings - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON: - var isNull bool - var n int - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - continue - } else { - dest[i] = nil - continue - } - } - return err - - case - fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD - fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] - fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal] - - num, isNull, n := readLengthEncodedInteger(data[pos:]) - pos += n - - switch { - case isNull: - dest[i] = nil - continue - case rows.rs.columns[i].fieldType == fieldTypeTime: - // database/sql does not support an equivalent to TIME, return a string - var dstlen uint8 - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 8 - case 1, 2, 3, 4, 5, 6: - dstlen = 8 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen) - case rows.mc.parseTime: - dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc) - default: - var dstlen uint8 - if rows.rs.columns[i].fieldType == fieldTypeDate { - dstlen = 10 - } else { - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 19 - case 1, 2, 3, 4, 5, 6: - dstlen = 19 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - } - dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen) - } - - if err == nil { - pos += int(num) - continue - } else { - return err - } - - // Please report if this happens! - default: - return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType) - } - } - - return nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/result.go b/vendor/github.com/go-sql-driver/mysql/result.go deleted file mode 100644 index c6438d03..00000000 --- a/vendor/github.com/go-sql-driver/mysql/result.go +++ /dev/null @@ -1,22 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -type mysqlResult struct { - affectedRows int64 - insertId int64 -} - -func (res *mysqlResult) LastInsertId() (int64, error) { - return res.insertId, nil -} - -func (res *mysqlResult) RowsAffected() (int64, error) { - return res.affectedRows, nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/rows.go b/vendor/github.com/go-sql-driver/mysql/rows.go deleted file mode 100644 index d3b1e282..00000000 --- a/vendor/github.com/go-sql-driver/mysql/rows.go +++ /dev/null @@ -1,216 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "database/sql/driver" - "io" - "math" - "reflect" -) - -type resultSet struct { - columns []mysqlField - columnNames []string - done bool -} - -type mysqlRows struct { - mc *mysqlConn - rs resultSet - finish func() -} - -type binaryRows struct { - mysqlRows -} - -type textRows struct { - mysqlRows -} - -func (rows *mysqlRows) Columns() []string { - if rows.rs.columnNames != nil { - return rows.rs.columnNames - } - - columns := make([]string, len(rows.rs.columns)) - if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { - for i := range columns { - if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { - columns[i] = tableName + "." + rows.rs.columns[i].name - } else { - columns[i] = rows.rs.columns[i].name - } - } - } else { - for i := range columns { - columns[i] = rows.rs.columns[i].name - } - } - - rows.rs.columnNames = columns - return columns -} - -func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { - return rows.rs.columns[i].typeDatabaseName() -} - -// func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { -// return int64(rows.rs.columns[i].length), true -// } - -func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { - return rows.rs.columns[i].flags&flagNotNULL == 0, true -} - -func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { - column := rows.rs.columns[i] - decimals := int64(column.decimals) - - switch column.fieldType { - case fieldTypeDecimal, fieldTypeNewDecimal: - if decimals > 0 { - return int64(column.length) - 2, decimals, true - } - return int64(column.length) - 1, decimals, true - case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: - return decimals, decimals, true - case fieldTypeFloat, fieldTypeDouble: - if decimals == 0x1f { - return math.MaxInt64, math.MaxInt64, true - } - return math.MaxInt64, decimals, true - } - - return 0, 0, false -} - -func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { - return rows.rs.columns[i].scanType() -} - -func (rows *mysqlRows) Close() (err error) { - if f := rows.finish; f != nil { - f() - rows.finish = nil - } - - mc := rows.mc - if mc == nil { - return nil - } - if err := mc.error(); err != nil { - return err - } - - // Remove unread packets from stream - if !rows.rs.done { - err = mc.readUntilEOF() - } - if err == nil { - if err = mc.discardResults(); err != nil { - return err - } - } - - rows.mc = nil - return err -} - -func (rows *mysqlRows) HasNextResultSet() (b bool) { - if rows.mc == nil { - return false - } - return rows.mc.status&statusMoreResultsExists != 0 -} - -func (rows *mysqlRows) nextResultSet() (int, error) { - if rows.mc == nil { - return 0, io.EOF - } - if err := rows.mc.error(); err != nil { - return 0, err - } - - // Remove unread packets from stream - if !rows.rs.done { - if err := rows.mc.readUntilEOF(); err != nil { - return 0, err - } - rows.rs.done = true - } - - if !rows.HasNextResultSet() { - rows.mc = nil - return 0, io.EOF - } - rows.rs = resultSet{} - return rows.mc.readResultSetHeaderPacket() -} - -func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { - for { - resLen, err := rows.nextResultSet() - if err != nil { - return 0, err - } - - if resLen > 0 { - return resLen, nil - } - - rows.rs.done = true - } -} - -func (rows *binaryRows) NextResultSet() error { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *binaryRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} - -func (rows *textRows) NextResultSet() (err error) { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *textRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go deleted file mode 100644 index ce7fe4cd..00000000 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ /dev/null @@ -1,211 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "database/sql/driver" - "fmt" - "io" - "reflect" - "strconv" -) - -type mysqlStmt struct { - mc *mysqlConn - id uint32 - paramCount int -} - -func (stmt *mysqlStmt) Close() error { - if stmt.mc == nil || stmt.mc.closed.IsSet() { - // driver.Stmt.Close can be called more than once, thus this function - // has to be idempotent. - // See also Issue #450 and golang/go#16019. - //errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) - stmt.mc = nil - return err -} - -func (stmt *mysqlStmt) NumInput() int { - return stmt.paramCount -} - -func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { - return converter{} -} - -func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - mc.affectedRows = 0 - mc.insertId = 0 - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - if resLen > 0 { - // Columns - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - - // Rows - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if err := mc.discardResults(); err != nil { - return nil, err - } - - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, nil -} - -func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { - return stmt.query(args) -} - -func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - rows := new(binaryRows) - - if resLen > 0 { - rows.mc = mc - rows.rs.columns, err = mc.readColumns(resLen) - } else { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - return rows, err -} - -type converter struct{} - -// ConvertValue mirrors the reference/default converter in database/sql/driver -// with _one_ exception. We support uint64 with their high bit and the default -// implementation does not. This function should be kept in sync with -// database/sql/driver defaultConverter.ConvertValue() except for that -// deliberate difference. -func (c converter) ConvertValue(v interface{}) (driver.Value, error) { - if driver.IsValue(v) { - return v, nil - } - - if vr, ok := v.(driver.Valuer); ok { - sv, err := callValuerValue(vr) - if err != nil { - return nil, err - } - if !driver.IsValue(sv) { - return nil, fmt.Errorf("non-Value type %T returned from Value", sv) - } - return sv, nil - } - - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Ptr: - // indirect pointers - if rv.IsNil() { - return nil, nil - } else { - return c.ConvertValue(rv.Elem().Interface()) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int(), nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: - return int64(rv.Uint()), nil - case reflect.Uint64: - u64 := rv.Uint() - if u64 >= 1<<63 { - return strconv.FormatUint(u64, 10), nil - } - return int64(u64), nil - case reflect.Float32, reflect.Float64: - return rv.Float(), nil - case reflect.Bool: - return rv.Bool(), nil - case reflect.Slice: - ek := rv.Type().Elem().Kind() - if ek == reflect.Uint8 { - return rv.Bytes(), nil - } - return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, ek) - case reflect.String: - return rv.String(), nil - } - return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) -} - -var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() - -// callValuerValue returns vr.Value(), with one exception: -// If vr.Value is an auto-generated method on a pointer type and the -// pointer is nil, it would panic at runtime in the panicwrap -// method. Treat it like nil instead. -// -// This is so people can implement driver.Value on value types and -// still use nil pointers to those types to mean nil/NULL, just like -// string/*string. -// -// This is an exact copy of the same-named unexported function from the -// database/sql package. -func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { - if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && - rv.IsNil() && - rv.Type().Elem().Implements(valuerReflectType) { - return nil, nil - } - return vr.Value() -} diff --git a/vendor/github.com/go-sql-driver/mysql/transaction.go b/vendor/github.com/go-sql-driver/mysql/transaction.go deleted file mode 100644 index 417d7279..00000000 --- a/vendor/github.com/go-sql-driver/mysql/transaction.go +++ /dev/null @@ -1,31 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -type mysqlTx struct { - mc *mysqlConn -} - -func (tx *mysqlTx) Commit() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("COMMIT") - tx.mc = nil - return -} - -func (tx *mysqlTx) Rollback() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("ROLLBACK") - tx.mc = nil - return -} diff --git a/vendor/github.com/go-sql-driver/mysql/utils.go b/vendor/github.com/go-sql-driver/mysql/utils.go deleted file mode 100644 index ca5d47d8..00000000 --- a/vendor/github.com/go-sql-driver/mysql/utils.go +++ /dev/null @@ -1,726 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "crypto/tls" - "database/sql/driver" - "encoding/binary" - "fmt" - "io" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// Registry for custom tls.Configs -var ( - tlsConfigLock sync.RWMutex - tlsConfigRegistry map[string]*tls.Config -) - -// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. -// Use the key as a value in the DSN where tls=value. -// -// Note: The provided tls.Config is exclusively owned by the driver after -// registering it. -// -// rootCertPool := x509.NewCertPool() -// pem, err := ioutil.ReadFile("/path/ca-cert.pem") -// if err != nil { -// log.Fatal(err) -// } -// if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { -// log.Fatal("Failed to append PEM.") -// } -// clientCert := make([]tls.Certificate, 0, 1) -// certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem") -// if err != nil { -// log.Fatal(err) -// } -// clientCert = append(clientCert, certs) -// mysql.RegisterTLSConfig("custom", &tls.Config{ -// RootCAs: rootCertPool, -// Certificates: clientCert, -// }) -// db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom") -// -func RegisterTLSConfig(key string, config *tls.Config) error { - if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" { - return fmt.Errorf("key '%s' is reserved", key) - } - - tlsConfigLock.Lock() - if tlsConfigRegistry == nil { - tlsConfigRegistry = make(map[string]*tls.Config) - } - - tlsConfigRegistry[key] = config - tlsConfigLock.Unlock() - return nil -} - -// DeregisterTLSConfig removes the tls.Config associated with key. -func DeregisterTLSConfig(key string) { - tlsConfigLock.Lock() - if tlsConfigRegistry != nil { - delete(tlsConfigRegistry, key) - } - tlsConfigLock.Unlock() -} - -func getTLSConfigClone(key string) (config *tls.Config) { - tlsConfigLock.RLock() - if v, ok := tlsConfigRegistry[key]; ok { - config = cloneTLSConfig(v) - } - tlsConfigLock.RUnlock() - return -} - -// Returns the bool value of the input. -// The 2nd return value indicates if the input was a valid bool value -func readBool(input string) (value bool, valid bool) { - switch input { - case "1", "true", "TRUE", "True": - return true, true - case "0", "false", "FALSE", "False": - return false, true - } - - // Not a valid bool value - return -} - -/****************************************************************************** -* Time related utils * -******************************************************************************/ - -// NullTime represents a time.Time that may be NULL. -// NullTime implements the Scanner interface so -// it can be used as a scan destination: -// -// var nt NullTime -// err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt) -// ... -// if nt.Valid { -// // use nt.Time -// } else { -// // NULL value -// } -// -// This NullTime implementation is not driver-specific -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -// Scan implements the Scanner interface. -// The value type must be time.Time or string / []byte (formatted time-string), -// otherwise Scan fails. -func (nt *NullTime) Scan(value interface{}) (err error) { - if value == nil { - nt.Time, nt.Valid = time.Time{}, false - return - } - - switch v := value.(type) { - case time.Time: - nt.Time, nt.Valid = v, true - return - case []byte: - nt.Time, err = parseDateTime(string(v), time.UTC) - nt.Valid = (err == nil) - return - case string: - nt.Time, err = parseDateTime(v, time.UTC) - nt.Valid = (err == nil) - return - } - - nt.Valid = false - return fmt.Errorf("Can't convert %T to time.Time", value) -} - -// Value implements the driver Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} - -func parseDateTime(str string, loc *time.Location) (t time.Time, err error) { - base := "0000-00-00 00:00:00.0000000" - switch len(str) { - case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM" - if str == base[:len(str)] { - return - } - t, err = time.Parse(timeFormat[:len(str)], str) - default: - err = fmt.Errorf("invalid time string: %s", str) - return - } - - // Adjust location - if err == nil && loc != time.UTC { - y, mo, d := t.Date() - h, mi, s := t.Clock() - t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil - } - - return -} - -func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { - switch num { - case 0: - return time.Time{}, nil - case 4: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - 0, 0, 0, 0, - loc, - ), nil - case 7: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - 0, - loc, - ), nil - case 11: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds - loc, - ), nil - } - return nil, fmt.Errorf("invalid DATETIME packet length %d", num) -} - -// zeroDateTime is used in formatBinaryDateTime to avoid an allocation -// if the DATE or DATETIME has the zero value. -// It must never be changed. -// The current behavior depends on database/sql copying the result. -var zeroDateTime = []byte("0000-00-00 00:00:00.000000") - -const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" -const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" - -func appendMicrosecs(dst, src []byte, decimals int) []byte { - if decimals <= 0 { - return dst - } - if len(src) == 0 { - return append(dst, ".000000"[:decimals+1]...) - } - - microsecs := binary.LittleEndian.Uint32(src[:4]) - p1 := byte(microsecs / 10000) - microsecs -= 10000 * uint32(p1) - p2 := byte(microsecs / 100) - microsecs -= 100 * uint32(p2) - p3 := byte(microsecs) - - switch decimals { - default: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], digits01[p3], - ) - case 1: - return append(dst, '.', - digits10[p1], - ) - case 2: - return append(dst, '.', - digits10[p1], digits01[p1], - ) - case 3: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], - ) - case 4: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - ) - case 5: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], - ) - } -} - -func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[:length], nil - } - var dst []byte // return value - var p1, p2, p3 byte // current digit pair - - switch length { - case 10, 19, 21, 22, 23, 24, 25, 26: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s length %d", t, length) - } - switch len(src) { - case 4, 7, 11: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s packet length %d", t, len(src)) - } - dst = make([]byte, 0, length) - // start with the date - year := binary.LittleEndian.Uint16(src[:2]) - pt := year / 100 - p1 = byte(year - 100*uint16(pt)) - p2, p3 = src[2], src[3] - dst = append(dst, - digits10[pt], digits01[pt], - digits10[p1], digits01[p1], '-', - digits10[p2], digits01[p2], '-', - digits10[p3], digits01[p3], - ) - if length == 10 { - return dst, nil - } - if len(src) == 4 { - return append(dst, zeroDateTime[10:length]...), nil - } - dst = append(dst, ' ') - p1 = src[4] // hour - src = src[5:] - - // p1 is 2-digit hour, src is after hour - p2, p3 = src[0], src[1] - dst = append(dst, - digits10[p1], digits01[p1], ':', - digits10[p2], digits01[p2], ':', - digits10[p3], digits01[p3], - ) - return appendMicrosecs(dst, src[2:], int(length)-20), nil -} - -func formatBinaryTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[11 : 11+length], nil - } - var dst []byte // return value - - switch length { - case - 8, // time (can be up to 10 when negative and 100+ hours) - 10, 11, 12, 13, 14, 15: // time with fractional seconds - default: - return nil, fmt.Errorf("illegal TIME length %d", length) - } - switch len(src) { - case 8, 12: - default: - return nil, fmt.Errorf("invalid TIME packet length %d", len(src)) - } - // +2 to enable negative time and 100+ hours - dst = make([]byte, 0, length+2) - if src[0] == 1 { - dst = append(dst, '-') - } - days := binary.LittleEndian.Uint32(src[1:5]) - hours := int64(days)*24 + int64(src[5]) - - if hours >= 100 { - dst = strconv.AppendInt(dst, hours, 10) - } else { - dst = append(dst, digits10[hours], digits01[hours]) - } - - min, sec := src[6], src[7] - dst = append(dst, ':', - digits10[min], digits01[min], ':', - digits10[sec], digits01[sec], - ) - return appendMicrosecs(dst, src[8:], int(length)-9), nil -} - -/****************************************************************************** -* Convert from and to bytes * -******************************************************************************/ - -func uint64ToBytes(n uint64) []byte { - return []byte{ - byte(n), - byte(n >> 8), - byte(n >> 16), - byte(n >> 24), - byte(n >> 32), - byte(n >> 40), - byte(n >> 48), - byte(n >> 56), - } -} - -func uint64ToString(n uint64) []byte { - var a [20]byte - i := 20 - - // U+0030 = 0 - // ... - // U+0039 = 9 - - var q uint64 - for n >= 10 { - i-- - q = n / 10 - a[i] = uint8(n-q*10) + 0x30 - n = q - } - - i-- - a[i] = uint8(n) + 0x30 - - return a[i:] -} - -// treats string value as unsigned integer representation -func stringToInt(b []byte) int { - val := 0 - for i := range b { - val *= 10 - val += int(b[i] - 0x30) - } - return val -} - -// returns the string read as a bytes slice, wheter the value is NULL, -// the number of bytes read and an error, in case the string is longer than -// the input slice -func readLengthEncodedString(b []byte) ([]byte, bool, int, error) { - // Get length - num, isNull, n := readLengthEncodedInteger(b) - if num < 1 { - return b[n:n], isNull, n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return b[n-int(num) : n : n], false, n, nil - } - return nil, false, n, io.EOF -} - -// returns the number of bytes skipped and an error, in case the string is -// longer than the input slice -func skipLengthEncodedString(b []byte) (int, error) { - // Get length - num, _, n := readLengthEncodedInteger(b) - if num < 1 { - return n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return n, nil - } - return n, io.EOF -} - -// returns the number read, whether the value is NULL and the number of bytes read -func readLengthEncodedInteger(b []byte) (uint64, bool, int) { - // See issue #349 - if len(b) == 0 { - return 0, true, 1 - } - - switch b[0] { - // 251: NULL - case 0xfb: - return 0, true, 1 - - // 252: value of following 2 - case 0xfc: - return uint64(b[1]) | uint64(b[2])<<8, false, 3 - - // 253: value of following 3 - case 0xfd: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 - - // 254: value of following 8 - case 0xfe: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 | - uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 | - uint64(b[7])<<48 | uint64(b[8])<<56, - false, 9 - } - - // 0-250: value of first byte - return uint64(b[0]), false, 1 -} - -// encodes a uint64 value and appends it to the given bytes slice -func appendLengthEncodedInteger(b []byte, n uint64) []byte { - switch { - case n <= 250: - return append(b, byte(n)) - - case n <= 0xffff: - return append(b, 0xfc, byte(n), byte(n>>8)) - - case n <= 0xffffff: - return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16)) - } - return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24), - byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) -} - -// reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. -// If cap(buf) is not enough, reallocate new buffer. -func reserveBuffer(buf []byte, appendSize int) []byte { - newSize := len(buf) + appendSize - if cap(buf) < newSize { - // Grow buffer exponentially - newBuf := make([]byte, len(buf)*2+appendSize) - copy(newBuf, buf) - buf = newBuf - } - return buf[:newSize] -} - -// escapeBytesBackslash escapes []byte with backslashes (\) -// This escapes the contents of a string (provided as []byte) by adding backslashes before special -// characters, and turning others into specific escape sequences, such as -// turning newlines into \n and null bytes into \0. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932 -func escapeBytesBackslash(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringBackslash is similar to escapeBytesBackslash but for string. -func escapeStringBackslash(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeBytesQuotes escapes apostrophes in []byte by doubling them up. -// This escapes the contents of a string by doubling up any apostrophes that -// it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in -// effect on the server. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038 -func escapeBytesQuotes(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringQuotes is similar to escapeBytesQuotes but for string. -func escapeStringQuotes(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -/****************************************************************************** -* Sync utils * -******************************************************************************/ - -// noCopy may be embedded into structs which must not be copied -// after the first use. -// -// See https://github.com/golang/go/issues/8005#issuecomment-190753527 -// for details. -type noCopy struct{} - -// Lock is a no-op used by -copylocks checker from `go vet`. -func (*noCopy) Lock() {} - -// atomicBool is a wrapper around uint32 for usage as a boolean value with -// atomic access. -type atomicBool struct { - _noCopy noCopy - value uint32 -} - -// IsSet returns wether the current boolean value is true -func (ab *atomicBool) IsSet() bool { - return atomic.LoadUint32(&ab.value) > 0 -} - -// Set sets the value of the bool regardless of the previous value -func (ab *atomicBool) Set(value bool) { - if value { - atomic.StoreUint32(&ab.value, 1) - } else { - atomic.StoreUint32(&ab.value, 0) - } -} - -// TrySet sets the value of the bool and returns wether the value changed -func (ab *atomicBool) TrySet(value bool) bool { - if value { - return atomic.SwapUint32(&ab.value, 1) == 0 - } - return atomic.SwapUint32(&ab.value, 0) > 0 -} - -// atomicError is a wrapper for atomically accessed error values -type atomicError struct { - _noCopy noCopy - value atomic.Value -} - -// Set sets the error value regardless of the previous value. -// The value must not be nil -func (ae *atomicError) Set(value error) { - ae.value.Store(value) -} - -// Value returns the current error value -func (ae *atomicError) Value() error { - if v := ae.value.Load(); v != nil { - // this will panic if the value doesn't implement the error interface - return v.(error) - } - return nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/utils_go17.go b/vendor/github.com/go-sql-driver/mysql/utils_go17.go deleted file mode 100644 index f5956345..00000000 --- a/vendor/github.com/go-sql-driver/mysql/utils_go17.go +++ /dev/null @@ -1,40 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -// +build go1.7 -// +build !go1.8 - -package mysql - -import "crypto/tls" - -func cloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/utils_go18.go b/vendor/github.com/go-sql-driver/mysql/utils_go18.go deleted file mode 100644 index c35c2a6a..00000000 --- a/vendor/github.com/go-sql-driver/mysql/utils_go18.go +++ /dev/null @@ -1,50 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -// +build go1.8 - -package mysql - -import ( - "crypto/tls" - "database/sql" - "database/sql/driver" - "errors" - "fmt" -) - -func cloneTLSConfig(c *tls.Config) *tls.Config { - return c.Clone() -} - -func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) { - dargs := make([]driver.Value, len(named)) - for n, param := range named { - if len(param.Name) > 0 { - // TODO: support the use of Named Parameters #561 - return nil, errors.New("mysql: driver does not support the use of Named Parameters") - } - dargs[n] = param.Value - } - return dargs, nil -} - -func mapIsolationLevel(level driver.IsolationLevel) (string, error) { - switch sql.IsolationLevel(level) { - case sql.LevelRepeatableRead: - return "REPEATABLE READ", nil - case sql.LevelReadCommitted: - return "READ COMMITTED", nil - case sql.LevelReadUncommitted: - return "READ UNCOMMITTED", nil - case sql.LevelSerializable: - return "SERIALIZABLE", nil - default: - return "", fmt.Errorf("mysql: unsupported isolation level: %v", level) - } -} diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/vendor/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/vendor/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f646931..00000000 --- a/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index 3cd3249f..00000000 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,253 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // Required and optional fields that are set in src will be set to that value in dst. - // Elements of repeated fields will be appended. - // - // Merge may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index 63b0f08b..00000000 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,427 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go deleted file mode 100644 index 35b882c0..00000000 --- a/vendor/github.com/golang/protobuf/proto/deprecated.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import "errors" - -// Deprecated: do not use. -type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } - -// Deprecated: do not use. -func GetStats() Stats { return Stats{} } - -// Deprecated: do not use. -func MarshalMessageSet(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: do not use. -func UnmarshalMessageSet([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: do not use. -func MarshalMessageSetJSON(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: do not use. -func UnmarshalMessageSetJSON([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: do not use. -func RegisterMessageSetType(Message, int32, string) {} diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index dea2617c..00000000 --- a/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,350 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. -func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di - } - return di -} - -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) - } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } - } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - vf := v.Field(i) - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 3abfed2c..00000000 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,203 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "reflect" -) - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index f9b6e41b..00000000 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,301 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - return bytes.Equal(u1, u2) -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1 := extensionAsLegacyType(e1.value) - m2 := extensionAsLegacyType(e2.value) - - if m1 == nil && m2 == nil { - // Both have only encoded form. - if bytes.Equal(e1.enc, e2.enc) { - continue - } - // The bytes are different, but the extensions might still be - // equal. We need to decode them to compare. - } - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - // If both have only encoded form and the bytes are the same, - // it is handled above. We get here when the bytes are different. - // We don't know how to decode it, so just compare them as byte - // slices. - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - return false - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index fa88add3..00000000 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,607 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "io" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} - -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} - -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} - -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} - -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} - -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, error) { - switch p := p.(type) { - case extendableProto: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return p, nil - case extendableProtoV1: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return extensionAdapter{p}, nil - } - // Don't allocate a specific error containing %T: - // this is the hot path for Clone and MarshalText. - return nil, errNotExtendable -} - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -func isNilPtr(x interface{}) bool { - v := reflect.ValueOf(x) - return v.Kind() == reflect.Ptr && v.IsNil() -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension - } -} - -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension - }) - e.p.extensionMap = make(map[int32]Extension) - } - return e.p.extensionMap -} - -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil - } - return e.p.extensionMap, &e.p.mu -} - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - - // value is a concrete value for the extension field. Let the type of - // desc.ExtensionType be the "API type" and the type of Extension.value - // be the "storage type". The API type and storage type are the same except: - // * For scalars (except []byte), the API type uses *T, - // while the storage type uses T. - // * For repeated fields, the API type uses []T, while the storage type - // uses *[]T. - // - // The reason for the divergence is so that the storage type more naturally - // matches what is expected of when retrieving the values through the - // protobuf reflection APIs. - // - // The value may only be populated if desc is also populated. - value interface{} - - // enc is the raw bytes for the extension field. - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, err := extendable(base) - if err != nil { - return - } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, err := extendable(pb) - if err != nil { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false - } - mu.Lock() - _, ok := extmap[extension.Field] - mu.Unlock() - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, err := extendable(pb) - if err != nil { - return - } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) -} - -// GetExtension retrieves a proto2 extended field from pb. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes of the field extension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - - if extension.ExtendedType != nil { - // can only check type if this is a complete descriptor - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err - } - } - - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return extensionAsLegacyType(e.value), nil - } - - if extension.ExtensionType == nil { - // incomplete descriptor - return e.enc, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = extensionAsStorageType(v) - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return extensionAsLegacyType(e.value), nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - if extension.ExtensionType == nil { - // incomplete descriptor, so no default - return nil, ErrMissingExtension - } - - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - unmarshal := typeUnmarshaler(t, extension.Tag) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate space to store the pointer/slice. - value := reflect.New(t).Elem() - - var err error - for { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - wire := int(x) & 7 - - b, err = unmarshal(b, valToPointer(value.Addr()), wire) - if err != nil { - return nil, err - } - - if len(b) == 0 { - break - } - } - return value.Interface(), nil -} - -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - registeredExtensions := RegisteredExtensions(pb) - - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil - } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } - } - - extensions = append(extensions, desc) - } - return extensions, nil -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, err := extendable(pb) - if err != nil { - return err - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType) - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: extensionAsStorageType(value)} - return nil -} - -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, err := extendable(pb) - if err != nil { - return - } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) - } -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} - -// extensionAsLegacyType converts an value in the storage type as the API type. -// See Extension.value. -func extensionAsLegacyType(v interface{}) interface{} { - switch rv := reflect.ValueOf(v); rv.Kind() { - case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - // Represent primitive types as a pointer to the value. - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() - case reflect.Ptr: - // Represent slice types as the value itself. - switch rv.Type().Elem().Kind() { - case reflect.Slice: - if rv.IsNil() { - v = reflect.Zero(rv.Type().Elem()).Interface() - } else { - v = rv.Elem().Interface() - } - } - } - return v -} - -// extensionAsStorageType converts an value in the API type as the storage type. -// See Extension.value. -func extensionAsStorageType(v interface{}) interface{} { - switch rv := reflect.ValueOf(v); rv.Kind() { - case reflect.Ptr: - // Represent slice types as the value itself. - switch rv.Type().Elem().Kind() { - case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - if rv.IsNil() { - v = reflect.Zero(rv.Type().Elem()).Interface() - } else { - v = rv.Elem().Interface() - } - } - case reflect.Slice: - // Represent slice types as a pointer to the value. - if rv.Type().Elem().Kind() != reflect.Uint8 { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() - } - } - return v -} diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index fdd328bb..00000000 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,965 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. -// Marshal reports this when a required field is not initialized. -// Unmarshal reports this when a required field is missing from the wire data. -type RequiredNotSetError struct{ field string } - -func (e *RequiredNotSetError) Error() string { - if e.field == "" { - return fmt.Sprintf("proto: required field not set") - } - return fmt.Sprintf("proto: required field %q not set", e.field) -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -type invalidUTF8Error struct{ field string } - -func (e *invalidUTF8Error) Error() string { - if e.field == "" { - return "proto: invalid UTF-8 detected" - } - return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) -} -func (e *invalidUTF8Error) InvalidUTF8() bool { - return true -} - -// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. -// This error should not be exposed to the external API as such errors should -// be recreated with the field information. -var errInvalidUTF8 = &invalidUTF8Error{} - -// isNonFatal reports whether the error is either a RequiredNotSet error -// or a InvalidUTF8 error. -func isNonFatal(err error) bool { - if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { - return true - } - if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { - return true - } - return false -} - -type nonFatal struct{ E error } - -// Merge merges err into nf and reports whether it was successful. -// Otherwise it returns false for any fatal non-nil errors. -func (nf *nonFatal) Merge(err error) (ok bool) { - if err == nil { - return true // not an error - } - if !isNonFatal(err) { - return false // fatal error - } - if nf.E == nil { - nf.E = err // store first instance of non-fatal error - } - return true -} - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -const ( - // ProtoPackageIsVersion3 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion3 = true - - // ProtoPackageIsVersion2 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion2 = true - - // ProtoPackageIsVersion1 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion1 = true -) - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index f48a7567..00000000 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,181 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -/* - * Support for message sets. - */ - -import ( - "errors" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func unmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index 94fa9194..00000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,360 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr, deref bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - if deref { - u = u.Elem() - } - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index dbfffe07..00000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,313 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr, deref bool) (p pointer) { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - p = pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } else { - // The interface is not of pointer type. The data word is the pointer - // to the data. - p = pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} - } - if deref { - p.p = *(*unsafe.Pointer)(p.p) - } - return p -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index 79668ff5..00000000 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,545 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - - mtype reflect.Type // set for map types only - MapKeyProp *Properties // set for map types only - MapValProp *Properties // set for map types only -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.MapKeyProp = &Properties{} - p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.MapValProp = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - p.setFieldProps(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -type ( - oneofFuncsIface interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - oneofWrappersIface interface { - XXX_OneofWrappers() []interface{} - } -) - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - return prop - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - var oots []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oots = m.XXX_OneofFuncs() - case oneofWrappersIface: - oots = m.XXX_OneofWrappers() - } - if len(oots) > 0 { - // Interpret oneof metadata. - prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T - Prop: new(Properties), - } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue - } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break - } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index 5cb11fa9..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2776 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) - deref bool // dereference the pointer before operating on it; implies isptr -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errLater error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name} - } - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errLater -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - case oneofWrappersIface: - oneofImplementers = m.XXX_OneofWrappers() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct { - t = t.Elem() - } - sizer, marshaler := typeMarshaler(t, tags, false, false) - var deref bool - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - t = reflect.PtrTo(t) - deref = true - } - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - deref: deref, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - validateUTF8 := true - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if validateUTF8 { - if pointer { - return sizeStringPtr, appendUTF8StringPtr - } - if slice { - return sizeStringSlice, appendUTF8StringSlice - } - if nozero { - return sizeStringValueNoZero, appendUTF8StringValueNoZero - } - return sizeStringValue, appendUTF8StringValue - } - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - - // If value is a message with nested maps, calling - // valSizer in marshal may be quadratic. We should use - // cached version in marshal (but not in size). - // If value is not message type, we don't have size cache, - // but it cannot be nested either. Just use valSizer. - valCachedSizer := valSizer - if valIsPtr && valType.Elem().Kind() == reflect.Struct { - u := getMarshalInfo(valType.Elem()) - valCachedSizer = func(ptr pointer, tagsize int) int { - // Same as message sizer, but use cache. - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.cachedsize(p) - return siz + SizeVarint(uint64(siz)) + tagsize - } - } - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - - var nerr nonFatal - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if !nerr.Merge(err) { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != ErrNil && !nerr.Merge(err) { // allow nil value in map - return b, err - } - } - return b, nerr.E - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if !nerr.Merge(err) { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - var nerr nonFatal - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 5525def6..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index acee2fc5..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,2053 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - if errLater == nil { - errLater = r - } - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if reqMask != u.reqMask && errLater == nil { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - errLater = &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return errLater -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask, name) - } - - // Find any types associated with oneof fields. - var oneofImplementers []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - case oneofWrappersIface: - oneofImplementers = m.XXX_OneofWrappers() - } - for _, v := range oneofImplementers { - tptr := reflect.TypeOf(v) // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tags := strings.Split(f.Tag.Get("protobuf"), ",") - fieldNum, err := strconv.Atoi(tags[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tags[1]) - } - var name string - for _, tag := range tags { - if strings.HasPrefix(tag, "name=") { - name = strings.TrimPrefix(tag, "name=") - break - } - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(fieldNum, of.field, unmarshal, 0, name) - } - } - - } - - // Get extension ranges, if any. - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0, "") - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - proto3 := false - validateUTF8 := true - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - if tag == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if validateUTF8 { - if pointer { - return unmarshalUTF8StringPtr - } - if slice { - return unmarshalUTF8StringSlice - } - return unmarshalUTF8StringValue - } - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := 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 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := 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 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := 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 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := 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 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(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) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(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) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(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) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(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) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - var nerr nonFatal - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if nerr.Merge(err) { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nerr.E - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - var nerr nonFatal - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if !nerr.Merge(err) { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nerr.E - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) == 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 1aaee725..00000000 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,843 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.MapValProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index bb55a3af..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,880 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.MapKeyProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.MapValProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go deleted file mode 100644 index 70276e8f..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/any.go +++ /dev/null @@ -1,141 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -// This file implements functions to marshal proto.Message to/from -// google.protobuf.Any message. - -import ( - "fmt" - "reflect" - "strings" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/any" -) - -const googleApis = "type.googleapis.com/" - -// AnyMessageName returns the name of the message contained in a google.protobuf.Any message. -// -// Note that regular type assertions should be done using the Is -// function. AnyMessageName is provided for less common use cases like filtering a -// sequence of Any messages based on a set of allowed message type names. -func AnyMessageName(any *any.Any) (string, error) { - if any == nil { - return "", fmt.Errorf("message is nil") - } - slash := strings.LastIndex(any.TypeUrl, "/") - if slash < 0 { - return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) - } - return any.TypeUrl[slash+1:], nil -} - -// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. -func MarshalAny(pb proto.Message) (*any.Any, error) { - value, err := proto.Marshal(pb) - if err != nil { - return nil, err - } - return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil -} - -// DynamicAny is a value that can be passed to UnmarshalAny to automatically -// allocate a proto.Message for the type specified in a google.protobuf.Any -// message. The allocated message is stored in the embedded proto.Message. -// -// Example: -// -// var x ptypes.DynamicAny -// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } -// fmt.Printf("unmarshaled message: %v", x.Message) -type DynamicAny struct { - proto.Message -} - -// Empty returns a new proto.Message of the type specified in a -// google.protobuf.Any message. It returns an error if corresponding message -// type isn't linked in. -func Empty(any *any.Any) (proto.Message, error) { - aname, err := AnyMessageName(any) - if err != nil { - return nil, err - } - - t := proto.MessageType(aname) - if t == nil { - return nil, fmt.Errorf("any: message type %q isn't linked in", aname) - } - return reflect.New(t.Elem()).Interface().(proto.Message), nil -} - -// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any -// message and places the decoded result in pb. It returns an error if type of -// contents of Any message does not match type of pb message. -// -// pb can be a proto.Message, or a *DynamicAny. -func UnmarshalAny(any *any.Any, pb proto.Message) error { - if d, ok := pb.(*DynamicAny); ok { - if d.Message == nil { - var err error - d.Message, err = Empty(any) - if err != nil { - return err - } - } - return UnmarshalAny(any, d.Message) - } - - aname, err := AnyMessageName(any) - if err != nil { - return err - } - - mname := proto.MessageName(pb) - if aname != mname { - return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) - } - return proto.Unmarshal(any.Value, pb) -} - -// Is returns true if any value contains a given message type. -func Is(any *any.Any, pb proto.Message) bool { - // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb), - // but it avoids scanning TypeUrl for the slash. - if any == nil { - return false - } - name := proto.MessageName(pb) - prefix := len(any.TypeUrl) - len(name) - return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go deleted file mode 100644 index 78ee5233..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/any.proto - -package any - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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.ProtoPackageIsVersion3 // please upgrade the proto package - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -type Any struct { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` - // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Any) Reset() { *m = Any{} } -func (m *Any) String() string { return proto.CompactTextString(m) } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { - return fileDescriptor_b53526c13ae22eb4, []int{0} -} - -func (*Any) XXX_WellKnownType() string { return "Any" } - -func (m *Any) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Any.Unmarshal(m, b) -} -func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Any.Marshal(b, m, deterministic) -} -func (m *Any) XXX_Merge(src proto.Message) { - xxx_messageInfo_Any.Merge(m, src) -} -func (m *Any) XXX_Size() int { - return xxx_messageInfo_Any.Size(m) -} -func (m *Any) XXX_DiscardUnknown() { - xxx_messageInfo_Any.DiscardUnknown(m) -} - -var xxx_messageInfo_Any proto.InternalMessageInfo - -func (m *Any) GetTypeUrl() string { - if m != nil { - return m.TypeUrl - } - return "" -} - -func (m *Any) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*Any)(nil), "google.protobuf.Any") -} - -func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_b53526c13ae22eb4) } - -var fileDescriptor_b53526c13ae22eb4 = []byte{ - // 185 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, - 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, - 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, - 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, - 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, - 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, - 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, - 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, - 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, - 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto deleted file mode 100644 index 49329425..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.proto +++ /dev/null @@ -1,154 +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. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/any"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go deleted file mode 100644 index c0d595da..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/doc.go +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -/* -Package ptypes contains code for interacting with well-known types. -*/ -package ptypes diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go deleted file mode 100644 index 26d1ca2f..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration.go +++ /dev/null @@ -1,102 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -// This file implements conversions between google.protobuf.Duration -// and time.Duration. - -import ( - "errors" - "fmt" - "time" - - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - // Range of a durpb.Duration in seconds, as specified in - // google/protobuf/duration.proto. This is about 10,000 years in seconds. - maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) - minSeconds = -maxSeconds -) - -// validateDuration determines whether the durpb.Duration is valid according to the -// definition in google/protobuf/duration.proto. A valid durpb.Duration -// may still be too large to fit into a time.Duration (the range of durpb.Duration -// is about 10,000 years, and the range of time.Duration is about 290). -func validateDuration(d *durpb.Duration) error { - if d == nil { - return errors.New("duration: nil Duration") - } - if d.Seconds < minSeconds || d.Seconds > maxSeconds { - return fmt.Errorf("duration: %v: seconds out of range", d) - } - if d.Nanos <= -1e9 || d.Nanos >= 1e9 { - return fmt.Errorf("duration: %v: nanos out of range", d) - } - // Seconds and Nanos must have the same sign, unless d.Nanos is zero. - if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { - return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) - } - return nil -} - -// Duration converts a durpb.Duration to a time.Duration. Duration -// returns an error if the durpb.Duration is invalid or is too large to be -// represented in a time.Duration. -func Duration(p *durpb.Duration) (time.Duration, error) { - if err := validateDuration(p); err != nil { - return 0, err - } - d := time.Duration(p.Seconds) * time.Second - if int64(d/time.Second) != p.Seconds { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - if p.Nanos != 0 { - d += time.Duration(p.Nanos) * time.Nanosecond - if (d < 0) != (p.Nanos < 0) { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - } - return d, nil -} - -// DurationProto converts a time.Duration to a durpb.Duration. -func DurationProto(d time.Duration) *durpb.Duration { - nanos := d.Nanoseconds() - secs := nanos / 1e9 - nanos -= secs * 1e9 - return &durpb.Duration{ - Seconds: secs, - Nanos: int32(nanos), - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go deleted file mode 100644 index 0d681ee2..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/duration.proto - -package duration - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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.ProtoPackageIsVersion3 // please upgrade the proto package - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_23597b2ebd7ac6c5, []int{0} -} - -func (*Duration) XXX_WellKnownType() string { return "Duration" } - -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (m *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(m, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) -} - -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") -} - -func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_23597b2ebd7ac6c5) } - -var fileDescriptor_23597b2ebd7ac6c5 = []byte{ - // 190 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, - 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, - 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, - 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, - 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, - 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, - 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, - 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, - 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, - 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, - 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto deleted file mode 100644 index 975fce41..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto +++ /dev/null @@ -1,117 +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. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/duration"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DurationProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -message Duration { - - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - int64 seconds = 1; - - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go deleted file mode 100644 index 8da0df01..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go +++ /dev/null @@ -1,132 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -// This file implements operations on google.protobuf.Timestamp. - -import ( - "errors" - "fmt" - "time" - - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -const ( - // Seconds field of the earliest valid Timestamp. - // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - minValidSeconds = -62135596800 - // Seconds field just after the latest valid Timestamp. - // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - maxValidSeconds = 253402300800 -) - -// validateTimestamp determines whether a Timestamp is valid. -// A valid timestamp represents a time in the range -// [0001-01-01, 10000-01-01) and has a Nanos field -// in the range [0, 1e9). -// -// If the Timestamp is valid, validateTimestamp returns nil. -// Otherwise, it returns an error that describes -// the problem. -// -// Every valid Timestamp can be represented by a time.Time, but the converse is not true. -func validateTimestamp(ts *tspb.Timestamp) error { - if ts == nil { - return errors.New("timestamp: nil Timestamp") - } - if ts.Seconds < minValidSeconds { - return fmt.Errorf("timestamp: %v before 0001-01-01", ts) - } - if ts.Seconds >= maxValidSeconds { - return fmt.Errorf("timestamp: %v after 10000-01-01", ts) - } - if ts.Nanos < 0 || ts.Nanos >= 1e9 { - return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) - } - return nil -} - -// Timestamp converts a google.protobuf.Timestamp proto to a time.Time. -// It returns an error if the argument is invalid. -// -// Unlike most Go functions, if Timestamp returns an error, the first return value -// is not the zero time.Time. Instead, it is the value obtained from the -// time.Unix function when passed the contents of the Timestamp, in the UTC -// locale. This may or may not be a meaningful time; many invalid Timestamps -// do map to valid time.Times. -// -// A nil Timestamp returns an error. The first return value in that case is -// undefined. -func Timestamp(ts *tspb.Timestamp) (time.Time, error) { - // Don't return the zero value on error, because corresponds to a valid - // timestamp. Instead return whatever time.Unix gives us. - var t time.Time - if ts == nil { - t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp - } else { - t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() - } - return t, validateTimestamp(ts) -} - -// TimestampNow returns a google.protobuf.Timestamp for the current time. -func TimestampNow() *tspb.Timestamp { - ts, err := TimestampProto(time.Now()) - if err != nil { - panic("ptypes: time.Now() out of Timestamp range") - } - return ts -} - -// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. -// It returns an error if the resulting Timestamp is invalid. -func TimestampProto(t time.Time) (*tspb.Timestamp, error) { - ts := &tspb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := validateTimestamp(ts); err != nil { - return nil, err - } - return ts, nil -} - -// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid -// Timestamps, it returns an error message in parentheses. -func TimestampString(ts *tspb.Timestamp) string { - t, err := Timestamp(ts) - if err != nil { - return fmt.Sprintf("(%v)", err) - } - return t.Format(time.RFC3339Nano) -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go deleted file mode 100644 index 31cd846d..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ /dev/null @@ -1,179 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/timestamp.proto - -package timestamp - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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.ProtoPackageIsVersion3 // please upgrade the proto package - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required. A proto3 JSON serializer should always use UTC (as indicated by -// "Z") when printing the Timestamp type and a proto3 JSON parser should be -// able to accept both UTC and other timezones (as indicated by an offset). -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- -// ) to obtain a formatter capable of generating timestamps in this format. -// -// -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_292007bbfe81227e, []int{0} -} - -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } - -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (m *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(m, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) -} - -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") -} - -func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_292007bbfe81227e) } - -var fileDescriptor_292007bbfe81227e = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, - 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, - 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, - 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, - 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, - 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, - 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, - 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, - 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, - 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto deleted file mode 100644 index eafb3fa0..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto +++ /dev/null @@ -1,135 +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. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/timestamp"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TimestampProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required. A proto3 JSON serializer should always use UTC (as indicated by -// "Z") when printing the Timestamp type and a proto3 JSON parser should be -// able to accept both UTC and other timezones (as indicated by an offset). -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- -// ) to obtain a formatter capable of generating timestamps in this format. -// -// -message Timestamp { - - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore deleted file mode 100644 index 042091d9..00000000 --- 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 bcfa1952..00000000 --- a/vendor/github.com/golang/snappy/AUTHORS +++ /dev/null @@ -1,15 +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. - -Damian Gryski -Google Inc. -Jan Mercl <0xjnml@gmail.com> -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 931ae316..00000000 --- a/vendor/github.com/golang/snappy/CONTRIBUTORS +++ /dev/null @@ -1,37 +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. - -Damian Gryski -Jan Mercl <0xjnml@gmail.com> -Kai Backman -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 6050c10f..00000000 --- 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 cea12879..00000000 --- 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 72efb035..00000000 --- a/vendor/github.com/golang/snappy/decode.go +++ /dev/null @@ -1,237 +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. -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. -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 -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - for { - if r.i < r.j { - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil - } - if !r.readFull(r.buf[:4], true) { - return 0, r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return 0, 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 0, 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 0, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return 0, 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 0, r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, 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 0, r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return 0, 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 0, r.err - } - if !r.readFull(r.decoded[:n], false) { - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, 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 0, r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return 0, r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return 0, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return 0, 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 0, r.err - } - } -} diff --git a/vendor/github.com/golang/snappy/decode_amd64.go b/vendor/github.com/golang/snappy/decode_amd64.go deleted file mode 100644 index fcd192b8..00000000 --- a/vendor/github.com/golang/snappy/decode_amd64.go +++ /dev/null @@ -1,14 +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 - -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_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s deleted file mode 100644 index e6179f65..00000000 --- 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_other.go b/vendor/github.com/golang/snappy/decode_other.go deleted file mode 100644 index 8c9f2049..00000000 --- a/vendor/github.com/golang/snappy/decode_other.go +++ /dev/null @@ -1,101 +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 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. 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:]) - for end := d + length; d != end; d++ { - dst[d] = dst[d-offset] - } - } - 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 8d393e90..00000000 --- a/vendor/github.com/golang/snappy/encode.go +++ /dev/null @@ -1,285 +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. -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. -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.go b/vendor/github.com/golang/snappy/encode_amd64.go deleted file mode 100644 index 150d91bc..00000000 --- a/vendor/github.com/golang/snappy/encode_amd64.go +++ /dev/null @@ -1,29 +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 - -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_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s deleted file mode 100644 index adfd979f..00000000 --- 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_other.go b/vendor/github.com/golang/snappy/encode_other.go deleted file mode 100644 index dbcae905..00000000 --- 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 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 ece692ea..00000000 --- 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/errwrap/LICENSE b/vendor/github.com/hashicorp/errwrap/LICENSE deleted file mode 100644 index c33dcc7c..00000000 --- a/vendor/github.com/hashicorp/errwrap/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/errwrap/README.md b/vendor/github.com/hashicorp/errwrap/README.md deleted file mode 100644 index 444df08f..00000000 --- a/vendor/github.com/hashicorp/errwrap/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# errwrap - -`errwrap` is a package for Go that formalizes the pattern of wrapping errors -and checking if an error contains another error. - -There is a common pattern in Go of taking a returned `error` value and -then wrapping it (such as with `fmt.Errorf`) before returning it. The problem -with this pattern is that you completely lose the original `error` structure. - -Arguably the _correct_ approach is that you should make a custom structure -implementing the `error` interface, and have the original error as a field -on that structure, such [as this example](http://golang.org/pkg/os/#PathError). -This is a good approach, but you have to know the entire chain of possible -rewrapping that happens, when you might just care about one. - -`errwrap` formalizes this pattern (it doesn't matter what approach you use -above) by giving a single interface for wrapping errors, checking if a specific -error is wrapped, and extracting that error. - -## Installation and Docs - -Install using `go get github.com/hashicorp/errwrap`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/errwrap - -## Usage - -#### Basic Usage - -Below is a very basic example of its usage: - -```go -// A function that always returns an error, but wraps it, like a real -// function might. -func tryOpen() error { - _, err := os.Open("/i/dont/exist") - if err != nil { - return errwrap.Wrapf("Doesn't exist: {{err}}", err) - } - - return nil -} - -func main() { - err := tryOpen() - - // We can use the Contains helpers to check if an error contains - // another error. It is safe to do this with a nil error, or with - // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, "does not exist") { - // Do something - } - if errwrap.ContainsType(err, new(os.PathError)) { - // Do something - } - - // Or we can use the associated `Get` functions to just extract - // a specific error. This would return nil if that specific error doesn't - // exist. - perr := errwrap.GetType(err, new(os.PathError)) -} -``` - -#### Custom Types - -If you're already making custom types that properly wrap errors, then -you can get all the functionality of `errwraps.Contains` and such by -implementing the `Wrapper` interface with just one function. Example: - -```go -type AppError { - Code ErrorCode - Err error -} - -func (e *AppError) WrappedErrors() []error { - return []error{e.Err} -} -``` - -Now this works: - -```go -err := &AppError{Err: fmt.Errorf("an error")} -if errwrap.ContainsType(err, fmt.Errorf("")) { - // This will work! -} -``` diff --git a/vendor/github.com/hashicorp/errwrap/errwrap.go b/vendor/github.com/hashicorp/errwrap/errwrap.go deleted file mode 100644 index a733bef1..00000000 --- a/vendor/github.com/hashicorp/errwrap/errwrap.go +++ /dev/null @@ -1,169 +0,0 @@ -// Package errwrap implements methods to formalize error wrapping in Go. -// -// All of the top-level functions that take an `error` are built to be able -// to take any error, not just wrapped errors. This allows you to use errwrap -// without having to type-check and type-cast everywhere. -package errwrap - -import ( - "errors" - "reflect" - "strings" -) - -// WalkFunc is the callback called for Walk. -type WalkFunc func(error) - -// Wrapper is an interface that can be implemented by custom types to -// have all the Contains, Get, etc. functions in errwrap work. -// -// When Walk reaches a Wrapper, it will call the callback for every -// wrapped error in addition to the wrapper itself. Since all the top-level -// functions in errwrap use Walk, this means that all those functions work -// with your custom type. -type Wrapper interface { - WrappedErrors() []error -} - -// Wrap defines that outer wraps inner, returning an error type that -// can be cleanly used with the other methods in this package, such as -// Contains, GetAll, etc. -// -// This function won't modify the error message at all (the outer message -// will be used). -func Wrap(outer, inner error) error { - return &wrappedError{ - Outer: outer, - Inner: inner, - } -} - -// Wrapf wraps an error with a formatting message. This is similar to using -// `fmt.Errorf` to wrap an error. If you're using `fmt.Errorf` to wrap -// errors, you should replace it with this. -// -// format is the format of the error message. The string '{{err}}' will -// be replaced with the original error message. -func Wrapf(format string, err error) error { - outerMsg := "" - if err != nil { - outerMsg = err.Error() - } - - outer := errors.New(strings.Replace( - format, "{{err}}", outerMsg, -1)) - - return Wrap(outer, err) -} - -// Contains checks if the given error contains an error with the -// message msg. If err is not a wrapped error, this will always return -// false unless the error itself happens to match this msg. -func Contains(err error, msg string) bool { - return len(GetAll(err, msg)) > 0 -} - -// ContainsType checks if the given error contains an error with -// the same concrete type as v. If err is not a wrapped error, this will -// check the err itself. -func ContainsType(err error, v interface{}) bool { - return len(GetAllType(err, v)) > 0 -} - -// Get is the same as GetAll but returns the deepest matching error. -func Get(err error, msg string) error { - es := GetAll(err, msg) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetType is the same as GetAllType but returns the deepest matching error. -func GetType(err error, v interface{}) error { - es := GetAllType(err, v) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetAll gets all the errors that might be wrapped in err with the -// given message. The order of the errors is such that the outermost -// matching error (the most recent wrap) is index zero, and so on. -func GetAll(err error, msg string) []error { - var result []error - - Walk(err, func(err error) { - if err.Error() == msg { - result = append(result, err) - } - }) - - return result -} - -// GetAllType gets all the errors that are the same type as v. -// -// The order of the return value is the same as described in GetAll. -func GetAllType(err error, v interface{}) []error { - var result []error - - var search string - if v != nil { - search = reflect.TypeOf(v).String() - } - Walk(err, func(err error) { - var needle string - if err != nil { - needle = reflect.TypeOf(err).String() - } - - if needle == search { - result = append(result, err) - } - }) - - return result -} - -// Walk walks all the wrapped errors in err and calls the callback. If -// err isn't a wrapped error, this will be called once for err. If err -// is a wrapped error, the callback will be called for both the wrapper -// that implements error as well as the wrapped error itself. -func Walk(err error, cb WalkFunc) { - if err == nil { - return - } - - switch e := err.(type) { - case *wrappedError: - cb(e.Outer) - Walk(e.Inner, cb) - case Wrapper: - cb(err) - - for _, err := range e.WrappedErrors() { - Walk(err, cb) - } - default: - cb(err) - } -} - -// wrappedError is an implementation of error that has both the -// outer and inner errors. -type wrappedError struct { - Outer error - Inner error -} - -func (w *wrappedError) Error() string { - return w.Outer.Error() -} - -func (w *wrappedError) WrappedErrors() []error { - return []error{w.Outer, w.Inner} -} diff --git a/vendor/github.com/hashicorp/errwrap/go.mod b/vendor/github.com/hashicorp/errwrap/go.mod deleted file mode 100644 index c9b84022..00000000 --- a/vendor/github.com/hashicorp/errwrap/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/errwrap diff --git a/vendor/github.com/hashicorp/go-cleanhttp/LICENSE b/vendor/github.com/hashicorp/go-cleanhttp/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/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-cleanhttp/README.md b/vendor/github.com/hashicorp/go-cleanhttp/README.md deleted file mode 100644 index 036e5313..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# cleanhttp - -Functions for accessing "clean" Go http.Client values - -------------- - -The Go standard library contains a default `http.Client` called -`http.DefaultClient`. It is a common idiom in Go code to start with -`http.DefaultClient` and tweak it as necessary, and in fact, this is -encouraged; from the `http` package documentation: - -> The Client's Transport typically has internal state (cached TCP connections), -so Clients should be reused instead of created as needed. Clients are safe for -concurrent use by multiple goroutines. - -Unfortunately, this is a shared value, and it is not uncommon for libraries to -assume that they are free to modify it at will. With enough dependencies, it -can be very easy to encounter strange problems and race conditions due to -manipulation of this shared value across libraries and goroutines (clients are -safe for concurrent use, but writing values to the client struct itself is not -protected). - -Making things worse is the fact that a bare `http.Client` will use a default -`http.Transport` called `http.DefaultTransport`, which is another global value -that behaves the same way. So it is not simply enough to replace -`http.DefaultClient` with `&http.Client{}`. - -This repository provides some simple functions to get a "clean" `http.Client` --- one that uses the same default values as the Go standard library, but -returns a client that does not share any state with other clients. diff --git a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go b/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go deleted file mode 100644 index 8d306bf5..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go +++ /dev/null @@ -1,57 +0,0 @@ -package cleanhttp - -import ( - "net" - "net/http" - "runtime" - "time" -) - -// DefaultTransport returns a new http.Transport with similar default values to -// http.DefaultTransport, but with idle connections and keepalives disabled. -func DefaultTransport() *http.Transport { - transport := DefaultPooledTransport() - transport.DisableKeepAlives = true - transport.MaxIdleConnsPerHost = -1 - return transport -} - -// DefaultPooledTransport returns a new http.Transport with similar default -// values to http.DefaultTransport. Do not use this for transient transports as -// it can leak file descriptors over time. Only use this for transports that -// will be re-used for the same host(s). -func DefaultPooledTransport() *http.Transport { - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, - } - return transport -} - -// DefaultClient returns a new http.Client with similar default values to -// http.Client, but with a non-shared Transport, idle connections disabled, and -// keepalives disabled. -func DefaultClient() *http.Client { - return &http.Client{ - Transport: DefaultTransport(), - } -} - -// DefaultPooledClient returns a new http.Client with similar default values to -// http.Client, but with a shared Transport. Do not use this function for -// transient clients as it can leak file descriptors over time. Only use this -// for clients that will be re-used for the same host(s). -func DefaultPooledClient() *http.Client { - return &http.Client{ - Transport: DefaultPooledTransport(), - } -} diff --git a/vendor/github.com/hashicorp/go-cleanhttp/doc.go b/vendor/github.com/hashicorp/go-cleanhttp/doc.go deleted file mode 100644 index 05841092..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package cleanhttp offers convenience utilities for acquiring "clean" -// http.Transport and http.Client structs. -// -// Values set on http.DefaultClient and http.DefaultTransport affect all -// callers. This can have detrimental effects, esepcially in TLS contexts, -// where client or root certificates set to talk to multiple endpoints can end -// up displacing each other, leading to hard-to-debug issues. This package -// provides non-shared http.Client and http.Transport structs to ensure that -// the configuration will not be overwritten by other parts of the application -// or dependencies. -// -// The DefaultClient and DefaultTransport functions disable idle connections -// and keepalives. Without ensuring that idle connections are closed before -// garbage collection, short-term clients/transports can leak file descriptors, -// eventually leading to "too many open files" errors. If you will be -// connecting to the same hosts repeatedly from the same client, you can use -// DefaultPooledClient to receive a client that has connection pooling -// semantics similar to http.DefaultClient. -// -package cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/go.mod b/vendor/github.com/hashicorp/go-cleanhttp/go.mod deleted file mode 100644 index 310f0756..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/go-cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go b/vendor/github.com/hashicorp/go-cleanhttp/handlers.go deleted file mode 100644 index 3c845dc0..00000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go +++ /dev/null @@ -1,48 +0,0 @@ -package cleanhttp - -import ( - "net/http" - "strings" - "unicode" -) - -// HandlerInput provides input options to cleanhttp's handlers -type HandlerInput struct { - ErrStatus int -} - -// PrintablePathCheckHandler is a middleware that ensures the request path -// contains only printable runes. -func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { - // Nil-check on input to make it optional - if input == nil { - input = &HandlerInput{ - ErrStatus: http.StatusBadRequest, - } - } - - // Default to http.StatusBadRequest on error - if input.ErrStatus == 0 { - input.ErrStatus = http.StatusBadRequest - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r != nil { - // Check URL path for non-printable characters - idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { - return !unicode.IsPrint(c) - }) - - if idx != -1 { - w.WriteHeader(input.ErrStatus) - return - } - - if next != nil { - next.ServeHTTP(w, r) - } - } - - return - }) -} diff --git a/vendor/github.com/hashicorp/go-hclog/.gitignore b/vendor/github.com/hashicorp/go-hclog/.gitignore deleted file mode 100644 index 42cc4105..00000000 --- a/vendor/github.com/hashicorp/go-hclog/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.idea* \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-hclog/LICENSE b/vendor/github.com/hashicorp/go-hclog/LICENSE deleted file mode 100644 index abaf1e45..00000000 --- a/vendor/github.com/hashicorp/go-hclog/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 HashiCorp - -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/hashicorp/go-hclog/README.md b/vendor/github.com/hashicorp/go-hclog/README.md deleted file mode 100644 index 1153e285..00000000 --- a/vendor/github.com/hashicorp/go-hclog/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# go-hclog - -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[godocs]: https://godoc.org/github.com/hashicorp/go-hclog - -`go-hclog` is a package for Go that provides a simple key/value logging -interface for use in development and production environments. - -It provides logging levels that provide decreased output based upon the -desired amount of output, unlike the standard library `log` package. - -It provides `Printf` style logging of values via `hclog.Fmt()`. - -It provides a human readable output mode for use in development as well as -JSON output mode for production. - -## Stability Note - -While this library is fully open source and HashiCorp will be maintaining it -(since we are and will be making extensive use of it), the API and output -format is subject to minor changes as we fully bake and vet it in our projects. -This notice will be removed once it's fully integrated into our major projects -and no further changes are anticipated. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-hclog`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/go-hclog - -## Usage - -### Use the global logger - -```go -hclog.Default().Info("hello world") -``` - -```text -2017-07-05T16:15:55.167-0700 [INFO ] hello world -``` - -(Note timestamps are removed in future examples for brevity.) - -### Create a new logger - -```go -appLogger := hclog.New(&hclog.LoggerOptions{ - Name: "my-app", - Level: hclog.LevelFromString("DEBUG"), -}) -``` - -### Emit an Info level message with 2 key/value pairs - -```go -input := "5.5" -_, err := strconv.ParseInt(input, 10, 32) -if err != nil { - appLogger.Info("Invalid input for ParseInt", "input", input, "error", err) -} -``` - -```text -... [INFO ] my-app: Invalid input for ParseInt: input=5.5 error="strconv.ParseInt: parsing "5.5": invalid syntax" -``` - -### Create a new Logger for a major subsystem - -```go -subsystemLogger := appLogger.Named("transport") -subsystemLogger.Info("we are transporting something") -``` - -```text -... [INFO ] my-app.transport: we are transporting something -``` - -Notice that logs emitted by `subsystemLogger` contain `my-app.transport`, -reflecting both the application and subsystem names. - -### Create a new Logger with fixed key/value pairs - -Using `With()` will include a specific key-value pair in all messages emitted -by that logger. - -```go -requestID := "5fb446b6-6eba-821d-df1b-cd7501b6a363" -requestLogger := subsystemLogger.With("request", requestID) -requestLogger.Info("we are transporting a request") -``` - -```text -... [INFO ] my-app.transport: we are transporting a request: request=5fb446b6-6eba-821d-df1b-cd7501b6a363 -``` - -This allows sub Loggers to be context specific without having to thread that -into all the callers. - -### Using `hclog.Fmt()` - -```go -var int totalBandwidth = 200 -appLogger.Info("total bandwidth exceeded", "bandwidth", hclog.Fmt("%d GB/s", totalBandwidth)) -``` - -```text -... [INFO ] my-app: total bandwidth exceeded: bandwidth="200 GB/s" -``` - -### Use this with code that uses the standard library logger - -If you want to use the standard library's `log.Logger` interface you can wrap -`hclog.Logger` by calling the `StandardLogger()` method. This allows you to use -it with the familiar `Println()`, `Printf()`, etc. For example: - -```go -stdLogger := appLogger.StandardLogger(&hclog.StandardLoggerOptions{ - InferLevels: true, -}) -// Printf() is provided by stdlib log.Logger interface, not hclog.Logger -stdLogger.Printf("[DEBUG] %+v", stdLogger) -``` - -```text -... [DEBUG] my-app: &{mu:{state:0 sema:0} prefix: flag:0 out:0xc42000a0a0 buf:[]} -``` - -Notice that if `appLogger` is initialized with the `INFO` log level _and_ you -specify `InferLevels: true`, you will not see any output here. You must change -`appLogger` to `DEBUG` to see output. See the docs for more information. diff --git a/vendor/github.com/hashicorp/go-hclog/global.go b/vendor/github.com/hashicorp/go-hclog/global.go deleted file mode 100644 index 55ce4396..00000000 --- a/vendor/github.com/hashicorp/go-hclog/global.go +++ /dev/null @@ -1,34 +0,0 @@ -package hclog - -import ( - "sync" -) - -var ( - protect sync.Once - def Logger - - // The options used to create the Default logger. These are - // read only when the Default logger is created, so set them - // as soon as the process starts. - DefaultOptions = &LoggerOptions{ - Level: DefaultLevel, - Output: DefaultOutput, - } -) - -// Return a logger that is held globally. This can be a good starting -// place, and then you can use .With() and .Name() to create sub-loggers -// to be used in more specific contexts. -func Default() Logger { - protect.Do(func() { - def = New(DefaultOptions) - }) - - return def -} - -// A short alias for Default() -func L() Logger { - return Default() -} diff --git a/vendor/github.com/hashicorp/go-hclog/go.mod b/vendor/github.com/hashicorp/go-hclog/go.mod deleted file mode 100644 index 0d079a65..00000000 --- a/vendor/github.com/hashicorp/go-hclog/go.mod +++ /dev/null @@ -1,7 +0,0 @@ -module github.com/hashicorp/go-hclog - -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/testify v1.2.2 -) diff --git a/vendor/github.com/hashicorp/go-hclog/go.sum b/vendor/github.com/hashicorp/go-hclog/go.sum deleted file mode 100644 index e03ee77d..00000000 --- a/vendor/github.com/hashicorp/go-hclog/go.sum +++ /dev/null @@ -1,6 +0,0 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/vendor/github.com/hashicorp/go-hclog/int.go b/vendor/github.com/hashicorp/go-hclog/int.go deleted file mode 100644 index 2aaa1f89..00000000 --- a/vendor/github.com/hashicorp/go-hclog/int.go +++ /dev/null @@ -1,507 +0,0 @@ -package hclog - -import ( - "bufio" - "bytes" - "encoding" - "encoding/json" - "fmt" - "log" - "os" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -var ( - _levelToBracket = map[Level]string{ - Debug: "[DEBUG]", - Trace: "[TRACE]", - Info: "[INFO] ", - Warn: "[WARN] ", - Error: "[ERROR]", - } -) - -// Given the options (nil for defaults), create a new Logger -func New(opts *LoggerOptions) Logger { - if opts == nil { - opts = &LoggerOptions{} - } - - output := opts.Output - if output == nil { - output = os.Stderr - } - - level := opts.Level - if level == NoLevel { - level = DefaultLevel - } - - mtx := opts.Mutex - if mtx == nil { - mtx = new(sync.Mutex) - } - - ret := &intLogger{ - m: mtx, - json: opts.JSONFormat, - caller: opts.IncludeLocation, - name: opts.Name, - timeFormat: TimeFormat, - w: bufio.NewWriter(output), - level: new(int32), - } - if opts.TimeFormat != "" { - ret.timeFormat = opts.TimeFormat - } - atomic.StoreInt32(ret.level, int32(level)) - return ret -} - -// The internal logger implementation. Internal in that it is defined entirely -// by this package. -type intLogger struct { - json bool - caller bool - name string - timeFormat string - - // this is a pointer so that it's shared by any derived loggers, since - // those derived loggers share the bufio.Writer as well. - m *sync.Mutex - w *bufio.Writer - level *int32 - - implied []interface{} -} - -// Make sure that intLogger is a Logger -var _ Logger = &intLogger{} - -// The time format to use for logging. This is a version of RFC3339 that -// contains millisecond precision -const TimeFormat = "2006-01-02T15:04:05.000Z0700" - -// Log a message and a set of key/value pairs if the given level is at -// or more severe that the threshold configured in the Logger. -func (z *intLogger) Log(level Level, msg string, args ...interface{}) { - if level < Level(atomic.LoadInt32(z.level)) { - return - } - - t := time.Now() - - z.m.Lock() - defer z.m.Unlock() - - if z.json { - z.logJson(t, level, msg, args...) - } else { - z.log(t, level, msg, args...) - } - - z.w.Flush() -} - -// Cleanup a path by returning the last 2 segments of the path only. -func trimCallerPath(path string) string { - // lovely borrowed from zap - // nb. To make sure we trim the path correctly on Windows too, we - // counter-intuitively need to use '/' and *not* os.PathSeparator here, - // because the path given originates from Go stdlib, specifically - // runtime.Caller() which (as of Mar/17) returns forward slashes even on - // Windows. - // - // See https://github.com/golang/go/issues/3335 - // and https://github.com/golang/go/issues/18151 - // - // for discussion on the issue on Go side. - // - - // Find the last separator. - // - idx := strings.LastIndexByte(path, '/') - if idx == -1 { - return path - } - - // Find the penultimate separator. - idx = strings.LastIndexByte(path[:idx], '/') - if idx == -1 { - return path - } - - return path[idx+1:] -} - -// Non-JSON logging format function -func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { - z.w.WriteString(t.Format(z.timeFormat)) - z.w.WriteByte(' ') - - s, ok := _levelToBracket[level] - if ok { - z.w.WriteString(s) - } else { - z.w.WriteString("[?????]") - } - - if z.caller { - if _, file, line, ok := runtime.Caller(3); ok { - z.w.WriteByte(' ') - z.w.WriteString(trimCallerPath(file)) - z.w.WriteByte(':') - z.w.WriteString(strconv.Itoa(line)) - z.w.WriteByte(':') - } - } - - z.w.WriteByte(' ') - - if z.name != "" { - z.w.WriteString(z.name) - z.w.WriteString(": ") - } - - z.w.WriteString(msg) - - args = append(z.implied, args...) - - var stacktrace CapturedStacktrace - - if args != nil && len(args) > 0 { - if len(args)%2 != 0 { - cs, ok := args[len(args)-1].(CapturedStacktrace) - if ok { - args = args[:len(args)-1] - stacktrace = cs - } else { - args = append(args, "") - } - } - - z.w.WriteByte(':') - - FOR: - for i := 0; i < len(args); i = i + 2 { - var ( - val string - raw bool - ) - - switch st := args[i+1].(type) { - case string: - val = st - case int: - val = strconv.FormatInt(int64(st), 10) - case int64: - val = strconv.FormatInt(int64(st), 10) - case int32: - val = strconv.FormatInt(int64(st), 10) - case int16: - val = strconv.FormatInt(int64(st), 10) - case int8: - val = strconv.FormatInt(int64(st), 10) - case uint: - val = strconv.FormatUint(uint64(st), 10) - case uint64: - val = strconv.FormatUint(uint64(st), 10) - case uint32: - val = strconv.FormatUint(uint64(st), 10) - case uint16: - val = strconv.FormatUint(uint64(st), 10) - case uint8: - val = strconv.FormatUint(uint64(st), 10) - case CapturedStacktrace: - stacktrace = st - continue FOR - case Format: - val = fmt.Sprintf(st[0].(string), st[1:]...) - default: - v := reflect.ValueOf(st) - if v.Kind() == reflect.Slice { - val = z.renderSlice(v) - raw = true - } else { - val = fmt.Sprintf("%v", st) - } - } - - z.w.WriteByte(' ') - z.w.WriteString(args[i].(string)) - z.w.WriteByte('=') - - if !raw && strings.ContainsAny(val, " \t\n\r") { - z.w.WriteByte('"') - z.w.WriteString(val) - z.w.WriteByte('"') - } else { - z.w.WriteString(val) - } - } - } - - z.w.WriteString("\n") - - if stacktrace != "" { - z.w.WriteString(string(stacktrace)) - } -} - -func (z *intLogger) renderSlice(v reflect.Value) string { - var buf bytes.Buffer - - buf.WriteRune('[') - - for i := 0; i < v.Len(); i++ { - if i > 0 { - buf.WriteString(", ") - } - - sv := v.Index(i) - - var val string - - switch sv.Kind() { - case reflect.String: - val = sv.String() - case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: - val = strconv.FormatInt(sv.Int(), 10) - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - val = strconv.FormatUint(sv.Uint(), 10) - default: - val = fmt.Sprintf("%v", sv.Interface()) - } - - if strings.ContainsAny(val, " \t\n\r") { - buf.WriteByte('"') - buf.WriteString(val) - buf.WriteByte('"') - } else { - buf.WriteString(val) - } - } - - buf.WriteRune(']') - - return buf.String() -} - -// JSON logging function -func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) { - vals := map[string]interface{}{ - "@message": msg, - "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"), - } - - var levelStr string - switch level { - case Error: - levelStr = "error" - case Warn: - levelStr = "warn" - case Info: - levelStr = "info" - case Debug: - levelStr = "debug" - case Trace: - levelStr = "trace" - default: - levelStr = "all" - } - - vals["@level"] = levelStr - - if z.name != "" { - vals["@module"] = z.name - } - - if z.caller { - if _, file, line, ok := runtime.Caller(3); ok { - vals["@caller"] = fmt.Sprintf("%s:%d", file, line) - } - } - - args = append(z.implied, args...) - - if args != nil && len(args) > 0 { - if len(args)%2 != 0 { - cs, ok := args[len(args)-1].(CapturedStacktrace) - if ok { - args = args[:len(args)-1] - vals["stacktrace"] = cs - } else { - args = append(args, "") - } - } - - for i := 0; i < len(args); i = i + 2 { - if _, ok := args[i].(string); !ok { - // As this is the logging function not much we can do here - // without injecting into logs... - continue - } - val := args[i+1] - switch sv := val.(type) { - case error: - // Check if val is of type error. If error type doesn't - // implement json.Marshaler or encoding.TextMarshaler - // then set val to err.Error() so that it gets marshaled - switch sv.(type) { - case json.Marshaler, encoding.TextMarshaler: - default: - val = sv.Error() - } - case Format: - val = fmt.Sprintf(sv[0].(string), sv[1:]...) - } - - vals[args[i].(string)] = val - } - } - - err := json.NewEncoder(z.w).Encode(vals) - if err != nil { - panic(err) - } -} - -// Emit the message and args at DEBUG level -func (z *intLogger) Debug(msg string, args ...interface{}) { - z.Log(Debug, msg, args...) -} - -// Emit the message and args at TRACE level -func (z *intLogger) Trace(msg string, args ...interface{}) { - z.Log(Trace, msg, args...) -} - -// Emit the message and args at INFO level -func (z *intLogger) Info(msg string, args ...interface{}) { - z.Log(Info, msg, args...) -} - -// Emit the message and args at WARN level -func (z *intLogger) Warn(msg string, args ...interface{}) { - z.Log(Warn, msg, args...) -} - -// Emit the message and args at ERROR level -func (z *intLogger) Error(msg string, args ...interface{}) { - z.Log(Error, msg, args...) -} - -// Indicate that the logger would emit TRACE level logs -func (z *intLogger) IsTrace() bool { - return Level(atomic.LoadInt32(z.level)) == Trace -} - -// Indicate that the logger would emit DEBUG level logs -func (z *intLogger) IsDebug() bool { - return Level(atomic.LoadInt32(z.level)) <= Debug -} - -// Indicate that the logger would emit INFO level logs -func (z *intLogger) IsInfo() bool { - return Level(atomic.LoadInt32(z.level)) <= Info -} - -// Indicate that the logger would emit WARN level logs -func (z *intLogger) IsWarn() bool { - return Level(atomic.LoadInt32(z.level)) <= Warn -} - -// Indicate that the logger would emit ERROR level logs -func (z *intLogger) IsError() bool { - return Level(atomic.LoadInt32(z.level)) <= Error -} - -// Return a sub-Logger for which every emitted log message will contain -// the given key/value pairs. This is used to create a context specific -// Logger. -func (z *intLogger) With(args ...interface{}) Logger { - if len(args)%2 != 0 { - panic("With() call requires paired arguments") - } - - var nz intLogger = *z - - result := make(map[string]interface{}, len(z.implied)+len(args)) - keys := make([]string, 0, len(z.implied)+len(args)) - - // Read existing args, store map and key for consistent sorting - for i := 0; i < len(z.implied); i += 2 { - key := z.implied[i].(string) - keys = append(keys, key) - result[key] = z.implied[i+1] - } - // Read new args, store map and key for consistent sorting - for i := 0; i < len(args); i += 2 { - key := args[i].(string) - _, exists := result[key] - if !exists { - keys = append(keys, key) - } - result[key] = args[i+1] - } - - // Sort keys to be consistent - sort.Strings(keys) - - nz.implied = make([]interface{}, 0, len(z.implied)+len(args)) - for _, k := range keys { - nz.implied = append(nz.implied, k) - nz.implied = append(nz.implied, result[k]) - } - - return &nz -} - -// Create a new sub-Logger that a name decending from the current name. -// This is used to create a subsystem specific Logger. -func (z *intLogger) Named(name string) Logger { - var nz intLogger = *z - - if nz.name != "" { - nz.name = nz.name + "." + name - } else { - nz.name = name - } - - return &nz -} - -// Create a new sub-Logger with an explicit name. This ignores the current -// name. This is used to create a standalone logger that doesn't fall -// within the normal hierarchy. -func (z *intLogger) ResetNamed(name string) Logger { - var nz intLogger = *z - - nz.name = name - - return &nz -} - -// Update the logging level on-the-fly. This will affect all subloggers as -// well. -func (z *intLogger) SetLevel(level Level) { - atomic.StoreInt32(z.level, int32(level)) -} - -// Create a *log.Logger that will send it's data through this Logger. This -// allows packages that expect to be using the standard library log to actually -// use this logger. -func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { - if opts == nil { - opts = &StandardLoggerOptions{} - } - - return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0) -} diff --git a/vendor/github.com/hashicorp/go-hclog/log.go b/vendor/github.com/hashicorp/go-hclog/log.go deleted file mode 100644 index d98714e0..00000000 --- a/vendor/github.com/hashicorp/go-hclog/log.go +++ /dev/null @@ -1,161 +0,0 @@ -package hclog - -import ( - "io" - "log" - "os" - "strings" - "sync" -) - -var ( - DefaultOutput = os.Stderr - DefaultLevel = Info -) - -type Level int32 - -const ( - // This is a special level used to indicate that no level has been - // set and allow for a default to be used. - NoLevel Level = 0 - - // The most verbose level. Intended to be used for the tracing of actions - // in code, such as function enters/exits, etc. - Trace Level = 1 - - // For programmer lowlevel analysis. - Debug Level = 2 - - // For information about steady state operations. - Info Level = 3 - - // For information about rare but handled events. - Warn Level = 4 - - // For information about unrecoverable events. - Error Level = 5 -) - -// When processing a value of this type, the logger automatically treats the first -// argument as a Printf formatting string and passes the rest as the values to be -// formatted. For example: L.Info(Fmt{"%d beans/day", beans}). This is a simple -// convience type for when formatting is required. -type Format []interface{} - -// Fmt returns a Format type. This is a convience function for creating a Format -// type. -func Fmt(str string, args ...interface{}) Format { - return append(Format{str}, args...) -} - -// LevelFromString returns a Level type for the named log level, or "NoLevel" if -// the level string is invalid. This facilitates setting the log level via -// config or environment variable by name in a predictable way. -func LevelFromString(levelStr string) Level { - // We don't care about case. Accept "INFO" or "info" - levelStr = strings.ToLower(strings.TrimSpace(levelStr)) - switch levelStr { - case "trace": - return Trace - case "debug": - return Debug - case "info": - return Info - case "warn": - return Warn - case "error": - return Error - default: - return NoLevel - } -} - -// The main Logger interface. All code should code against this interface only. -type Logger interface { - // Args are alternating key, val pairs - // keys must be strings - // vals can be any type, but display is implementation specific - // Emit a message and key/value pairs at the TRACE level - Trace(msg string, args ...interface{}) - - // Emit a message and key/value pairs at the DEBUG level - Debug(msg string, args ...interface{}) - - // Emit a message and key/value pairs at the INFO level - Info(msg string, args ...interface{}) - - // Emit a message and key/value pairs at the WARN level - Warn(msg string, args ...interface{}) - - // Emit a message and key/value pairs at the ERROR level - Error(msg string, args ...interface{}) - - // Indicate if TRACE logs would be emitted. This and the other Is* guards - // are used to elide expensive logging code based on the current level. - IsTrace() bool - - // Indicate if DEBUG logs would be emitted. This and the other Is* guards - IsDebug() bool - - // Indicate if INFO logs would be emitted. This and the other Is* guards - IsInfo() bool - - // Indicate if WARN logs would be emitted. This and the other Is* guards - IsWarn() bool - - // Indicate if ERROR logs would be emitted. This and the other Is* guards - IsError() bool - - // Creates a sublogger that will always have the given key/value pairs - With(args ...interface{}) Logger - - // Create a logger that will prepend the name string on the front of all messages. - // If the logger already has a name, the new value will be appended to the current - // name. That way, a major subsystem can use this to decorate all it's own logs - // without losing context. - Named(name string) Logger - - // Create a logger that will prepend the name string on the front of all messages. - // This sets the name of the logger to the value directly, unlike Named which honor - // the current name as well. - ResetNamed(name string) Logger - - // Updates the level. This should affect all sub-loggers as well. If an - // implementation cannot update the level on the fly, it should no-op. - SetLevel(level Level) - - // Return a value that conforms to the stdlib log.Logger interface - StandardLogger(opts *StandardLoggerOptions) *log.Logger -} - -type StandardLoggerOptions struct { - // Indicate that some minimal parsing should be done on strings to try - // and detect their level and re-emit them. - // This supports the strings like [ERROR], [ERR] [TRACE], [WARN], [INFO], - // [DEBUG] and strip it off before reapplying it. - InferLevels bool -} - -type LoggerOptions struct { - // Name of the subsystem to prefix logs with - Name string - - // The threshold for the logger. Anything less severe is supressed - Level Level - - // Where to write the logs to. Defaults to os.Stderr if nil - Output io.Writer - - // An optional mutex pointer in case Output is shared - Mutex *sync.Mutex - - // Control if the output should be in JSON. - JSONFormat bool - - // Include file and line information in each log line - IncludeLocation bool - - // The time format to use instead of the default - TimeFormat string -} diff --git a/vendor/github.com/hashicorp/go-hclog/nulllogger.go b/vendor/github.com/hashicorp/go-hclog/nulllogger.go deleted file mode 100644 index 0942361a..00000000 --- a/vendor/github.com/hashicorp/go-hclog/nulllogger.go +++ /dev/null @@ -1,47 +0,0 @@ -package hclog - -import ( - "io/ioutil" - "log" -) - -// NewNullLogger instantiates a Logger for which all calls -// will succeed without doing anything. -// Useful for testing purposes. -func NewNullLogger() Logger { - return &nullLogger{} -} - -type nullLogger struct{} - -func (l *nullLogger) Trace(msg string, args ...interface{}) {} - -func (l *nullLogger) Debug(msg string, args ...interface{}) {} - -func (l *nullLogger) Info(msg string, args ...interface{}) {} - -func (l *nullLogger) Warn(msg string, args ...interface{}) {} - -func (l *nullLogger) Error(msg string, args ...interface{}) {} - -func (l *nullLogger) IsTrace() bool { return false } - -func (l *nullLogger) IsDebug() bool { return false } - -func (l *nullLogger) IsInfo() bool { return false } - -func (l *nullLogger) IsWarn() bool { return false } - -func (l *nullLogger) IsError() bool { return false } - -func (l *nullLogger) With(args ...interface{}) Logger { return l } - -func (l *nullLogger) Named(name string) Logger { return l } - -func (l *nullLogger) ResetNamed(name string) Logger { return l } - -func (l *nullLogger) SetLevel(level Level) {} - -func (l *nullLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { - return log.New(ioutil.Discard, "", log.LstdFlags) -} diff --git a/vendor/github.com/hashicorp/go-hclog/stacktrace.go b/vendor/github.com/hashicorp/go-hclog/stacktrace.go deleted file mode 100644 index 8af1a3be..00000000 --- a/vendor/github.com/hashicorp/go-hclog/stacktrace.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2016 Uber Technologies, Inc. -// -// 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. - -package hclog - -import ( - "bytes" - "runtime" - "strconv" - "strings" - "sync" -) - -var ( - _stacktraceIgnorePrefixes = []string{ - "runtime.goexit", - "runtime.main", - } - _stacktracePool = sync.Pool{ - New: func() interface{} { - return newProgramCounters(64) - }, - } -) - -// A stacktrace gathered by a previous call to log.Stacktrace. If passed -// to a logging function, the stacktrace will be appended. -type CapturedStacktrace string - -// Gather a stacktrace of the current goroutine and return it to be passed -// to a logging function. -func Stacktrace() CapturedStacktrace { - return CapturedStacktrace(takeStacktrace()) -} - -func takeStacktrace() string { - programCounters := _stacktracePool.Get().(*programCounters) - defer _stacktracePool.Put(programCounters) - - var buffer bytes.Buffer - - for { - // Skip the call to runtime.Counters and takeStacktrace so that the - // program counters start at the caller of takeStacktrace. - n := runtime.Callers(2, programCounters.pcs) - if n < cap(programCounters.pcs) { - programCounters.pcs = programCounters.pcs[:n] - break - } - // Don't put the too-short counter slice back into the pool; this lets - // the pool adjust if we consistently take deep stacktraces. - programCounters = newProgramCounters(len(programCounters.pcs) * 2) - } - - i := 0 - frames := runtime.CallersFrames(programCounters.pcs) - for frame, more := frames.Next(); more; frame, more = frames.Next() { - if shouldIgnoreStacktraceFunction(frame.Function) { - continue - } - if i != 0 { - buffer.WriteByte('\n') - } - i++ - buffer.WriteString(frame.Function) - buffer.WriteByte('\n') - buffer.WriteByte('\t') - buffer.WriteString(frame.File) - buffer.WriteByte(':') - buffer.WriteString(strconv.Itoa(int(frame.Line))) - } - - return buffer.String() -} - -func shouldIgnoreStacktraceFunction(function string) bool { - for _, prefix := range _stacktraceIgnorePrefixes { - if strings.HasPrefix(function, prefix) { - return true - } - } - return false -} - -type programCounters struct { - pcs []uintptr -} - -func newProgramCounters(size int) *programCounters { - return &programCounters{make([]uintptr, size)} -} diff --git a/vendor/github.com/hashicorp/go-hclog/stdlog.go b/vendor/github.com/hashicorp/go-hclog/stdlog.go deleted file mode 100644 index 2bb927fc..00000000 --- a/vendor/github.com/hashicorp/go-hclog/stdlog.go +++ /dev/null @@ -1,62 +0,0 @@ -package hclog - -import ( - "bytes" - "strings" -) - -// Provides a io.Writer to shim the data out of *log.Logger -// and back into our Logger. This is basically the only way to -// build upon *log.Logger. -type stdlogAdapter struct { - hl Logger - inferLevels bool -} - -// Take the data, infer the levels if configured, and send it through -// a regular Logger -func (s *stdlogAdapter) Write(data []byte) (int, error) { - str := string(bytes.TrimRight(data, " \t\n")) - - if s.inferLevels { - level, str := s.pickLevel(str) - switch level { - case Trace: - s.hl.Trace(str) - case Debug: - s.hl.Debug(str) - case Info: - s.hl.Info(str) - case Warn: - s.hl.Warn(str) - case Error: - s.hl.Error(str) - default: - s.hl.Info(str) - } - } else { - s.hl.Info(str) - } - - return len(data), nil -} - -// Detect, based on conventions, what log level this is -func (s *stdlogAdapter) pickLevel(str string) (Level, string) { - switch { - case strings.HasPrefix(str, "[DEBUG]"): - return Debug, strings.TrimSpace(str[7:]) - case strings.HasPrefix(str, "[TRACE]"): - return Trace, strings.TrimSpace(str[7:]) - case strings.HasPrefix(str, "[INFO]"): - return Info, strings.TrimSpace(str[6:]) - case strings.HasPrefix(str, "[WARN]"): - return Warn, strings.TrimSpace(str[7:]) - case strings.HasPrefix(str, "[ERROR]"): - return Error, strings.TrimSpace(str[7:]) - case strings.HasPrefix(str, "[ERR]"): - return Error, strings.TrimSpace(str[5:]) - default: - return Info, str - } -} diff --git a/vendor/github.com/hashicorp/go-immutable-radix/.gitignore b/vendor/github.com/hashicorp/go-immutable-radix/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/.gitignore +++ /dev/null @@ -1,24 +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 -*.prof diff --git a/vendor/github.com/hashicorp/go-immutable-radix/.travis.yml b/vendor/github.com/hashicorp/go-immutable-radix/.travis.yml deleted file mode 100644 index 1a0bbea6..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: go -go: - - tip diff --git a/vendor/github.com/hashicorp/go-immutable-radix/LICENSE b/vendor/github.com/hashicorp/go-immutable-radix/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/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-immutable-radix/README.md b/vendor/github.com/hashicorp/go-immutable-radix/README.md deleted file mode 100644 index 8910fcc0..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/README.md +++ /dev/null @@ -1,41 +0,0 @@ -go-immutable-radix [![Build Status](https://travis-ci.org/hashicorp/go-immutable-radix.png)](https://travis-ci.org/hashicorp/go-immutable-radix) -========= - -Provides the `iradix` package that implements an immutable [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 - -A tree supports using a transaction to batch multiple updates (insert, delete) -in a more efficient manner than performing each operation one at a time. - -For a mutable variant, see [go-radix](https://github.com/armon/go-radix). - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-immutable-radix). - -Example -======= - -Below is a simple example of usage - -```go -// Create a tree -r := iradix.New() -r, _, _ = r.Insert([]byte("foo"), 1) -r, _, _ = r.Insert([]byte("bar"), 2) -r, _, _ = r.Insert([]byte("foobar"), 2) - -// Find the longest prefix match -m, _, _ := r.Root().LongestPrefix([]byte("foozip")) -if string(m) != "foo" { - panic("should be foo") -} -``` - diff --git a/vendor/github.com/hashicorp/go-immutable-radix/edges.go b/vendor/github.com/hashicorp/go-immutable-radix/edges.go deleted file mode 100644 index a6367477..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/edges.go +++ /dev/null @@ -1,21 +0,0 @@ -package iradix - -import "sort" - -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) -} diff --git a/vendor/github.com/hashicorp/go-immutable-radix/go.mod b/vendor/github.com/hashicorp/go-immutable-radix/go.mod deleted file mode 100644 index 27e7b7c9..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/go.mod +++ /dev/null @@ -1,6 +0,0 @@ -module github.com/hashicorp/go-immutable-radix - -require ( - github.com/hashicorp/go-uuid v1.0.0 - github.com/hashicorp/golang-lru v0.5.0 -) diff --git a/vendor/github.com/hashicorp/go-immutable-radix/go.sum b/vendor/github.com/hashicorp/go-immutable-radix/go.sum deleted file mode 100644 index 7de5dfc5..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= diff --git a/vendor/github.com/hashicorp/go-immutable-radix/iradix.go b/vendor/github.com/hashicorp/go-immutable-radix/iradix.go deleted file mode 100644 index e5e6e57f..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/iradix.go +++ /dev/null @@ -1,662 +0,0 @@ -package iradix - -import ( - "bytes" - "strings" - - "github.com/hashicorp/golang-lru/simplelru" -) - -const ( - // defaultModifiedCache is the default size of the modified node - // cache used per transaction. This is used to cache the updates - // to the nodes near the root, while the leaves do not need to be - // cached. This is important for very large transactions to prevent - // the modified cache from growing to be enormous. This is also used - // to set the max size of the mutation notify maps since those should - // also be bounded in a similar way. - defaultModifiedCache = 8192 -) - -// Tree implements an immutable 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. The immutability -// means that it is safe to concurrently read from a Tree without any -// coordination. -type Tree struct { - root *Node - size int -} - -// New returns an empty Tree -func New() *Tree { - t := &Tree{ - root: &Node{ - mutateCh: make(chan struct{}), - }, - } - return t -} - -// Len is used to return the number of elements in the tree -func (t *Tree) Len() int { - return t.size -} - -// Txn is a transaction on the tree. This transaction is applied -// atomically and returns a new tree when committed. A transaction -// is not thread safe, and should only be used by a single goroutine. -type Txn struct { - // root is the modified root for the transaction. - root *Node - - // snap is a snapshot of the root node for use if we have to run the - // slow notify algorithm. - snap *Node - - // size tracks the size of the tree as it is modified during the - // transaction. - size int - - // writable is a cache of writable nodes that have been created during - // the course of the transaction. This allows us to re-use the same - // nodes for further writes and avoid unnecessary copies of nodes that - // have never been exposed outside the transaction. This will only hold - // up to defaultModifiedCache number of entries. - writable *simplelru.LRU - - // trackChannels is used to hold channels that need to be notified to - // signal mutation of the tree. This will only hold up to - // defaultModifiedCache number of entries, after which we will set the - // trackOverflow flag, which will cause us to use a more expensive - // algorithm to perform the notifications. Mutation tracking is only - // performed if trackMutate is true. - trackChannels map[chan struct{}]struct{} - trackOverflow bool - trackMutate bool -} - -// Txn starts a new transaction that can be used to mutate the tree -func (t *Tree) Txn() *Txn { - txn := &Txn{ - root: t.root, - snap: t.root, - size: t.size, - } - return txn -} - -// TrackMutate can be used to toggle if mutations are tracked. If this is enabled -// then notifications will be issued for affected internal nodes and leaves when -// the transaction is committed. -func (t *Txn) TrackMutate(track bool) { - t.trackMutate = track -} - -// trackChannel safely attempts to track the given mutation channel, setting the -// overflow flag if we can no longer track any more. This limits the amount of -// state that will accumulate during a transaction and we have a slower algorithm -// to switch to if we overflow. -func (t *Txn) trackChannel(ch chan struct{}) { - // In overflow, make sure we don't store any more objects. - if t.trackOverflow { - return - } - - // If this would overflow the state we reject it and set the flag (since - // we aren't tracking everything that's required any longer). - if len(t.trackChannels) >= defaultModifiedCache { - // Mark that we are in the overflow state - t.trackOverflow = true - - // Clear the map so that the channels can be garbage collected. It is - // safe to do this since we have already overflowed and will be using - // the slow notify algorithm. - t.trackChannels = nil - return - } - - // Create the map on the fly when we need it. - if t.trackChannels == nil { - t.trackChannels = make(map[chan struct{}]struct{}) - } - - // Otherwise we are good to track it. - t.trackChannels[ch] = struct{}{} -} - -// writeNode returns a node to be modified, if the current node has already been -// modified during the course of the transaction, it is used in-place. Set -// forLeafUpdate to true if you are getting a write node to update the leaf, -// which will set leaf mutation tracking appropriately as well. -func (t *Txn) writeNode(n *Node, forLeafUpdate bool) *Node { - // Ensure the writable set exists. - if t.writable == nil { - lru, err := simplelru.NewLRU(defaultModifiedCache, nil) - if err != nil { - panic(err) - } - t.writable = lru - } - - // If this node has already been modified, we can continue to use it - // during this transaction. We know that we don't need to track it for - // a node update since the node is writable, but if this is for a leaf - // update we track it, in case the initial write to this node didn't - // update the leaf. - if _, ok := t.writable.Get(n); ok { - if t.trackMutate && forLeafUpdate && n.leaf != nil { - t.trackChannel(n.leaf.mutateCh) - } - return n - } - - // Mark this node as being mutated. - if t.trackMutate { - t.trackChannel(n.mutateCh) - } - - // Mark its leaf as being mutated, if appropriate. - if t.trackMutate && forLeafUpdate && n.leaf != nil { - t.trackChannel(n.leaf.mutateCh) - } - - // Copy the existing node. If you have set forLeafUpdate it will be - // safe to replace this leaf with another after you get your node for - // writing. You MUST replace it, because the channel associated with - // this leaf will be closed when this transaction is committed. - nc := &Node{ - mutateCh: make(chan struct{}), - leaf: n.leaf, - } - if n.prefix != nil { - nc.prefix = make([]byte, len(n.prefix)) - copy(nc.prefix, n.prefix) - } - if len(n.edges) != 0 { - nc.edges = make([]edge, len(n.edges)) - copy(nc.edges, n.edges) - } - - // Mark this node as writable. - t.writable.Add(nc, nil) - return nc -} - -// Visit all the nodes in the tree under n, and add their mutateChannels to the transaction -// Returns the size of the subtree visited -func (t *Txn) trackChannelsAndCount(n *Node) int { - // Count only leaf nodes - leaves := 0 - if n.leaf != nil { - leaves = 1 - } - // Mark this node as being mutated. - if t.trackMutate { - t.trackChannel(n.mutateCh) - } - - // Mark its leaf as being mutated, if appropriate. - if t.trackMutate && n.leaf != nil { - t.trackChannel(n.leaf.mutateCh) - } - - // Recurse on the children - for _, e := range n.edges { - leaves += t.trackChannelsAndCount(e.node) - } - return leaves -} - -// mergeChild is called to collapse the given node with its child. This is only -// called when the given node is not a leaf and has a single edge. -func (t *Txn) mergeChild(n *Node) { - // Mark the child node as being mutated since we are about to abandon - // it. We don't need to mark the leaf since we are retaining it if it - // is there. - e := n.edges[0] - child := e.node - if t.trackMutate { - t.trackChannel(child.mutateCh) - } - - // Merge the nodes. - n.prefix = concat(n.prefix, child.prefix) - n.leaf = child.leaf - if len(child.edges) != 0 { - n.edges = make([]edge, len(child.edges)) - copy(n.edges, child.edges) - } else { - n.edges = nil - } -} - -// insert does a recursive insertion -func (t *Txn) insert(n *Node, k, search []byte, v interface{}) (*Node, interface{}, bool) { - // Handle key exhaustion - if len(search) == 0 { - var oldVal interface{} - didUpdate := false - if n.isLeaf() { - oldVal = n.leaf.val - didUpdate = true - } - - nc := t.writeNode(n, true) - nc.leaf = &leafNode{ - mutateCh: make(chan struct{}), - key: k, - val: v, - } - return nc, oldVal, didUpdate - } - - // Look for the edge - idx, child := n.getEdge(search[0]) - - // No edge, create one - if child == nil { - e := edge{ - label: search[0], - node: &Node{ - mutateCh: make(chan struct{}), - leaf: &leafNode{ - mutateCh: make(chan struct{}), - key: k, - val: v, - }, - prefix: search, - }, - } - nc := t.writeNode(n, false) - nc.addEdge(e) - return nc, nil, false - } - - // Determine longest prefix of the search key on match - commonPrefix := longestPrefix(search, child.prefix) - if commonPrefix == len(child.prefix) { - search = search[commonPrefix:] - newChild, oldVal, didUpdate := t.insert(child, k, search, v) - if newChild != nil { - nc := t.writeNode(n, false) - nc.edges[idx].node = newChild - return nc, oldVal, didUpdate - } - return nil, oldVal, didUpdate - } - - // Split the node - nc := t.writeNode(n, false) - splitNode := &Node{ - mutateCh: make(chan struct{}), - prefix: search[:commonPrefix], - } - nc.replaceEdge(edge{ - label: search[0], - node: splitNode, - }) - - // Restore the existing child node - modChild := t.writeNode(child, false) - splitNode.addEdge(edge{ - label: modChild.prefix[commonPrefix], - node: modChild, - }) - modChild.prefix = modChild.prefix[commonPrefix:] - - // Create a new leaf node - leaf := &leafNode{ - mutateCh: make(chan struct{}), - key: k, - val: v, - } - - // If the new key is a subset, add to to this node - search = search[commonPrefix:] - if len(search) == 0 { - splitNode.leaf = leaf - return nc, nil, false - } - - // Create a new edge for the node - splitNode.addEdge(edge{ - label: search[0], - node: &Node{ - mutateCh: make(chan struct{}), - leaf: leaf, - prefix: search, - }, - }) - return nc, nil, false -} - -// delete does a recursive deletion -func (t *Txn) delete(parent, n *Node, search []byte) (*Node, *leafNode) { - // Check for key exhaustion - if len(search) == 0 { - if !n.isLeaf() { - return nil, nil - } - // Copy the pointer in case we are in a transaction that already - // modified this node since the node will be reused. Any changes - // made to the node will not affect returning the original leaf - // value. - oldLeaf := n.leaf - - // Remove the leaf node - nc := t.writeNode(n, true) - nc.leaf = nil - - // Check if this node should be merged - if n != t.root && len(nc.edges) == 1 { - t.mergeChild(nc) - } - return nc, oldLeaf - } - - // Look for an edge - label := search[0] - idx, child := n.getEdge(label) - if child == nil || !bytes.HasPrefix(search, child.prefix) { - return nil, nil - } - - // Consume the search prefix - search = search[len(child.prefix):] - newChild, leaf := t.delete(n, child, search) - if newChild == nil { - return nil, nil - } - - // Copy this node. WATCH OUT - it's safe to pass "false" here because we - // will only ADD a leaf via nc.mergeChild() if there isn't one due to - // the !nc.isLeaf() check in the logic just below. This is pretty subtle, - // so be careful if you change any of the logic here. - nc := t.writeNode(n, false) - - // Delete the edge if the node has no edges - if newChild.leaf == nil && len(newChild.edges) == 0 { - nc.delEdge(label) - if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() { - t.mergeChild(nc) - } - } else { - nc.edges[idx].node = newChild - } - return nc, leaf -} - -// delete does a recursive deletion -func (t *Txn) deletePrefix(parent, n *Node, search []byte) (*Node, int) { - // Check for key exhaustion - if len(search) == 0 { - nc := t.writeNode(n, true) - if n.isLeaf() { - nc.leaf = nil - } - nc.edges = nil - return nc, t.trackChannelsAndCount(n) - } - - // Look for an edge - label := search[0] - idx, child := n.getEdge(label) - // We make sure that either the child node's prefix starts with the search term, or the search term starts with the child node's prefix - // Need to do both so that we can delete prefixes that don't correspond to any node in the tree - if child == nil || (!bytes.HasPrefix(child.prefix, search) && !bytes.HasPrefix(search, child.prefix)) { - return nil, 0 - } - - // Consume the search prefix - if len(child.prefix) > len(search) { - search = []byte("") - } else { - search = search[len(child.prefix):] - } - newChild, numDeletions := t.deletePrefix(n, child, search) - if newChild == nil { - return nil, 0 - } - // Copy this node. WATCH OUT - it's safe to pass "false" here because we - // will only ADD a leaf via nc.mergeChild() if there isn't one due to - // the !nc.isLeaf() check in the logic just below. This is pretty subtle, - // so be careful if you change any of the logic here. - - nc := t.writeNode(n, false) - - // Delete the edge if the node has no edges - if newChild.leaf == nil && len(newChild.edges) == 0 { - nc.delEdge(label) - if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() { - t.mergeChild(nc) - } - } else { - nc.edges[idx].node = newChild - } - return nc, numDeletions -} - -// Insert is used to add or update a given key. The return provides -// the previous value and a bool indicating if any was set. -func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) { - newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v) - if newRoot != nil { - t.root = newRoot - } - if !didUpdate { - t.size++ - } - return oldVal, didUpdate -} - -// Delete is used to delete a given key. Returns the old value if any, -// and a bool indicating if the key was set. -func (t *Txn) Delete(k []byte) (interface{}, bool) { - newRoot, leaf := t.delete(nil, t.root, k) - if newRoot != nil { - t.root = newRoot - } - if leaf != nil { - t.size-- - return leaf.val, true - } - return nil, false -} - -// DeletePrefix is used to delete an entire subtree that matches the prefix -// This will delete all nodes under that prefix -func (t *Txn) DeletePrefix(prefix []byte) bool { - newRoot, numDeletions := t.deletePrefix(nil, t.root, prefix) - if newRoot != nil { - t.root = newRoot - t.size = t.size - numDeletions - return true - } - return false - -} - -// Root returns the current root of the radix tree within this -// transaction. The root is not safe across insert and delete operations, -// but can be used to read the current state during a transaction. -func (t *Txn) Root() *Node { - return t.root -} - -// Get is used to lookup a specific key, returning -// the value and if it was found -func (t *Txn) Get(k []byte) (interface{}, bool) { - return t.root.Get(k) -} - -// GetWatch is used to lookup a specific key, returning -// the watch channel, value and if it was found -func (t *Txn) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) { - return t.root.GetWatch(k) -} - -// Commit is used to finalize the transaction and return a new tree. If mutation -// tracking is turned on then notifications will also be issued. -func (t *Txn) Commit() *Tree { - nt := t.CommitOnly() - if t.trackMutate { - t.Notify() - } - return nt -} - -// CommitOnly is used to finalize the transaction and return a new tree, but -// does not issue any notifications until Notify is called. -func (t *Txn) CommitOnly() *Tree { - nt := &Tree{t.root, t.size} - t.writable = nil - return nt -} - -// slowNotify does a complete comparison of the before and after trees in order -// to trigger notifications. This doesn't require any additional state but it -// is very expensive to compute. -func (t *Txn) slowNotify() { - snapIter := t.snap.rawIterator() - rootIter := t.root.rawIterator() - for snapIter.Front() != nil || rootIter.Front() != nil { - // If we've exhausted the nodes in the old snapshot, we know - // there's nothing remaining to notify. - if snapIter.Front() == nil { - return - } - snapElem := snapIter.Front() - - // If we've exhausted the nodes in the new root, we know we need - // to invalidate everything that remains in the old snapshot. We - // know from the loop condition there's something in the old - // snapshot. - if rootIter.Front() == nil { - close(snapElem.mutateCh) - if snapElem.isLeaf() { - close(snapElem.leaf.mutateCh) - } - snapIter.Next() - continue - } - - // Do one string compare so we can check the various conditions - // below without repeating the compare. - cmp := strings.Compare(snapIter.Path(), rootIter.Path()) - - // If the snapshot is behind the root, then we must have deleted - // this node during the transaction. - if cmp < 0 { - close(snapElem.mutateCh) - if snapElem.isLeaf() { - close(snapElem.leaf.mutateCh) - } - snapIter.Next() - continue - } - - // If the snapshot is ahead of the root, then we must have added - // this node during the transaction. - if cmp > 0 { - rootIter.Next() - continue - } - - // If we have the same path, then we need to see if we mutated a - // node and possibly the leaf. - rootElem := rootIter.Front() - if snapElem != rootElem { - close(snapElem.mutateCh) - if snapElem.leaf != nil && (snapElem.leaf != rootElem.leaf) { - close(snapElem.leaf.mutateCh) - } - } - snapIter.Next() - rootIter.Next() - } -} - -// Notify is used along with TrackMutate to trigger notifications. This must -// only be done once a transaction is committed via CommitOnly, and it is called -// automatically by Commit. -func (t *Txn) Notify() { - if !t.trackMutate { - return - } - - // If we've overflowed the tracking state we can't use it in any way and - // need to do a full tree compare. - if t.trackOverflow { - t.slowNotify() - } else { - for ch := range t.trackChannels { - close(ch) - } - } - - // Clean up the tracking state so that a re-notify is safe (will trigger - // the else clause above which will be a no-op). - t.trackChannels = nil - t.trackOverflow = false -} - -// Insert is used to add or update a given key. The return provides -// the new tree, previous value and a bool indicating if any was set. -func (t *Tree) Insert(k []byte, v interface{}) (*Tree, interface{}, bool) { - txn := t.Txn() - old, ok := txn.Insert(k, v) - return txn.Commit(), old, ok -} - -// Delete is used to delete a given key. Returns the new tree, -// old value if any, and a bool indicating if the key was set. -func (t *Tree) Delete(k []byte) (*Tree, interface{}, bool) { - txn := t.Txn() - old, ok := txn.Delete(k) - return txn.Commit(), old, ok -} - -// DeletePrefix is used to delete all nodes starting with a given prefix. Returns the new tree, -// and a bool indicating if the prefix matched any nodes -func (t *Tree) DeletePrefix(k []byte) (*Tree, bool) { - txn := t.Txn() - ok := txn.DeletePrefix(k) - return txn.Commit(), ok -} - -// Root returns the root node of the tree which can be used for richer -// query operations. -func (t *Tree) Root() *Node { - return t.root -} - -// Get is used to lookup a specific key, returning -// the value and if it was found -func (t *Tree) Get(k []byte) (interface{}, bool) { - return t.root.Get(k) -} - -// longestPrefix finds the length of the shared prefix -// of two strings -func longestPrefix(k1, k2 []byte) 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 -} - -// concat two byte slices, returning a third new copy -func concat(a, b []byte) []byte { - c := make([]byte, len(a)+len(b)) - copy(c, a) - copy(c[len(a):], b) - return c -} diff --git a/vendor/github.com/hashicorp/go-immutable-radix/iter.go b/vendor/github.com/hashicorp/go-immutable-radix/iter.go deleted file mode 100644 index 9815e025..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/iter.go +++ /dev/null @@ -1,91 +0,0 @@ -package iradix - -import "bytes" - -// Iterator is used to iterate over a set of nodes -// in pre-order -type Iterator struct { - node *Node - stack []edges -} - -// SeekPrefixWatch is used to seek the iterator to a given prefix -// and returns the watch channel of the finest granularity -func (i *Iterator) SeekPrefixWatch(prefix []byte) (watch <-chan struct{}) { - // Wipe the stack - i.stack = nil - n := i.node - watch = n.mutateCh - search := prefix - for { - // Check for key exhaution - if len(search) == 0 { - i.node = n - return - } - - // Look for an edge - _, n = n.getEdge(search[0]) - if n == nil { - i.node = nil - return - } - - // Update to the finest granularity as the search makes progress - watch = n.mutateCh - - // Consume the search prefix - if bytes.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - - } else if bytes.HasPrefix(n.prefix, search) { - i.node = n - return - } else { - i.node = nil - return - } - } -} - -// SeekPrefix is used to seek the iterator to a given prefix -func (i *Iterator) SeekPrefix(prefix []byte) { - i.SeekPrefixWatch(prefix) -} - -// Next returns the next node in order -func (i *Iterator) Next() ([]byte, interface{}, bool) { - // Initialize our stack if needed - if i.stack == nil && i.node != nil { - i.stack = []edges{ - edges{ - edge{node: i.node}, - }, - } - } - - for len(i.stack) > 0 { - // Inspect the last element of the stack - n := len(i.stack) - last := i.stack[n-1] - elem := last[0].node - - // Update the stack - if len(last) > 1 { - i.stack[n-1] = last[1:] - } else { - i.stack = i.stack[:n-1] - } - - // Push the edges onto the frontier - if len(elem.edges) > 0 { - i.stack = append(i.stack, elem.edges) - } - - // Return the leaf values if any - if elem.leaf != nil { - return elem.leaf.key, elem.leaf.val, true - } - } - return nil, nil, false -} diff --git a/vendor/github.com/hashicorp/go-immutable-radix/node.go b/vendor/github.com/hashicorp/go-immutable-radix/node.go deleted file mode 100644 index 7a065e7a..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/node.go +++ /dev/null @@ -1,292 +0,0 @@ -package iradix - -import ( - "bytes" - "sort" -) - -// WalkFn is used when walking the tree. Takes a -// key and value, returning if iteration should -// be terminated. -type WalkFn func(k []byte, v interface{}) bool - -// leafNode is used to represent a value -type leafNode struct { - mutateCh chan struct{} - key []byte - val interface{} -} - -// edge is used to represent an edge node -type edge struct { - label byte - node *Node -} - -// Node is an immutable node in the radix tree -type Node struct { - // mutateCh is closed if this node is modified - mutateCh chan struct{} - - // leaf is used to store possible leaf - leaf *leafNode - - // prefix is the common prefix we ignore - prefix []byte - - // 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) { - num := len(n.edges) - idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= e.label - }) - n.edges = append(n.edges, e) - if idx != num { - copy(n.edges[idx+1:], n.edges[idx:num]) - n.edges[idx] = e - } -} - -func (n *Node) replaceEdge(e edge) { - num := len(n.edges) - idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= e.label - }) - if idx < num && n.edges[idx].label == e.label { - n.edges[idx].node = e.node - return - } - panic("replacing missing edge") -} - -func (n *Node) getEdge(label byte) (int, *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 idx, n.edges[idx].node - } - return -1, 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] - } -} - -func (n *Node) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) { - search := k - watch := n.mutateCh - for { - // Check for key exhaustion - if len(search) == 0 { - if n.isLeaf() { - return n.leaf.mutateCh, n.leaf.val, true - } - break - } - - // Look for an edge - _, n = n.getEdge(search[0]) - if n == nil { - break - } - - // Update to the finest granularity as the search makes progress - watch = n.mutateCh - - // Consume the search prefix - if bytes.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } - return watch, nil, false -} - -func (n *Node) Get(k []byte) (interface{}, bool) { - _, val, ok := n.GetWatch(k) - return val, ok -} - -// LongestPrefix is like Get, but instead of an -// exact match, it will return the longest prefix match. -func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) { - var last *leafNode - search := k - 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 bytes.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - } else { - break - } - } - if last != nil { - return last.key, last.val, true - } - return nil, nil, false -} - -// Minimum is used to return the minimum value in the tree -func (n *Node) Minimum() ([]byte, interface{}, bool) { - 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, nil, false -} - -// Maximum is used to return the maximum value in the tree -func (n *Node) Maximum() ([]byte, interface{}, bool) { - 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 - } else { - break - } - } - return nil, nil, false -} - -// Iterator is used to return an iterator at -// the given node to walk the tree -func (n *Node) Iterator() *Iterator { - return &Iterator{node: n} -} - -// rawIterator is used to return a raw iterator at the given node to walk the -// tree. -func (n *Node) rawIterator() *rawIterator { - iter := &rawIterator{node: n} - iter.Next() - return iter -} - -// Walk is used to walk the tree -func (n *Node) Walk(fn WalkFn) { - recursiveWalk(n, fn) -} - -// WalkPrefix is used to walk the tree under a prefix -func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) { - 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 bytes.HasPrefix(search, n.prefix) { - search = search[len(n.prefix):] - - } else if bytes.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 (n *Node) WalkPath(path []byte, fn WalkFn) { - 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 bytes.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 -} diff --git a/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go b/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go deleted file mode 100644 index 04814c13..00000000 --- a/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go +++ /dev/null @@ -1,78 +0,0 @@ -package iradix - -// rawIterator visits each of the nodes in the tree, even the ones that are not -// leaves. It keeps track of the effective path (what a leaf at a given node -// would be called), which is useful for comparing trees. -type rawIterator struct { - // node is the starting node in the tree for the iterator. - node *Node - - // stack keeps track of edges in the frontier. - stack []rawStackEntry - - // pos is the current position of the iterator. - pos *Node - - // path is the effective path of the current iterator position, - // regardless of whether the current node is a leaf. - path string -} - -// rawStackEntry is used to keep track of the cumulative common path as well as -// its associated edges in the frontier. -type rawStackEntry struct { - path string - edges edges -} - -// Front returns the current node that has been iterated to. -func (i *rawIterator) Front() *Node { - return i.pos -} - -// Path returns the effective path of the current node, even if it's not actually -// a leaf. -func (i *rawIterator) Path() string { - return i.path -} - -// Next advances the iterator to the next node. -func (i *rawIterator) Next() { - // Initialize our stack if needed. - if i.stack == nil && i.node != nil { - i.stack = []rawStackEntry{ - rawStackEntry{ - edges: edges{ - edge{node: i.node}, - }, - }, - } - } - - for len(i.stack) > 0 { - // Inspect the last element of the stack. - n := len(i.stack) - last := i.stack[n-1] - elem := last.edges[0].node - - // Update the stack. - if len(last.edges) > 1 { - i.stack[n-1].edges = last.edges[1:] - } else { - i.stack = i.stack[:n-1] - } - - // Push the edges onto the frontier. - if len(elem.edges) > 0 { - path := last.path + string(elem.prefix) - i.stack = append(i.stack, rawStackEntry{path, elem.edges}) - } - - i.pos = elem - i.path = last.path + string(elem.prefix) - return - } - - i.pos = nil - i.path = "" -} diff --git a/vendor/github.com/hashicorp/go-memdb/.gitignore b/vendor/github.com/hashicorp/go-memdb/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/hashicorp/go-memdb/.gitignore +++ /dev/null @@ -1,24 +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 -*.prof diff --git a/vendor/github.com/hashicorp/go-memdb/.travis.yml b/vendor/github.com/hashicorp/go-memdb/.travis.yml deleted file mode 100644 index 9e770fa2..00000000 --- a/vendor/github.com/hashicorp/go-memdb/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go - -go: - - "1.10" - -script: - - go test diff --git a/vendor/github.com/hashicorp/go-memdb/LICENSE b/vendor/github.com/hashicorp/go-memdb/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-memdb/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-memdb/README.md b/vendor/github.com/hashicorp/go-memdb/README.md deleted file mode 100644 index 65e1eaef..00000000 --- a/vendor/github.com/hashicorp/go-memdb/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# go-memdb - -Provides the `memdb` package that implements a simple in-memory database -built on immutable radix trees. The database provides Atomicity, Consistency -and Isolation from ACID. Being that it is in-memory, it does not provide durability. -The database is instantiated with a schema that specifies the tables and indices -that exist and allows transactions to be executed. - -The database provides the following: - -* Multi-Version Concurrency Control (MVCC) - By leveraging immutable radix trees - the database is able to support any number of concurrent readers without locking, - and allows a writer to make progress. - -* Transaction Support - The database allows for rich transactions, in which multiple - objects are inserted, updated or deleted. The transactions can span multiple tables, - and are applied atomically. The database provides atomicity and isolation in ACID - terminology, such that until commit the updates are not visible. - -* Rich Indexing - Tables can support any number of indexes, which can be simple like - a single field index, or more advanced compound field indexes. Certain types like - UUID can be efficiently compressed from strings into byte indexes for reduced - storage requirements. - -* Watches - Callers can populate a watch set as part of a query, which can be used to - detect when a modification has been made to the database which affects the query - results. This lets callers easily watch for changes in the database in a very general - way. - -For the underlying immutable radix trees, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix). - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-memdb). - -Example -======= - -Below is a simple example of usage - -```go -// Create a sample struct -type Person struct { - Email string - Name string - Age int -} - -// Create the DB schema -schema := &memdb.DBSchema{ - Tables: map[string]*memdb.TableSchema{ - "person": &memdb.TableSchema{ - Name: "person", - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{Field: "Email"}, - }, - }, - }, - }, -} - -// Create a new data base -db, err := memdb.NewMemDB(schema) -if err != nil { - panic(err) -} - -// Create a write transaction -txn := db.Txn(true) - -// Insert a new person -p := &Person{"joe@aol.com", "Joe", 30} -if err := txn.Insert("person", p); err != nil { - panic(err) -} - -// Commit the transaction -txn.Commit() - -// Create read-only transaction -txn = db.Txn(false) -defer txn.Abort() - -// Lookup by email -raw, err := txn.First("person", "id", "joe@aol.com") -if err != nil { - panic(err) -} - -// Say hi! -fmt.Printf("Hello %s!", raw.(*Person).Name) - -``` - diff --git a/vendor/github.com/hashicorp/go-memdb/filter.go b/vendor/github.com/hashicorp/go-memdb/filter.go deleted file mode 100644 index 2e3a9b3f..00000000 --- a/vendor/github.com/hashicorp/go-memdb/filter.go +++ /dev/null @@ -1,33 +0,0 @@ -package memdb - -// FilterFunc is a function that takes the results of an iterator and returns -// whether the result should be filtered out. -type FilterFunc func(interface{}) bool - -// FilterIterator is used to wrap a ResultIterator and apply a filter over it. -type FilterIterator struct { - // filter is the filter function applied over the base iterator. - filter FilterFunc - - // iter is the iterator that is being wrapped. - iter ResultIterator -} - -func NewFilterIterator(wrap ResultIterator, filter FilterFunc) *FilterIterator { - return &FilterIterator{ - filter: filter, - iter: wrap, - } -} - -// WatchCh returns the watch channel of the wrapped iterator. -func (f *FilterIterator) WatchCh() <-chan struct{} { return f.iter.WatchCh() } - -// Next returns the next non-filtered result from the wrapped iterator -func (f *FilterIterator) Next() interface{} { - for { - if value := f.iter.Next(); value == nil || !f.filter(value) { - return value - } - } -} diff --git a/vendor/github.com/hashicorp/go-memdb/index.go b/vendor/github.com/hashicorp/go-memdb/index.go deleted file mode 100644 index 23bcbcd4..00000000 --- a/vendor/github.com/hashicorp/go-memdb/index.go +++ /dev/null @@ -1,582 +0,0 @@ -package memdb - -import ( - "encoding/binary" - "encoding/hex" - "fmt" - "reflect" - "strings" -) - -// Indexer is an interface used for defining indexes. Indexes are used -// for efficient lookup of objects in a MemDB table. An Indexer must also -// implement one of SingleIndexer or MultiIndexer. -// -// Indexers are primarily responsible for returning the lookup key as -// a byte slice. The byte slice is the key data in the underlying data storage. -type Indexer interface { - // FromArgs is called to build the exact index key from a list of arguments. - FromArgs(args ...interface{}) ([]byte, error) -} - -// SingleIndexer is an interface used for defining indexes that generate a -// single value per object -type SingleIndexer interface { - // FromObject extracts the index value from an object. The return values - // are whether the index value was found, the index value, and any error - // while extracting the index value, respectively. - FromObject(raw interface{}) (bool, []byte, error) -} - -// MultiIndexer is an interface used for defining indexes that generate -// multiple values per object. Each value is stored as a seperate index -// pointing to the same object. -// -// For example, an index that extracts the first and last name of a person -// and allows lookup based on eitherd would be a MultiIndexer. The FromObject -// of this example would split the first and last name and return both as -// values. -type MultiIndexer interface { - // FromObject extracts index values from an object. The return values - // are the same as a SingleIndexer except there can be multiple index - // values. - FromObject(raw interface{}) (bool, [][]byte, error) -} - -// PrefixIndexer is an optional interface on top of an Indexer that allows -// indexes to support prefix-based iteration. -type PrefixIndexer interface { - // PrefixFromArgs is the same as FromArgs for an Indexer except that - // the index value returned should return all prefix-matched values. - PrefixFromArgs(args ...interface{}) ([]byte, error) -} - -// StringFieldIndex is used to extract a field from an object -// using reflection and builds an index on that field. -type StringFieldIndex struct { - Field string - Lowercase bool -} - -func (s *StringFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - fv = reflect.Indirect(fv) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - val := fv.String() - if val == "" { - return false, nil, nil - } - - if s.Lowercase { - val = strings.ToLower(val) - } - - // Add the null character as a terminator - val += "\x00" - return true, []byte(val), nil -} - -func (s *StringFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - arg, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - arg = strings.ToLower(arg) - } - // Add the null character as a terminator - arg += "\x00" - return []byte(arg), nil -} - -func (s *StringFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - val, err := s.FromArgs(args...) - if err != nil { - return nil, err - } - - // Strip the null terminator, the rest is a prefix - n := len(val) - if n > 0 { - return val[:n-1], nil - } - return val, nil -} - -// StringSliceFieldIndex builds an index from a field on an object that is a -// string slice ([]string). Each value within the string slice can be used for -// lookup. -type StringSliceFieldIndex struct { - Field string - Lowercase bool -} - -func (s *StringSliceFieldIndex) FromObject(obj interface{}) (bool, [][]byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - if fv.Kind() != reflect.Slice || fv.Type().Elem().Kind() != reflect.String { - return false, nil, fmt.Errorf("field '%s' is not a string slice", s.Field) - } - - length := fv.Len() - vals := make([][]byte, 0, length) - for i := 0; i < fv.Len(); i++ { - val := fv.Index(i).String() - if val == "" { - continue - } - - if s.Lowercase { - val = strings.ToLower(val) - } - - // Add the null character as a terminator - val += "\x00" - vals = append(vals, []byte(val)) - } - if len(vals) == 0 { - return false, nil, nil - } - return true, vals, nil -} - -func (s *StringSliceFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - arg, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - arg = strings.ToLower(arg) - } - // Add the null character as a terminator - arg += "\x00" - return []byte(arg), nil -} - -func (s *StringSliceFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - val, err := s.FromArgs(args...) - if err != nil { - return nil, err - } - - // Strip the null terminator, the rest is a prefix - n := len(val) - if n > 0 { - return val[:n-1], nil - } - return val, nil -} - -// StringMapFieldIndex is used to extract a field of type map[string]string -// from an object using reflection and builds an index on that field. -type StringMapFieldIndex struct { - Field string - Lowercase bool -} - -var MapType = reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")).Kind() - -func (s *StringMapFieldIndex) FromObject(obj interface{}) (bool, [][]byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - if !fv.IsValid() { - return false, nil, fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - if fv.Kind() != MapType { - return false, nil, fmt.Errorf("field '%s' is not a map[string]string", s.Field) - } - - length := fv.Len() - vals := make([][]byte, 0, length) - for _, key := range fv.MapKeys() { - k := key.String() - if k == "" { - continue - } - val := fv.MapIndex(key).String() - - if s.Lowercase { - k = strings.ToLower(k) - val = strings.ToLower(val) - } - - // Add the null character as a terminator - k += "\x00" + val + "\x00" - - vals = append(vals, []byte(k)) - } - if len(vals) == 0 { - return false, nil, nil - } - return true, vals, nil -} - -func (s *StringMapFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) > 2 || len(args) == 0 { - return nil, fmt.Errorf("must provide one or two arguments") - } - key, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - key = strings.ToLower(key) - } - // Add the null character as a terminator - key += "\x00" - - if len(args) == 2 { - val, ok := args[1].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[1]) - } - if s.Lowercase { - val = strings.ToLower(val) - } - // Add the null character as a terminator - key += val + "\x00" - } - - return []byte(key), nil -} - -// UintFieldIndex is used to extract a uint field from an object using -// reflection and builds an index on that field. -type UintFieldIndex struct { - Field string -} - -func (u *UintFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(u.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", u.Field, obj) - } - - // Check the type - k := fv.Kind() - size, ok := IsUintType(k) - if !ok { - return false, nil, fmt.Errorf("field %q is of type %v; want a uint", u.Field, k) - } - - // Get the value and encode it - val := fv.Uint() - buf := make([]byte, size) - binary.PutUvarint(buf, val) - - return true, buf, nil -} - -func (u *UintFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - - v := reflect.ValueOf(args[0]) - if !v.IsValid() { - return nil, fmt.Errorf("%#v is invalid", args[0]) - } - - k := v.Kind() - size, ok := IsUintType(k) - if !ok { - return nil, fmt.Errorf("arg is of type %v; want a uint", k) - } - - val := v.Uint() - buf := make([]byte, size) - binary.PutUvarint(buf, val) - - return buf, nil -} - -// IsUintType returns whether the passed type is a type of uint and the number -// of bytes needed to encode the type. -func IsUintType(k reflect.Kind) (size int, okay bool) { - switch k { - case reflect.Uint: - return binary.MaxVarintLen64, true - case reflect.Uint8: - return 2, true - case reflect.Uint16: - return binary.MaxVarintLen16, true - case reflect.Uint32: - return binary.MaxVarintLen32, true - case reflect.Uint64: - return binary.MaxVarintLen64, true - default: - return 0, false - } -} - -// UUIDFieldIndex is used to extract a field from an object -// using reflection and builds an index on that field by treating -// it as a UUID. This is an optimization to using a StringFieldIndex -// as the UUID can be more compactly represented in byte form. -type UUIDFieldIndex struct { - Field string -} - -func (u *UUIDFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(u.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", u.Field, obj) - } - - val := fv.String() - if val == "" { - return false, nil, nil - } - - buf, err := u.parseString(val, true) - return true, buf, err -} - -func (u *UUIDFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - switch arg := args[0].(type) { - case string: - return u.parseString(arg, true) - case []byte: - if len(arg) != 16 { - return nil, fmt.Errorf("byte slice must be 16 characters") - } - return arg, nil - default: - return nil, - fmt.Errorf("argument must be a string or byte slice: %#v", args[0]) - } -} - -func (u *UUIDFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - switch arg := args[0].(type) { - case string: - return u.parseString(arg, false) - case []byte: - return arg, nil - default: - return nil, - fmt.Errorf("argument must be a string or byte slice: %#v", args[0]) - } -} - -// parseString parses a UUID from the string. If enforceLength is false, it will -// parse a partial UUID. An error is returned if the input, stripped of hyphens, -// is not even length. -func (u *UUIDFieldIndex) parseString(s string, enforceLength bool) ([]byte, error) { - // Verify the length - l := len(s) - if enforceLength && l != 36 { - return nil, fmt.Errorf("UUID must be 36 characters") - } else if l > 36 { - return nil, fmt.Errorf("Invalid UUID length. UUID have 36 characters; got %d", l) - } - - hyphens := strings.Count(s, "-") - if hyphens > 4 { - return nil, fmt.Errorf(`UUID should have maximum of 4 "-"; got %d`, hyphens) - } - - // The sanitized length is the length of the original string without the "-". - sanitized := strings.Replace(s, "-", "", -1) - sanitizedLength := len(sanitized) - if sanitizedLength%2 != 0 { - return nil, fmt.Errorf("Input (without hyphens) must be even length") - } - - dec, err := hex.DecodeString(sanitized) - if err != nil { - return nil, fmt.Errorf("Invalid UUID: %v", err) - } - - return dec, nil -} - -// FieldSetIndex is used to extract a field from an object using reflection and -// builds an index on whether the field is set by comparing it against its -// type's nil value. -type FieldSetIndex struct { - Field string -} - -func (f *FieldSetIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(f.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", f.Field, obj) - } - - if fv.Interface() == reflect.Zero(fv.Type()).Interface() { - return true, []byte{0}, nil - } - - return true, []byte{1}, nil -} - -func (f *FieldSetIndex) FromArgs(args ...interface{}) ([]byte, error) { - return fromBoolArgs(args) -} - -// ConditionalIndex builds an index based on a condition specified by a passed -// user function. This function may examine the passed object and return a -// boolean to encapsulate an arbitrarily complex conditional. -type ConditionalIndex struct { - Conditional ConditionalIndexFunc -} - -// ConditionalIndexFunc is the required function interface for a -// ConditionalIndex. -type ConditionalIndexFunc func(obj interface{}) (bool, error) - -func (c *ConditionalIndex) FromObject(obj interface{}) (bool, []byte, error) { - // Call the user's function - res, err := c.Conditional(obj) - if err != nil { - return false, nil, fmt.Errorf("ConditionalIndexFunc(%#v) failed: %v", obj, err) - } - - if res { - return true, []byte{1}, nil - } - - return true, []byte{0}, nil -} - -func (c *ConditionalIndex) FromArgs(args ...interface{}) ([]byte, error) { - return fromBoolArgs(args) -} - -// fromBoolArgs is a helper that expects only a single boolean argument and -// returns a single length byte array containing either a one or zero depending -// on whether the passed input is true or false respectively. -func fromBoolArgs(args []interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - - if val, ok := args[0].(bool); !ok { - return nil, fmt.Errorf("argument must be a boolean type: %#v", args[0]) - } else if val { - return []byte{1}, nil - } - - return []byte{0}, nil -} - -// CompoundIndex is used to build an index using multiple sub-indexes -// Prefix based iteration is supported as long as the appropriate prefix -// of indexers support it. All sub-indexers are only assumed to expect -// a single argument. -type CompoundIndex struct { - Indexes []Indexer - - // AllowMissing results in an index based on only the indexers - // that return data. If true, you may end up with 2/3 columns - // indexed which might be useful for an index scan. Otherwise, - // the CompoundIndex requires all indexers to be satisfied. - AllowMissing bool -} - -func (c *CompoundIndex) FromObject(raw interface{}) (bool, []byte, error) { - var out []byte - for i, idxRaw := range c.Indexes { - idx, ok := idxRaw.(SingleIndexer) - if !ok { - return false, nil, fmt.Errorf("sub-index %d error: %s", i, "sub-index must be a SingleIndexer") - } - ok, val, err := idx.FromObject(raw) - if err != nil { - return false, nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - if !ok { - if c.AllowMissing { - break - } else { - return false, nil, nil - } - } - out = append(out, val...) - } - return true, out, nil -} - -func (c *CompoundIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != len(c.Indexes) { - return nil, fmt.Errorf("less arguments than index fields") - } - var out []byte - for i, arg := range args { - val, err := c.Indexes[i].FromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } - return out, nil -} - -func (c *CompoundIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - if len(args) > len(c.Indexes) { - return nil, fmt.Errorf("more arguments than index fields") - } - var out []byte - for i, arg := range args { - if i+1 < len(args) { - val, err := c.Indexes[i].FromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } else { - prefixIndexer, ok := c.Indexes[i].(PrefixIndexer) - if !ok { - return nil, fmt.Errorf("sub-index %d does not support prefix scanning", i) - } - val, err := prefixIndexer.PrefixFromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } - } - return out, nil -} diff --git a/vendor/github.com/hashicorp/go-memdb/memdb.go b/vendor/github.com/hashicorp/go-memdb/memdb.go deleted file mode 100644 index 65c92073..00000000 --- a/vendor/github.com/hashicorp/go-memdb/memdb.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package memdb provides an in-memory database that supports transactions -// and MVCC. -package memdb - -import ( - "sync" - "sync/atomic" - "unsafe" - - "github.com/hashicorp/go-immutable-radix" -) - -// MemDB is an in-memory database. -// -// MemDB provides a table abstraction to store objects (rows) with multiple -// indexes based on inserted values. The database makes use of immutable radix -// trees to provide transactions and MVCC. -type MemDB struct { - schema *DBSchema - root unsafe.Pointer // *iradix.Tree underneath - primary bool - - // There can only be a single writer at once - writer sync.Mutex -} - -// NewMemDB creates a new MemDB with the given schema -func NewMemDB(schema *DBSchema) (*MemDB, error) { - // Validate the schema - if err := schema.Validate(); err != nil { - return nil, err - } - - // Create the MemDB - db := &MemDB{ - schema: schema, - root: unsafe.Pointer(iradix.New()), - primary: true, - } - if err := db.initialize(); err != nil { - return nil, err - } - - return db, nil -} - -// getRoot is used to do an atomic load of the root pointer -func (db *MemDB) getRoot() *iradix.Tree { - root := (*iradix.Tree)(atomic.LoadPointer(&db.root)) - return root -} - -// Txn is used to start a new transaction, in either read or write mode. -// There can only be a single concurrent writer, but any number of readers. -func (db *MemDB) Txn(write bool) *Txn { - if write { - db.writer.Lock() - } - txn := &Txn{ - db: db, - write: write, - rootTxn: db.getRoot().Txn(), - } - return txn -} - -// Snapshot is used to capture a point-in-time snapshot -// of the database that will not be affected by any write -// operations to the existing DB. -func (db *MemDB) Snapshot() *MemDB { - clone := &MemDB{ - schema: db.schema, - root: unsafe.Pointer(db.getRoot()), - primary: false, - } - return clone -} - -// initialize is used to setup the DB for use after creation. This should -// be called only once after allocating a MemDB. -func (db *MemDB) initialize() error { - root := db.getRoot() - for tName, tableSchema := range db.schema.Tables { - for iName := range tableSchema.Indexes { - index := iradix.New() - path := indexPath(tName, iName) - root, _, _ = root.Insert(path, index) - } - } - db.root = unsafe.Pointer(root) - return nil -} - -// indexPath returns the path from the root to the given table index -func indexPath(table, index string) []byte { - return []byte(table + "." + index) -} diff --git a/vendor/github.com/hashicorp/go-memdb/schema.go b/vendor/github.com/hashicorp/go-memdb/schema.go deleted file mode 100644 index e6a9b526..00000000 --- a/vendor/github.com/hashicorp/go-memdb/schema.go +++ /dev/null @@ -1,114 +0,0 @@ -package memdb - -import "fmt" - -// DBSchema is the schema to use for the full database with a MemDB instance. -// -// MemDB will require a valid schema. Schema validation can be tested using -// the Validate function. Calling this function is recommended in unit tests. -type DBSchema struct { - // Tables is the set of tables within this database. The key is the - // table name and must match the Name in TableSchema. - Tables map[string]*TableSchema -} - -// Validate validates the schema. -func (s *DBSchema) Validate() error { - if s == nil { - return fmt.Errorf("schema is nil") - } - - if len(s.Tables) == 0 { - return fmt.Errorf("schema has no tables defined") - } - - for name, table := range s.Tables { - if name != table.Name { - return fmt.Errorf("table name mis-match for '%s'", name) - } - - if err := table.Validate(); err != nil { - return fmt.Errorf("table %q: %s", name, err) - } - } - - return nil -} - -// TableSchema is the schema for a single table. -type TableSchema struct { - // Name of the table. This must match the key in the Tables map in DBSchema. - Name string - - // Indexes is the set of indexes for querying this table. The key - // is a unique name for the index and must match the Name in the - // IndexSchema. - Indexes map[string]*IndexSchema -} - -// Validate is used to validate the table schema -func (s *TableSchema) Validate() error { - if s.Name == "" { - return fmt.Errorf("missing table name") - } - - if len(s.Indexes) == 0 { - return fmt.Errorf("missing table indexes for '%s'", s.Name) - } - - if _, ok := s.Indexes["id"]; !ok { - return fmt.Errorf("must have id index") - } - - if !s.Indexes["id"].Unique { - return fmt.Errorf("id index must be unique") - } - - if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok { - return fmt.Errorf("id index must be a SingleIndexer") - } - - for name, index := range s.Indexes { - if name != index.Name { - return fmt.Errorf("index name mis-match for '%s'", name) - } - - if err := index.Validate(); err != nil { - return fmt.Errorf("index %q: %s", name, err) - } - } - - return nil -} - -// IndexSchema is the schema for an index. An index defines how a table is -// queried. -type IndexSchema struct { - // Name of the index. This must be unique among a tables set of indexes. - // This must match the key in the map of Indexes for a TableSchema. - Name string - - // AllowMissing if true ignores this index if it doesn't produce a - // value. For example, an index that extracts a field that doesn't - // exist from a structure. - AllowMissing bool - - Unique bool - Indexer Indexer -} - -func (s *IndexSchema) Validate() error { - if s.Name == "" { - return fmt.Errorf("missing index name") - } - if s.Indexer == nil { - return fmt.Errorf("missing index function for '%s'", s.Name) - } - switch s.Indexer.(type) { - case SingleIndexer: - case MultiIndexer: - default: - return fmt.Errorf("indexer for '%s' must be a SingleIndexer or MultiIndexer", s.Name) - } - return nil -} diff --git a/vendor/github.com/hashicorp/go-memdb/txn.go b/vendor/github.com/hashicorp/go-memdb/txn.go deleted file mode 100644 index 2b85087e..00000000 --- a/vendor/github.com/hashicorp/go-memdb/txn.go +++ /dev/null @@ -1,644 +0,0 @@ -package memdb - -import ( - "bytes" - "fmt" - "strings" - "sync/atomic" - "unsafe" - - "github.com/hashicorp/go-immutable-radix" -) - -const ( - id = "id" -) - -var ( - // ErrNotFound is returned when the requested item is not found - ErrNotFound = fmt.Errorf("not found") -) - -// tableIndex is a tuple of (Table, Index) used for lookups -type tableIndex struct { - Table string - Index string -} - -// Txn is a transaction against a MemDB. -// This can be a read or write transaction. -type Txn struct { - db *MemDB - write bool - rootTxn *iradix.Txn - after []func() - - modified map[tableIndex]*iradix.Txn -} - -// readableIndex returns a transaction usable for reading the given -// index in a table. If a write transaction is in progress, we may need -// to use an existing modified txn. -func (txn *Txn) readableIndex(table, index string) *iradix.Txn { - // Look for existing transaction - if txn.write && txn.modified != nil { - key := tableIndex{table, index} - exist, ok := txn.modified[key] - if ok { - return exist - } - } - - // Create a read transaction - path := indexPath(table, index) - raw, _ := txn.rootTxn.Get(path) - indexTxn := raw.(*iradix.Tree).Txn() - return indexTxn -} - -// writableIndex returns a transaction usable for modifying the -// given index in a table. -func (txn *Txn) writableIndex(table, index string) *iradix.Txn { - if txn.modified == nil { - txn.modified = make(map[tableIndex]*iradix.Txn) - } - - // Look for existing transaction - key := tableIndex{table, index} - exist, ok := txn.modified[key] - if ok { - return exist - } - - // Start a new transaction - path := indexPath(table, index) - raw, _ := txn.rootTxn.Get(path) - indexTxn := raw.(*iradix.Tree).Txn() - - // If we are the primary DB, enable mutation tracking. Snapshots should - // not notify, otherwise we will trigger watches on the primary DB when - // the writes will not be visible. - indexTxn.TrackMutate(txn.db.primary) - - // Keep this open for the duration of the txn - txn.modified[key] = indexTxn - return indexTxn -} - -// Abort is used to cancel this transaction. -// This is a noop for read transactions. -func (txn *Txn) Abort() { - // Noop for a read transaction - if !txn.write { - return - } - - // Check if already aborted or committed - if txn.rootTxn == nil { - return - } - - // Clear the txn - txn.rootTxn = nil - txn.modified = nil - - // Release the writer lock since this is invalid - txn.db.writer.Unlock() -} - -// Commit is used to finalize this transaction. -// This is a noop for read transactions. -func (txn *Txn) Commit() { - // Noop for a read transaction - if !txn.write { - return - } - - // Check if already aborted or committed - if txn.rootTxn == nil { - return - } - - // Commit each sub-transaction scoped to (table, index) - for key, subTxn := range txn.modified { - path := indexPath(key.Table, key.Index) - final := subTxn.CommitOnly() - txn.rootTxn.Insert(path, final) - } - - // Update the root of the DB - newRoot := txn.rootTxn.CommitOnly() - atomic.StorePointer(&txn.db.root, unsafe.Pointer(newRoot)) - - // Now issue all of the mutation updates (this is safe to call - // even if mutation tracking isn't enabled); we do this after - // the root pointer is swapped so that waking responders will - // see the new state. - for _, subTxn := range txn.modified { - subTxn.Notify() - } - txn.rootTxn.Notify() - - // Clear the txn - txn.rootTxn = nil - txn.modified = nil - - // Release the writer lock since this is invalid - txn.db.writer.Unlock() - - // Run the deferred functions, if any - for i := len(txn.after); i > 0; i-- { - fn := txn.after[i-1] - fn() - } -} - -// Insert is used to add or update an object into the given table -func (txn *Txn) Insert(table string, obj interface{}) error { - if !txn.write { - return fmt.Errorf("cannot insert in read-only transaction") - } - - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return fmt.Errorf("invalid table '%s'", table) - } - - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(obj) - if err != nil { - return fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return fmt.Errorf("object missing primary index") - } - - // Lookup the object by ID first, to see if this is an update - idTxn := txn.writableIndex(table, id) - existing, update := idTxn.Get(idVal) - - // On an update, there is an existing object with the given - // primary ID. We do the update by deleting the current object - // and inserting the new object. - for name, indexSchema := range tableSchema.Indexes { - indexTxn := txn.writableIndex(table, name) - - // Determine the new index value - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(obj) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(obj) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - if ok && !indexSchema.Unique { - for i := range vals { - vals[i] = append(vals[i], idVal...) - } - } - - // Handle the update by deleting from the index first - if update { - var ( - okExist bool - valsExist [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var valExist []byte - okExist, valExist, err = indexer.FromObject(existing) - valsExist = [][]byte{valExist} - case MultiIndexer: - okExist, valsExist, err = indexer.FromObject(existing) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - if okExist { - for i, valExist := range valsExist { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - if !indexSchema.Unique { - valExist = append(valExist, idVal...) - } - - // If we are writing to the same index with the same value, - // we can avoid the delete as the insert will overwrite the - // value anyways. - if i >= len(vals) || !bytes.Equal(valExist, vals[i]) { - indexTxn.Delete(valExist) - } - } - } - } - - // If there is no index value, either this is an error or an expected - // case and we can skip updating - if !ok { - if indexSchema.AllowMissing { - continue - } else { - return fmt.Errorf("missing value for index '%s'", name) - } - } - - // Update the value of the index - for _, val := range vals { - indexTxn.Insert(val, obj) - } - } - return nil -} - -// Delete is used to delete a single object from the given table -// This object must already exist in the table -func (txn *Txn) Delete(table string, obj interface{}) error { - if !txn.write { - return fmt.Errorf("cannot delete in read-only transaction") - } - - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return fmt.Errorf("invalid table '%s'", table) - } - - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(obj) - if err != nil { - return fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return fmt.Errorf("object missing primary index") - } - - // Lookup the object by ID first, check fi we should continue - idTxn := txn.writableIndex(table, id) - existing, ok := idTxn.Get(idVal) - if !ok { - return ErrNotFound - } - - // Remove the object from all the indexes - for name, indexSchema := range tableSchema.Indexes { - indexTxn := txn.writableIndex(table, name) - - // Handle the update by deleting from the index first - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(existing) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(existing) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - if ok { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - for _, val := range vals { - if !indexSchema.Unique { - val = append(val, idVal...) - } - indexTxn.Delete(val) - } - } - } - return nil -} - -// DeletePrefix is used to delete an entire subtree based on a prefix. -// The given index must be a prefix index, and will be used to perform a scan and enumerate the set of objects to delete. -// These will be removed from all other indexes, and then a special prefix operation will delete the objects from the given index in an efficient subtree delete operation. -// This is useful when you have a very large number of objects indexed by the given index, along with a much smaller number of entries in the other indexes for those objects. -func (txn *Txn) DeletePrefix(table string, prefix_index string, prefix string) (bool, error) { - if !txn.write { - return false, fmt.Errorf("cannot delete in read-only transaction") - } - - if !strings.HasSuffix(prefix_index, "_prefix") { - return false, fmt.Errorf("Index name for DeletePrefix must be a prefix index, Got %v ", prefix_index) - } - - deletePrefixIndex := strings.TrimSuffix(prefix_index, "_prefix") - - // Get an iterator over all of the keys with the given prefix. - entries, err := txn.Get(table, prefix_index, prefix) - if err != nil { - return false, fmt.Errorf("failed kvs lookup: %s", err) - } - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return false, fmt.Errorf("invalid table '%s'", table) - } - - foundAny := false - for entry := entries.Next(); entry != nil; entry = entries.Next() { - if !foundAny { - foundAny = true - } - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(entry) - if err != nil { - return false, fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return false, fmt.Errorf("object missing primary index") - } - // Remove the object from all the indexes except the given prefix index - for name, indexSchema := range tableSchema.Indexes { - if name == deletePrefixIndex { - continue - } - indexTxn := txn.writableIndex(table, name) - - // Handle the update by deleting from the index first - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(entry) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(entry) - } - if err != nil { - return false, fmt.Errorf("failed to build index '%s': %v", name, err) - } - - if ok { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - for _, val := range vals { - if !indexSchema.Unique { - val = append(val, idVal...) - } - indexTxn.Delete(val) - } - } - } - } - if foundAny { - indexTxn := txn.writableIndex(table, deletePrefixIndex) - ok = indexTxn.DeletePrefix([]byte(prefix)) - if !ok { - panic(fmt.Errorf("prefix %v matched some entries but DeletePrefix did not delete any ", prefix)) - } - return true, nil - } - return false, nil -} - -// DeleteAll is used to delete all the objects in a given table -// matching the constraints on the index -func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) { - if !txn.write { - return 0, fmt.Errorf("cannot delete in read-only transaction") - } - - // Get all the objects - iter, err := txn.Get(table, index, args...) - if err != nil { - return 0, err - } - - // Put them into a slice so there are no safety concerns while actually - // performing the deletes - var objs []interface{} - for { - obj := iter.Next() - if obj == nil { - break - } - - objs = append(objs, obj) - } - - // Do the deletes - num := 0 - for _, obj := range objs { - if err := txn.Delete(table, obj); err != nil { - return num, err - } - num++ - } - return num, nil -} - -// FirstWatch is used to return the first matching object for -// the given constraints on the index along with the watch channel -func (txn *Txn) FirstWatch(table, index string, args ...interface{}) (<-chan struct{}, interface{}, error) { - // Get the index value - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, nil, err - } - - // Get the index itself - indexTxn := txn.readableIndex(table, indexSchema.Name) - - // Do an exact lookup - if indexSchema.Unique && val != nil && indexSchema.Name == index { - watch, obj, ok := indexTxn.GetWatch(val) - if !ok { - return watch, nil, nil - } - return watch, obj, nil - } - - // Handle non-unique index by using an iterator and getting the first value - iter := indexTxn.Root().Iterator() - watch := iter.SeekPrefixWatch(val) - _, value, _ := iter.Next() - return watch, value, nil -} - -// First is used to return the first matching object for -// the given constraints on the index -func (txn *Txn) First(table, index string, args ...interface{}) (interface{}, error) { - _, val, err := txn.FirstWatch(table, index, args...) - return val, err -} - -// LongestPrefix is used to fetch the longest prefix match for the given -// constraints on the index. Note that this will not work with the memdb -// StringFieldIndex because it adds null terminators which prevent the -// algorithm from correctly finding a match (it will get to right before the -// null and fail to find a leaf node). This should only be used where the prefix -// given is capable of matching indexed entries directly, which typically only -// applies to a custom indexer. See the unit test for an example. -func (txn *Txn) LongestPrefix(table, index string, args ...interface{}) (interface{}, error) { - // Enforce that this only works on prefix indexes. - if !strings.HasSuffix(index, "_prefix") { - return nil, fmt.Errorf("must use '%s_prefix' on index", index) - } - - // Get the index value. - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, err - } - - // This algorithm only makes sense against a unique index, otherwise the - // index keys will have the IDs appended to them. - if !indexSchema.Unique { - return nil, fmt.Errorf("index '%s' is not unique", index) - } - - // Find the longest prefix match with the given index. - indexTxn := txn.readableIndex(table, indexSchema.Name) - if _, value, ok := indexTxn.Root().LongestPrefix(val); ok { - return value, nil - } - return nil, nil -} - -// getIndexValue is used to get the IndexSchema and the value -// used to scan the index given the parameters. This handles prefix based -// scans when the index has the "_prefix" suffix. The index must support -// prefix iteration. -func (txn *Txn) getIndexValue(table, index string, args ...interface{}) (*IndexSchema, []byte, error) { - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return nil, nil, fmt.Errorf("invalid table '%s'", table) - } - - // Check for a prefix scan - prefixScan := false - if strings.HasSuffix(index, "_prefix") { - index = strings.TrimSuffix(index, "_prefix") - prefixScan = true - } - - // Get the index schema - indexSchema, ok := tableSchema.Indexes[index] - if !ok { - return nil, nil, fmt.Errorf("invalid index '%s'", index) - } - - // Hot-path for when there are no arguments - if len(args) == 0 { - return indexSchema, nil, nil - } - - // Special case the prefix scanning - if prefixScan { - prefixIndexer, ok := indexSchema.Indexer.(PrefixIndexer) - if !ok { - return indexSchema, nil, - fmt.Errorf("index '%s' does not support prefix scanning", index) - } - - val, err := prefixIndexer.PrefixFromArgs(args...) - if err != nil { - return indexSchema, nil, fmt.Errorf("index error: %v", err) - } - return indexSchema, val, err - } - - // Get the exact match index - val, err := indexSchema.Indexer.FromArgs(args...) - if err != nil { - return indexSchema, nil, fmt.Errorf("index error: %v", err) - } - return indexSchema, val, err -} - -// ResultIterator is used to iterate over a list of results -// from a Get query on a table. -type ResultIterator interface { - WatchCh() <-chan struct{} - Next() interface{} -} - -// Get is used to construct a ResultIterator over all the -// rows that match the given constraints of an index. -func (txn *Txn) Get(table, index string, args ...interface{}) (ResultIterator, error) { - // Get the index value to scan - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, err - } - - // Get the index itself - indexTxn := txn.readableIndex(table, indexSchema.Name) - indexRoot := indexTxn.Root() - - // Get an interator over the index - indexIter := indexRoot.Iterator() - - // Seek the iterator to the appropriate sub-set - watchCh := indexIter.SeekPrefixWatch(val) - - // Create an iterator - iter := &radixIterator{ - iter: indexIter, - watchCh: watchCh, - } - return iter, nil -} - -// Defer is used to push a new arbitrary function onto a stack which -// gets called when a transaction is committed and finished. Deferred -// functions are called in LIFO order, and only invoked at the end of -// write transactions. -func (txn *Txn) Defer(fn func()) { - txn.after = append(txn.after, fn) -} - -// radixIterator is used to wrap an underlying iradix iterator. -// This is much more efficient than a sliceIterator as we are not -// materializing the entire view. -type radixIterator struct { - iter *iradix.Iterator - watchCh <-chan struct{} -} - -func (r *radixIterator) WatchCh() <-chan struct{} { - return r.watchCh -} - -func (r *radixIterator) Next() interface{} { - _, value, ok := r.iter.Next() - if !ok { - return nil - } - return value -} diff --git a/vendor/github.com/hashicorp/go-memdb/watch.go b/vendor/github.com/hashicorp/go-memdb/watch.go deleted file mode 100644 index a6f01213..00000000 --- a/vendor/github.com/hashicorp/go-memdb/watch.go +++ /dev/null @@ -1,129 +0,0 @@ -package memdb - -import ( - "context" - "time" -) - -// WatchSet is a collection of watch channels. -type WatchSet map[<-chan struct{}]struct{} - -// NewWatchSet constructs a new watch set. -func NewWatchSet() WatchSet { - return make(map[<-chan struct{}]struct{}) -} - -// Add appends a watchCh to the WatchSet if non-nil. -func (w WatchSet) Add(watchCh <-chan struct{}) { - if w == nil { - return - } - - if _, ok := w[watchCh]; !ok { - w[watchCh] = struct{}{} - } -} - -// AddWithLimit appends a watchCh to the WatchSet if non-nil, and if the given -// softLimit hasn't been exceeded. Otherwise, it will watch the given alternate -// channel. It's expected that the altCh will be the same on many calls to this -// function, so you will exceed the soft limit a little bit if you hit this, but -// not by much. -// -// This is useful if you want to track individual items up to some limit, after -// which you watch a higher-level channel (usually a channel from start start of -// an iterator higher up in the radix tree) that will watch a superset of items. -func (w WatchSet) AddWithLimit(softLimit int, watchCh <-chan struct{}, altCh <-chan struct{}) { - // This is safe for a nil WatchSet so we don't need to check that here. - if len(w) < softLimit { - w.Add(watchCh) - } else { - w.Add(altCh) - } -} - -// Watch is used to wait for either the watch set to trigger or a timeout. -// Returns true on timeout. -func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { - if w == nil { - return false - } - - // Create a context that gets cancelled when the timeout is triggered - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - go func() { - select { - case <-timeoutCh: - cancel() - case <-ctx.Done(): - } - }() - - return w.WatchCtx(ctx) == context.Canceled -} - -// WatchCtx is used to wait for either the watch set to trigger or for the -// context to be cancelled. Watch with a timeout channel can be mimicked by -// creating a context with a deadline. WatchCtx should be preferred over Watch. -func (w WatchSet) WatchCtx(ctx context.Context) error { - if w == nil { - return nil - } - - if n := len(w); n <= aFew { - idx := 0 - chunk := make([]<-chan struct{}, aFew) - for watchCh := range w { - chunk[idx] = watchCh - idx++ - } - return watchFew(ctx, chunk) - } - - return w.watchMany(ctx) -} - -// watchMany is used if there are many watchers. -func (w WatchSet) watchMany(ctx context.Context) error { - // Set up a goroutine for each watcher. - triggerCh := make(chan struct{}, 1) - watcher := func(chunk []<-chan struct{}) { - if err := watchFew(ctx, chunk); err == nil { - select { - case triggerCh <- struct{}{}: - default: - } - } - } - - // Apportion the watch channels into chunks we can feed into the - // watchFew helper. - idx := 0 - chunk := make([]<-chan struct{}, aFew) - for watchCh := range w { - subIdx := idx % aFew - chunk[subIdx] = watchCh - idx++ - - // Fire off this chunk and start a fresh one. - if idx%aFew == 0 { - go watcher(chunk) - chunk = make([]<-chan struct{}, aFew) - } - } - - // Make sure to watch any residual channels in the last chunk. - if idx%aFew != 0 { - go watcher(chunk) - } - - // Wait for a channel to trigger or timeout. - select { - case <-triggerCh: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} diff --git a/vendor/github.com/hashicorp/go-memdb/watch_few.go b/vendor/github.com/hashicorp/go-memdb/watch_few.go deleted file mode 100644 index 880f098b..00000000 --- a/vendor/github.com/hashicorp/go-memdb/watch_few.go +++ /dev/null @@ -1,117 +0,0 @@ -package memdb - -//go:generate sh -c "go run watch-gen/main.go >watch_few.go" - -import( - "context" -) - -// aFew gives how many watchers this function is wired to support. You must -// always pass a full slice of this length, but unused channels can be nil. -const aFew = 32 - -// watchFew is used if there are only a few watchers as a performance -// optimization. -func watchFew(ctx context.Context, ch []<-chan struct{}) error { - select { - - case <-ch[0]: - return nil - - case <-ch[1]: - return nil - - case <-ch[2]: - return nil - - case <-ch[3]: - return nil - - case <-ch[4]: - return nil - - case <-ch[5]: - return nil - - case <-ch[6]: - return nil - - case <-ch[7]: - return nil - - case <-ch[8]: - return nil - - case <-ch[9]: - return nil - - case <-ch[10]: - return nil - - case <-ch[11]: - return nil - - case <-ch[12]: - return nil - - case <-ch[13]: - return nil - - case <-ch[14]: - return nil - - case <-ch[15]: - return nil - - case <-ch[16]: - return nil - - case <-ch[17]: - return nil - - case <-ch[18]: - return nil - - case <-ch[19]: - return nil - - case <-ch[20]: - return nil - - case <-ch[21]: - return nil - - case <-ch[22]: - return nil - - case <-ch[23]: - return nil - - case <-ch[24]: - return nil - - case <-ch[25]: - return nil - - case <-ch[26]: - return nil - - case <-ch[27]: - return nil - - case <-ch[28]: - return nil - - case <-ch[29]: - return nil - - case <-ch[30]: - return nil - - case <-ch[31]: - return nil - - case <-ctx.Done(): - return ctx.Err() - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/.travis.yml b/vendor/github.com/hashicorp/go-multierror/.travis.yml deleted file mode 100644 index 304a8359..00000000 --- a/vendor/github.com/hashicorp/go-multierror/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.x - -branches: - only: - - master - -script: make test testrace diff --git a/vendor/github.com/hashicorp/go-multierror/LICENSE b/vendor/github.com/hashicorp/go-multierror/LICENSE deleted file mode 100644 index 82b4de97..00000000 --- a/vendor/github.com/hashicorp/go-multierror/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-multierror/Makefile b/vendor/github.com/hashicorp/go-multierror/Makefile deleted file mode 100644 index b97cd6ed..00000000 --- a/vendor/github.com/hashicorp/go-multierror/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TEST?=./... - -default: test - -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} - -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} - -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" - -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "/vendor/" \ - | xargs -n1 go generate - -.PHONY: default test testrace updatedeps generate diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md deleted file mode 100644 index ead5830f..00000000 --- a/vendor/github.com/hashicorp/go-multierror/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# go-multierror - -[![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: https://travis-ci.org/hashicorp/go-multierror -[godocs]: https://godoc.org/github.com/hashicorp/go-multierror - -`go-multierror` is a package for Go that provides a mechanism for -representing a list of `error` values as a single `error`. - -This allows a function in Go to return an `error` that might actually -be a list of errors. If the caller knows this, they can unwrap the -list and access the errors. If the caller doesn't know, the error -formats to a nice human-readable format. - -`go-multierror` implements the -[errwrap](https://github.com/hashicorp/errwrap) interface so that it can -be used with that library, as well. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-multierror`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/go-multierror - -## Usage - -go-multierror is easy to use and purposely built to be unobtrusive in -existing Go applications/libraries that may not be aware of it. - -**Building a list of errors** - -The `Append` function is used to create a list of errors. This function -behaves a lot like the Go built-in `append` function: it doesn't matter -if the first argument is nil, a `multierror.Error`, or any other `error`, -the function behaves as you would expect. - -```go -var result error - -if err := step1(); err != nil { - result = multierror.Append(result, err) -} -if err := step2(); err != nil { - result = multierror.Append(result, err) -} - -return result -``` - -**Customizing the formatting of the errors** - -By specifying a custom `ErrorFormat`, you can customize the format -of the `Error() string` function: - -```go -var result *multierror.Error - -// ... accumulate errors here, maybe using Append - -if result != nil { - result.ErrorFormat = func([]error) string { - return "errors!" - } -} -``` - -**Accessing the list of errors** - -`multierror.Error` implements `error` so if the caller doesn't know about -multierror, it will work just fine. But if you're aware a multierror might -be returned, you can use type switches to access the list of errors: - -```go -if err := something(); err != nil { - if merr, ok := err.(*multierror.Error); ok { - // Use merr.Errors - } -} -``` - -**Returning a multierror only if there are errors** - -If you build a `multierror.Error`, you can use the `ErrorOrNil` function -to return an `error` implementation only if there are errors to return: - -```go -var result *multierror.Error - -// ... accumulate errors here - -// Return the `error` only if errors were added to the multierror, otherwise -// return nil since there are no errors. -return result.ErrorOrNil() -``` diff --git a/vendor/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/hashicorp/go-multierror/append.go deleted file mode 100644 index 775b6e75..00000000 --- a/vendor/github.com/hashicorp/go-multierror/append.go +++ /dev/null @@ -1,41 +0,0 @@ -package multierror - -// Append is a helper function that will append more errors -// onto an Error in order to create a larger multi-error. -// -// If err is not a multierror.Error, then it will be turned into -// one. If any of the errs are multierr.Error, they will be flattened -// one level into err. -func Append(err error, errs ...error) *Error { - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Go through each error and flatten - for _, e := range errs { - switch e := e.(type) { - case *Error: - if e != nil { - err.Errors = append(err.Errors, e.Errors...) - } - default: - if e != nil { - err.Errors = append(err.Errors, e) - } - } - } - - return err - default: - newErrs := make([]error, 0, len(errs)+1) - if err != nil { - newErrs = append(newErrs, err) - } - newErrs = append(newErrs, errs...) - - return Append(&Error{}, newErrs...) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/flatten.go b/vendor/github.com/hashicorp/go-multierror/flatten.go deleted file mode 100644 index aab8e9ab..00000000 --- a/vendor/github.com/hashicorp/go-multierror/flatten.go +++ /dev/null @@ -1,26 +0,0 @@ -package multierror - -// Flatten flattens the given error, merging any *Errors together into -// a single *Error. -func Flatten(err error) error { - // If it isn't an *Error, just return the error as-is - if _, ok := err.(*Error); !ok { - return err - } - - // Otherwise, make the result and flatten away! - flatErr := new(Error) - flatten(err, flatErr) - return flatErr -} - -func flatten(err error, flatErr *Error) { - switch err := err.(type) { - case *Error: - for _, e := range err.Errors { - flatten(e, flatErr) - } - default: - flatErr.Errors = append(flatErr.Errors, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/hashicorp/go-multierror/format.go deleted file mode 100644 index 47f13c49..00000000 --- a/vendor/github.com/hashicorp/go-multierror/format.go +++ /dev/null @@ -1,27 +0,0 @@ -package multierror - -import ( - "fmt" - "strings" -) - -// ErrorFormatFunc is a function callback that is called by Error to -// turn the list of errors into a string. -type ErrorFormatFunc func([]error) string - -// ListFormatFunc is a basic formatter that outputs the number of errors -// that occurred along with a bullet point list of the errors. -func ListFormatFunc(es []error) string { - if len(es) == 1 { - return fmt.Sprintf("1 error occurred:\n\t* %s\n\n", es[0]) - } - - points := make([]string, len(es)) - for i, err := range es { - points[i] = fmt.Sprintf("* %s", err) - } - - return fmt.Sprintf( - "%d errors occurred:\n\t%s\n\n", - len(es), strings.Join(points, "\n\t")) -} diff --git a/vendor/github.com/hashicorp/go-multierror/go.mod b/vendor/github.com/hashicorp/go-multierror/go.mod deleted file mode 100644 index 2534331d..00000000 --- a/vendor/github.com/hashicorp/go-multierror/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/go-multierror - -require github.com/hashicorp/errwrap v1.0.0 diff --git a/vendor/github.com/hashicorp/go-multierror/go.sum b/vendor/github.com/hashicorp/go-multierror/go.sum deleted file mode 100644 index 85b1f8ff..00000000 --- a/vendor/github.com/hashicorp/go-multierror/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4= -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go deleted file mode 100644 index 89b1422d..00000000 --- a/vendor/github.com/hashicorp/go-multierror/multierror.go +++ /dev/null @@ -1,51 +0,0 @@ -package multierror - -import ( - "fmt" -) - -// Error is an error type to track multiple errors. This is used to -// accumulate errors in cases and return them as a single "error". -type Error struct { - Errors []error - ErrorFormat ErrorFormatFunc -} - -func (e *Error) Error() string { - fn := e.ErrorFormat - if fn == nil { - fn = ListFormatFunc - } - - return fn(e.Errors) -} - -// ErrorOrNil returns an error interface if this Error represents -// a list of errors, or returns nil if the list of errors is empty. This -// function is useful at the end of accumulation to make sure that the value -// returned represents the existence of errors. -func (e *Error) ErrorOrNil() error { - if e == nil { - return nil - } - if len(e.Errors) == 0 { - return nil - } - - return e -} - -func (e *Error) GoString() string { - return fmt.Sprintf("*%#v", *e) -} - -// WrappedErrors returns the list of errors that this Error is wrapping. -// It is an implementation of the errwrap.Wrapper interface so that -// multierror.Error can be used with that library. -// -// This method is not safe to be called concurrently and is no different -// than accessing the Errors field directly. It is implemented only to -// satisfy the errwrap.Wrapper interface. -func (e *Error) WrappedErrors() []error { - return e.Errors -} diff --git a/vendor/github.com/hashicorp/go-multierror/prefix.go b/vendor/github.com/hashicorp/go-multierror/prefix.go deleted file mode 100644 index 5c477abe..00000000 --- a/vendor/github.com/hashicorp/go-multierror/prefix.go +++ /dev/null @@ -1,37 +0,0 @@ -package multierror - -import ( - "fmt" - - "github.com/hashicorp/errwrap" -) - -// Prefix is a helper function that will prefix some text -// to the given error. If the error is a multierror.Error, then -// it will be prefixed to each wrapped error. -// -// This is useful to use when appending multiple multierrors -// together in order to give better scoping. -func Prefix(err error, prefix string) error { - if err == nil { - return nil - } - - format := fmt.Sprintf("%s {{err}}", prefix) - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Wrap each of the errors - for i, e := range err.Errors { - err.Errors[i] = errwrap.Wrapf(format, e) - } - - return err - default: - return errwrap.Wrapf(format, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/sort.go b/vendor/github.com/hashicorp/go-multierror/sort.go deleted file mode 100644 index fecb14e8..00000000 --- a/vendor/github.com/hashicorp/go-multierror/sort.go +++ /dev/null @@ -1,16 +0,0 @@ -package multierror - -// Len implements sort.Interface function for length -func (err Error) Len() int { - return len(err.Errors) -} - -// Swap implements sort.Interface function for swapping elements -func (err Error) Swap(i, j int) { - err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i] -} - -// Less implements sort.Interface function for determining order -func (err Error) Less(i, j int) bool { - return err.Errors[i].Error() < err.Errors[j].Error() -} diff --git a/vendor/github.com/hashicorp/go-plugin/.gitignore b/vendor/github.com/hashicorp/go-plugin/.gitignore deleted file mode 100644 index e43b0f98..00000000 --- a/vendor/github.com/hashicorp/go-plugin/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.DS_Store diff --git a/vendor/github.com/hashicorp/go-plugin/LICENSE b/vendor/github.com/hashicorp/go-plugin/LICENSE deleted file mode 100644 index 82b4de97..00000000 --- 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 fe305ad5..00000000 --- a/vendor/github.com/hashicorp/go-plugin/README.md +++ /dev/null @@ -1,168 +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), and -[Vault](https://www.vaultproject.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. - -**Plugin fetching.** We will integrate with [go-getter](https://github.com/hashicorp/go-getter) -to support automatic download + install of plugins. Paired with cryptographically -secure plugins (above), we can make this a safe operation for an amazing -user experience. - -## 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 bfab795a..00000000 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ /dev/null @@ -1,871 +0,0 @@ -package plugin - -import ( - "bufio" - "context" - "crypto/subtle" - "crypto/tls" - "errors" - "fmt" - "hash" - "io" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - "unicode" - - hclog "github.com/hashicorp/go-hclog" -) - -// 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 - doneLogging chan struct{} - l sync.Mutex - address net.Addr - process *os.Process - client ClientProtocol - protocol Protocol - logger hclog.Logger - doneCtx context.Context - negotiatedVersion int -} - -// 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 automatically be - // hooked up to os.Stdin, Stdout, and Stderr, respectively. - // - // If the default values (nil) are used, then this package will not - // sync any of these streams. - 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 -} - -// 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 - Addr net.Addr - Pid int -} - -// 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 -} - -// 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 - doneCh := c.doneLogging - c.l.Unlock() - - // If there is no process, there is nothing to kill. - if process == nil { - return - } - - defer func() { - // Make sure there is no reference to the old process after it has been - // killed. - c.l.Lock() - defer c.l.Unlock() - c.process = nil - }() - - // 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) - } - } - } - - // 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 <-doneCh: - // FIXME: this is never reached under normal circumstances, because - // the plugin process is never signaled to exit. We can reach this - // if the child process exited abnormally before the Kill call. - return - case <-time.After(250 * time.Millisecond): - c.logger.Warn("plugin failed to exit gracefully") - } - } - - // If graceful exiting failed, just kill it - process.Kill() - - // Wait for the client to finish logging so we have a complete log - <-doneCh -} - -// 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 stock 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 - } - } - - // Create the logging channel for when we kill - c.doneLogging = make(chan struct{}) - // Create a context for when we kill - var ctxCancel context.CancelFunc - c.doneCtx, ctxCancel = context.WithCancel(context.Background()) - - if c.config.Reattach != nil { - // Verify the process still exists. If not, then it is an error - p, err := os.FindProcess(c.config.Reattach.Pid) - if err != nil { - return nil, err - } - - // 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() - - // Goroutine to mark exit status - go func(pid int) { - // ensure the context is cancelled when we're done - defer 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 - - // Close the logging channel since that doesn't work on reattach - close(c.doneLogging) - }(p.Pid) - - // Set the address and process - c.address = c.config.Reattach.Addr - c.process = p - c.protocol = c.config.Reattach.Protocol - if c.protocol == "" { - // Default the protocol to net/rpc for backwards compatibility - c.protocol = ProtocolNetRPC - } - - return c.address, nil - } - - 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, ",")), - } - - stdout_r, stdout_w := io.Pipe() - stderr_r, stderr_w := io.Pipe() - - cmd := c.config.Cmd - cmd.Env = append(cmd.Env, os.Environ()...) - cmd.Env = append(cmd.Env, env...) - cmd.Stdin = os.Stdin - cmd.Stderr = stderr_w - cmd.Stdout = stdout_w - - if c.config.SecureConfig != nil { - 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 - } - } - - 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) - } - }() - - // Start goroutine to wait for process to exit - exitCh := make(chan struct{}) - go func() { - // Make sure we close the write end of our stderr/stdout so - // that the readers send EOF properly. - defer stderr_w.Close() - defer stdout_w.Close() - - // ensure the context is cancelled when we're done - defer ctxCancel() - - // Wait for the command to end. - err := cmd.Wait() - - debugMsgArgs := []interface{}{ - "path", cmd.Path, - "pid", c.process.Pid, - } - if err != nil { - debugMsgArgs = append(debugMsgArgs, - []interface{}{"error", err.Error()}...) - } - - // Log and make sure to flush the logs write away - c.logger.Debug("plugin process exited", debugMsgArgs...) - os.Stderr.Sync() - - // Mark that we exited - close(exitCh) - - // Set that we exited, which takes a lock - c.l.Lock() - defer c.l.Unlock() - c.exited = true - }() - - // Start goroutine that logs the stderr - go c.logStderr(stderr_r) - - // Start a goroutine that is going to be reading the lines - // out of stdout - linesCh := make(chan []byte) - go func() { - defer close(linesCh) - - buf := bufio.NewReader(stdout_r) - for { - line, err := buf.ReadBytes('\n') - if line != nil { - linesCh <- line - } - - if err == io.EOF { - return - } - } - }() - - // Make sure after we exit we read the lines from stdout forever - // so they don't block since it is an io.Pipe - defer func() { - go func() { - 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 <-exitCh: - err = errors.New("plugin exited before we could connect") - case lineBytes := <-linesCh: - // Trim the line and split by "|" in order to get the parts of - // the output. - line := strings.TrimSpace(string(lineBytes)) - 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 int64 - coreProtocol, err = strconv.ParseInt(parts[0], 10, 0) - if err != nil { - err = fmt.Errorf("Error parsing core protocol version: %s", err) - return - } - - if int(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 - } - - } - - c.address = addr - return -} - -// 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 -} - -func (c *Client) logStderr(r io.Reader) { - bufR := bufio.NewReader(r) - l := c.logger.Named(filepath.Base(c.config.Cmd.Path)) - - for { - line, err := bufR.ReadString('\n') - if line != "" { - c.config.Stderr.Write([]byte(line)) - line = strings.TrimRightFunc(line, unicode.IsSpace) - - entry, err := parseJSON(line) - // If output is not JSON format, print directly to Debug - if err != nil { - 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...) - } - } - } - - if err == io.EOF { - break - } - } - - // Flag that we've completed logging for others - close(c.doneLogging) -} 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 d22c566e..00000000 --- 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 22a7baa6..00000000 --- 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/go.mod b/vendor/github.com/hashicorp/go-plugin/go.mod deleted file mode 100644 index 20112852..00000000 --- a/vendor/github.com/hashicorp/go-plugin/go.mod +++ /dev/null @@ -1,13 +0,0 @@ -module github.com/hashicorp/go-plugin - -require ( - github.com/golang/protobuf v1.2.0 - github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd - github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb - github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 - github.com/oklog/run v1.0.0 - golang.org/x/net v0.0.0-20180826012351-8a410e7b638d - golang.org/x/text v0.3.0 // indirect - google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 // indirect - google.golang.org/grpc v1.14.0 -) diff --git a/vendor/github.com/hashicorp/go-plugin/go.sum b/vendor/github.com/hashicorp/go-plugin/go.sum deleted file mode 100644 index 9ae0bec8..00000000 --- a/vendor/github.com/hashicorp/go-plugin/go.sum +++ /dev/null @@ -1,18 +0,0 @@ -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd h1:rNuUHR+CvK1IS89MMtcF0EpcVMZtjKfPRp4MEmt/aTs= -github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 h1:7GoSOOW2jpsfkntVKaS2rAr1TJqfcxotyaUcuxoZSzg= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/grpc v1.14.0 h1:ArxJuB1NWfPY6r9Gp9gqwplT0Ge7nqv9msgu03lHLmo= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= 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 49fd21c6..00000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_broker.go +++ /dev/null @@ -1,455 +0,0 @@ -package plugin - -import ( - "context" - "crypto/tls" - "errors" - "fmt" - "log" - "net" - "sync" - "sync/atomic" - "time" - - "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(*ConnInfo) error - Recv() (*ConnInfo, error) - Close() -} - -// sendErr is used to pass errors back during a send. -type sendErr struct { - i *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 *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 *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 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 *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() (*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 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 *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: NewGRPCBrokerClient(conn), - send: make(chan *sendErr), - recv: make(chan *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 *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() (*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 *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(&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 *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 *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_broker.pb.go b/vendor/github.com/hashicorp/go-plugin/grpc_broker.pb.go deleted file mode 100644 index d490dafb..00000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_broker.pb.go +++ /dev/null @@ -1,190 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_broker.proto - -/* -Package plugin is a generated protocol buffer package. - -It is generated from these files: - grpc_broker.proto - -It has these top-level messages: - ConnInfo -*/ -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" json:"service_id,omitempty"` - Network string `protobuf:"bytes,2,opt,name=network" json:"network,omitempty"` - Address string `protobuf:"bytes,3,opt,name=address" json:"address,omitempty"` -} - -func (m *ConnInfo) Reset() { *m = ConnInfo{} } -func (m *ConnInfo) String() string { return proto.CompactTextString(m) } -func (*ConnInfo) ProtoMessage() {} -func (*ConnInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -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 - -// Client API for GRPCBroker service - -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 := grpc.NewClientStream(ctx, &_GRPCBroker_serviceDesc.Streams[0], c.cc, "/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 -} - -// 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", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 170 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, 0x93, 0xd8, 0xc0, 0x4e, 0x36, 0x06, 0x04, 0x00, 0x00, - 0xff, 0xff, 0x7b, 0x5d, 0xfb, 0xe1, 0xc7, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_broker.proto b/vendor/github.com/hashicorp/go-plugin/grpc_broker.proto deleted file mode 100644 index f5783485..00000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_broker.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; -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/grpc_client.go b/vendor/github.com/hashicorp/go-plugin/grpc_client.go deleted file mode 100644 index 44294d0d..00000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_client.go +++ /dev/null @@ -1,107 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "fmt" - "net" - "time" - - "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)) (*grpc.ClientConn, error) { - // Build dialing options. - opts := make([]grpc.DialOption, 0, 5) - - // We use a custom dialer so that we can connect over unix domain sockets - opts = append(opts, grpc.WithDialer(dialer)) - - // go-plugin expects to block the connection - opts = append(opts, grpc.WithBlock()) - - // 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))) - } - - // 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) - if err != nil { - return nil, err - } - - // Start the broker. - brokerGRPCClient := newGRPCBrokerClient(conn) - broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig) - go broker.Run() - go brokerGRPCClient.StartStream() - - return &GRPCClient{ - Conn: conn, - Plugins: c.config.Plugins, - doneCtx: doneCtx, - broker: broker, - }, 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 -} - -// ClientProtocol impl. -func (c *GRPCClient) Close() error { - c.broker.Close() - 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_server.go b/vendor/github.com/hashicorp/go-plugin/grpc_server.go deleted file mode 100644 index 3a727393..00000000 --- a/vendor/github.com/hashicorp/go-plugin/grpc_server.go +++ /dev/null @@ -1,132 +0,0 @@ -package plugin - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "net" - - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/health" - "google.golang.org/grpc/health/grpc_health_v1" -) - -// 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 -} - -// 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 broker service - brokerServer := newGRPCBrokerServer() - RegisterGRPCBrokerServer(s.server, brokerServer) - s.broker = newGRPCBroker(brokerServer, s.TLS) - go s.broker.Run() - - // 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 registring %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) { - // Start serving in a goroutine - go s.server.Serve(lis) - - // Wait until graceful completion - <-s.DoneCh -} - -// 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/log_entry.go b/vendor/github.com/hashicorp/go-plugin/log_entry.go deleted file mode 100644 index 2996c14c..00000000 --- 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 string) (*logEntry, error) { - var raw map[string]interface{} - entry := &logEntry{} - - err := json.Unmarshal([]byte(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/mux_broker.go b/vendor/github.com/hashicorp/go-plugin/mux_broker.go deleted file mode 100644 index 01c45ad7..00000000 --- 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 79d96746..00000000 --- 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 88c999a5..00000000 --- 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 70ba546b..00000000 --- a/vendor/github.com/hashicorp/go-plugin/process_posix.go +++ /dev/null @@ -1,19 +0,0 @@ -// +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 9f7b0180..00000000 --- a/vendor/github.com/hashicorp/go-plugin/process_windows.go +++ /dev/null @@ -1,29 +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 - } - - 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 0cfc19e5..00000000 --- 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 f30a4b1d..00000000 --- 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 5bb18dd5..00000000 --- a/vendor/github.com/hashicorp/go-plugin/rpc_server.go +++ /dev/null @@ -1,197 +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 { - log.Printf("[ERR] plugin: plugin server: %s", 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 c278e53a..00000000 --- a/vendor/github.com/hashicorp/go-plugin/server.go +++ /dev/null @@ -1,404 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "log" - "net" - "os" - "os/signal" - "runtime" - "sort" - "strconv" - "strings" - "sync/atomic" - - "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 -} - -// 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 -// errors will be outputted to os.Stderr. -// -// This is the method that plugins should call in their main() functions. -func Serve(opts *ServeConfig) { - // 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") - os.Exit(1) - } - - // 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") - os.Exit(1) - } - - // negotiate the version and plugins - // start with default version in the handshake config - protoVersion, protoType, pluginSet := protocolVersion(opts) - - // Logging goes to the original stderr - log.SetOutput(os.Stderr) - - logger := opts.Logger - if logger == nil { - // internal logger to os.Stderr - logger = hclog.New(&hclog.LoggerOptions{ - Level: hclog.Trace, - Output: os.Stderr, - JSONFormat: true, - }) - } - - // Create our new stdout, stderr files. These will override our built-in - // stdout/stderr so that it works across the stream boundary. - 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) - } - - // 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 - } - } - - // Create the channel to tell us when we're done - doneCh := make(chan struct{}) - - // 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, - } - - default: - panic("unknown server protocol: " + protoType) - } - - // Initialize the servers - if err := server.Init(); err != nil { - logger.Error("protocol init", "error", err) - return - } - - // Build the extra configuration - extra := "" - if v := server.Config(); v != "" { - extra = base64.StdEncoding.EncodeToString([]byte(v)) - } - if extra != "" { - extra = "|" + extra - } - - 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. - fmt.Printf("%d|%d|%s|%s|%s%s\n", - CoreProtocolVersion, - protoVersion, - listener.Addr().Network(), - listener.Addr().String(), - protoType, - extra) - os.Stdout.Sync() - - // Eat the interrupts - ch := make(chan os.Signal, 1) - signal.Notify(ch, os.Interrupt) - go func() { - var count int32 = 0 - for { - <-ch - newCount := atomic.AddInt32(&count, 1) - logger.Debug("plugin received interrupt signal, ignoring", "count", newCount) - } - }() - - // Set our new out, err - os.Stdout = stdout_w - os.Stderr = stderr_w - - // Accept connections and wait for completion - go server.Serve(listener) - <-doneCh -} - -func serverListener() (net.Listener, error) { - if runtime.GOOS == "windows" { - return serverListener_tcp() - } - - return serverListener_unix() -} - -func serverListener_tcp() (net.Listener, error) { - minPort, err := strconv.ParseInt(os.Getenv("PLUGIN_MIN_PORT"), 10, 32) - if err != nil { - return nil, err - } - - maxPort, err := strconv.ParseInt(os.Getenv("PLUGIN_MAX_PORT"), 10, 32) - if err != nil { - return nil, err - } - - 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 033079ea..00000000 --- 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 1d547aaa..00000000 --- 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 2f541d96..00000000 --- a/vendor/github.com/hashicorp/go-plugin/testing.go +++ /dev/null @@ -1,175 +0,0 @@ -package plugin - -import ( - "bytes" - "context" - "io" - "net" - "net/rpc" - - "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, - Server: DefaultGRPCServer, - Stdout: new(bytes.Buffer), - Stderr: new(bytes.Buffer), - } - 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(), - } - - return client, server -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore b/vendor/github.com/hashicorp/go-retryablehttp/.gitignore deleted file mode 100644 index caab963a..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.idea/ -*.iml -*.test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml b/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml deleted file mode 100644 index 2df4e7df..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.8.1 - -branches: - only: - - master - -script: make updatedeps test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE b/vendor/github.com/hashicorp/go-retryablehttp/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/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-retryablehttp/Makefile b/vendor/github.com/hashicorp/go-retryablehttp/Makefile deleted file mode 100644 index da17640e..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -default: test - -test: - go vet ./... - go test -race ./... - -updatedeps: - go get -f -t -u ./... - go get -f -u ./... - -.PHONY: default test updatedeps diff --git a/vendor/github.com/hashicorp/go-retryablehttp/README.md b/vendor/github.com/hashicorp/go-retryablehttp/README.md deleted file mode 100644 index ccdc7e87..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/README.md +++ /dev/null @@ -1,46 +0,0 @@ -go-retryablehttp -================ - -[![Build Status](http://img.shields.io/travis/hashicorp/go-retryablehttp.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: http://travis-ci.org/hashicorp/go-retryablehttp -[godocs]: http://godoc.org/github.com/hashicorp/go-retryablehttp - -The `retryablehttp` package provides a familiar HTTP client interface with -automatic retries and exponential backoff. It is a thin wrapper over the -standard `net/http` client library and exposes nearly the same public API. This -makes `retryablehttp` very easy to drop into existing programs. - -`retryablehttp` performs automatic retries under certain conditions. Mainly, if -an error is returned by the client (connection errors, etc.), or if a 500-range -response code is received (except 501), then a retry is invoked after a wait -period. Otherwise, the response is returned and left to the caller to -interpret. - -The main difference from `net/http` is that requests which take a request body -(POST/PUT et. al) can have the body provided in a number of ways (some more or -less efficient) that allow "rewinding" the request body if the initial request -fails so that the full request can be attempted again. See the -[godoc](http://godoc.org/github.com/hashicorp/go-retryablehttp) for more -details. - -Example Use -=========== - -Using this library should look almost identical to what you would do with -`net/http`. The most simple example of a GET request is shown below: - -```go -resp, err := retryablehttp.Get("/foo") -if err != nil { - panic(err) -} -``` - -The returned response object is an `*http.Response`, the same thing you would -usually get from `net/http`. Had the request failed one or more times, the above -call would block and retry with exponential backoff. - -For more usage and examples see the -[godoc](http://godoc.org/github.com/hashicorp/go-retryablehttp). diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go deleted file mode 100644 index 04d3216b..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ /dev/null @@ -1,500 +0,0 @@ -// The retryablehttp package provides a familiar HTTP client interface with -// automatic retries and exponential backoff. It is a thin wrapper over the -// standard net/http client library and exposes nearly the same public API. -// This makes retryablehttp very easy to drop into existing programs. -// -// retryablehttp performs automatic retries under certain conditions. Mainly, if -// an error is returned by the client (connection errors etc), or if a 500-range -// response is received, then a retry is invoked. Otherwise, the response is -// returned and left to the caller to interpret. -// -// Requests which take a request body should provide a non-nil function -// parameter. The best choice is to provide either a function satisfying -// ReaderFunc which provides multiple io.Readers in an efficient manner, a -// *bytes.Buffer (the underlying raw byte slice will be used) or a raw byte -// slice. As it is a reference type, and we will wrap it as needed by readers, -// we can efficiently re-use the request body without needing to copy it. If an -// io.Reader (such as a *bytes.Reader) is provided, the full body will be read -// prior to the first request, and will be efficiently re-used for any retries. -// ReadSeeker can be used, but some users have observed occasional data races -// between the net/http library and the Seek functionality of some -// implementations of ReadSeeker, so should be avoided if possible. -package retryablehttp - -import ( - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "log" - "math" - "math/rand" - "net/http" - "net/url" - "os" - "strings" - "time" - - "github.com/hashicorp/go-cleanhttp" -) - -var ( - // Default retry configuration - defaultRetryWaitMin = 1 * time.Second - defaultRetryWaitMax = 30 * time.Second - defaultRetryMax = 4 - - // defaultClient is used for performing requests without explicitly making - // a new client. It is purposely private to avoid modifications. - defaultClient = NewClient() - - // random is used to generate pseudo-random numbers. - random = rand.New(rand.NewSource(time.Now().UnixNano())) - - // We need to consume response bodies to maintain http connections, but - // limit the size we consume to respReadLimit. - respReadLimit = int64(4096) -) - -// ReaderFunc is the type of function that can be given natively to NewRequest -type ReaderFunc func() (io.Reader, error) - -// LenReader is an interface implemented by many in-memory io.Reader's. Used -// for automatically sending the right Content-Length header when possible. -type LenReader interface { - Len() int -} - -// Request wraps the metadata needed to create HTTP requests. -type Request struct { - // body is a seekable reader over the request body payload. This is - // used to rewind the request data in between retries. - body ReaderFunc - - // Embed an HTTP request directly. This makes a *Request act exactly - // like an *http.Request so that all meta methods are supported. - *http.Request -} - -// WithContext returns wrapped Request with a shallow copy of underlying *http.Request -// with its context changed to ctx. The provided ctx must be non-nil. -func (r *Request) WithContext(ctx context.Context) *Request { - r.Request = r.Request.WithContext(ctx) - return r -} - -// NewRequest creates a new wrapped request. -func NewRequest(method, url string, rawBody interface{}) (*Request, error) { - var err error - var body ReaderFunc - var contentLength int64 - - if rawBody != nil { - switch rawBody.(type) { - // If they gave us a function already, great! Use it. - case ReaderFunc: - body = rawBody.(ReaderFunc) - tmp, err := body() - if err != nil { - return nil, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - case func() (io.Reader, error): - body = rawBody.(func() (io.Reader, error)) - tmp, err := body() - if err != nil { - return nil, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - // If a regular byte slice, we can read it over and over via new - // readers - case []byte: - buf := rawBody.([]byte) - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - // If a bytes.Buffer we can read the underlying byte slice over and - // over - case *bytes.Buffer: - buf := rawBody.(*bytes.Buffer) - body = func() (io.Reader, error) { - return bytes.NewReader(buf.Bytes()), nil - } - contentLength = int64(buf.Len()) - - // We prioritize *bytes.Reader here because we don't really want to - // deal with it seeking so want it to match here instead of the - // io.ReadSeeker case. - case *bytes.Reader: - buf, err := ioutil.ReadAll(rawBody.(*bytes.Reader)) - if err != nil { - return nil, err - } - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - // Compat case - case io.ReadSeeker: - raw := rawBody.(io.ReadSeeker) - body = func() (io.Reader, error) { - raw.Seek(0, 0) - return ioutil.NopCloser(raw), nil - } - if lr, ok := raw.(LenReader); ok { - contentLength = int64(lr.Len()) - } - - // Read all in so we can reset - case io.Reader: - buf, err := ioutil.ReadAll(rawBody.(io.Reader)) - if err != nil { - return nil, err - } - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - default: - return nil, fmt.Errorf("cannot handle type %T", rawBody) - } - } - - httpReq, err := http.NewRequest(method, url, nil) - if err != nil { - return nil, err - } - httpReq.ContentLength = contentLength - - return &Request{body, httpReq}, nil -} - -// RequestLogHook allows a function to run before each retry. The HTTP -// request which will be made, and the retry number (0 for the initial -// request) are available to users. The internal logger is exposed to -// consumers. -type RequestLogHook func(*log.Logger, *http.Request, int) - -// ResponseLogHook is like RequestLogHook, but allows running a function -// on each HTTP response. This function will be invoked at the end of -// every HTTP request executed, regardless of whether a subsequent retry -// needs to be performed or not. If the response body is read or closed -// from this method, this will affect the response returned from Do(). -type ResponseLogHook func(*log.Logger, *http.Response) - -// CheckRetry specifies a policy for handling retries. It is called -// following each request with the response and error values returned by -// the http.Client. If CheckRetry returns false, the Client stops retrying -// and returns the response to the caller. If CheckRetry returns an error, -// that error value is returned in lieu of the error from the request. The -// Client will close any response body when retrying, but if the retry is -// aborted it is up to the CheckResponse callback to properly close any -// response body before returning. -type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error) - -// Backoff specifies a policy for how long to wait between retries. -// It is called after a failing request to determine the amount of time -// that should pass before trying again. -type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration - -// ErrorHandler is called if retries are expired, containing the last status -// from the http library. If not specified, default behavior for the library is -// to close the body and return an error indicating how many tries were -// attempted. If overriding this, be sure to close the body if needed. -type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error) - -// Client is used to make HTTP requests. It adds additional functionality -// like automatic retries to tolerate minor outages. -type Client struct { - HTTPClient *http.Client // Internal HTTP client. - Logger *log.Logger // Customer logger instance. - - RetryWaitMin time.Duration // Minimum time to wait - RetryWaitMax time.Duration // Maximum time to wait - RetryMax int // Maximum number of retries - - // RequestLogHook allows a user-supplied function to be called - // before each retry. - RequestLogHook RequestLogHook - - // ResponseLogHook allows a user-supplied function to be called - // with the response from each HTTP request executed. - ResponseLogHook ResponseLogHook - - // CheckRetry specifies the policy for handling retries, and is called - // after each request. The default policy is DefaultRetryPolicy. - CheckRetry CheckRetry - - // Backoff specifies the policy for how long to wait between retries - Backoff Backoff - - // ErrorHandler specifies the custom error handler to use, if any - ErrorHandler ErrorHandler -} - -// NewClient creates a new Client with default settings. -func NewClient() *Client { - return &Client{ - HTTPClient: cleanhttp.DefaultClient(), - Logger: log.New(os.Stderr, "", log.LstdFlags), - RetryWaitMin: defaultRetryWaitMin, - RetryWaitMax: defaultRetryWaitMax, - RetryMax: defaultRetryMax, - CheckRetry: DefaultRetryPolicy, - Backoff: DefaultBackoff, - } -} - -// DefaultRetryPolicy provides a default callback for Client.CheckRetry, which -// will retry on connection errors and server errors. -func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { - // do not retry on context.Canceled or context.DeadlineExceeded - if ctx.Err() != nil { - return false, ctx.Err() - } - - if err != nil { - return true, err - } - // Check the response code. We retry on 500-range responses to allow - // the server time to recover, as 500's are typically not permanent - // errors and may relate to outages on the server side. This will catch - // invalid response codes as well, like 0 and 999. - if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) { - return true, nil - } - - return false, nil -} - -// DefaultBackoff provides a default callback for Client.Backoff which -// will perform exponential backoff based on the attempt number and limited -// by the provided minimum and maximum durations. -func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - mult := math.Pow(2, float64(attemptNum)) * float64(min) - sleep := time.Duration(mult) - if float64(sleep) != mult || sleep > max { - sleep = max - } - return sleep -} - -// LinearJitterBackoff provides a callback for Client.Backoff which will -// perform linear backoff based on the attempt number and with jitter to -// prevent a thundering herd. -// -// min and max here are *not* absolute values. The number to be multipled by -// the attempt number will be chosen at random from between them, thus they are -// bounding the jitter. -// -// For instance: -// * To get strictly linear backoff of one second increasing each retry, set -// both to one second (1s, 2s, 3s, 4s, ...) -// * To get a small amount of jitter centered around one second increasing each -// retry, set to around one second, such as a min of 800ms and max of 1200ms -// (892ms, 2102ms, 2945ms, 4312ms, ...) -// * To get extreme jitter, set to a very wide spread, such as a min of 100ms -// and a max of 20s (15382ms, 292ms, 51321ms, 35234ms, ...) -func LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - // attemptNum always starts at zero but we want to start at 1 for multiplication - attemptNum++ - - if max <= min { - // Unclear what to do here, or they are the same, so return min * - // attemptNum - return min * time.Duration(attemptNum) - } - - // Pick a random number that lies somewhere between the min and max and - // multiply by the attemptNum. attemptNum starts at zero so we always - // increment here. We first get a random percentage, then apply that to the - // difference between min and max, and add to min. - jitter := random.Float64() * float64(max-min) - jitterMin := int64(jitter) + int64(min) - return time.Duration(jitterMin * int64(attemptNum)) -} - -// PassthroughErrorHandler is an ErrorHandler that directly passes through the -// values from the net/http library for the final request. The body is not -// closed. -func PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) { - return resp, err -} - -// Do wraps calling an HTTP method with retries. -func (c *Client) Do(req *Request) (*http.Response, error) { - if c.Logger != nil { - c.Logger.Printf("[DEBUG] %s %s", req.Method, req.URL) - } - - var resp *http.Response - var err error - - for i := 0; ; i++ { - var code int // HTTP response code - - // Always rewind the request body when non-nil. - if req.body != nil { - body, err := req.body() - if err != nil { - return resp, err - } - if c, ok := body.(io.ReadCloser); ok { - req.Request.Body = c - } else { - req.Request.Body = ioutil.NopCloser(body) - } - } - - if c.RequestLogHook != nil { - c.RequestLogHook(c.Logger, req.Request, i) - } - - // Attempt the request - resp, err = c.HTTPClient.Do(req.Request) - if resp != nil { - code = resp.StatusCode - } - - // Check if we should continue with retries. - checkOK, checkErr := c.CheckRetry(req.Request.Context(), resp, err) - - if err != nil { - if c.Logger != nil { - c.Logger.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err) - } - } else { - // Call this here to maintain the behavior of logging all requests, - // even if CheckRetry signals to stop. - if c.ResponseLogHook != nil { - // Call the response logger function if provided. - c.ResponseLogHook(c.Logger, resp) - } - } - - // Now decide if we should continue. - if !checkOK { - if checkErr != nil { - err = checkErr - } - return resp, err - } - - // We do this before drainBody beause there's no need for the I/O if - // we're breaking out - remain := c.RetryMax - i - if remain <= 0 { - break - } - - // We're going to retry, consume any response to reuse the connection. - if err == nil && resp != nil { - c.drainBody(resp.Body) - } - - wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp) - desc := fmt.Sprintf("%s %s", req.Method, req.URL) - if code > 0 { - desc = fmt.Sprintf("%s (status: %d)", desc, code) - } - if c.Logger != nil { - c.Logger.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain) - } - time.Sleep(wait) - } - - if c.ErrorHandler != nil { - return c.ErrorHandler(resp, err, c.RetryMax+1) - } - - // By default, we close the response body and return an error without - // returning the response - if resp != nil { - resp.Body.Close() - } - return nil, fmt.Errorf("%s %s giving up after %d attempts", - req.Method, req.URL, c.RetryMax+1) -} - -// Try to read the response body so we can reuse this connection. -func (c *Client) drainBody(body io.ReadCloser) { - defer body.Close() - _, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit)) - if err != nil { - if c.Logger != nil { - c.Logger.Printf("[ERR] error reading response body: %v", err) - } - } -} - -// Get is a shortcut for doing a GET request without making a new client. -func Get(url string) (*http.Response, error) { - return defaultClient.Get(url) -} - -// Get is a convenience helper for doing simple GET requests. -func (c *Client) Get(url string) (*http.Response, error) { - req, err := NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Head is a shortcut for doing a HEAD request without making a new client. -func Head(url string) (*http.Response, error) { - return defaultClient.Head(url) -} - -// Head is a convenience method for doing simple HEAD requests. -func (c *Client) Head(url string) (*http.Response, error) { - req, err := NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Post is a shortcut for doing a POST request without making a new client. -func Post(url, bodyType string, body interface{}) (*http.Response, error) { - return defaultClient.Post(url, bodyType, body) -} - -// Post is a convenience method for doing simple POST requests. -func (c *Client) Post(url, bodyType string, body interface{}) (*http.Response, error) { - req, err := NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return c.Do(req) -} - -// PostForm is a shortcut to perform a POST with form data without creating -// a new client. -func PostForm(url string, data url.Values) (*http.Response, error) { - return defaultClient.PostForm(url, data) -} - -// PostForm is a convenience method for doing simple POST operations using -// pre-filled url.Values form data. -func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) { - return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/go.mod b/vendor/github.com/hashicorp/go-retryablehttp/go.mod deleted file mode 100644 index d28c8c8e..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/go-retryablehttp - -require github.com/hashicorp/go-cleanhttp v0.5.0 diff --git a/vendor/github.com/hashicorp/go-retryablehttp/go.sum b/vendor/github.com/hashicorp/go-retryablehttp/go.sum deleted file mode 100644 index 3ed0fd98..00000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= -github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= diff --git a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml b/vendor/github.com/hashicorp/go-rootcerts/.travis.yml deleted file mode 100644 index 80e1de44..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.6 - -branches: - only: - - master - -script: make test diff --git a/vendor/github.com/hashicorp/go-rootcerts/LICENSE b/vendor/github.com/hashicorp/go-rootcerts/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/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-rootcerts/Makefile b/vendor/github.com/hashicorp/go-rootcerts/Makefile deleted file mode 100644 index c3989e78..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -TEST?=./... - -test: - go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 - go vet $(TEST) - go test $(TEST) -race - -.PHONY: test diff --git a/vendor/github.com/hashicorp/go-rootcerts/README.md b/vendor/github.com/hashicorp/go-rootcerts/README.md deleted file mode 100644 index f5abffc2..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# rootcerts - -Functions for loading root certificates for TLS connections. - ------ - -Go's standard library `crypto/tls` provides a common mechanism for configuring -TLS connections in `tls.Config`. The `RootCAs` field on this struct is a pool -of certificates for the client to use as a trust store when verifying server -certificates. - -This library contains utility functions for loading certificates destined for -that field, as well as one other important thing: - -When the `RootCAs` field is `nil`, the standard library attempts to load the -host's root CA set. This behavior is OS-specific, and the Darwin -implementation contains [a bug that prevents trusted certificates from the -System and Login keychains from being loaded][1]. This library contains -Darwin-specific behavior that works around that bug. - -[1]: https://github.com/golang/go/issues/14514 - -## Example Usage - -Here's a snippet demonstrating how this library is meant to be used: - -```go -func httpClient() (*http.Client, error) - tlsConfig := &tls.Config{} - err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{ - CAFile: os.Getenv("MYAPP_CAFILE"), - CAPath: os.Getenv("MYAPP_CAPATH"), - }) - if err != nil { - return nil, err - } - c := cleanhttp.DefaultClient() - t := cleanhttp.DefaultTransport() - t.TLSClientConfig = tlsConfig - c.Transport = t - return c, nil -} -``` diff --git a/vendor/github.com/hashicorp/go-rootcerts/doc.go b/vendor/github.com/hashicorp/go-rootcerts/doc.go deleted file mode 100644 index b55cc628..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package rootcerts contains functions to aid in loading CA certificates for -// TLS connections. -// -// In addition, its default behavior on Darwin works around an open issue [1] -// in Go's crypto/x509 that prevents certicates from being loaded from the -// System or Login keychains. -// -// [1] https://github.com/golang/go/issues/14514 -package rootcerts diff --git a/vendor/github.com/hashicorp/go-rootcerts/go.mod b/vendor/github.com/hashicorp/go-rootcerts/go.mod deleted file mode 100644 index 3c0e0e69..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/go-rootcerts - -require github.com/mitchellh/go-homedir v1.0.0 diff --git a/vendor/github.com/hashicorp/go-rootcerts/go.sum b/vendor/github.com/hashicorp/go-rootcerts/go.sum deleted file mode 100644 index d12bb759..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go deleted file mode 100644 index aeb30ece..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go +++ /dev/null @@ -1,103 +0,0 @@ -package rootcerts - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "os" - "path/filepath" -) - -// Config determines where LoadCACerts will load certificates from. When both -// CAFile and CAPath are blank, this library's functions will either load -// system roots explicitly and return them, or set the CertPool to nil to allow -// Go's standard library to load system certs. -type Config struct { - // CAFile is a path to a PEM-encoded certificate file or bundle. Takes - // precedence over CAPath. - CAFile string - - // CAPath is a path to a directory populated with PEM-encoded certificates. - CAPath string -} - -// ConfigureTLS sets up the RootCAs on the provided tls.Config based on the -// Config specified. -func ConfigureTLS(t *tls.Config, c *Config) error { - if t == nil { - return nil - } - pool, err := LoadCACerts(c) - if err != nil { - return err - } - t.RootCAs = pool - return nil -} - -// LoadCACerts loads a CertPool based on the Config specified. -func LoadCACerts(c *Config) (*x509.CertPool, error) { - if c == nil { - c = &Config{} - } - if c.CAFile != "" { - return LoadCAFile(c.CAFile) - } - if c.CAPath != "" { - return LoadCAPath(c.CAPath) - } - - return LoadSystemCAs() -} - -// LoadCAFile loads a single PEM-encoded file from the path specified. -func LoadCAFile(caFile string) (*x509.CertPool, error) { - pool := x509.NewCertPool() - - pem, err := ioutil.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("Error loading CA File: %s", err) - } - - ok := pool.AppendCertsFromPEM(pem) - if !ok { - return nil, fmt.Errorf("Error loading CA File: Couldn't parse PEM in: %s", caFile) - } - - return pool, nil -} - -// LoadCAPath walks the provided path and loads all certificates encounted into -// a pool. -func LoadCAPath(caPath string) (*x509.CertPool, error) { - pool := x509.NewCertPool() - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if info.IsDir() { - return nil - } - - pem, err := ioutil.ReadFile(path) - if err != nil { - return fmt.Errorf("Error loading file from CAPath: %s", err) - } - - ok := pool.AppendCertsFromPEM(pem) - if !ok { - return fmt.Errorf("Error loading CA Path: Couldn't parse PEM in: %s", path) - } - - return nil - } - - err := filepath.Walk(caPath, walkFn) - if err != nil { - return nil, err - } - - return pool, nil -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go deleted file mode 100644 index 66b1472c..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !darwin - -package rootcerts - -import "crypto/x509" - -// LoadSystemCAs does nothing on non-Darwin systems. We return nil so that -// default behavior of standard TLS config libraries is triggered, which is to -// load system certs. -func LoadSystemCAs() (*x509.CertPool, error) { - return nil, nil -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go deleted file mode 100644 index a9a04065..00000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go +++ /dev/null @@ -1,48 +0,0 @@ -package rootcerts - -import ( - "crypto/x509" - "os/exec" - "path" - - "github.com/mitchellh/go-homedir" -) - -// LoadSystemCAs has special behavior on Darwin systems to work around -func LoadSystemCAs() (*x509.CertPool, error) { - pool := x509.NewCertPool() - - for _, keychain := range certKeychains() { - err := addCertsFromKeychain(pool, keychain) - if err != nil { - return nil, err - } - } - - return pool, nil -} - -func addCertsFromKeychain(pool *x509.CertPool, keychain string) error { - cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain) - data, err := cmd.Output() - if err != nil { - return err - } - - pool.AppendCertsFromPEM(data) - - return nil -} - -func certKeychains() []string { - keychains := []string{ - "/System/Library/Keychains/SystemRootCertificates.keychain", - "/Library/Keychains/System.keychain", - } - home, err := homedir.Dir() - if err == nil { - loginKeychain := path.Join(home, "Library", "Keychains", "login.keychain") - keychains = append(keychains, loginKeychain) - } - return keychains -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/.gitignore b/vendor/github.com/hashicorp/go-sockaddr/.gitignore deleted file mode 100644 index 41720b86..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/.gitignore +++ /dev/null @@ -1,26 +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 -*.prof -.cover.out* -coverage.html diff --git a/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile b/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile deleted file mode 100644 index f3dfd24c..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile +++ /dev/null @@ -1,65 +0,0 @@ -TOOLS= golang.org/x/tools/cover -GOCOVER_TMPFILE?= $(GOCOVER_FILE).tmp -GOCOVER_FILE?= .cover.out -GOCOVERHTML?= coverage.html -FIND=`/usr/bin/which 2> /dev/null gfind find | /usr/bin/grep -v ^no | /usr/bin/head -n 1` -XARGS=`/usr/bin/which 2> /dev/null gxargs xargs | /usr/bin/grep -v ^no | /usr/bin/head -n 1` - -test:: $(GOCOVER_FILE) - @$(MAKE) -C cmd/sockaddr test - -cover:: coverage_report - -$(GOCOVER_FILE):: - @${FIND} . -type d ! -path '*cmd*' ! -path '*.git*' -print0 | ${XARGS} -0 -I % sh -ec "cd % && rm -f $(GOCOVER_TMPFILE) && go test -coverprofile=$(GOCOVER_TMPFILE)" - - @echo 'mode: set' > $(GOCOVER_FILE) - @${FIND} . -type f ! -path '*cmd*' ! -path '*.git*' -name "$(GOCOVER_TMPFILE)" -print0 | ${XARGS} -0 -n1 cat $(GOCOVER_TMPFILE) | grep -v '^mode: ' >> ${PWD}/$(GOCOVER_FILE) - -$(GOCOVERHTML): $(GOCOVER_FILE) - go tool cover -html=$(GOCOVER_FILE) -o $(GOCOVERHTML) - -coverage_report:: $(GOCOVER_FILE) - go tool cover -html=$(GOCOVER_FILE) - -audit_tools:: - @go get -u github.com/golang/lint/golint && echo "Installed golint:" - @go get -u github.com/fzipp/gocyclo && echo "Installed gocyclo:" - @go get -u github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:" - @go get -u github.com/client9/misspell/cmd/misspell && echo "Installed misspell:" - @go get -u github.com/gordonklaus/ineffassign && echo "Installed ineffassign:" - -audit:: - deadcode - go tool vet -all *.go - go tool vet -shadow=true *.go - golint *.go - ineffassign . - gocyclo -over 65 *.go - misspell *.go - -clean:: - rm -f $(GOCOVER_FILE) $(GOCOVERHTML) - -dev:: - @go build - @$(MAKE) -B -C cmd/sockaddr sockaddr - -install:: - @go install - @$(MAKE) -C cmd/sockaddr install - -doc:: - @echo Visit: http://127.0.0.1:6161/pkg/github.com/hashicorp/go-sockaddr/ - godoc -http=:6161 -goroot $GOROOT - -world:: - @set -e; \ - for os in solaris darwin freebsd linux windows; do \ - for arch in amd64; do \ - printf "Building on %s-%s\n" "$${os}" "$${arch}" ; \ - env GOOS="$${os}" GOARCH="$${arch}" go build -o /dev/null; \ - done; \ - done - - $(MAKE) -C cmd/sockaddr world diff --git a/vendor/github.com/hashicorp/go-sockaddr/LICENSE b/vendor/github.com/hashicorp/go-sockaddr/LICENSE deleted file mode 100644 index a612ad98..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/LICENSE +++ /dev/null @@ -1,373 +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-sockaddr/README.md b/vendor/github.com/hashicorp/go-sockaddr/README.md deleted file mode 100644 index a2e170ae..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# go-sockaddr - -## `sockaddr` Library - -Socket address convenience functions for Go. `go-sockaddr` is a convenience -library that makes doing the right thing with IP addresses easy. `go-sockaddr` -is loosely modeled after the UNIX `sockaddr_t` and creates a union of the family -of `sockaddr_t` types (see below for an ascii diagram). Library documentation -is available -at -[https://godoc.org/github.com/hashicorp/go-sockaddr](https://godoc.org/github.com/hashicorp/go-sockaddr). -The primary intent of the library was to make it possible to define heuristics -for selecting the correct IP addresses when a configuration is evaluated at -runtime. See -the -[docs](https://godoc.org/github.com/hashicorp/go-sockaddr), -[`template` package](https://godoc.org/github.com/hashicorp/go-sockaddr/template), -tests, -and -[CLI utility](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr) -for details and hints as to how to use this library. - -For example, with this library it is possible to find an IP address that: - -* is attached to a default route - ([`GetDefaultInterfaces()`](https://godoc.org/github.com/hashicorp/go-sockaddr#GetDefaultInterfaces)) -* is contained within a CIDR block ([`IfByNetwork()`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByNetwork)) -* is an RFC1918 address - ([`IfByRFC("1918")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC)) -* is ordered - ([`OrderedIfAddrBy(args)`](https://godoc.org/github.com/hashicorp/go-sockaddr#OrderedIfAddrBy) where - `args` includes, but is not limited - to, - [`AscIfType`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscIfType), - [`AscNetworkSize`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscNetworkSize)) -* excludes all IPv6 addresses - ([`IfByType("^(IPv4)$")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByType)) -* is larger than a `/32` - ([`IfByMaskSize(32)`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByMaskSize)) -* is not on a `down` interface - ([`ExcludeIfs("flags", "down")`](https://godoc.org/github.com/hashicorp/go-sockaddr#ExcludeIfs)) -* preferences an IPv6 address over an IPv4 address - ([`SortIfByType()`](https://godoc.org/github.com/hashicorp/go-sockaddr#SortIfByType) + - [`ReverseIfAddrs()`](https://godoc.org/github.com/hashicorp/go-sockaddr#ReverseIfAddrs)); and -* excludes any IP in RFC6890 address - ([`IfByRFC("6890")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC)) - -Or any combination or variation therein. - -There are also a few simple helper functions such as `GetPublicIP` and -`GetPrivateIP` which both return strings and select the first public or private -IP address on the default interface, respectively. Similarly, there is also a -helper function called `GetInterfaceIP` which returns the first usable IP -address on the named interface. - -## `sockaddr` CLI - -Given the possible complexity of the `sockaddr` library, there is a CLI utility -that accompanies the library, also -called -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr). -The -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr) -utility exposes nearly all of the functionality of the library and can be used -either as an administrative tool or testing tool. To install -the -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr), -run: - -```text -$ go get -u github.com/hashicorp/go-sockaddr/cmd/sockaddr -``` - -If you're familiar with UNIX's `sockaddr` struct's, the following diagram -mapping the C `sockaddr` (top) to `go-sockaddr` structs (bottom) and -interfaces will be helpful: - -``` -+-------------------------------------------------------+ -| | -| sockaddr | -| SockAddr | -| | -| +--------------+ +----------------------------------+ | -| | sockaddr_un | | | | -| | SockAddrUnix | | sockaddr_in{,6} | | -| +--------------+ | IPAddr | | -| | | | -| | +-------------+ +--------------+ | | -| | | sockaddr_in | | sockaddr_in6 | | | -| | | IPv4Addr | | IPv6Addr | | | -| | +-------------+ +--------------+ | | -| | | | -| +----------------------------------+ | -| | -+-------------------------------------------------------+ -``` - -## Inspiration and Design - -There were many subtle inspirations that led to this design, but the most direct -inspiration for the filtering syntax was -OpenBSD's -[`pf.conf(5)`](https://www.freebsd.org/cgi/man.cgi?query=pf.conf&apropos=0&sektion=0&arch=default&format=html#PARAMETERS) firewall -syntax that lets you select the first IP address on a given named interface. -The original problem stemmed from: - -* needing to create immutable images using [Packer](https://www.packer.io) that - ran the [Consul](https://www.consul.io) process (Consul can only use one IP - address at a time); -* images that may or may not have multiple interfaces or IP addresses at - runtime; and -* we didn't want to rely on configuration management to render out the correct - IP address if the VM image was being used in an auto-scaling group. - -Instead we needed some way to codify a heuristic that would correctly select the -right IP address but the input parameters were not known when the image was -created. diff --git a/vendor/github.com/hashicorp/go-sockaddr/doc.go b/vendor/github.com/hashicorp/go-sockaddr/doc.go deleted file mode 100644 index 90671deb..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package sockaddr is a Go implementation of the UNIX socket family data types and -related helper functions. -*/ -package sockaddr diff --git a/vendor/github.com/hashicorp/go-sockaddr/go.mod b/vendor/github.com/hashicorp/go-sockaddr/go.mod deleted file mode 100644 index 7c07b5ba..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/go-sockaddr diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go deleted file mode 100644 index 0811b275..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go +++ /dev/null @@ -1,254 +0,0 @@ -package sockaddr - -import "strings" - -// ifAddrAttrMap is a map of the IfAddr type-specific attributes. -var ifAddrAttrMap map[AttrName]func(IfAddr) string -var ifAddrAttrs []AttrName - -func init() { - ifAddrAttrInit() -} - -// GetPrivateIP returns a string with a single IP address that is part of RFC -// 6890 and has a default route. If the system can't determine its IP address -// or find an RFC 6890 IP address, an empty string will be returned instead. -// This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetPrivateInterfaces | attr "address"}}' -/// ``` -func GetPrivateIP() (string, error) { - privateIfs, err := GetPrivateInterfaces() - if err != nil { - return "", err - } - if len(privateIfs) < 1 { - return "", nil - } - - ifAddr := privateIfs[0] - ip := *ToIPAddr(ifAddr.SockAddr) - return ip.NetIP().String(), nil -} - -// GetPrivateIPs returns a string with all IP addresses that are part of RFC -// 6890 (regardless of whether or not there is a default route, unlike -// GetPublicIP). If the system can't find any RFC 6890 IP addresses, an empty -// string will be returned instead. This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "RFC" "6890" | join "address" " "}}' -/// ``` -func GetPrivateIPs() (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } else if len(ifAddrs) < 1 { - return "", nil - } - - ifAddrs, _ = FilterIfByType(ifAddrs, TypeIP) - if len(ifAddrs) == 0 { - return "", nil - } - - OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(ifAddrs) - - ifAddrs, _, err = IfByRFC("6890", ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - _, ifAddrs, err = IfByRFC(ForwardingBlacklistRFC, ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// GetPublicIP returns a string with a single IP address that is NOT part of RFC -// 6890 and has a default route. If the system can't determine its IP address -// or find a non RFC 6890 IP address, an empty string will be returned instead. -// This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetPublicInterfaces | attr "address"}}' -/// ``` -func GetPublicIP() (string, error) { - publicIfs, err := GetPublicInterfaces() - if err != nil { - return "", err - } else if len(publicIfs) < 1 { - return "", nil - } - - ifAddr := publicIfs[0] - ip := *ToIPAddr(ifAddr.SockAddr) - return ip.NetIP().String(), nil -} - -// GetPublicIPs returns a string with all IP addresses that are NOT part of RFC -// 6890 (regardless of whether or not there is a default route, unlike -// GetPublicIP). If the system can't find any non RFC 6890 IP addresses, an -// empty string will be returned instead. This function is the `eval` -// equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | exclude "RFC" "6890" | join "address" " "}}' -/// ``` -func GetPublicIPs() (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } else if len(ifAddrs) < 1 { - return "", nil - } - - ifAddrs, _ = FilterIfByType(ifAddrs, TypeIP) - if len(ifAddrs) == 0 { - return "", nil - } - - OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(ifAddrs) - - _, ifAddrs, err = IfByRFC("6890", ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// GetInterfaceIP returns a string with a single IP address sorted by the size -// of the network (i.e. IP addresses with a smaller netmask, larger network -// size, are sorted first). This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "name" <> | sort "type,size" | include "flag" "forwardable" | attr "address" }}' -/// ``` -func GetInterfaceIP(namedIfRE string) (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByName(namedIfRE, ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByFlag("forwardable", ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, err = SortIfBy("+type,+size", ifAddrs) - if err != nil { - return "", err - } - - if len(ifAddrs) == 0 { - return "", err - } - - ip := ToIPAddr(ifAddrs[0].SockAddr) - if ip == nil { - return "", err - } - - return IPAddrAttr(*ip, "address"), nil -} - -// GetInterfaceIPs returns a string with all IPs, sorted by the size of the -// network (i.e. IP addresses with a smaller netmask, larger network size, are -// sorted first), on a named interface. This function is the `eval` equivalent -// of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "name" <> | sort "type,size" | join "address" " "}}' -/// ``` -func GetInterfaceIPs(namedIfRE string) (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByName(namedIfRE, ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, err = SortIfBy("+type,+size", ifAddrs) - if err != nil { - return "", err - } - - if len(ifAddrs) == 0 { - return "", err - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// IfAddrAttrs returns a list of attributes supported by the IfAddr type -func IfAddrAttrs() []AttrName { - return ifAddrAttrs -} - -// IfAddrAttr returns a string representation of an attribute for the given -// IfAddr. -func IfAddrAttr(ifAddr IfAddr, attrName AttrName) string { - fn, found := ifAddrAttrMap[attrName] - if !found { - return "" - } - - return fn(ifAddr) -} - -// ifAddrAttrInit is called once at init() -func ifAddrAttrInit() { - // Sorted for human readability - ifAddrAttrs = []AttrName{ - "flags", - "name", - } - - ifAddrAttrMap = map[AttrName]func(ifAddr IfAddr) string{ - "flags": func(ifAddr IfAddr) string { - return ifAddr.Interface.Flags.String() - }, - "name": func(ifAddr IfAddr) string { - return ifAddr.Interface.Name - }, - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go deleted file mode 100644 index 2a706c34..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go +++ /dev/null @@ -1,1281 +0,0 @@ -package sockaddr - -import ( - "encoding/binary" - "errors" - "fmt" - "math/big" - "net" - "regexp" - "sort" - "strconv" - "strings" -) - -var ( - // Centralize all regexps and regexp.Copy() where necessary. - signRE *regexp.Regexp = regexp.MustCompile(`^[\s]*[+-]`) - whitespaceRE *regexp.Regexp = regexp.MustCompile(`[\s]+`) - ifNameRE *regexp.Regexp = regexp.MustCompile(`^(?:Ethernet|Wireless LAN) adapter ([^:]+):`) - ipAddrRE *regexp.Regexp = regexp.MustCompile(`^ IPv[46] Address\. \. \. \. \. \. \. \. \. \. \. : ([^\s]+)`) -) - -// IfAddrs is a slice of IfAddr -type IfAddrs []IfAddr - -func (ifs IfAddrs) Len() int { return len(ifs) } - -// CmpIfFunc is the function signature that must be met to be used in the -// OrderedIfAddrBy multiIfAddrSorter -type CmpIfAddrFunc func(p1, p2 *IfAddr) int - -// multiIfAddrSorter implements the Sort interface, sorting the IfAddrs within. -type multiIfAddrSorter struct { - ifAddrs IfAddrs - cmp []CmpIfAddrFunc -} - -// Sort sorts the argument slice according to the Cmp functions passed to -// OrderedIfAddrBy. -func (ms *multiIfAddrSorter) Sort(ifAddrs IfAddrs) { - ms.ifAddrs = ifAddrs - sort.Sort(ms) -} - -// OrderedIfAddrBy sorts SockAddr by the list of sort function pointers. -func OrderedIfAddrBy(cmpFuncs ...CmpIfAddrFunc) *multiIfAddrSorter { - return &multiIfAddrSorter{ - cmp: cmpFuncs, - } -} - -// Len is part of sort.Interface. -func (ms *multiIfAddrSorter) Len() int { - return len(ms.ifAddrs) -} - -// Less is part of sort.Interface. It is implemented by looping along the Cmp() -// functions until it finds a comparison that is either less than or greater -// than. A return value of 0 defers sorting to the next function in the -// multisorter (which means the results of sorting may leave the resutls in a -// non-deterministic order). -func (ms *multiIfAddrSorter) Less(i, j int) bool { - p, q := &ms.ifAddrs[i], &ms.ifAddrs[j] - // Try all but the last comparison. - var k int - for k = 0; k < len(ms.cmp)-1; k++ { - cmp := ms.cmp[k] - x := cmp(p, q) - switch x { - case -1: - // p < q, so we have a decision. - return true - case 1: - // p > q, so we have a decision. - return false - } - // p == q; try the next comparison. - } - // All comparisons to here said "equal", so just return whatever the - // final comparison reports. - switch ms.cmp[k](p, q) { - case -1: - return true - case 1: - return false - default: - // Still a tie! Now what? - return false - panic("undefined sort order for remaining items in the list") - } -} - -// Swap is part of sort.Interface. -func (ms *multiIfAddrSorter) Swap(i, j int) { - ms.ifAddrs[i], ms.ifAddrs[j] = ms.ifAddrs[j], ms.ifAddrs[i] -} - -// AscIfAddress is a sorting function to sort IfAddrs by their respective -// address type. Non-equal types are deferred in the sort. -func AscIfAddress(p1Ptr, p2Ptr *IfAddr) int { - return AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfDefault is a sorting function to sort IfAddrs by whether or not they -// have a default route or not. Non-equal types are deferred in the sort. -// -// FIXME: This is a particularly expensive sorting operation because of the -// non-memoized calls to NewRouteInfo(). In an ideal world the routeInfo data -// once at the start of the sort and pass it along as a context or by wrapping -// the IfAddr type with this information (this would also solve the inability to -// return errors and the possibility of failing silently). Fortunately, -// N*log(N) where N = 3 is only ~6.2 invocations. Not ideal, but not worth -// optimizing today. The common case is this gets called once or twice. -// Patches welcome. -func AscIfDefault(p1Ptr, p2Ptr *IfAddr) int { - ri, err := NewRouteInfo() - if err != nil { - return sortDeferDecision - } - - defaultIfName, err := ri.GetDefaultInterfaceName() - if err != nil { - return sortDeferDecision - } - - switch { - case p1Ptr.Interface.Name == defaultIfName && p2Ptr.Interface.Name == defaultIfName: - return sortDeferDecision - case p1Ptr.Interface.Name == defaultIfName: - return sortReceiverBeforeArg - case p2Ptr.Interface.Name == defaultIfName: - return sortArgBeforeReceiver - default: - return sortDeferDecision - } -} - -// AscIfName is a sorting function to sort IfAddrs by their interface names. -func AscIfName(p1Ptr, p2Ptr *IfAddr) int { - return strings.Compare(p1Ptr.Name, p2Ptr.Name) -} - -// AscIfNetworkSize is a sorting function to sort IfAddrs by their respective -// network mask size. -func AscIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int { - return AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfPort is a sorting function to sort IfAddrs by their respective -// port type. Non-equal types are deferred in the sort. -func AscIfPort(p1Ptr, p2Ptr *IfAddr) int { - return AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfPrivate is a sorting function to sort IfAddrs by "private" values before -// "public" values. Both IPv4 and IPv6 are compared against RFC6890 (RFC6890 -// includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and IPv6 -// includes RFC4193). -func AscIfPrivate(p1Ptr, p2Ptr *IfAddr) int { - return AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfType is a sorting function to sort IfAddrs by their respective address -// type. Non-equal types are deferred in the sort. -func AscIfType(p1Ptr, p2Ptr *IfAddr) int { - return AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfAddress is identical to AscIfAddress but reverse ordered. -func DescIfAddress(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfDefault is identical to AscIfDefault but reverse ordered. -func DescIfDefault(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscIfDefault(p1Ptr, p2Ptr) -} - -// DescIfName is identical to AscIfName but reverse ordered. -func DescIfName(p1Ptr, p2Ptr *IfAddr) int { - return -1 * strings.Compare(p1Ptr.Name, p2Ptr.Name) -} - -// DescIfNetworkSize is identical to AscIfNetworkSize but reverse ordered. -func DescIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfPort is identical to AscIfPort but reverse ordered. -func DescIfPort(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfPrivate is identical to AscIfPrivate but reverse ordered. -func DescIfPrivate(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfType is identical to AscIfType but reverse ordered. -func DescIfType(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// FilterIfByType filters IfAddrs and returns a list of the matching type -func FilterIfByType(ifAddrs IfAddrs, type_ SockAddrType) (matchedIfs, excludedIfs IfAddrs) { - excludedIfs = make(IfAddrs, 0, len(ifAddrs)) - matchedIfs = make(IfAddrs, 0, len(ifAddrs)) - - for _, ifAddr := range ifAddrs { - if ifAddr.SockAddr.Type()&type_ != 0 { - matchedIfs = append(matchedIfs, ifAddr) - } else { - excludedIfs = append(excludedIfs, ifAddr) - } - } - return matchedIfs, excludedIfs -} - -// IfAttr forwards the selector to IfAttr.Attr() for resolution. If there is -// more than one IfAddr, only the first IfAddr is used. -func IfAttr(selectorName string, ifAddr IfAddr) (string, error) { - attrName := AttrName(strings.ToLower(selectorName)) - attrVal, err := ifAddr.Attr(attrName) - return attrVal, err -} - -// IfAttrs forwards the selector to IfAttrs.Attr() for resolution. If there is -// more than one IfAddr, only the first IfAddr is used. -func IfAttrs(selectorName string, ifAddrs IfAddrs) (string, error) { - if len(ifAddrs) == 0 { - return "", nil - } - - attrName := AttrName(strings.ToLower(selectorName)) - attrVal, err := ifAddrs[0].Attr(attrName) - return attrVal, err -} - -// GetAllInterfaces iterates over all available network interfaces and finds all -// available IP addresses on each interface and converts them to -// sockaddr.IPAddrs, and returning the result as an array of IfAddr. -func GetAllInterfaces() (IfAddrs, error) { - ifs, err := net.Interfaces() - if err != nil { - return nil, err - } - - ifAddrs := make(IfAddrs, 0, len(ifs)) - for _, intf := range ifs { - addrs, err := intf.Addrs() - if err != nil { - return nil, err - } - - for _, addr := range addrs { - var ipAddr IPAddr - ipAddr, err = NewIPAddr(addr.String()) - if err != nil { - return IfAddrs{}, fmt.Errorf("unable to create an IP address from %q", addr.String()) - } - - ifAddr := IfAddr{ - SockAddr: ipAddr, - Interface: intf, - } - ifAddrs = append(ifAddrs, ifAddr) - } - } - - return ifAddrs, nil -} - -// GetDefaultInterfaces returns IfAddrs of the addresses attached to the default -// route. -func GetDefaultInterfaces() (IfAddrs, error) { - ri, err := NewRouteInfo() - if err != nil { - return nil, err - } - - defaultIfName, err := ri.GetDefaultInterfaceName() - if err != nil { - return nil, err - } - - var defaultIfs, ifAddrs IfAddrs - ifAddrs, err = GetAllInterfaces() - for _, ifAddr := range ifAddrs { - if ifAddr.Name == defaultIfName { - defaultIfs = append(defaultIfs, ifAddr) - } - } - - return defaultIfs, nil -} - -// GetPrivateInterfaces returns an IfAddrs that are part of RFC 6890 and have a -// default route. If the system can't determine its IP address or find an RFC -// 6890 IP address, an empty IfAddrs will be returned instead. This function is -// the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | include "RFC" "6890" }}' -/// ``` -func GetPrivateInterfaces() (IfAddrs, error) { - privateIfs, err := GetAllInterfaces() - if err != nil { - return IfAddrs{}, err - } - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - privateIfs, _ = FilterIfByType(privateIfs, TypeIP) - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - privateIfs, _, err = IfByFlag("forwardable", privateIfs) - if err != nil { - return IfAddrs{}, err - } - - privateIfs, _, err = IfByFlag("up", privateIfs) - if err != nil { - return IfAddrs{}, err - } - - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(privateIfs) - - privateIfs, _, err = IfByRFC("6890", privateIfs) - if err != nil { - return IfAddrs{}, err - } else if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - return privateIfs, nil -} - -// GetPublicInterfaces returns an IfAddrs that are NOT part of RFC 6890 and has a -// default route. If the system can't determine its IP address or find a non -// RFC 6890 IP address, an empty IfAddrs will be returned instead. This -// function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | exclude "RFC" "6890" }}' -/// ``` -func GetPublicInterfaces() (IfAddrs, error) { - publicIfs, err := GetAllInterfaces() - if err != nil { - return IfAddrs{}, err - } - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - publicIfs, _ = FilterIfByType(publicIfs, TypeIP) - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - publicIfs, _, err = IfByFlag("forwardable", publicIfs) - if err != nil { - return IfAddrs{}, err - } - - publicIfs, _, err = IfByFlag("up", publicIfs) - if err != nil { - return IfAddrs{}, err - } - - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(publicIfs) - - _, publicIfs, err = IfByRFC("6890", publicIfs) - if err != nil { - return IfAddrs{}, err - } else if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - return publicIfs, nil -} - -// IfByAddress returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByAddress(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile address regexp %+q: %v", inputRe, err) - } - - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - for _, addr := range ifAddrs { - if re.MatchString(addr.SockAddr.String()) { - matchedAddrs = append(matchedAddrs, addr) - } else { - excludedAddrs = append(excludedAddrs, addr) - } - } - - return matchedAddrs, excludedAddrs, nil -} - -// IfByName returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByName(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile name regexp %+q: %v", inputRe, err) - } - - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - for _, addr := range ifAddrs { - if re.MatchString(addr.Name) { - matchedAddrs = append(matchedAddrs, addr) - } else { - excludedAddrs = append(excludedAddrs, addr) - } - } - - return matchedAddrs, excludedAddrs, nil -} - -// IfByPort returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByPort(inputRe string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile port regexp %+q: %v", inputRe, err) - } - - ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP) - matchedIfs = make(IfAddrs, 0, len(ipIfs)) - excludedIfs = append(IfAddrs(nil), nonIfs...) - for _, addr := range ipIfs { - ipAddr := ToIPAddr(addr.SockAddr) - if ipAddr == nil { - continue - } - - port := strconv.FormatInt(int64((*ipAddr).IPPort()), 10) - if re.MatchString(port) { - matchedIfs = append(matchedIfs, addr) - } else { - excludedIfs = append(excludedIfs, addr) - } - } - - return matchedIfs, excludedIfs, nil -} - -// IfByRFC returns a list of matched and non-matched IfAddrs that contain the -// relevant RFC-specified traits. -func IfByRFC(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - inputRFC, err := strconv.ParseUint(selectorParam, 10, 64) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to parse RFC number %q: %v", selectorParam, err) - } - - matchedIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - - rfcNetMap := KnownRFCs() - rfcNets, ok := rfcNetMap[uint(inputRFC)] - if !ok { - return nil, nil, fmt.Errorf("unsupported RFC %d", inputRFC) - } - - for _, ifAddr := range ifAddrs { - var contained bool - for _, rfcNet := range rfcNets { - if rfcNet.Contains(ifAddr.SockAddr) { - matchedIfAddrs = append(matchedIfAddrs, ifAddr) - contained = true - break - } - } - if !contained { - remainingIfAddrs = append(remainingIfAddrs, ifAddr) - } - } - - return matchedIfAddrs, remainingIfAddrs, nil -} - -// IfByRFCs returns a list of matched and non-matched IfAddrs that contain the -// relevant RFC-specified traits. Multiple RFCs can be specified and separated -// by the `|` symbol. No protection is taken to ensure an IfAddr does not end -// up in both the included and excluded list. -func IfByRFCs(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - var includedIfs, excludedIfs IfAddrs - for _, rfcStr := range strings.Split(selectorParam, "|") { - includedRFCIfs, excludedRFCIfs, err := IfByRFC(rfcStr, ifAddrs) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to lookup RFC number %q: %v", rfcStr, err) - } - includedIfs = append(includedIfs, includedRFCIfs...) - excludedIfs = append(excludedIfs, excludedRFCIfs...) - } - - return includedIfs, excludedIfs, nil -} - -// IfByMaskSize returns a list of matched and non-matched IfAddrs that have the -// matching mask size. -func IfByMaskSize(selectorParam string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) { - maskSize, err := strconv.ParseUint(selectorParam, 10, 64) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("invalid exclude size argument (%q): %v", selectorParam, err) - } - - ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP) - matchedIfs = make(IfAddrs, 0, len(ipIfs)) - excludedIfs = append(IfAddrs(nil), nonIfs...) - for _, addr := range ipIfs { - ipAddr := ToIPAddr(addr.SockAddr) - if ipAddr == nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to filter mask sizes on non-IP type %s: %v", addr.SockAddr.Type().String(), addr.SockAddr.String()) - } - - switch { - case (*ipAddr).Type()&TypeIPv4 != 0 && maskSize > 32: - return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv4 address: %d", maskSize) - case (*ipAddr).Type()&TypeIPv6 != 0 && maskSize > 128: - return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv6 address: %d", maskSize) - } - - if (*ipAddr).Maskbits() == int(maskSize) { - matchedIfs = append(matchedIfs, addr) - } else { - excludedIfs = append(excludedIfs, addr) - } - } - - return matchedIfs, excludedIfs, nil -} - -// IfByType returns a list of matching and non-matching IfAddr that match the -// specified type. For instance: -// -// include "type" "IPv4,IPv6" -// -// will include any IfAddrs that is either an IPv4 or IPv6 address. Any -// addresses on those interfaces that don't match will be included in the -// remainder results. -func IfByType(inputTypes string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - matchingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - - ifTypes := strings.Split(strings.ToLower(inputTypes), "|") - for _, ifType := range ifTypes { - switch ifType { - case "ip", "ipv4", "ipv6", "unix": - // Valid types - default: - return nil, nil, fmt.Errorf("unsupported type %q %q", ifType, inputTypes) - } - } - - for _, ifAddr := range ifAddrs { - for _, ifType := range ifTypes { - var matched bool - switch { - case ifType == "ip" && ifAddr.SockAddr.Type()&TypeIP != 0: - matched = true - case ifType == "ipv4" && ifAddr.SockAddr.Type()&TypeIPv4 != 0: - matched = true - case ifType == "ipv6" && ifAddr.SockAddr.Type()&TypeIPv6 != 0: - matched = true - case ifType == "unix" && ifAddr.SockAddr.Type()&TypeUnix != 0: - matched = true - } - - if matched { - matchingIfAddrs = append(matchingIfAddrs, ifAddr) - } else { - remainingIfAddrs = append(remainingIfAddrs, ifAddr) - } - } - } - - return matchingIfAddrs, remainingIfAddrs, nil -} - -// IfByFlag returns a list of matching and non-matching IfAddrs that match the -// specified type. For instance: -// -// include "flag" "up,broadcast" -// -// will include any IfAddrs that have both the "up" and "broadcast" flags set. -// Any addresses on those interfaces that don't match will be omitted from the -// results. -func IfByFlag(inputFlags string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - - var wantForwardable, - wantGlobalUnicast, - wantInterfaceLocalMulticast, - wantLinkLocalMulticast, - wantLinkLocalUnicast, - wantLoopback, - wantMulticast, - wantUnspecified bool - var ifFlags net.Flags - var checkFlags, checkAttrs bool - for _, flagName := range strings.Split(strings.ToLower(inputFlags), "|") { - switch flagName { - case "broadcast": - checkFlags = true - ifFlags = ifFlags | net.FlagBroadcast - case "down": - checkFlags = true - ifFlags = (ifFlags &^ net.FlagUp) - case "forwardable": - checkAttrs = true - wantForwardable = true - case "global unicast": - checkAttrs = true - wantGlobalUnicast = true - case "interface-local multicast": - checkAttrs = true - wantInterfaceLocalMulticast = true - case "link-local multicast": - checkAttrs = true - wantLinkLocalMulticast = true - case "link-local unicast": - checkAttrs = true - wantLinkLocalUnicast = true - case "loopback": - checkAttrs = true - checkFlags = true - ifFlags = ifFlags | net.FlagLoopback - wantLoopback = true - case "multicast": - checkAttrs = true - checkFlags = true - ifFlags = ifFlags | net.FlagMulticast - wantMulticast = true - case "point-to-point": - checkFlags = true - ifFlags = ifFlags | net.FlagPointToPoint - case "unspecified": - checkAttrs = true - wantUnspecified = true - case "up": - checkFlags = true - ifFlags = ifFlags | net.FlagUp - default: - return nil, nil, fmt.Errorf("Unknown interface flag: %+q", flagName) - } - } - - for _, ifAddr := range ifAddrs { - var matched bool - if checkFlags && ifAddr.Interface.Flags&ifFlags == ifFlags { - matched = true - } - if checkAttrs { - if ip := ToIPAddr(ifAddr.SockAddr); ip != nil { - netIP := (*ip).NetIP() - switch { - case wantGlobalUnicast && netIP.IsGlobalUnicast(): - matched = true - case wantInterfaceLocalMulticast && netIP.IsInterfaceLocalMulticast(): - matched = true - case wantLinkLocalMulticast && netIP.IsLinkLocalMulticast(): - matched = true - case wantLinkLocalUnicast && netIP.IsLinkLocalUnicast(): - matched = true - case wantLoopback && netIP.IsLoopback(): - matched = true - case wantMulticast && netIP.IsMulticast(): - matched = true - case wantUnspecified && netIP.IsUnspecified(): - matched = true - case wantForwardable && !IsRFC(ForwardingBlacklist, ifAddr.SockAddr): - matched = true - } - } - } - if matched { - matchedAddrs = append(matchedAddrs, ifAddr) - } else { - excludedAddrs = append(excludedAddrs, ifAddr) - } - } - return matchedAddrs, excludedAddrs, nil -} - -// IfByNetwork returns an IfAddrs that are equal to or included within the -// network passed in by selector. -func IfByNetwork(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, IfAddrs, error) { - var includedIfs, excludedIfs IfAddrs - for _, netStr := range strings.Split(selectorParam, "|") { - netAddr, err := NewIPAddr(netStr) - if err != nil { - return nil, nil, fmt.Errorf("unable to create an IP address from %+q: %v", netStr, err) - } - - for _, ifAddr := range inputIfAddrs { - if netAddr.Contains(ifAddr.SockAddr) { - includedIfs = append(includedIfs, ifAddr) - } else { - excludedIfs = append(excludedIfs, ifAddr) - } - } - } - - return includedIfs, excludedIfs, nil -} - -// IfAddrMath will return a new IfAddr struct with a mutated value. -func IfAddrMath(operation, value string, inputIfAddr IfAddr) (IfAddr, error) { - // Regexp used to enforce the sign being a required part of the grammar for - // some values. - signRe := signRE.Copy() - - switch strings.ToLower(operation) { - case "address": - // "address" operates on the IP address and is allowed to overflow or - // underflow networks, however it will wrap along the underlying address's - // underlying type. - - if !signRe.MatchString(value) { - return IfAddr{}, fmt.Errorf("sign (+/-) is required for operation %q", operation) - } - - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - // 33 == Accept any uint32 value - // TODO(seanc@): Add the ability to parse hex - i, err := strconv.ParseInt(value, 10, 33) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - ipv4Uint32 := uint32(ipv4.Address) - ipv4Uint32 += uint32(i) - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: ipv4.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - // 64 == Accept any int32 value - // TODO(seanc@): Add the ability to parse hex. Also parse a bignum int. - i, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - ipv6BigIntA := new(big.Int) - ipv6BigIntA.Set(ipv6.Address) - ipv6BigIntB := big.NewInt(i) - - ipv6Addr := ipv6BigIntA.Add(ipv6BigIntA, ipv6BigIntB) - ipv6Addr.And(ipv6Addr, ipv6HostMask) - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(ipv6Addr), - Mask: ipv6.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - case "network": - // "network" operates on the network address. Positive values start at the - // network address and negative values wrap at the network address, which - // means a "-1" value on a network will be the broadcast address after - // wrapping is applied. - - if !signRe.MatchString(value) { - return IfAddr{}, fmt.Errorf("sign (+/-) is required for operation %q", operation) - } - - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - // 33 == Accept any uint32 value - // TODO(seanc@): Add the ability to parse hex - i, err := strconv.ParseInt(value, 10, 33) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - ipv4Uint32 := uint32(ipv4.NetworkAddress()) - - // Wrap along network mask boundaries. EZ-mode wrapping made possible by - // use of int64 vs a uint. - var wrappedMask int64 - if i >= 0 { - wrappedMask = i - } else { - wrappedMask = 1 + i + int64(^uint32(ipv4.Mask)) - } - - ipv4Uint32 = ipv4Uint32 + (uint32(wrappedMask) &^ uint32(ipv4.Mask)) - - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: ipv4.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - // 64 == Accept any int32 value - // TODO(seanc@): Add the ability to parse hex. Also parse a bignum int. - i, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - ipv6BigInt := new(big.Int) - ipv6BigInt.Set(ipv6.NetworkAddress()) - - mask := new(big.Int) - mask.Set(ipv6.Mask) - if i > 0 { - wrappedMask := new(big.Int) - wrappedMask.SetInt64(i) - - wrappedMask.AndNot(wrappedMask, mask) - ipv6BigInt.Add(ipv6BigInt, wrappedMask) - } else { - // Mask off any bits that exceed the network size. Subtract the - // wrappedMask from the last usable - 1 - wrappedMask := new(big.Int) - wrappedMask.SetInt64(-1 * i) - wrappedMask.Sub(wrappedMask, big.NewInt(1)) - - wrappedMask.AndNot(wrappedMask, mask) - - lastUsable := new(big.Int) - lastUsable.Set(ipv6.LastUsable().(IPv6Addr).Address) - - ipv6BigInt = lastUsable.Sub(lastUsable, wrappedMask) - } - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(ipv6BigInt), - Mask: ipv6.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - case "mask": - // "mask" operates on the IP address and returns the IP address on - // which the given integer mask has been applied. If the applied mask - // corresponds to a larger network than the mask of the IP address, - // the latter will be replaced by the former. - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - i, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - if i > 32 { - return IfAddr{}, fmt.Errorf("parameter for operation %q on ipv4 addresses must be between 0 and 32", operation) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - - ipv4Mask := net.CIDRMask(int(i), 32) - ipv4MaskUint32 := binary.BigEndian.Uint32(ipv4Mask) - - maskedIpv4 := ipv4.NetIP().Mask(ipv4Mask) - maskedIpv4Uint32 := binary.BigEndian.Uint32(maskedIpv4) - - maskedIpv4MaskUint32 := uint32(ipv4.Mask) - - if ipv4MaskUint32 < maskedIpv4MaskUint32 { - maskedIpv4MaskUint32 = ipv4MaskUint32 - } - - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(maskedIpv4Uint32), - Mask: IPv4Mask(maskedIpv4MaskUint32), - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - i, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - if i > 128 { - return IfAddr{}, fmt.Errorf("parameter for operation %q on ipv6 addresses must be between 0 and 64", operation) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - - ipv6Mask := net.CIDRMask(int(i), 128) - ipv6MaskBigInt := new(big.Int) - ipv6MaskBigInt.SetBytes(ipv6Mask) - - maskedIpv6 := ipv6.NetIP().Mask(ipv6Mask) - maskedIpv6BigInt := new(big.Int) - maskedIpv6BigInt.SetBytes(maskedIpv6) - - maskedIpv6MaskBigInt := new(big.Int) - maskedIpv6MaskBigInt.Set(ipv6.Mask) - - if ipv6MaskBigInt.Cmp(maskedIpv6MaskBigInt) == -1 { - maskedIpv6MaskBigInt = ipv6MaskBigInt - } - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(maskedIpv6BigInt), - Mask: IPv6Mask(maskedIpv6MaskBigInt), - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - default: - return IfAddr{}, fmt.Errorf("unsupported math operation: %q", operation) - } -} - -// IfAddrsMath will apply an IfAddrMath operation each IfAddr struct. Any -// failure will result in zero results. -func IfAddrsMath(operation, value string, inputIfAddrs IfAddrs) (IfAddrs, error) { - outputAddrs := make(IfAddrs, 0, len(inputIfAddrs)) - for _, ifAddr := range inputIfAddrs { - result, err := IfAddrMath(operation, value, ifAddr) - if err != nil { - return IfAddrs{}, fmt.Errorf("unable to perform an IPMath operation on %s: %v", ifAddr, err) - } - outputAddrs = append(outputAddrs, result) - } - return outputAddrs, nil -} - -// IncludeIfs returns an IfAddrs based on the passed in selector. -func IncludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - var includedIfs IfAddrs - var err error - - switch strings.ToLower(selectorName) { - case "address": - includedIfs, _, err = IfByAddress(selectorParam, inputIfAddrs) - case "flag", "flags": - includedIfs, _, err = IfByFlag(selectorParam, inputIfAddrs) - case "name": - includedIfs, _, err = IfByName(selectorParam, inputIfAddrs) - case "network": - includedIfs, _, err = IfByNetwork(selectorParam, inputIfAddrs) - case "port": - includedIfs, _, err = IfByPort(selectorParam, inputIfAddrs) - case "rfc", "rfcs": - includedIfs, _, err = IfByRFCs(selectorParam, inputIfAddrs) - case "size": - includedIfs, _, err = IfByMaskSize(selectorParam, inputIfAddrs) - case "type": - includedIfs, _, err = IfByType(selectorParam, inputIfAddrs) - default: - return IfAddrs{}, fmt.Errorf("invalid include selector %q", selectorName) - } - - if err != nil { - return IfAddrs{}, err - } - - return includedIfs, nil -} - -// ExcludeIfs returns an IfAddrs based on the passed in selector. -func ExcludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - var excludedIfs IfAddrs - var err error - - switch strings.ToLower(selectorName) { - case "address": - _, excludedIfs, err = IfByAddress(selectorParam, inputIfAddrs) - case "flag", "flags": - _, excludedIfs, err = IfByFlag(selectorParam, inputIfAddrs) - case "name": - _, excludedIfs, err = IfByName(selectorParam, inputIfAddrs) - case "network": - _, excludedIfs, err = IfByNetwork(selectorParam, inputIfAddrs) - case "port": - _, excludedIfs, err = IfByPort(selectorParam, inputIfAddrs) - case "rfc", "rfcs": - _, excludedIfs, err = IfByRFCs(selectorParam, inputIfAddrs) - case "size": - _, excludedIfs, err = IfByMaskSize(selectorParam, inputIfAddrs) - case "type": - _, excludedIfs, err = IfByType(selectorParam, inputIfAddrs) - default: - return IfAddrs{}, fmt.Errorf("invalid exclude selector %q", selectorName) - } - - if err != nil { - return IfAddrs{}, err - } - - return excludedIfs, nil -} - -// SortIfBy returns an IfAddrs sorted based on the passed in selector. Multiple -// sort clauses can be passed in as a comma delimited list without whitespace. -func SortIfBy(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - sortedIfs := append(IfAddrs(nil), inputIfAddrs...) - - clauses := strings.Split(selectorParam, ",") - sortFuncs := make([]CmpIfAddrFunc, len(clauses)) - - for i, clause := range clauses { - switch strings.TrimSpace(strings.ToLower(clause)) { - case "+address", "address": - // The "address" selector returns an array of IfAddrs - // ordered by the network address. IfAddrs that are not - // comparable will be at the end of the list and in a - // non-deterministic order. - sortFuncs[i] = AscIfAddress - case "-address": - sortFuncs[i] = DescIfAddress - case "+default", "default": - sortFuncs[i] = AscIfDefault - case "-default": - sortFuncs[i] = DescIfDefault - case "+name", "name": - // The "name" selector returns an array of IfAddrs - // ordered by the interface name. - sortFuncs[i] = AscIfName - case "-name": - sortFuncs[i] = DescIfName - case "+port", "port": - // The "port" selector returns an array of IfAddrs - // ordered by the port, if included in the IfAddr. - // IfAddrs that are not comparable will be at the end of - // the list and in a non-deterministic order. - sortFuncs[i] = AscIfPort - case "-port": - sortFuncs[i] = DescIfPort - case "+private", "private": - // The "private" selector returns an array of IfAddrs - // ordered by private addresses first. IfAddrs that are - // not comparable will be at the end of the list and in - // a non-deterministic order. - sortFuncs[i] = AscIfPrivate - case "-private": - sortFuncs[i] = DescIfPrivate - case "+size", "size": - // The "size" selector returns an array of IfAddrs - // ordered by the size of the network mask, smaller mask - // (larger number of hosts per network) to largest - // (e.g. a /24 sorts before a /32). - sortFuncs[i] = AscIfNetworkSize - case "-size": - sortFuncs[i] = DescIfNetworkSize - case "+type", "type": - // The "type" selector returns an array of IfAddrs - // ordered by the type of the IfAddr. The sort order is - // Unix, IPv4, then IPv6. - sortFuncs[i] = AscIfType - case "-type": - sortFuncs[i] = DescIfType - default: - // Return an empty list for invalid sort types. - return IfAddrs{}, fmt.Errorf("unknown sort type: %q", clause) - } - } - - OrderedIfAddrBy(sortFuncs...).Sort(sortedIfs) - - return sortedIfs, nil -} - -// UniqueIfAddrsBy creates a unique set of IfAddrs based on the matching -// selector. UniqueIfAddrsBy assumes the input has already been sorted. -func UniqueIfAddrsBy(selectorName string, inputIfAddrs IfAddrs) (IfAddrs, error) { - attrName := strings.ToLower(selectorName) - - ifs := make(IfAddrs, 0, len(inputIfAddrs)) - var lastMatch string - for _, ifAddr := range inputIfAddrs { - var out string - switch attrName { - case "address": - out = ifAddr.SockAddr.String() - case "name": - out = ifAddr.Name - default: - return nil, fmt.Errorf("unsupported unique constraint %+q", selectorName) - } - - switch { - case lastMatch == "", lastMatch != out: - lastMatch = out - ifs = append(ifs, ifAddr) - case lastMatch == out: - continue - } - } - - return ifs, nil -} - -// JoinIfAddrs joins an IfAddrs and returns a string -func JoinIfAddrs(selectorName string, joinStr string, inputIfAddrs IfAddrs) (string, error) { - outputs := make([]string, 0, len(inputIfAddrs)) - attrName := AttrName(strings.ToLower(selectorName)) - - for _, ifAddr := range inputIfAddrs { - var attrVal string - var err error - attrVal, err = ifAddr.Attr(attrName) - if err != nil { - return "", err - } - outputs = append(outputs, attrVal) - } - return strings.Join(outputs, joinStr), nil -} - -// LimitIfAddrs returns a slice of IfAddrs based on the specified limit. -func LimitIfAddrs(lim uint, in IfAddrs) (IfAddrs, error) { - // Clamp the limit to the length of the array - if int(lim) > len(in) { - lim = uint(len(in)) - } - - return in[0:lim], nil -} - -// OffsetIfAddrs returns a slice of IfAddrs based on the specified offset. -func OffsetIfAddrs(off int, in IfAddrs) (IfAddrs, error) { - var end bool - if off < 0 { - end = true - off = off * -1 - } - - if off > len(in) { - return IfAddrs{}, fmt.Errorf("unable to seek past the end of the interface array: offset (%d) exceeds the number of interfaces (%d)", off, len(in)) - } - - if end { - return in[len(in)-off:], nil - } - return in[off:], nil -} - -func (ifAddr IfAddr) String() string { - return fmt.Sprintf("%s %v", ifAddr.SockAddr, ifAddr.Interface) -} - -// parseDefaultIfNameFromRoute parses standard route(8)'s output for the *BSDs -// and Solaris. -func parseDefaultIfNameFromRoute(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - for _, line := range lines { - kvs := strings.SplitN(line, ":", 2) - if len(kvs) != 2 { - continue - } - - if strings.TrimSpace(kvs[0]) == "interface" { - ifName := strings.TrimSpace(kvs[1]) - return ifName, nil - } - } - - return "", errors.New("No default interface found") -} - -// parseDefaultIfNameFromIPCmd parses the default interface from ip(8) for -// Linux. -func parseDefaultIfNameFromIPCmd(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - re := whitespaceRE.Copy() - for _, line := range lines { - kvs := re.Split(line, -1) - if len(kvs) < 5 { - continue - } - - if kvs[0] == "default" && - kvs[1] == "via" && - kvs[3] == "dev" { - ifName := strings.TrimSpace(kvs[4]) - return ifName, nil - } - } - - return "", errors.New("No default interface found") -} - -// parseDefaultIfNameWindows parses the default interface from `netstat -rn` and -// `ipconfig` on Windows. -func parseDefaultIfNameWindows(routeOut, ipconfigOut string) (string, error) { - defaultIPAddr, err := parseDefaultIPAddrWindowsRoute(routeOut) - if err != nil { - return "", err - } - - ifName, err := parseDefaultIfNameWindowsIPConfig(defaultIPAddr, ipconfigOut) - if err != nil { - return "", err - } - - return ifName, nil -} - -// parseDefaultIPAddrWindowsRoute parses the IP address on the default interface -// `netstat -rn`. -// -// NOTES(sean): Only IPv4 addresses are parsed at this time. If you have an -// IPv6 connected host, submit an issue on github.com/hashicorp/go-sockaddr with -// the output from `netstat -rn`, `ipconfig`, and version of Windows to see IPv6 -// support added. -func parseDefaultIPAddrWindowsRoute(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - re := whitespaceRE.Copy() - for _, line := range lines { - kvs := re.Split(strings.TrimSpace(line), -1) - if len(kvs) < 3 { - continue - } - - if kvs[0] == "0.0.0.0" && kvs[1] == "0.0.0.0" { - defaultIPAddr := strings.TrimSpace(kvs[3]) - return defaultIPAddr, nil - } - } - - return "", errors.New("No IP on default interface found") -} - -// parseDefaultIfNameWindowsIPConfig parses the output of `ipconfig` to find the -// interface name forwarding traffic to the default gateway. -func parseDefaultIfNameWindowsIPConfig(defaultIPAddr, routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - ifNameRe := ifNameRE.Copy() - ipAddrRe := ipAddrRE.Copy() - var ifName string - for _, line := range lines { - switch ifNameMatches := ifNameRe.FindStringSubmatch(line); { - case len(ifNameMatches) > 1: - ifName = ifNameMatches[1] - continue - } - - switch ipAddrMatches := ipAddrRe.FindStringSubmatch(line); { - case len(ipAddrMatches) > 1 && ipAddrMatches[1] == defaultIPAddr: - return ifName, nil - } - } - - return "", errors.New("No default interface found with matching IP") -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifattr.go b/vendor/github.com/hashicorp/go-sockaddr/ifattr.go deleted file mode 100644 index 6984cb4a..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifattr.go +++ /dev/null @@ -1,65 +0,0 @@ -package sockaddr - -import ( - "fmt" - "net" -) - -// IfAddr is a union of a SockAddr and a net.Interface. -type IfAddr struct { - SockAddr - net.Interface -} - -// Attr returns the named attribute as a string -func (ifAddr IfAddr) Attr(attrName AttrName) (string, error) { - val := IfAddrAttr(ifAddr, attrName) - if val != "" { - return val, nil - } - - return Attr(ifAddr.SockAddr, attrName) -} - -// Attr returns the named attribute as a string -func Attr(sa SockAddr, attrName AttrName) (string, error) { - switch sockType := sa.Type(); { - case sockType&TypeIP != 0: - ip := *ToIPAddr(sa) - attrVal := IPAddrAttr(ip, attrName) - if attrVal != "" { - return attrVal, nil - } - - if sockType == TypeIPv4 { - ipv4 := *ToIPv4Addr(sa) - attrVal := IPv4AddrAttr(ipv4, attrName) - if attrVal != "" { - return attrVal, nil - } - } else if sockType == TypeIPv6 { - ipv6 := *ToIPv6Addr(sa) - attrVal := IPv6AddrAttr(ipv6, attrName) - if attrVal != "" { - return attrVal, nil - } - } - - case sockType == TypeUnix: - us := *ToUnixSock(sa) - attrVal := UnixSockAttr(us, attrName) - if attrVal != "" { - return attrVal, nil - } - } - - // Non type-specific attributes - switch attrName { - case "string": - return sa.String(), nil - case "type": - return sa.Type().String(), nil - } - - return "", fmt.Errorf("unsupported attribute name %q", attrName) -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go deleted file mode 100644 index b47d15c2..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go +++ /dev/null @@ -1,169 +0,0 @@ -package sockaddr - -import ( - "fmt" - "math/big" - "net" - "strings" -) - -// Constants for the sizes of IPv3, IPv4, and IPv6 address types. -const ( - IPv3len = 6 - IPv4len = 4 - IPv6len = 16 -) - -// IPAddr is a generic IP address interface for IPv4 and IPv6 addresses, -// networks, and socket endpoints. -type IPAddr interface { - SockAddr - AddressBinString() string - AddressHexString() string - Cmp(SockAddr) int - CmpAddress(SockAddr) int - CmpPort(SockAddr) int - FirstUsable() IPAddr - Host() IPAddr - IPPort() IPPort - LastUsable() IPAddr - Maskbits() int - NetIP() *net.IP - NetIPMask() *net.IPMask - NetIPNet() *net.IPNet - Network() IPAddr - Octets() []int -} - -// IPPort is the type for an IP port number for the TCP and UDP IP transports. -type IPPort uint16 - -// IPPrefixLen is a typed integer representing the prefix length for a given -// IPAddr. -type IPPrefixLen byte - -// ipAddrAttrMap is a map of the IPAddr type-specific attributes. -var ipAddrAttrMap map[AttrName]func(IPAddr) string -var ipAddrAttrs []AttrName - -func init() { - ipAddrInit() -} - -// NewIPAddr creates a new IPAddr from a string. Returns nil if the string is -// not an IPv4 or an IPv6 address. -func NewIPAddr(addr string) (IPAddr, error) { - ipv4Addr, err := NewIPv4Addr(addr) - if err == nil { - return ipv4Addr, nil - } - - ipv6Addr, err := NewIPv6Addr(addr) - if err == nil { - return ipv6Addr, nil - } - - return nil, fmt.Errorf("invalid IPAddr %v", addr) -} - -// IPAddrAttr returns a string representation of an attribute for the given -// IPAddr. -func IPAddrAttr(ip IPAddr, selector AttrName) string { - fn, found := ipAddrAttrMap[selector] - if !found { - return "" - } - - return fn(ip) -} - -// IPAttrs returns a list of attributes supported by the IPAddr type -func IPAttrs() []AttrName { - return ipAddrAttrs -} - -// MustIPAddr is a helper method that must return an IPAddr or panic on invalid -// input. -func MustIPAddr(addr string) IPAddr { - ip, err := NewIPAddr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPAddr from %+q: %v", addr, err)) - } - return ip -} - -// ipAddrInit is called once at init() -func ipAddrInit() { - // Sorted for human readability - ipAddrAttrs = []AttrName{ - "host", - "address", - "port", - "netmask", - "network", - "mask_bits", - "binary", - "hex", - "first_usable", - "last_usable", - "octets", - } - - ipAddrAttrMap = map[AttrName]func(ip IPAddr) string{ - "address": func(ip IPAddr) string { - return ip.NetIP().String() - }, - "binary": func(ip IPAddr) string { - return ip.AddressBinString() - }, - "first_usable": func(ip IPAddr) string { - return ip.FirstUsable().String() - }, - "hex": func(ip IPAddr) string { - return ip.AddressHexString() - }, - "host": func(ip IPAddr) string { - return ip.Host().String() - }, - "last_usable": func(ip IPAddr) string { - return ip.LastUsable().String() - }, - "mask_bits": func(ip IPAddr) string { - return fmt.Sprintf("%d", ip.Maskbits()) - }, - "netmask": func(ip IPAddr) string { - switch v := ip.(type) { - case IPv4Addr: - ipv4Mask := IPv4Addr{ - Address: IPv4Address(v.Mask), - Mask: IPv4HostMask, - } - return ipv4Mask.String() - case IPv6Addr: - ipv6Mask := new(big.Int) - ipv6Mask.Set(v.Mask) - ipv6MaskAddr := IPv6Addr{ - Address: IPv6Address(ipv6Mask), - Mask: ipv6HostMask, - } - return ipv6MaskAddr.String() - default: - return fmt.Sprintf("", ip) - } - }, - "network": func(ip IPAddr) string { - return ip.Network().NetIP().String() - }, - "octets": func(ip IPAddr) string { - octets := ip.Octets() - octetStrs := make([]string, 0, len(octets)) - for _, octet := range octets { - octetStrs = append(octetStrs, fmt.Sprintf("%d", octet)) - } - return strings.Join(octetStrs, " ") - }, - "port": func(ip IPAddr) string { - return fmt.Sprintf("%d", ip.IPPort()) - }, - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go deleted file mode 100644 index 6eeb7ddd..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go +++ /dev/null @@ -1,98 +0,0 @@ -package sockaddr - -import "bytes" - -type IPAddrs []IPAddr - -func (s IPAddrs) Len() int { return len(s) } -func (s IPAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// // SortIPAddrsByCmp is a type that satisfies sort.Interface and can be used -// // by the routines in this package. The SortIPAddrsByCmp type is used to -// // sort IPAddrs by Cmp() -// type SortIPAddrsByCmp struct{ IPAddrs } - -// // Less reports whether the element with index i should sort before the -// // element with index j. -// func (s SortIPAddrsByCmp) Less(i, j int) bool { -// // Sort by Type, then address, then port number. -// return Less(s.IPAddrs[i], s.IPAddrs[j]) -// } - -// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and -// can be used by the routines in this package. The -// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest -// network (most specific to largest network). -type SortIPAddrsByNetworkSize struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsByNetworkSize) Less(i, j int) bool { - // Sort masks with a larger binary value (i.e. fewer hosts per network - // prefix) after masks with a smaller value (larger number of hosts per - // prefix). - switch bytes.Compare([]byte(*s.IPAddrs[i].NetIPMask()), []byte(*s.IPAddrs[j].NetIPMask())) { - case 0: - // Fall through to the second test if the net.IPMasks are the - // same. - break - case 1: - return true - case -1: - return false - default: - panic("bad, m'kay?") - } - - // Sort IPs based on the length (i.e. prefer IPv4 over IPv6). - iLen := len(*s.IPAddrs[i].NetIP()) - jLen := len(*s.IPAddrs[j].NetIP()) - if iLen != jLen { - return iLen > jLen - } - - // Sort IPs based on their network address from lowest to highest. - switch bytes.Compare(s.IPAddrs[i].NetIPNet().IP, s.IPAddrs[j].NetIPNet().IP) { - case 0: - break - case 1: - return false - case -1: - return true - default: - panic("lol wut?") - } - - // If a host does not have a port set, it always sorts after hosts - // that have a port (e.g. a host with a /32 and port number is more - // specific and should sort first over a host with a /32 but no port - // set). - if s.IPAddrs[i].IPPort() == 0 || s.IPAddrs[j].IPPort() == 0 { - return false - } - return s.IPAddrs[i].IPPort() < s.IPAddrs[j].IPPort() -} - -// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and -// can be used by the routines in this package. The -// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest -// network (most specific to largest network). -type SortIPAddrsBySpecificMaskLen struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsBySpecificMaskLen) Less(i, j int) bool { - return s.IPAddrs[i].Maskbits() > s.IPAddrs[j].Maskbits() -} - -// SortIPAddrsByBroadMaskLen is a type that satisfies sort.Interface and can -// be used by the routines in this package. The SortIPAddrsByBroadMaskLen -// type is used to sort IPAddrs by largest network (i.e. largest subnets -// first). -type SortIPAddrsByBroadMaskLen struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsByBroadMaskLen) Less(i, j int) bool { - return s.IPAddrs[i].Maskbits() < s.IPAddrs[j].Maskbits() -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go deleted file mode 100644 index 4d395dc9..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go +++ /dev/null @@ -1,516 +0,0 @@ -package sockaddr - -import ( - "encoding/binary" - "fmt" - "net" - "regexp" - "strconv" - "strings" -) - -type ( - // IPv4Address is a named type representing an IPv4 address. - IPv4Address uint32 - - // IPv4Network is a named type representing an IPv4 network. - IPv4Network uint32 - - // IPv4Mask is a named type representing an IPv4 network mask. - IPv4Mask uint32 -) - -// IPv4HostMask is a constant represents a /32 IPv4 Address -// (i.e. 255.255.255.255). -const IPv4HostMask = IPv4Mask(0xffffffff) - -// ipv4AddrAttrMap is a map of the IPv4Addr type-specific attributes. -var ipv4AddrAttrMap map[AttrName]func(IPv4Addr) string -var ipv4AddrAttrs []AttrName -var trailingHexNetmaskRE *regexp.Regexp - -// IPv4Addr implements a convenience wrapper around the union of Go's -// built-in net.IP and net.IPNet types. In UNIX-speak, IPv4Addr implements -// `sockaddr` when the the address family is set to AF_INET -// (i.e. `sockaddr_in`). -type IPv4Addr struct { - IPAddr - Address IPv4Address - Mask IPv4Mask - Port IPPort -} - -func init() { - ipv4AddrInit() - trailingHexNetmaskRE = regexp.MustCompile(`/([0f]{8})$`) -} - -// NewIPv4Addr creates an IPv4Addr from a string. String can be in the form -// of either an IPv4:port (e.g. `1.2.3.4:80`, in which case the mask is -// assumed to be a `/32`), an IPv4 address (e.g. `1.2.3.4`, also with a `/32` -// mask), or an IPv4 CIDR (e.g. `1.2.3.4/24`, which has its IP port -// initialized to zero). ipv4Str can not be a hostname. -// -// NOTE: Many net.*() routines will initialize and return an IPv6 address. -// To create uint32 values from net.IP, always test to make sure the address -// returned can be converted to a 4 byte array using To4(). -func NewIPv4Addr(ipv4Str string) (IPv4Addr, error) { - // Strip off any bogus hex-encoded netmasks that will be mis-parsed by Go. In - // particular, clients with the Barracuda VPN client will see something like: - // `192.168.3.51/00ffffff` as their IP address. - trailingHexNetmaskRe := trailingHexNetmaskRE.Copy() - if match := trailingHexNetmaskRe.FindStringIndex(ipv4Str); match != nil { - ipv4Str = ipv4Str[:match[0]] - } - - // Parse as an IPv4 CIDR - ipAddr, network, err := net.ParseCIDR(ipv4Str) - if err == nil { - ipv4 := ipAddr.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address", ipv4Str) - } - - // If we see an IPv6 netmask, convert it to an IPv4 mask. - netmaskSepPos := strings.LastIndexByte(ipv4Str, '/') - if netmaskSepPos != -1 && netmaskSepPos+1 < len(ipv4Str) { - netMask, err := strconv.ParseUint(ipv4Str[netmaskSepPos+1:], 10, 8) - if err != nil { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: unable to parse CIDR netmask: %v", ipv4Str, err) - } else if netMask > 128 { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: invalid CIDR netmask", ipv4Str) - } - - if netMask >= 96 { - // Convert the IPv6 netmask to an IPv4 netmask - network.Mask = net.CIDRMask(int(netMask-96), IPv4len*8) - } - } - ipv4Addr := IPv4Addr{ - Address: IPv4Address(binary.BigEndian.Uint32(ipv4)), - Mask: IPv4Mask(binary.BigEndian.Uint32(network.Mask)), - } - return ipv4Addr, nil - } - - // Attempt to parse ipv4Str as a /32 host with a port number. - tcpAddr, err := net.ResolveTCPAddr("tcp4", ipv4Str) - if err == nil { - ipv4 := tcpAddr.IP.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to resolve %+q as an IPv4 address", ipv4Str) - } - - ipv4Uint32 := binary.BigEndian.Uint32(ipv4) - ipv4Addr := IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: IPv4HostMask, - Port: IPPort(tcpAddr.Port), - } - - return ipv4Addr, nil - } - - // Parse as a naked IPv4 address - ip := net.ParseIP(ipv4Str) - if ip != nil { - ipv4 := ip.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to string convert %+q to an IPv4 address", ipv4Str) - } - - ipv4Uint32 := binary.BigEndian.Uint32(ipv4) - ipv4Addr := IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: IPv4HostMask, - } - return ipv4Addr, nil - } - - return IPv4Addr{}, fmt.Errorf("Unable to parse %+q to an IPv4 address: %v", ipv4Str, err) -} - -// AddressBinString returns a string with the IPv4Addr's Address represented -// as a sequence of '0' and '1' characters. This method is useful for -// debugging or by operators who want to inspect an address. -func (ipv4 IPv4Addr) AddressBinString() string { - return fmt.Sprintf("%032s", strconv.FormatUint(uint64(ipv4.Address), 2)) -} - -// AddressHexString returns a string with the IPv4Addr address represented as -// a sequence of hex characters. This method is useful for debugging or by -// operators who want to inspect an address. -func (ipv4 IPv4Addr) AddressHexString() string { - return fmt.Sprintf("%08s", strconv.FormatUint(uint64(ipv4.Address), 16)) -} - -// Broadcast is an IPv4Addr-only method that returns the broadcast address of -// the network. -// -// NOTE: IPv6 only supports multicast, so this method only exists for -// IPv4Addr. -func (ipv4 IPv4Addr) Broadcast() IPAddr { - // Nothing should listen on a broadcast address. - return IPv4Addr{ - Address: IPv4Address(ipv4.BroadcastAddress()), - Mask: IPv4HostMask, - } -} - -// BroadcastAddress returns a IPv4Network of the IPv4Addr's broadcast -// address. -func (ipv4 IPv4Addr) BroadcastAddress() IPv4Network { - return IPv4Network(uint32(ipv4.Address)&uint32(ipv4.Mask) | ^uint32(ipv4.Mask)) -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its address is lower than arg -// - 0 if the SockAddr arg is equal to the receiving IPv4Addr or the argument is -// of a different type. -// - 1 If the argument should sort first. -func (ipv4 IPv4Addr) CmpAddress(sa SockAddr) int { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return sortDeferDecision - } - - switch { - case ipv4.Address == ipv4b.Address: - return sortDeferDecision - case ipv4.Address < ipv4b.Address: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpPort follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its port is lower than arg -// - 0 if the SockAddr arg's port number is equal to the receiving IPv4Addr, -// regardless of type. -// - 1 If the argument should sort first. -func (ipv4 IPv4Addr) CmpPort(sa SockAddr) int { - var saPort IPPort - switch v := sa.(type) { - case IPv4Addr: - saPort = v.Port - case IPv6Addr: - saPort = v.Port - default: - return sortDeferDecision - } - - switch { - case ipv4.Port == saPort: - return sortDeferDecision - case ipv4.Port < saPort: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpRFC follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because it belongs to the RFC and its -// arg does not -// - 0 if the receiver and arg both belong to the same RFC or neither do. -// - 1 If the arg belongs to the RFC but receiver does not. -func (ipv4 IPv4Addr) CmpRFC(rfcNum uint, sa SockAddr) int { - recvInRFC := IsRFC(rfcNum, ipv4) - ipv4b, ok := sa.(IPv4Addr) - if !ok { - // If the receiver is part of the desired RFC and the SockAddr - // argument is not, return -1 so that the receiver sorts before - // the non-IPv4 SockAddr. Conversely, if the receiver is not - // part of the RFC, punt on sorting and leave it for the next - // sorter. - if recvInRFC { - return sortReceiverBeforeArg - } else { - return sortDeferDecision - } - } - - argInRFC := IsRFC(rfcNum, ipv4b) - switch { - case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC): - // If a and b both belong to the RFC, or neither belong to - // rfcNum, defer sorting to the next sorter. - return sortDeferDecision - case recvInRFC && !argInRFC: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// Contains returns true if the SockAddr is contained within the receiver. -func (ipv4 IPv4Addr) Contains(sa SockAddr) bool { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return false - } - - return ipv4.ContainsNetwork(ipv4b) -} - -// ContainsAddress returns true if the IPv4Address is contained within the -// receiver. -func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool { - return IPv4Address(ipv4.NetworkAddress()) <= x && - IPv4Address(ipv4.BroadcastAddress()) >= x -} - -// ContainsNetwork returns true if the network from IPv4Addr is contained -// within the receiver. -func (ipv4 IPv4Addr) ContainsNetwork(x IPv4Addr) bool { - return ipv4.NetworkAddress() <= x.NetworkAddress() && - ipv4.BroadcastAddress() >= x.BroadcastAddress() -} - -// DialPacketArgs returns the arguments required to be passed to -// net.DialUDP(). If the Mask of ipv4 is not a /32 or the Port is 0, -// DialPacketArgs() will fail. See Host() to create an IPv4Addr with its -// mask set to /32. -func (ipv4 IPv4Addr) DialPacketArgs() (network, dialArgs string) { - if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 { - return "udp4", "" - } - return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// DialStreamArgs returns the arguments required to be passed to -// net.DialTCP(). If the Mask of ipv4 is not a /32 or the Port is 0, -// DialStreamArgs() will fail. See Host() to create an IPv4Addr with its -// mask set to /32. -func (ipv4 IPv4Addr) DialStreamArgs() (network, dialArgs string) { - if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 { - return "tcp4", "" - } - return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// Equal returns true if a SockAddr is equal to the receiving IPv4Addr. -func (ipv4 IPv4Addr) Equal(sa SockAddr) bool { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return false - } - - if ipv4.Port != ipv4b.Port { - return false - } - - if ipv4.Address != ipv4b.Address { - return false - } - - if ipv4.NetIPNet().String() != ipv4b.NetIPNet().String() { - return false - } - - return true -} - -// FirstUsable returns an IPv4Addr set to the first address following the -// network prefix. The first usable address in a network is normally the -// gateway and should not be used except by devices forwarding packets -// between two administratively distinct networks (i.e. a router). This -// function does not discriminate against first usable vs "first address that -// should be used." For example, FirstUsable() on "192.168.1.10/24" would -// return the address "192.168.1.1/24". -func (ipv4 IPv4Addr) FirstUsable() IPAddr { - addr := ipv4.NetworkAddress() - - // If /32, return the address itself. If /31 assume a point-to-point - // link and return the lower address. - if ipv4.Maskbits() < 31 { - addr++ - } - - return IPv4Addr{ - Address: IPv4Address(addr), - Mask: IPv4HostMask, - } -} - -// Host returns a copy of ipv4 with its mask set to /32 so that it can be -// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or -// ListenStreamArgs(). -func (ipv4 IPv4Addr) Host() IPAddr { - // Nothing should listen on a broadcast address. - return IPv4Addr{ - Address: ipv4.Address, - Mask: IPv4HostMask, - Port: ipv4.Port, - } -} - -// IPPort returns the Port number attached to the IPv4Addr -func (ipv4 IPv4Addr) IPPort() IPPort { - return ipv4.Port -} - -// LastUsable returns the last address before the broadcast address in a -// given network. -func (ipv4 IPv4Addr) LastUsable() IPAddr { - addr := ipv4.BroadcastAddress() - - // If /32, return the address itself. If /31 assume a point-to-point - // link and return the upper address. - if ipv4.Maskbits() < 31 { - addr-- - } - - return IPv4Addr{ - Address: IPv4Address(addr), - Mask: IPv4HostMask, - } -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUDP(). If the Mask of ipv4 is not a /32, ListenPacketArgs() -// will fail. See Host() to create an IPv4Addr with its mask set to /32. -func (ipv4 IPv4Addr) ListenPacketArgs() (network, listenArgs string) { - if ipv4.Mask != IPv4HostMask { - return "udp4", "" - } - return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenTCP(). If the Mask of ipv4 is not a /32, ListenStreamArgs() -// will fail. See Host() to create an IPv4Addr with its mask set to /32. -func (ipv4 IPv4Addr) ListenStreamArgs() (network, listenArgs string) { - if ipv4.Mask != IPv4HostMask { - return "tcp4", "" - } - return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// Maskbits returns the number of network mask bits in a given IPv4Addr. For -// example, the Maskbits() of "192.168.1.1/24" would return 24. -func (ipv4 IPv4Addr) Maskbits() int { - mask := make(net.IPMask, IPv4len) - binary.BigEndian.PutUint32(mask, uint32(ipv4.Mask)) - maskOnes, _ := mask.Size() - return maskOnes -} - -// MustIPv4Addr is a helper method that must return an IPv4Addr or panic on -// invalid input. -func MustIPv4Addr(addr string) IPv4Addr { - ipv4, err := NewIPv4Addr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPv4Addr from %+q: %v", addr, err)) - } - return ipv4 -} - -// NetIP returns the address as a net.IP (address is always presized to -// IPv4). -func (ipv4 IPv4Addr) NetIP() *net.IP { - x := make(net.IP, IPv4len) - binary.BigEndian.PutUint32(x, uint32(ipv4.Address)) - return &x -} - -// NetIPMask create a new net.IPMask from the IPv4Addr. -func (ipv4 IPv4Addr) NetIPMask() *net.IPMask { - ipv4Mask := net.IPMask{} - ipv4Mask = make(net.IPMask, IPv4len) - binary.BigEndian.PutUint32(ipv4Mask, uint32(ipv4.Mask)) - return &ipv4Mask -} - -// NetIPNet create a new net.IPNet from the IPv4Addr. -func (ipv4 IPv4Addr) NetIPNet() *net.IPNet { - ipv4net := &net.IPNet{} - ipv4net.IP = make(net.IP, IPv4len) - binary.BigEndian.PutUint32(ipv4net.IP, uint32(ipv4.NetworkAddress())) - ipv4net.Mask = *ipv4.NetIPMask() - return ipv4net -} - -// Network returns the network prefix or network address for a given network. -func (ipv4 IPv4Addr) Network() IPAddr { - return IPv4Addr{ - Address: IPv4Address(ipv4.NetworkAddress()), - Mask: ipv4.Mask, - } -} - -// NetworkAddress returns an IPv4Network of the IPv4Addr's network address. -func (ipv4 IPv4Addr) NetworkAddress() IPv4Network { - return IPv4Network(uint32(ipv4.Address) & uint32(ipv4.Mask)) -} - -// Octets returns a slice of the four octets in an IPv4Addr's Address. The -// order of the bytes is big endian. -func (ipv4 IPv4Addr) Octets() []int { - return []int{ - int(ipv4.Address >> 24), - int((ipv4.Address >> 16) & 0xff), - int((ipv4.Address >> 8) & 0xff), - int(ipv4.Address & 0xff), - } -} - -// String returns a string representation of the IPv4Addr -func (ipv4 IPv4Addr) String() string { - if ipv4.Port != 0 { - return fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) - } - - if ipv4.Maskbits() == 32 { - return ipv4.NetIP().String() - } - - return fmt.Sprintf("%s/%d", ipv4.NetIP().String(), ipv4.Maskbits()) -} - -// Type is used as a type switch and returns TypeIPv4 -func (IPv4Addr) Type() SockAddrType { - return TypeIPv4 -} - -// IPv4AddrAttr returns a string representation of an attribute for the given -// IPv4Addr. -func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string { - fn, found := ipv4AddrAttrMap[selector] - if !found { - return "" - } - - return fn(ipv4) -} - -// IPv4Attrs returns a list of attributes supported by the IPv4Addr type -func IPv4Attrs() []AttrName { - return ipv4AddrAttrs -} - -// ipv4AddrInit is called once at init() -func ipv4AddrInit() { - // Sorted for human readability - ipv4AddrAttrs = []AttrName{ - "size", // Same position as in IPv6 for output consistency - "broadcast", - "uint32", - } - - ipv4AddrAttrMap = map[AttrName]func(ipv4 IPv4Addr) string{ - "broadcast": func(ipv4 IPv4Addr) string { - return ipv4.Broadcast().String() - }, - "size": func(ipv4 IPv4Addr) string { - return fmt.Sprintf("%d", 1< 2 && ipv6Str[0] == '[' && ipv6Str[len(ipv6Str)-1] == ']' { - ipv6Str = ipv6Str[1 : len(ipv6Str)-1] - } - ip := net.ParseIP(ipv6Str) - if ip != nil { - ipv6 := ip.To16() - if ipv6 == nil { - return IPv6Addr{}, fmt.Errorf("Unable to string convert %+q to a 16byte IPv6 address", ipv6Str) - } - - ipv6BigIntAddr := new(big.Int) - ipv6BigIntAddr.SetBytes(ipv6) - - ipv6BigIntMask := new(big.Int) - ipv6BigIntMask.Set(ipv6HostMask) - - return IPv6Addr{ - Address: IPv6Address(ipv6BigIntAddr), - Mask: IPv6Mask(ipv6BigIntMask), - }, nil - } - - // Parse as an IPv6 CIDR - ipAddr, network, err := net.ParseCIDR(ipv6Str) - if err == nil { - ipv6 := ipAddr.To16() - if ipv6 == nil { - return IPv6Addr{}, fmt.Errorf("Unable to convert %+q to a 16byte IPv6 address", ipv6Str) - } - - ipv6BigIntAddr := new(big.Int) - ipv6BigIntAddr.SetBytes(ipv6) - - ipv6BigIntMask := new(big.Int) - ipv6BigIntMask.SetBytes(network.Mask) - - ipv6Addr := IPv6Addr{ - Address: IPv6Address(ipv6BigIntAddr), - Mask: IPv6Mask(ipv6BigIntMask), - } - return ipv6Addr, nil - } - - return IPv6Addr{}, fmt.Errorf("Unable to parse %+q to an IPv6 address: %v", ipv6Str, err) -} - -// AddressBinString returns a string with the IPv6Addr's Address represented -// as a sequence of '0' and '1' characters. This method is useful for -// debugging or by operators who want to inspect an address. -func (ipv6 IPv6Addr) AddressBinString() string { - bi := big.Int(*ipv6.Address) - return fmt.Sprintf("%0128s", bi.Text(2)) -} - -// AddressHexString returns a string with the IPv6Addr address represented as -// a sequence of hex characters. This method is useful for debugging or by -// operators who want to inspect an address. -func (ipv6 IPv6Addr) AddressHexString() string { - bi := big.Int(*ipv6.Address) - return fmt.Sprintf("%032s", bi.Text(16)) -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its address is lower than arg -// - 0 if the SockAddr arg equal to the receiving IPv6Addr or the argument is of a -// different type. -// - 1 If the argument should sort first. -func (ipv6 IPv6Addr) CmpAddress(sa SockAddr) int { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return sortDeferDecision - } - - ipv6aBigInt := new(big.Int) - ipv6aBigInt.Set(ipv6.Address) - ipv6bBigInt := new(big.Int) - ipv6bBigInt.Set(ipv6b.Address) - - return ipv6aBigInt.Cmp(ipv6bBigInt) -} - -// CmpPort follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its port is lower than arg -// - 0 if the SockAddr arg's port number is equal to the receiving IPv6Addr, -// regardless of type. -// - 1 If the argument should sort first. -func (ipv6 IPv6Addr) CmpPort(sa SockAddr) int { - var saPort IPPort - switch v := sa.(type) { - case IPv4Addr: - saPort = v.Port - case IPv6Addr: - saPort = v.Port - default: - return sortDeferDecision - } - - switch { - case ipv6.Port == saPort: - return sortDeferDecision - case ipv6.Port < saPort: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpRFC follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because it belongs to the RFC and its -// arg does not -// - 0 if the receiver and arg both belong to the same RFC or neither do. -// - 1 If the arg belongs to the RFC but receiver does not. -func (ipv6 IPv6Addr) CmpRFC(rfcNum uint, sa SockAddr) int { - recvInRFC := IsRFC(rfcNum, ipv6) - ipv6b, ok := sa.(IPv6Addr) - if !ok { - // If the receiver is part of the desired RFC and the SockAddr - // argument is not, sort receiver before the non-IPv6 SockAddr. - // Conversely, if the receiver is not part of the RFC, punt on - // sorting and leave it for the next sorter. - if recvInRFC { - return sortReceiverBeforeArg - } else { - return sortDeferDecision - } - } - - argInRFC := IsRFC(rfcNum, ipv6b) - switch { - case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC): - // If a and b both belong to the RFC, or neither belong to - // rfcNum, defer sorting to the next sorter. - return sortDeferDecision - case recvInRFC && !argInRFC: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// Contains returns true if the SockAddr is contained within the receiver. -func (ipv6 IPv6Addr) Contains(sa SockAddr) bool { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return false - } - - return ipv6.ContainsNetwork(ipv6b) -} - -// ContainsAddress returns true if the IPv6Address is contained within the -// receiver. -func (ipv6 IPv6Addr) ContainsAddress(x IPv6Address) bool { - xAddr := IPv6Addr{ - Address: x, - Mask: ipv6HostMask, - } - - { - xIPv6 := xAddr.FirstUsable().(IPv6Addr) - yIPv6 := ipv6.FirstUsable().(IPv6Addr) - if xIPv6.CmpAddress(yIPv6) >= 1 { - return false - } - } - - { - xIPv6 := xAddr.LastUsable().(IPv6Addr) - yIPv6 := ipv6.LastUsable().(IPv6Addr) - if xIPv6.CmpAddress(yIPv6) <= -1 { - return false - } - } - return true -} - -// ContainsNetwork returns true if the network from IPv6Addr is contained within -// the receiver. -func (x IPv6Addr) ContainsNetwork(y IPv6Addr) bool { - { - xIPv6 := x.FirstUsable().(IPv6Addr) - yIPv6 := y.FirstUsable().(IPv6Addr) - if ret := xIPv6.CmpAddress(yIPv6); ret >= 1 { - return false - } - } - - { - xIPv6 := x.LastUsable().(IPv6Addr) - yIPv6 := y.LastUsable().(IPv6Addr) - if ret := xIPv6.CmpAddress(yIPv6); ret <= -1 { - return false - } - } - return true -} - -// DialPacketArgs returns the arguments required to be passed to -// net.DialUDP(). If the Mask of ipv6 is not a /128 or the Port is 0, -// DialPacketArgs() will fail. See Host() to create an IPv6Addr with its -// mask set to /128. -func (ipv6 IPv6Addr) DialPacketArgs() (network, dialArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 { - return "udp6", "" - } - return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// DialStreamArgs returns the arguments required to be passed to -// net.DialTCP(). If the Mask of ipv6 is not a /128 or the Port is 0, -// DialStreamArgs() will fail. See Host() to create an IPv6Addr with its -// mask set to /128. -func (ipv6 IPv6Addr) DialStreamArgs() (network, dialArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 { - return "tcp6", "" - } - return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// Equal returns true if a SockAddr is equal to the receiving IPv4Addr. -func (ipv6a IPv6Addr) Equal(sa SockAddr) bool { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return false - } - - if ipv6a.NetIP().String() != ipv6b.NetIP().String() { - return false - } - - if ipv6a.NetIPNet().String() != ipv6b.NetIPNet().String() { - return false - } - - if ipv6a.Port != ipv6b.Port { - return false - } - - return true -} - -// FirstUsable returns an IPv6Addr set to the first address following the -// network prefix. The first usable address in a network is normally the -// gateway and should not be used except by devices forwarding packets -// between two administratively distinct networks (i.e. a router). This -// function does not discriminate against first usable vs "first address that -// should be used." For example, FirstUsable() on "2001:0db8::0003/64" would -// return "2001:0db8::00011". -func (ipv6 IPv6Addr) FirstUsable() IPAddr { - return IPv6Addr{ - Address: IPv6Address(ipv6.NetworkAddress()), - Mask: ipv6HostMask, - } -} - -// Host returns a copy of ipv6 with its mask set to /128 so that it can be -// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or -// ListenStreamArgs(). -func (ipv6 IPv6Addr) Host() IPAddr { - // Nothing should listen on a broadcast address. - return IPv6Addr{ - Address: ipv6.Address, - Mask: ipv6HostMask, - Port: ipv6.Port, - } -} - -// IPPort returns the Port number attached to the IPv6Addr -func (ipv6 IPv6Addr) IPPort() IPPort { - return ipv6.Port -} - -// LastUsable returns the last address in a given network. -func (ipv6 IPv6Addr) LastUsable() IPAddr { - addr := new(big.Int) - addr.Set(ipv6.Address) - - mask := new(big.Int) - mask.Set(ipv6.Mask) - - negMask := new(big.Int) - negMask.Xor(ipv6HostMask, mask) - - lastAddr := new(big.Int) - lastAddr.And(addr, mask) - lastAddr.Or(lastAddr, negMask) - - return IPv6Addr{ - Address: IPv6Address(lastAddr), - Mask: ipv6HostMask, - } -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUDP(). If the Mask of ipv6 is not a /128, ListenPacketArgs() -// will fail. See Host() to create an IPv6Addr with its mask set to /128. -func (ipv6 IPv6Addr) ListenPacketArgs() (network, listenArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 { - return "udp6", "" - } - return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenTCP(). If the Mask of ipv6 is not a /128, ListenStreamArgs() -// will fail. See Host() to create an IPv6Addr with its mask set to /128. -func (ipv6 IPv6Addr) ListenStreamArgs() (network, listenArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 { - return "tcp6", "" - } - return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// Maskbits returns the number of network mask bits in a given IPv6Addr. For -// example, the Maskbits() of "2001:0db8::0003/64" would return 64. -func (ipv6 IPv6Addr) Maskbits() int { - maskOnes, _ := ipv6.NetIPNet().Mask.Size() - - return maskOnes -} - -// MustIPv6Addr is a helper method that must return an IPv6Addr or panic on -// invalid input. -func MustIPv6Addr(addr string) IPv6Addr { - ipv6, err := NewIPv6Addr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPv6Addr from %+q: %v", addr, err)) - } - return ipv6 -} - -// NetIP returns the address as a net.IP. -func (ipv6 IPv6Addr) NetIP() *net.IP { - return bigIntToNetIPv6(ipv6.Address) -} - -// NetIPMask create a new net.IPMask from the IPv6Addr. -func (ipv6 IPv6Addr) NetIPMask() *net.IPMask { - ipv6Mask := make(net.IPMask, IPv6len) - m := big.Int(*ipv6.Mask) - copy(ipv6Mask, m.Bytes()) - return &ipv6Mask -} - -// Network returns a pointer to the net.IPNet within IPv4Addr receiver. -func (ipv6 IPv6Addr) NetIPNet() *net.IPNet { - ipv6net := &net.IPNet{} - ipv6net.IP = make(net.IP, IPv6len) - copy(ipv6net.IP, *ipv6.NetIP()) - ipv6net.Mask = *ipv6.NetIPMask() - return ipv6net -} - -// Network returns the network prefix or network address for a given network. -func (ipv6 IPv6Addr) Network() IPAddr { - return IPv6Addr{ - Address: IPv6Address(ipv6.NetworkAddress()), - Mask: ipv6.Mask, - } -} - -// NetworkAddress returns an IPv6Network of the IPv6Addr's network address. -func (ipv6 IPv6Addr) NetworkAddress() IPv6Network { - addr := new(big.Int) - addr.SetBytes((*ipv6.Address).Bytes()) - - mask := new(big.Int) - mask.SetBytes(*ipv6.NetIPMask()) - - netAddr := new(big.Int) - netAddr.And(addr, mask) - - return IPv6Network(netAddr) -} - -// Octets returns a slice of the 16 octets in an IPv6Addr's Address. The -// order of the bytes is big endian. -func (ipv6 IPv6Addr) Octets() []int { - x := make([]int, IPv6len) - for i, b := range *bigIntToNetIPv6(ipv6.Address) { - x[i] = int(b) - } - - return x -} - -// String returns a string representation of the IPv6Addr -func (ipv6 IPv6Addr) String() string { - if ipv6.Port != 0 { - return fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) - } - - if ipv6.Maskbits() == 128 { - return ipv6.NetIP().String() - } - - return fmt.Sprintf("%s/%d", ipv6.NetIP().String(), ipv6.Maskbits()) -} - -// Type is used as a type switch and returns TypeIPv6 -func (IPv6Addr) Type() SockAddrType { - return TypeIPv6 -} - -// IPv6Attrs returns a list of attributes supported by the IPv6Addr type -func IPv6Attrs() []AttrName { - return ipv6AddrAttrs -} - -// IPv6AddrAttr returns a string representation of an attribute for the given -// IPv6Addr. -func IPv6AddrAttr(ipv6 IPv6Addr, selector AttrName) string { - fn, found := ipv6AddrAttrMap[selector] - if !found { - return "" - } - - return fn(ipv6) -} - -// ipv6AddrInit is called once at init() -func ipv6AddrInit() { - // Sorted for human readability - ipv6AddrAttrs = []AttrName{ - "size", // Same position as in IPv6 for output consistency - "uint128", - } - - ipv6AddrAttrMap = map[AttrName]func(ipv6 IPv6Addr) string{ - "size": func(ipv6 IPv6Addr) string { - netSize := big.NewInt(1) - netSize = netSize.Lsh(netSize, uint(IPv6len*8-ipv6.Maskbits())) - return netSize.Text(10) - }, - "uint128": func(ipv6 IPv6Addr) string { - b := big.Int(*ipv6.Address) - return b.Text(10) - }, - } -} - -// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the -// correctly padded values. -func bigIntToNetIPv6(bi *big.Int) *net.IP { - x := make(net.IP, IPv6len) - ipv6Bytes := bi.Bytes() - - // It's possibe for ipv6Bytes to be less than IPv6len bytes in size. If - // they are different sizes we to pad the size of response. - if len(ipv6Bytes) < IPv6len { - buf := new(bytes.Buffer) - buf.Grow(IPv6len) - - for i := len(ipv6Bytes); i < IPv6len; i++ { - if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil { - panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err)) - } - } - - for _, b := range ipv6Bytes { - if err := binary.Write(buf, binary.BigEndian, b); err != nil { - panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err)) - } - } - - ipv6Bytes = buf.Bytes() - } - i := copy(x, ipv6Bytes) - if i != IPv6len { - panic("IPv6 wrong size") - } - return &x -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/rfc.go b/vendor/github.com/hashicorp/go-sockaddr/rfc.go deleted file mode 100644 index 02e188f6..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/rfc.go +++ /dev/null @@ -1,948 +0,0 @@ -package sockaddr - -// ForwardingBlacklist is a faux RFC that includes a list of non-forwardable IP -// blocks. -const ForwardingBlacklist = 4294967295 -const ForwardingBlacklistRFC = "4294967295" - -// IsRFC tests to see if an SockAddr matches the specified RFC -func IsRFC(rfcNum uint, sa SockAddr) bool { - rfcNetMap := KnownRFCs() - rfcNets, ok := rfcNetMap[rfcNum] - if !ok { - return false - } - - var contained bool - for _, rfcNet := range rfcNets { - if rfcNet.Contains(sa) { - contained = true - break - } - } - return contained -} - -// KnownRFCs returns an initial set of known RFCs. -// -// NOTE (sean@): As this list evolves over time, please submit patches to keep -// this list current. If something isn't right, inquire, as it may just be a -// bug on my part. Some of the inclusions were based on my judgement as to what -// would be a useful value (e.g. RFC3330). -// -// Useful resources: -// -// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml -// * https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml -// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml -func KnownRFCs() map[uint]SockAddrs { - // NOTE(sean@): Multiple SockAddrs per RFC lend themselves well to a - // RADIX tree, but `ENOTIME`. Patches welcome. - return map[uint]SockAddrs{ - 919: { - // [RFC919] Broadcasting Internet Datagrams - MustIPv4Addr("255.255.255.255/32"), // [RFC1122], §7 Broadcast IP Addressing - Proposed Standards - }, - 1122: { - // [RFC1122] Requirements for Internet Hosts -- Communication Layers - MustIPv4Addr("0.0.0.0/8"), // [RFC1122], §3.2.1.3 - MustIPv4Addr("127.0.0.0/8"), // [RFC1122], §3.2.1.3 - }, - 1112: { - // [RFC1112] Host Extensions for IP Multicasting - MustIPv4Addr("224.0.0.0/4"), // [RFC1112], §4 Host Group Addresses - }, - 1918: { - // [RFC1918] Address Allocation for Private Internets - MustIPv4Addr("10.0.0.0/8"), - MustIPv4Addr("172.16.0.0/12"), - MustIPv4Addr("192.168.0.0/16"), - }, - 2544: { - // [RFC2544] Benchmarking Methodology for Network - // Interconnect Devices - MustIPv4Addr("198.18.0.0/15"), - }, - 2765: { - // [RFC2765] Stateless IP/ICMP Translation Algorithm - // (SIIT) (obsoleted by RFCs 6145, which itself was - // later obsoleted by 7915). - - // [RFC2765], §2.1 Addresses - MustIPv6Addr("0:0:0:0:0:ffff:0:0/96"), - }, - 2928: { - // [RFC2928] Initial IPv6 Sub-TLA ID Assignments - MustIPv6Addr("2001::/16"), // Superblock - //MustIPv6Addr("2001:0000::/23"), // IANA - //MustIPv6Addr("2001:0200::/23"), // APNIC - //MustIPv6Addr("2001:0400::/23"), // ARIN - //MustIPv6Addr("2001:0600::/23"), // RIPE NCC - //MustIPv6Addr("2001:0800::/23"), // (future assignment) - // ... - //MustIPv6Addr("2001:FE00::/23"), // (future assignment) - }, - 3056: { // 6to4 address - // [RFC3056] Connection of IPv6 Domains via IPv4 Clouds - - // [RFC3056], §2 IPv6 Prefix Allocation - MustIPv6Addr("2002::/16"), - }, - 3068: { - // [RFC3068] An Anycast Prefix for 6to4 Relay Routers - // (obsolete by RFC7526) - - // [RFC3068], § 6to4 Relay anycast address - MustIPv4Addr("192.88.99.0/24"), - - // [RFC3068], §2.5 6to4 IPv6 relay anycast address - // - // NOTE: /120 == 128-(32-24) - MustIPv6Addr("2002:c058:6301::/120"), - }, - 3171: { - // [RFC3171] IANA Guidelines for IPv4 Multicast Address Assignments - MustIPv4Addr("224.0.0.0/4"), - }, - 3330: { - // [RFC3330] Special-Use IPv4 Addresses - - // Addresses in this block refer to source hosts on - // "this" network. Address 0.0.0.0/32 may be used as a - // source address for this host on this network; other - // addresses within 0.0.0.0/8 may be used to refer to - // specified hosts on this network [RFC1700, page 4]. - MustIPv4Addr("0.0.0.0/8"), - - // 10.0.0.0/8 - This block is set aside for use in - // private networks. Its intended use is documented in - // [RFC1918]. Addresses within this block should not - // appear on the public Internet. - MustIPv4Addr("10.0.0.0/8"), - - // 14.0.0.0/8 - This block is set aside for assignments - // to the international system of Public Data Networks - // [RFC1700, page 181]. The registry of assignments - // within this block can be accessed from the "Public - // Data Network Numbers" link on the web page at - // http://www.iana.org/numbers.html. Addresses within - // this block are assigned to users and should be - // treated as such. - - // 24.0.0.0/8 - This block was allocated in early 1996 - // for use in provisioning IP service over cable - // television systems. Although the IANA initially was - // involved in making assignments to cable operators, - // this responsibility was transferred to American - // Registry for Internet Numbers (ARIN) in May 2001. - // Addresses within this block are assigned in the - // normal manner and should be treated as such. - - // 39.0.0.0/8 - This block was used in the "Class A - // Subnet Experiment" that commenced in May 1995, as - // documented in [RFC1797]. The experiment has been - // completed and this block has been returned to the - // pool of addresses reserved for future allocation or - // assignment. This block therefore no longer has a - // special use and is subject to allocation to a - // Regional Internet Registry for assignment in the - // normal manner. - - // 127.0.0.0/8 - This block is assigned for use as the Internet host - // loopback address. A datagram sent by a higher level protocol to an - // address anywhere within this block should loop back inside the host. - // This is ordinarily implemented using only 127.0.0.1/32 for loopback, - // but no addresses within this block should ever appear on any network - // anywhere [RFC1700, page 5]. - MustIPv4Addr("127.0.0.0/8"), - - // 128.0.0.0/16 - This block, corresponding to the - // numerically lowest of the former Class B addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 169.254.0.0/16 - This is the "link local" block. It - // is allocated for communication between hosts on a - // single link. Hosts obtain these addresses by - // auto-configuration, such as when a DHCP server may - // not be found. - MustIPv4Addr("169.254.0.0/16"), - - // 172.16.0.0/12 - This block is set aside for use in - // private networks. Its intended use is documented in - // [RFC1918]. Addresses within this block should not - // appear on the public Internet. - MustIPv4Addr("172.16.0.0/12"), - - // 191.255.0.0/16 - This block, corresponding to the numerically highest - // to the former Class B addresses, was initially and is still reserved - // by the IANA. Given the present classless nature of the IP address - // space, the basis for the reservation no longer applies and addresses - // in this block are subject to future allocation to a Regional Internet - // Registry for assignment in the normal manner. - - // 192.0.0.0/24 - This block, corresponding to the - // numerically lowest of the former Class C addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 192.0.2.0/24 - This block is assigned as "TEST-NET" for use in - // documentation and example code. It is often used in conjunction with - // domain names example.com or example.net in vendor and protocol - // documentation. Addresses within this block should not appear on the - // public Internet. - MustIPv4Addr("192.0.2.0/24"), - - // 192.88.99.0/24 - This block is allocated for use as 6to4 relay - // anycast addresses, according to [RFC3068]. - MustIPv4Addr("192.88.99.0/24"), - - // 192.168.0.0/16 - This block is set aside for use in private networks. - // Its intended use is documented in [RFC1918]. Addresses within this - // block should not appear on the public Internet. - MustIPv4Addr("192.168.0.0/16"), - - // 198.18.0.0/15 - This block has been allocated for use - // in benchmark tests of network interconnect devices. - // Its use is documented in [RFC2544]. - MustIPv4Addr("198.18.0.0/15"), - - // 223.255.255.0/24 - This block, corresponding to the - // numerically highest of the former Class C addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 224.0.0.0/4 - This block, formerly known as the Class - // D address space, is allocated for use in IPv4 - // multicast address assignments. The IANA guidelines - // for assignments from this space are described in - // [RFC3171]. - MustIPv4Addr("224.0.0.0/4"), - - // 240.0.0.0/4 - This block, formerly known as the Class E address - // space, is reserved. The "limited broadcast" destination address - // 255.255.255.255 should never be forwarded outside the (sub-)net of - // the source. The remainder of this space is reserved - // for future use. [RFC1700, page 4] - MustIPv4Addr("240.0.0.0/4"), - }, - 3849: { - // [RFC3849] IPv6 Address Prefix Reserved for Documentation - MustIPv6Addr("2001:db8::/32"), // [RFC3849], §4 IANA Considerations - }, - 3927: { - // [RFC3927] Dynamic Configuration of IPv4 Link-Local Addresses - MustIPv4Addr("169.254.0.0/16"), // [RFC3927], §2.1 Link-Local Address Selection - }, - 4038: { - // [RFC4038] Application Aspects of IPv6 Transition - - // [RFC4038], §4.2. IPv6 Applications in a Dual-Stack Node - MustIPv6Addr("0:0:0:0:0:ffff::/96"), - }, - 4193: { - // [RFC4193] Unique Local IPv6 Unicast Addresses - MustIPv6Addr("fc00::/7"), - }, - 4291: { - // [RFC4291] IP Version 6 Addressing Architecture - - // [RFC4291], §2.5.2 The Unspecified Address - MustIPv6Addr("::/128"), - - // [RFC4291], §2.5.3 The Loopback Address - MustIPv6Addr("::1/128"), - - // [RFC4291], §2.5.5.1. IPv4-Compatible IPv6 Address - MustIPv6Addr("::/96"), - - // [RFC4291], §2.5.5.2. IPv4-Mapped IPv6 Address - MustIPv6Addr("::ffff:0:0/96"), - - // [RFC4291], §2.5.6 Link-Local IPv6 Unicast Addresses - MustIPv6Addr("fe80::/10"), - - // [RFC4291], §2.5.7 Site-Local IPv6 Unicast Addresses - // (depreciated) - MustIPv6Addr("fec0::/10"), - - // [RFC4291], §2.7 Multicast Addresses - MustIPv6Addr("ff00::/8"), - - // IPv6 Multicast Information. - // - // In the following "table" below, `ff0x` is replaced - // with the following values depending on the scope of - // the query: - // - // IPv6 Multicast Scopes: - // * ff00/9 // reserved - // * ff01/9 // interface-local - // * ff02/9 // link-local - // * ff03/9 // realm-local - // * ff04/9 // admin-local - // * ff05/9 // site-local - // * ff08/9 // organization-local - // * ff0e/9 // global - // * ff0f/9 // reserved - // - // IPv6 Multicast Addresses: - // * ff0x::2 // All routers - // * ff02::5 // OSPFIGP - // * ff02::6 // OSPFIGP Designated Routers - // * ff02::9 // RIP Routers - // * ff02::a // EIGRP Routers - // * ff02::d // All PIM Routers - // * ff02::1a // All RPL Routers - // * ff0x::fb // mDNSv6 - // * ff0x::101 // All Network Time Protocol (NTP) servers - // * ff02::1:1 // Link Name - // * ff02::1:2 // All-dhcp-agents - // * ff02::1:3 // Link-local Multicast Name Resolution - // * ff05::1:3 // All-dhcp-servers - // * ff02::1:ff00:0/104 // Solicited-node multicast address. - // * ff02::2:ff00:0/104 // Node Information Queries - }, - 4380: { - // [RFC4380] Teredo: Tunneling IPv6 over UDP through - // Network Address Translations (NATs) - - // [RFC4380], §2.6 Global Teredo IPv6 Service Prefix - MustIPv6Addr("2001:0000::/32"), - }, - 4773: { - // [RFC4773] Administration of the IANA Special Purpose IPv6 Address Block - MustIPv6Addr("2001:0000::/23"), // IANA - }, - 4843: { - // [RFC4843] An IPv6 Prefix for Overlay Routable Cryptographic Hash Identifiers (ORCHID) - MustIPv6Addr("2001:10::/28"), // [RFC4843], §7 IANA Considerations - }, - 5180: { - // [RFC5180] IPv6 Benchmarking Methodology for Network Interconnect Devices - MustIPv6Addr("2001:0200::/48"), // [RFC5180], §8 IANA Considerations - }, - 5735: { - // [RFC5735] Special Use IPv4 Addresses - MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1 - MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2 - MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3 - MustIPv4Addr("198.18.0.0/15"), // Benchmarks - }, - 5737: { - // [RFC5737] IPv4 Address Blocks Reserved for Documentation - MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1 - MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2 - MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3 - }, - 6052: { - // [RFC6052] IPv6 Addressing of IPv4/IPv6 Translators - MustIPv6Addr("64:ff9b::/96"), // [RFC6052], §2.1. Well-Known Prefix - }, - 6333: { - // [RFC6333] Dual-Stack Lite Broadband Deployments Following IPv4 Exhaustion - MustIPv4Addr("192.0.0.0/29"), // [RFC6333], §5.7 Well-Known IPv4 Address - }, - 6598: { - // [RFC6598] IANA-Reserved IPv4 Prefix for Shared Address Space - MustIPv4Addr("100.64.0.0/10"), - }, - 6666: { - // [RFC6666] A Discard Prefix for IPv6 - MustIPv6Addr("0100::/64"), - }, - 6890: { - // [RFC6890] Special-Purpose IP Address Registries - - // From "RFC6890 §2.2.1 Information Requirements": - /* - The IPv4 and IPv6 Special-Purpose Address Registries maintain the - following information regarding each entry: - - o Address Block - A block of IPv4 or IPv6 addresses that has been - registered for a special purpose. - - o Name - A descriptive name for the special-purpose address block. - - o RFC - The RFC through which the special-purpose address block was - requested. - - o Allocation Date - The date upon which the special-purpose address - block was allocated. - - o Termination Date - The date upon which the allocation is to be - terminated. This field is applicable for limited-use allocations - only. - - o Source - A boolean value indicating whether an address from the - allocated special-purpose address block is valid when used as the - source address of an IP datagram that transits two devices. - - o Destination - A boolean value indicating whether an address from - the allocated special-purpose address block is valid when used as - the destination address of an IP datagram that transits two - devices. - - o Forwardable - A boolean value indicating whether a router may - forward an IP datagram whose destination address is drawn from the - allocated special-purpose address block between external - interfaces. - - o Global - A boolean value indicating whether an IP datagram whose - destination address is drawn from the allocated special-purpose - address block is forwardable beyond a specified administrative - domain. - - o Reserved-by-Protocol - A boolean value indicating whether the - special-purpose address block is reserved by IP, itself. This - value is "TRUE" if the RFC that created the special-purpose - address block requires all compliant IP implementations to behave - in a special way when processing packets either to or from - addresses contained by the address block. - - If the value of "Destination" is FALSE, the values of "Forwardable" - and "Global" must also be false. - */ - - /*+----------------------+----------------------------+ - * | Attribute | Value | - * +----------------------+----------------------------+ - * | Address Block | 0.0.0.0/8 | - * | Name | "This host on this network"| - * | RFC | [RFC1122], Section 3.2.1.3 | - * | Allocation Date | September 1981 | - * | Termination Date | N/A | - * | Source | True | - * | Destination | False | - * | Forwardable | False | - * | Global | False | - * | Reserved-by-Protocol | True | - * +----------------------+----------------------------+*/ - MustIPv4Addr("0.0.0.0/8"), - - /*+----------------------+---------------+ - * | Attribute | Value | - * +----------------------+---------------+ - * | Address Block | 10.0.0.0/8 | - * | Name | Private-Use | - * | RFC | [RFC1918] | - * | Allocation Date | February 1996 | - * | Termination Date | N/A | - * | Source | True | - * | Destination | True | - * | Forwardable | True | - * | Global | False | - * | Reserved-by-Protocol | False | - * +----------------------+---------------+ */ - MustIPv4Addr("10.0.0.0/8"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 100.64.0.0/10 | - | Name | Shared Address Space | - | RFC | [RFC6598] | - | Allocation Date | April 2012 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------+*/ - MustIPv4Addr("100.64.0.0/10"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 127.0.0.0/8 | - | Name | Loopback | - | RFC | [RFC1122], Section 3.2.1.3 | - | Allocation Date | September 1981 | - | Termination Date | N/A | - | Source | False [1] | - | Destination | False [1] | - | Forwardable | False [1] | - | Global | False [1] | - | Reserved-by-Protocol | True | - +----------------------+----------------------------+*/ - // [1] Several protocols have been granted exceptions to - // this rule. For examples, see [RFC4379] and - // [RFC5884]. - MustIPv4Addr("127.0.0.0/8"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 169.254.0.0/16 | - | Name | Link Local | - | RFC | [RFC3927] | - | Allocation Date | May 2005 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+----------------+*/ - MustIPv4Addr("169.254.0.0/16"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 172.16.0.0/12 | - | Name | Private-Use | - | RFC | [RFC1918] | - | Allocation Date | February 1996 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - MustIPv4Addr("172.16.0.0/12"), - - /*+----------------------+---------------------------------+ - | Attribute | Value | - +----------------------+---------------------------------+ - | Address Block | 192.0.0.0/24 [2] | - | Name | IETF Protocol Assignments | - | RFC | Section 2.1 of this document | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------------------------+*/ - // [2] Not usable unless by virtue of a more specific - // reservation. - MustIPv4Addr("192.0.0.0/24"), - - /*+----------------------+--------------------------------+ - | Attribute | Value | - +----------------------+--------------------------------+ - | Address Block | 192.0.0.0/29 | - | Name | IPv4 Service Continuity Prefix | - | RFC | [RFC6333], [RFC7335] | - | Allocation Date | June 2011 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------------------------+*/ - MustIPv4Addr("192.0.0.0/29"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 192.0.2.0/24 | - | Name | Documentation (TEST-NET-1) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("192.0.2.0/24"), - - /*+----------------------+--------------------+ - | Attribute | Value | - +----------------------+--------------------+ - | Address Block | 192.88.99.0/24 | - | Name | 6to4 Relay Anycast | - | RFC | [RFC3068] | - | Allocation Date | June 2001 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | True | - | Reserved-by-Protocol | False | - +----------------------+--------------------+*/ - MustIPv4Addr("192.88.99.0/24"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 192.168.0.0/16 | - | Name | Private-Use | - | RFC | [RFC1918] | - | Allocation Date | February 1996 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - MustIPv4Addr("192.168.0.0/16"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 198.18.0.0/15 | - | Name | Benchmarking | - | RFC | [RFC2544] | - | Allocation Date | March 1999 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - MustIPv4Addr("198.18.0.0/15"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 198.51.100.0/24 | - | Name | Documentation (TEST-NET-2) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("198.51.100.0/24"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 203.0.113.0/24 | - | Name | Documentation (TEST-NET-3) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("203.0.113.0/24"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 240.0.0.0/4 | - | Name | Reserved | - | RFC | [RFC1112], Section 4 | - | Allocation Date | August 1989 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+----------------------+*/ - MustIPv4Addr("240.0.0.0/4"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 255.255.255.255/32 | - | Name | Limited Broadcast | - | RFC | [RFC0919], Section 7 | - | Allocation Date | October 1984 | - | Termination Date | N/A | - | Source | False | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------+*/ - MustIPv4Addr("255.255.255.255/32"), - - /*+----------------------+------------------+ - | Attribute | Value | - +----------------------+------------------+ - | Address Block | ::1/128 | - | Name | Loopback Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+------------------+*/ - MustIPv6Addr("::1/128"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | ::/128 | - | Name | Unspecified Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+---------------------+*/ - MustIPv6Addr("::/128"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | 64:ff9b::/96 | - | Name | IPv4-IPv6 Translat. | - | RFC | [RFC6052] | - | Allocation Date | October 2010 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | True | - | Reserved-by-Protocol | False | - +----------------------+---------------------+*/ - MustIPv6Addr("64:ff9b::/96"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | ::ffff:0:0/96 | - | Name | IPv4-mapped Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+---------------------+*/ - MustIPv6Addr("::ffff:0:0/96"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 100::/64 | - | Name | Discard-Only Address Block | - | RFC | [RFC6666] | - | Allocation Date | June 2012 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv6Addr("100::/64"), - - /*+----------------------+---------------------------+ - | Attribute | Value | - +----------------------+---------------------------+ - | Address Block | 2001::/23 | - | Name | IETF Protocol Assignments | - | RFC | [RFC2928] | - | Allocation Date | September 2000 | - | Termination Date | N/A | - | Source | False[1] | - | Destination | False[1] | - | Forwardable | False[1] | - | Global | False[1] | - | Reserved-by-Protocol | False | - +----------------------+---------------------------+*/ - // [1] Unless allowed by a more specific allocation. - MustIPv6Addr("2001::/16"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 2001::/32 | - | Name | TEREDO | - | RFC | [RFC4380] | - | Allocation Date | January 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001::/16"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 2001:2::/48 | - | Name | Benchmarking | - | RFC | [RFC5180] | - | Allocation Date | April 2008 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:2::/48"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 2001:db8::/32 | - | Name | Documentation | - | RFC | [RFC3849] | - | Allocation Date | July 2004 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:db8::/32"), - - /*+----------------------+--------------+ - | Attribute | Value | - +----------------------+--------------+ - | Address Block | 2001:10::/28 | - | Name | ORCHID | - | RFC | [RFC4843] | - | Allocation Date | March 2007 | - | Termination Date | March 2014 | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:10::/28"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 2002::/16 [2] | - | Name | 6to4 | - | RFC | [RFC3056] | - | Allocation Date | February 2001 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | N/A [2] | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - // [2] See [RFC3056] for details. - MustIPv6Addr("2002::/16"), - - /*+----------------------+--------------+ - | Attribute | Value | - +----------------------+--------------+ - | Address Block | fc00::/7 | - | Name | Unique-Local | - | RFC | [RFC4193] | - | Allocation Date | October 2005 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------+*/ - MustIPv6Addr("fc00::/7"), - - /*+----------------------+-----------------------+ - | Attribute | Value | - +----------------------+-----------------------+ - | Address Block | fe80::/10 | - | Name | Linked-Scoped Unicast | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+-----------------------+*/ - MustIPv6Addr("fe80::/10"), - }, - 7335: { - // [RFC7335] IPv4 Service Continuity Prefix - MustIPv4Addr("192.0.0.0/29"), // [RFC7335], §6 IANA Considerations - }, - ForwardingBlacklist: { // Pseudo-RFC - // Blacklist of non-forwardable IP blocks taken from RFC6890 - // - // TODO: the attributes for forwardable should be - // searcahble and embedded in the main list of RFCs - // above. - MustIPv4Addr("0.0.0.0/8"), - MustIPv4Addr("127.0.0.0/8"), - MustIPv4Addr("169.254.0.0/16"), - MustIPv4Addr("192.0.0.0/24"), - MustIPv4Addr("192.0.2.0/24"), - MustIPv4Addr("198.51.100.0/24"), - MustIPv4Addr("203.0.113.0/24"), - MustIPv4Addr("240.0.0.0/4"), - MustIPv4Addr("255.255.255.255/32"), - MustIPv6Addr("::1/128"), - MustIPv6Addr("::/128"), - MustIPv6Addr("::ffff:0:0/96"), - - // There is no way of expressing a whitelist per RFC2928 - // atm without creating a negative mask, which I don't - // want to do atm. - //MustIPv6Addr("2001::/23"), - - MustIPv6Addr("2001:db8::/32"), - MustIPv6Addr("2001:10::/28"), - MustIPv6Addr("fe80::/10"), - }, - } -} - -// VisitAllRFCs iterates over all known RFCs and calls the visitor -func VisitAllRFCs(fn func(rfcNum uint, sockaddrs SockAddrs)) { - rfcNetMap := KnownRFCs() - - // Blacklist of faux-RFCs. Don't show the world that we're abusing the - // RFC system in this library. - rfcBlacklist := map[uint]struct{}{ - ForwardingBlacklist: {}, - } - - for rfcNum, sas := range rfcNetMap { - if _, found := rfcBlacklist[rfcNum]; !found { - fn(rfcNum, sas) - } - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info.go b/vendor/github.com/hashicorp/go-sockaddr/route_info.go deleted file mode 100644 index 2a3ee1db..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info.go +++ /dev/null @@ -1,19 +0,0 @@ -package sockaddr - -// RouteInterface specifies an interface for obtaining memoized route table and -// network information from a given OS. -type RouteInterface interface { - // GetDefaultInterfaceName returns the name of the interface that has a - // default route or an error and an empty string if a problem was - // encountered. - GetDefaultInterfaceName() (string, error) -} - -// VisitCommands visits each command used by the platform-specific RouteInfo -// implementation. -func (ri routeInfo) VisitCommands(fn func(name string, cmd []string)) { - for k, v := range ri.cmds { - cmds := append([]string(nil), v...) - fn(k, cmds) - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go deleted file mode 100644 index 705757ab..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build darwin dragonfly freebsd netbsd openbsd - -package sockaddr - -import "os/exec" - -var cmds map[string][]string = map[string][]string{ - "route": {"/sbin/route", "-n", "get", "default"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil { - return "", err - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go deleted file mode 100644 index d1b009f6..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build android nacl plan9 - -package sockaddr - -import "errors" - -// getDefaultIfName is the default interface function for unsupported platforms. -func getDefaultIfName() (string, error) { - return "", errors.New("No default interface found (unsupported platform)") -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go deleted file mode 100644 index c2ec91ea..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go +++ /dev/null @@ -1,40 +0,0 @@ -package sockaddr - -import ( - "errors" - "os/exec" -) - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a Linux-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - // CoreOS Container Linux moved ip to /usr/bin/ip, so look it up on - // $PATH and fallback to /sbin/ip on error. - path, _ := exec.LookPath("ip") - if path == "" { - path = "/sbin/ip" - } - - return routeInfo{ - cmds: map[string][]string{"ip": {path, "route"}}, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(ri.cmds["ip"][0], ri.cmds["ip"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromIPCmd(string(out)); err != nil { - return "", errors.New("No default interface found") - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go deleted file mode 100644 index ee8e7984..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go +++ /dev/null @@ -1,37 +0,0 @@ -package sockaddr - -import ( - "errors" - "os/exec" -) - -var cmds map[string][]string = map[string][]string{ - "route": {"/usr/sbin/route", "-n", "get", "default"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil { - return "", errors.New("No default interface found") - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go deleted file mode 100644 index 3da97288..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go +++ /dev/null @@ -1,41 +0,0 @@ -package sockaddr - -import "os/exec" - -var cmds map[string][]string = map[string][]string{ - "netstat": {"netstat", "-rn"}, - "ipconfig": {"ipconfig"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - ifNameOut, err := exec.Command(cmds["netstat"][0], cmds["netstat"][1:]...).Output() - if err != nil { - return "", err - } - - ipconfigOut, err := exec.Command(cmds["ipconfig"][0], cmds["ipconfig"][1:]...).Output() - if err != nil { - return "", err - } - - ifName, err := parseDefaultIfNameWindows(string(ifNameOut), string(ipconfigOut)) - if err != nil { - return "", err - } - - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go deleted file mode 100644 index 826c91c2..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go +++ /dev/null @@ -1,206 +0,0 @@ -package sockaddr - -import ( - "encoding/json" - "fmt" - "strings" -) - -type SockAddrType int -type AttrName string - -const ( - TypeUnknown SockAddrType = 0x0 - TypeUnix = 0x1 - TypeIPv4 = 0x2 - TypeIPv6 = 0x4 - - // TypeIP is the union of TypeIPv4 and TypeIPv6 - TypeIP = 0x6 -) - -type SockAddr interface { - // CmpRFC returns 0 if SockAddr exactly matches one of the matched RFC - // networks, -1 if the receiver is contained within the RFC network, or - // 1 if the address is not contained within the RFC. - CmpRFC(rfcNum uint, sa SockAddr) int - - // Contains returns true if the SockAddr arg is contained within the - // receiver - Contains(SockAddr) bool - - // Equal allows for the comparison of two SockAddrs - Equal(SockAddr) bool - - DialPacketArgs() (string, string) - DialStreamArgs() (string, string) - ListenPacketArgs() (string, string) - ListenStreamArgs() (string, string) - - // String returns the string representation of SockAddr - String() string - - // Type returns the SockAddrType - Type() SockAddrType -} - -// sockAddrAttrMap is a map of the SockAddr type-specific attributes. -var sockAddrAttrMap map[AttrName]func(SockAddr) string -var sockAddrAttrs []AttrName - -func init() { - sockAddrInit() -} - -// New creates a new SockAddr from the string. The order in which New() -// attempts to construct a SockAddr is: IPv4Addr, IPv6Addr, SockAddrUnix. -// -// NOTE: New() relies on the heuristic wherein if the path begins with either a -// '.' or '/' character before creating a new UnixSock. For UNIX sockets that -// are absolute paths or are nested within a sub-directory, this works as -// expected, however if the UNIX socket is contained in the current working -// directory, this will fail unless the path begins with "./" -// (e.g. "./my-local-socket"). Calls directly to NewUnixSock() do not suffer -// this limitation. Invalid IP addresses such as "256.0.0.0/-1" will run afoul -// of this heuristic and be assumed to be a valid UNIX socket path (which they -// are, but it is probably not what you want and you won't realize it until you -// stat(2) the file system to discover it doesn't exist). -func NewSockAddr(s string) (SockAddr, error) { - ipv4Addr, err := NewIPv4Addr(s) - if err == nil { - return ipv4Addr, nil - } - - ipv6Addr, err := NewIPv6Addr(s) - if err == nil { - return ipv6Addr, nil - } - - // Check to make sure the string begins with either a '.' or '/', or - // contains a '/'. - if len(s) > 1 && (strings.IndexAny(s[0:1], "./") != -1 || strings.IndexByte(s, '/') != -1) { - unixSock, err := NewUnixSock(s) - if err == nil { - return unixSock, nil - } - } - - return nil, fmt.Errorf("Unable to convert %q to an IPv4 or IPv6 address, or a UNIX Socket", s) -} - -// ToIPAddr returns an IPAddr type or nil if the type conversion fails. -func ToIPAddr(sa SockAddr) *IPAddr { - ipa, ok := sa.(IPAddr) - if !ok { - return nil - } - return &ipa -} - -// ToIPv4Addr returns an IPv4Addr type or nil if the type conversion fails. -func ToIPv4Addr(sa SockAddr) *IPv4Addr { - switch v := sa.(type) { - case IPv4Addr: - return &v - default: - return nil - } -} - -// ToIPv6Addr returns an IPv6Addr type or nil if the type conversion fails. -func ToIPv6Addr(sa SockAddr) *IPv6Addr { - switch v := sa.(type) { - case IPv6Addr: - return &v - default: - return nil - } -} - -// ToUnixSock returns a UnixSock type or nil if the type conversion fails. -func ToUnixSock(sa SockAddr) *UnixSock { - switch v := sa.(type) { - case UnixSock: - return &v - default: - return nil - } -} - -// SockAddrAttr returns a string representation of an attribute for the given -// SockAddr. -func SockAddrAttr(sa SockAddr, selector AttrName) string { - fn, found := sockAddrAttrMap[selector] - if !found { - return "" - } - - return fn(sa) -} - -// String() for SockAddrType returns a string representation of the -// SockAddrType (e.g. "IPv4", "IPv6", "UNIX", "IP", or "unknown"). -func (sat SockAddrType) String() string { - switch sat { - case TypeIPv4: - return "IPv4" - case TypeIPv6: - return "IPv6" - // There is no concrete "IP" type. Leaving here as a reminder. - // case TypeIP: - // return "IP" - case TypeUnix: - return "UNIX" - default: - panic("unsupported type") - } -} - -// sockAddrInit is called once at init() -func sockAddrInit() { - sockAddrAttrs = []AttrName{ - "type", // type should be first - "string", - } - - sockAddrAttrMap = map[AttrName]func(sa SockAddr) string{ - "string": func(sa SockAddr) string { - return sa.String() - }, - "type": func(sa SockAddr) string { - return sa.Type().String() - }, - } -} - -// UnixSockAttrs returns a list of attributes supported by the UnixSock type -func SockAddrAttrs() []AttrName { - return sockAddrAttrs -} - -// Although this is pretty trivial to do in a program, having the logic here is -// useful all around. Note that this marshals into a *string* -- the underlying -// string representation of the sockaddr. If you then unmarshal into this type -// in Go, all will work as expected, but externally you can take what comes out -// and use the string value directly. -type SockAddrMarshaler struct { - SockAddr -} - -func (s *SockAddrMarshaler) MarshalJSON() ([]byte, error) { - return json.Marshal(s.SockAddr.String()) -} - -func (s *SockAddrMarshaler) UnmarshalJSON(in []byte) error { - var str string - err := json.Unmarshal(in, &str) - if err != nil { - return err - } - sa, err := NewSockAddr(str) - if err != nil { - return err - } - s.SockAddr = sa - return nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go deleted file mode 100644 index 75fbffb1..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go +++ /dev/null @@ -1,193 +0,0 @@ -package sockaddr - -import ( - "bytes" - "sort" -) - -// SockAddrs is a slice of SockAddrs -type SockAddrs []SockAddr - -func (s SockAddrs) Len() int { return len(s) } -func (s SockAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// CmpAddrFunc is the function signature that must be met to be used in the -// OrderedAddrBy multiAddrSorter -type CmpAddrFunc func(p1, p2 *SockAddr) int - -// multiAddrSorter implements the Sort interface, sorting the SockAddrs within. -type multiAddrSorter struct { - addrs SockAddrs - cmp []CmpAddrFunc -} - -// Sort sorts the argument slice according to the Cmp functions passed to -// OrderedAddrBy. -func (ms *multiAddrSorter) Sort(sockAddrs SockAddrs) { - ms.addrs = sockAddrs - sort.Sort(ms) -} - -// OrderedAddrBy sorts SockAddr by the list of sort function pointers. -func OrderedAddrBy(cmpFuncs ...CmpAddrFunc) *multiAddrSorter { - return &multiAddrSorter{ - cmp: cmpFuncs, - } -} - -// Len is part of sort.Interface. -func (ms *multiAddrSorter) Len() int { - return len(ms.addrs) -} - -// Less is part of sort.Interface. It is implemented by looping along the -// Cmp() functions until it finds a comparison that is either less than, -// equal to, or greater than. -func (ms *multiAddrSorter) Less(i, j int) bool { - p, q := &ms.addrs[i], &ms.addrs[j] - // Try all but the last comparison. - var k int - for k = 0; k < len(ms.cmp)-1; k++ { - cmp := ms.cmp[k] - x := cmp(p, q) - switch x { - case -1: - // p < q, so we have a decision. - return true - case 1: - // p > q, so we have a decision. - return false - } - // p == q; try the next comparison. - } - // All comparisons to here said "equal", so just return whatever the - // final comparison reports. - switch ms.cmp[k](p, q) { - case -1: - return true - case 1: - return false - default: - // Still a tie! Now what? - return false - } -} - -// Swap is part of sort.Interface. -func (ms *multiAddrSorter) Swap(i, j int) { - ms.addrs[i], ms.addrs[j] = ms.addrs[j], ms.addrs[i] -} - -const ( - // NOTE (sean@): These constants are here for code readability only and - // are sprucing up the code for readability purposes. Some of the - // Cmp*() variants have confusing logic (especially when dealing with - // mixed-type comparisons) and this, I think, has made it easier to grok - // the code faster. - sortReceiverBeforeArg = -1 - sortDeferDecision = 0 - sortArgBeforeReceiver = 1 -) - -// AscAddress is a sorting function to sort SockAddrs by their respective -// address type. Non-equal types are deferred in the sort. -func AscAddress(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr: - return v.CmpAddress(p2) - case IPv6Addr: - return v.CmpAddress(p2) - case UnixSock: - return v.CmpAddress(p2) - default: - return sortDeferDecision - } -} - -// AscPort is a sorting function to sort SockAddrs by their respective address -// type. Non-equal types are deferred in the sort. -func AscPort(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr: - return v.CmpPort(p2) - case IPv6Addr: - return v.CmpPort(p2) - default: - return sortDeferDecision - } -} - -// AscPrivate is a sorting function to sort "more secure" private values before -// "more public" values. Both IPv4 and IPv6 are compared against RFC6890 -// (RFC6890 includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and -// IPv6 includes RFC4193). -func AscPrivate(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr, IPv6Addr: - return v.CmpRFC(6890, p2) - default: - return sortDeferDecision - } -} - -// AscNetworkSize is a sorting function to sort SockAddrs based on their network -// size. Non-equal types are deferred in the sort. -func AscNetworkSize(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - p1Type := p1.Type() - p2Type := p2.Type() - - // Network size operations on non-IP types make no sense - if p1Type != p2Type && p1Type != TypeIP { - return sortDeferDecision - } - - ipA := p1.(IPAddr) - ipB := p2.(IPAddr) - - return bytes.Compare([]byte(*ipA.NetIPMask()), []byte(*ipB.NetIPMask())) -} - -// AscType is a sorting function to sort "more secure" types before -// "less-secure" types. -func AscType(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - p1Type := p1.Type() - p2Type := p2.Type() - switch { - case p1Type < p2Type: - return sortReceiverBeforeArg - case p1Type == p2Type: - return sortDeferDecision - case p1Type > p2Type: - return sortArgBeforeReceiver - default: - return sortDeferDecision - } -} - -// FilterByType returns two lists: a list of matched and unmatched SockAddrs -func (sas SockAddrs) FilterByType(type_ SockAddrType) (matched, excluded SockAddrs) { - matched = make(SockAddrs, 0, len(sas)) - excluded = make(SockAddrs, 0, len(sas)) - - for _, sa := range sas { - if sa.Type()&type_ != 0 { - matched = append(matched, sa) - } else { - excluded = append(excluded, sa) - } - } - return matched, excluded -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/unixsock.go b/vendor/github.com/hashicorp/go-sockaddr/unixsock.go deleted file mode 100644 index f3be3f67..00000000 --- a/vendor/github.com/hashicorp/go-sockaddr/unixsock.go +++ /dev/null @@ -1,135 +0,0 @@ -package sockaddr - -import ( - "fmt" - "strings" -) - -type UnixSock struct { - SockAddr - path string -} -type UnixSocks []*UnixSock - -// unixAttrMap is a map of the UnixSockAddr type-specific attributes. -var unixAttrMap map[AttrName]func(UnixSock) string -var unixAttrs []AttrName - -func init() { - unixAttrInit() -} - -// NewUnixSock creates an UnixSock from a string path. String can be in the -// form of either URI-based string (e.g. `file:///etc/passwd`), an absolute -// path (e.g. `/etc/passwd`), or a relative path (e.g. `./foo`). -func NewUnixSock(s string) (ret UnixSock, err error) { - ret.path = s - return ret, nil -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its name lexically sorts before arg -// - 0 if the SockAddr arg is not a UnixSock, or is a UnixSock with the same path. -// - 1 If the argument should sort first. -func (us UnixSock) CmpAddress(sa SockAddr) int { - usb, ok := sa.(UnixSock) - if !ok { - return sortDeferDecision - } - - return strings.Compare(us.Path(), usb.Path()) -} - -// DialPacketArgs returns the arguments required to be passed to net.DialUnix() -// with the `unixgram` network type. -func (us UnixSock) DialPacketArgs() (network, dialArgs string) { - return "unixgram", us.path -} - -// DialStreamArgs returns the arguments required to be passed to net.DialUnix() -// with the `unix` network type. -func (us UnixSock) DialStreamArgs() (network, dialArgs string) { - return "unix", us.path -} - -// Equal returns true if a SockAddr is equal to the receiving UnixSock. -func (us UnixSock) Equal(sa SockAddr) bool { - usb, ok := sa.(UnixSock) - if !ok { - return false - } - - if us.Path() != usb.Path() { - return false - } - - return true -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUnixgram() with the `unixgram` network type. -func (us UnixSock) ListenPacketArgs() (network, dialArgs string) { - return "unixgram", us.path -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenUnix() with the `unix` network type. -func (us UnixSock) ListenStreamArgs() (network, dialArgs string) { - return "unix", us.path -} - -// MustUnixSock is a helper method that must return an UnixSock or panic on -// invalid input. -func MustUnixSock(addr string) UnixSock { - us, err := NewUnixSock(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create a UnixSock from %+q: %v", addr, err)) - } - return us -} - -// Path returns the given path of the UnixSock -func (us UnixSock) Path() string { - return us.path -} - -// String returns the path of the UnixSock -func (us UnixSock) String() string { - return fmt.Sprintf("%+q", us.path) -} - -// Type is used as a type switch and returns TypeUnix -func (UnixSock) Type() SockAddrType { - return TypeUnix -} - -// UnixSockAttrs returns a list of attributes supported by the UnixSockAddr type -func UnixSockAttrs() []AttrName { - return unixAttrs -} - -// UnixSockAttr returns a string representation of an attribute for the given -// UnixSock. -func UnixSockAttr(us UnixSock, attrName AttrName) string { - fn, found := unixAttrMap[attrName] - if !found { - return "" - } - - return fn(us) -} - -// unixAttrInit is called once at init() -func unixAttrInit() { - // Sorted for human readability - unixAttrs = []AttrName{ - "path", - } - - unixAttrMap = map[AttrName]func(us UnixSock) string{ - "path": func(us UnixSock) string { - return us.Path() - }, - } -} 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 76984907..00000000 --- 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 e87a115e..00000000 --- a/vendor/github.com/hashicorp/go-uuid/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-uuid/README.md b/vendor/github.com/hashicorp/go-uuid/README.md deleted file mode 100644 index fbde8b9a..00000000 --- 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/go.mod b/vendor/github.com/hashicorp/go-uuid/go.mod deleted file mode 100644 index dd57f9d2..00000000 --- a/vendor/github.com/hashicorp/go-uuid/go.mod +++ /dev/null @@ -1 +0,0 @@ -module 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 911227f6..00000000 --- a/vendor/github.com/hashicorp/go-uuid/uuid.go +++ /dev/null @@ -1,65 +0,0 @@ -package uuid - -import ( - "crypto/rand" - "encoding/hex" - "fmt" -) - -// GenerateRandomBytes is used to generate random bytes of given size. -func GenerateRandomBytes(size int) ([]byte, error) { - buf := make([]byte, size) - if _, err := rand.Read(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) { - buf, err := GenerateRandomBytes(uuidLen) - 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/.travis.yml b/vendor/github.com/hashicorp/go-version/.travis.yml deleted file mode 100644 index 542ca8b7..00000000 --- a/vendor/github.com/hashicorp/go-version/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.0 - - 1.1 - - 1.2 - - 1.3 - - 1.4 - - 1.9 - - "1.10" - -script: - - go test diff --git a/vendor/github.com/hashicorp/go-version/LICENSE b/vendor/github.com/hashicorp/go-version/LICENSE deleted file mode 100644 index c33dcc7c..00000000 --- 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 6f3a15ce..00000000 --- a/vendor/github.com/hashicorp/go-version/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# Versioning Library for Go -[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/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 d0557596..00000000 --- a/vendor/github.com/hashicorp/go-version/constraint.go +++ /dev/null @@ -1,204 +0,0 @@ -package version - -import ( - "fmt" - "reflect" - "regexp" - "strings" -) - -// Constraint represents a single constraint for a version, such as -// ">= 1.0". -type Constraint struct { - f constraintFunc - check *Version - original string -} - -// 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]constraintFunc - -var constraintRegexp *regexp.Regexp - -func init() { - constraintOperators = map[string]constraintFunc{ - "": constraintEqual, - "=": constraintEqual, - "!=": constraintNotEqual, - ">": constraintGreaterThan, - "<": constraintLessThan, - ">=": constraintGreaterThanEqual, - "<=": constraintLessThanEqual, - "~>": 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 -} - -// 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 -} - -// 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) -} - -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 - } - - return &Constraint{ - f: constraintOperators[matches[1]], - 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 -//------------------------------------------------------------------- - -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/go.mod b/vendor/github.com/hashicorp/go-version/go.mod deleted file mode 100644 index f5285555..00000000 --- a/vendor/github.com/hashicorp/go-version/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/go-version 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 4d1e6e22..00000000 --- a/vendor/github.com/hashicorp/go-version/version.go +++ /dev/null @@ -1,347 +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 - -// 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\-~]+)*))?` + - `?` - -// Version represents a single version. -type Version struct { - metadata string - pre string - segments []int64 - si int - original string -} - -func init() { - versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$") -} - -// NewVersion parses the given version and returns a new -// Version. -func NewVersion(v string) (*Version, error) { - matches := versionRegexp.FindStringSubmatch(v) - if matches == nil { - return nil, fmt.Errorf("Malformed version: %s", v) - } - segmentsStr := strings.Split(matches[1], ".") - segments := make([]int64, len(segmentsStr)) - si := 0 - 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] = int64(val) - si++ - } - - // 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: si, - 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, -// or GreaterThan 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 -} - -// Equal tests if two versions are equal. -func (v *Version) Equal(o *Version) bool { - 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 -} - -// LessThan tests if this version is less than another version. -func (v *Version) LessThan(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 -} 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 cc888d43..00000000 --- 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 83656241..00000000 --- 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 e474cd07..00000000 --- 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/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE deleted file mode 100644 index be2cc4df..00000000 --- a/vendor/github.com/hashicorp/golang-lru/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. 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 33e58cfa..00000000 --- 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 555225a2..00000000 --- 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 2547df97..00000000 --- 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/go.mod b/vendor/github.com/hashicorp/golang-lru/go.mod deleted file mode 100644 index 824cb97e..00000000 --- a/vendor/github.com/hashicorp/golang-lru/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/golang-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 c8d9b0a2..00000000 --- a/vendor/github.com/hashicorp/golang-lru/lru.go +++ /dev/null @@ -1,110 +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() - defer c.lock.Unlock() - return c.lru.Add(key, value) -} - -// Get looks up a key's value from the cache. -func (c *Cache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - return c.lru.Get(key) -} - -// 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() - defer c.lock.RUnlock() - return c.lru.Contains(key) -} - -// 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() - defer c.lock.RUnlock() - return c.lru.Peek(key) -} - -// 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 -} - -// Remove removes the provided key from the cache. -func (c *Cache) Remove(key interface{}) { - c.lock.Lock() - c.lru.Remove(key) - c.lock.Unlock() -} - -// RemoveOldest removes the oldest item from the cache. -func (c *Cache) RemoveOldest() { - c.lock.Lock() - c.lru.RemoveOldest() - c.lock.Unlock() -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *Cache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Keys() -} - -// Len returns the number of items in the cache. -func (c *Cache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Len() -} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go deleted file mode 100644 index 5673773b..00000000 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go +++ /dev/null @@ -1,161 +0,0 @@ -package simplelru - -import ( - "container/list" - "errors" -) - -// EvictCallback is used to get a callback when a cache entry is evicted -type EvictCallback func(key interface{}, value interface{}) - -// LRU implements a non-thread safe fixed size LRU cache -type LRU struct { - size int - evictList *list.List - items map[interface{}]*list.Element - onEvict EvictCallback -} - -// entry is used to hold a value in the evictList -type entry struct { - key interface{} - value interface{} -} - -// NewLRU constructs an LRU of the given size -func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { - if size <= 0 { - return nil, errors.New("Must provide a positive size") - } - c := &LRU{ - size: size, - evictList: list.New(), - items: make(map[interface{}]*list.Element), - onEvict: onEvict, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *LRU) Purge() { - for k, v := range c.items { - if c.onEvict != nil { - c.onEvict(k, v.Value.(*entry).value) - } - delete(c.items, k) - } - c.evictList.Init() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *LRU) Add(key, value interface{}) (evicted bool) { - // Check for existing item - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - ent.Value.(*entry).value = value - return false - } - - // Add new item - ent := &entry{key, value} - entry := c.evictList.PushFront(ent) - c.items[key] = entry - - evict := c.evictList.Len() > c.size - // Verify size not exceeded - if evict { - c.removeOldest() - } - return evict -} - -// Get looks up a key's value from the cache. -func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - return ent.Value.(*entry).value, true - } - return -} - -// Contains checks if a key is in the cache, without updating the recent-ness -// or deleting it for being stale. -func (c *LRU) Contains(key interface{}) (ok bool) { - _, ok = c.items[key] - return ok -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { - var ent *list.Element - if ent, ok = c.items[key]; ok { - return ent.Value.(*entry).value, true - } - return nil, ok -} - -// Remove removes the provided key from the cache, returning if the -// key was contained. -func (c *LRU) Remove(key interface{}) (present bool) { - if ent, ok := c.items[key]; ok { - c.removeElement(ent) - return true - } - return false -} - -// RemoveOldest removes the oldest item from the cache. -func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// GetOldest returns the oldest entry -func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *LRU) Keys() []interface{} { - keys := make([]interface{}, len(c.items)) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() { - keys[i] = ent.Value.(*entry).key - i++ - } - return keys -} - -// Len returns the number of items in the cache. -func (c *LRU) Len() int { - return c.evictList.Len() -} - -// removeOldest removes the oldest item from the cache. -func (c *LRU) removeOldest() { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - } -} - -// removeElement is used to remove a given list element from the cache -func (c *LRU) removeElement(e *list.Element) { - c.evictList.Remove(e) - kv := e.Value.(*entry) - delete(c.items, kv.key) - if c.onEvict != nil { - c.onEvict(kv.key, kv.value) - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go deleted file mode 100644 index 74c70774..00000000 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go +++ /dev/null @@ -1,36 +0,0 @@ -package simplelru - -// LRUCache is the interface for simple LRU cache. -type LRUCache interface { - // Adds a value to the cache, returns true if an eviction occurred and - // updates the "recently used"-ness of the key. - Add(key, value interface{}) bool - - // Returns key's value from the cache and - // updates the "recently used"-ness of the key. #value, isFound - Get(key interface{}) (value interface{}, ok bool) - - // Check if a key exsists in cache without updating the recent-ness. - Contains(key interface{}) (ok bool) - - // Returns key's value without updating the "recently used"-ness of the key. - Peek(key interface{}) (value interface{}, ok bool) - - // Removes a key from the cache. - Remove(key interface{}) bool - - // Removes the oldest entry from cache. - RemoveOldest() (interface{}, interface{}, bool) - - // Returns the oldest entry from the cache. #key, value, isFound - GetOldest() (interface{}, interface{}, bool) - - // Returns a slice of the keys in the cache, from oldest to newest. - Keys() []interface{} - - // Returns the number of items in the cache. - Len() int - - // Clear all cache entries - Purge() -} diff --git a/vendor/github.com/hashicorp/hcl/.gitignore b/vendor/github.com/hashicorp/hcl/.gitignore deleted file mode 100644 index 822fa09f..00000000 --- a/vendor/github.com/hashicorp/hcl/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -y.output - -# ignore intellij files -.idea -*.iml -*.ipr -*.iws - -*.test diff --git a/vendor/github.com/hashicorp/hcl/.travis.yml b/vendor/github.com/hashicorp/hcl/.travis.yml deleted file mode 100644 index cb63a321..00000000 --- a/vendor/github.com/hashicorp/hcl/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -sudo: false - -language: go - -go: - - 1.x - - tip - -branches: - only: - - master - -script: make test diff --git a/vendor/github.com/hashicorp/hcl/LICENSE b/vendor/github.com/hashicorp/hcl/LICENSE deleted file mode 100644 index c33dcc7c..00000000 --- a/vendor/github.com/hashicorp/hcl/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/hcl/Makefile b/vendor/github.com/hashicorp/hcl/Makefile deleted file mode 100644 index 9fafd501..00000000 --- a/vendor/github.com/hashicorp/hcl/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -TEST?=./... - -default: test - -fmt: generate - go fmt ./... - -test: generate - go get -t ./... - go test $(TEST) $(TESTARGS) - -generate: - go generate ./... - -updatedeps: - go get -u golang.org/x/tools/cmd/stringer - -.PHONY: default generate test updatedeps diff --git a/vendor/github.com/hashicorp/hcl/README.md b/vendor/github.com/hashicorp/hcl/README.md deleted file mode 100644 index c8223326..00000000 --- a/vendor/github.com/hashicorp/hcl/README.md +++ /dev/null @@ -1,125 +0,0 @@ -# HCL - -[![GoDoc](https://godoc.org/github.com/hashicorp/hcl?status.png)](https://godoc.org/github.com/hashicorp/hcl) [![Build Status](https://travis-ci.org/hashicorp/hcl.svg?branch=master)](https://travis-ci.org/hashicorp/hcl) - -HCL (HashiCorp Configuration Language) is a configuration language built -by HashiCorp. The goal of HCL is to build a structured configuration language -that is both human and machine friendly for use with command-line tools, but -specifically targeted towards DevOps tools, servers, etc. - -HCL is also fully JSON compatible. That is, JSON can be used as completely -valid input to a system expecting HCL. This helps makes systems -interoperable with other systems. - -HCL is heavily inspired by -[libucl](https://github.com/vstakhov/libucl), -nginx configuration, and others similar. - -## Why? - -A common question when viewing HCL is to ask the question: why not -JSON, YAML, etc.? - -Prior to HCL, the tools we built at [HashiCorp](http://www.hashicorp.com) -used a variety of configuration languages from full programming languages -such as Ruby to complete data structure languages such as JSON. What we -learned is that some people wanted human-friendly configuration languages -and some people wanted machine-friendly languages. - -JSON fits a nice balance in this, but is fairly verbose and most -importantly doesn't support comments. With YAML, we found that beginners -had a really hard time determining what the actual structure was, and -ended up guessing more often than not whether to use a hyphen, colon, etc. -in order to represent some configuration key. - -Full programming languages such as Ruby enable complex behavior -a configuration language shouldn't usually allow, and also forces -people to learn some set of Ruby. - -Because of this, we decided to create our own configuration language -that is JSON-compatible. Our configuration language (HCL) is designed -to be written and modified by humans. The API for HCL allows JSON -as an input so that it is also machine-friendly (machines can generate -JSON instead of trying to generate HCL). - -Our goal with HCL is not to alienate other configuration languages. -It is instead to provide HCL as a specialized language for our tools, -and JSON as the interoperability layer. - -## Syntax - -For a complete grammar, please see the parser itself. A high-level overview -of the syntax and grammar is listed here. - - * Single line comments start with `#` or `//` - - * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments - are not allowed. A multi-line comment (also known as a block comment) - terminates at the first `*/` found. - - * Values are assigned with the syntax `key = value` (whitespace doesn't - matter). The value can be any primitive: a string, number, boolean, - object, or list. - - * Strings are double-quoted and can contain any UTF-8 characters. - Example: `"Hello, World"` - - * Multi-line strings start with `<- - echo %Path% - - go version - - go env - - go get -t ./... - -build_script: -- cmd: go test -v ./... diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go deleted file mode 100644 index bed9ebbe..00000000 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ /dev/null @@ -1,729 +0,0 @@ -package hcl - -import ( - "errors" - "fmt" - "reflect" - "sort" - "strconv" - "strings" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/parser" - "github.com/hashicorp/hcl/hcl/token" -) - -// This is the tag to use with structures to have settings for HCL -const tagName = "hcl" - -var ( - // nodeType holds a reference to the type of ast.Node - nodeType reflect.Type = findNodeType() -) - -// Unmarshal accepts a byte slice as input and writes the -// data to the value pointed to by v. -func Unmarshal(bs []byte, v interface{}) error { - root, err := parse(bs) - if err != nil { - return err - } - - return DecodeObject(v, root) -} - -// Decode reads the given input and decodes it into the structure -// given by `out`. -func Decode(out interface{}, in string) error { - obj, err := Parse(in) - if err != nil { - return err - } - - return DecodeObject(out, obj) -} - -// DecodeObject is a lower-level version of Decode. It decodes a -// raw Object into the given output. -func DecodeObject(out interface{}, n ast.Node) error { - val := reflect.ValueOf(out) - if val.Kind() != reflect.Ptr { - return errors.New("result must be a pointer") - } - - // If we have the file, we really decode the root node - if f, ok := n.(*ast.File); ok { - n = f.Node - } - - var d decoder - return d.decode("root", n, val.Elem()) -} - -type decoder struct { - stack []reflect.Kind -} - -func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error { - k := result - - // If we have an interface with a valid value, we use that - // for the check. - if result.Kind() == reflect.Interface { - elem := result.Elem() - if elem.IsValid() { - k = elem - } - } - - // Push current onto stack unless it is an interface. - if k.Kind() != reflect.Interface { - d.stack = append(d.stack, k.Kind()) - - // Schedule a pop - defer func() { - d.stack = d.stack[:len(d.stack)-1] - }() - } - - switch k.Kind() { - case reflect.Bool: - return d.decodeBool(name, node, result) - case reflect.Float32, reflect.Float64: - return d.decodeFloat(name, node, result) - case reflect.Int, reflect.Int32, reflect.Int64: - return d.decodeInt(name, node, result) - case reflect.Interface: - // When we see an interface, we make our own thing - return d.decodeInterface(name, node, result) - case reflect.Map: - return d.decodeMap(name, node, result) - case reflect.Ptr: - return d.decodePtr(name, node, result) - case reflect.Slice: - return d.decodeSlice(name, node, result) - case reflect.String: - return d.decodeString(name, node, result) - case reflect.Struct: - return d.decodeStruct(name, node, result) - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown kind to decode into: %s", name, k.Kind()), - } - } -} - -func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - if n.Token.Type == token.BOOL { - v, err := strconv.ParseBool(n.Token.Text) - if err != nil { - return err - } - - result.Set(reflect.ValueOf(v)) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeFloat(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - if n.Token.Type == token.FLOAT || n.Token.Type == token.NUMBER { - v, err := strconv.ParseFloat(n.Token.Text, 64) - if err != nil { - return err - } - - result.Set(reflect.ValueOf(v).Convert(result.Type())) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - switch n.Token.Type { - case token.NUMBER: - v, err := strconv.ParseInt(n.Token.Text, 0, 0) - if err != nil { - return err - } - - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } - return nil - case token.STRING: - v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0) - if err != nil { - return err - } - - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeInterface(name string, node ast.Node, result reflect.Value) error { - // When we see an ast.Node, we retain the value to enable deferred decoding. - // Very useful in situations where we want to preserve ast.Node information - // like Pos - if result.Type() == nodeType && result.CanSet() { - result.Set(reflect.ValueOf(node)) - return nil - } - - var set reflect.Value - redecode := true - - // For testing types, ObjectType should just be treated as a list. We - // set this to a temporary var because we want to pass in the real node. - testNode := node - if ot, ok := node.(*ast.ObjectType); ok { - testNode = ot.List - } - - switch n := testNode.(type) { - case *ast.ObjectList: - // If we're at the root or we're directly within a slice, then we - // decode objects into map[string]interface{}, otherwise we decode - // them into lists. - if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice { - var temp map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeMap( - reflect.MapOf( - reflect.TypeOf(""), - tempVal.Type().Elem())) - - set = result - } else { - var temp []map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, len(n.Items)) - set = result - } - case *ast.ObjectType: - // If we're at the root or we're directly within a slice, then we - // decode objects into map[string]interface{}, otherwise we decode - // them into lists. - if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice { - var temp map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeMap( - reflect.MapOf( - reflect.TypeOf(""), - tempVal.Type().Elem())) - - set = result - } else { - var temp []map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, 1) - set = result - } - case *ast.ListType: - var temp []interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, 0) - set = result - case *ast.LiteralType: - switch n.Token.Type { - case token.BOOL: - var result bool - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.FLOAT: - var result float64 - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.NUMBER: - var result int - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.STRING, token.HEREDOC: - set = reflect.Indirect(reflect.New(reflect.TypeOf(""))) - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: cannot decode into interface: %T", name, node), - } - } - default: - return fmt.Errorf( - "%s: cannot decode into interface: %T", - name, node) - } - - // Set the result to what its supposed to be, then reset - // result so we don't reflect into this method anymore. - result.Set(set) - - if redecode { - // Revisit the node so that we can use the newly instantiated - // thing and populate it. - if err := d.decode(name, node, result); err != nil { - return err - } - } - - return nil -} - -func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) error { - if item, ok := node.(*ast.ObjectItem); ok { - node = &ast.ObjectList{Items: []*ast.ObjectItem{item}} - } - - if ot, ok := node.(*ast.ObjectType); ok { - node = ot.List - } - - n, ok := node.(*ast.ObjectList) - if !ok { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: not an object type for map (%T)", name, node), - } - } - - // If we have an interface, then we can address the interface, - // but not the slice itself, so get the element but set the interface - set := result - if result.Kind() == reflect.Interface { - result = result.Elem() - } - - resultType := result.Type() - resultElemType := resultType.Elem() - resultKeyType := resultType.Key() - if resultKeyType.Kind() != reflect.String { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: map must have string keys", name), - } - } - - // Make a map if it is nil - resultMap := result - if result.IsNil() { - resultMap = reflect.MakeMap( - reflect.MapOf(resultKeyType, resultElemType)) - } - - // Go through each element and decode it. - done := make(map[string]struct{}) - for _, item := range n.Items { - if item.Val == nil { - continue - } - - // github.com/hashicorp/terraform/issue/5740 - if len(item.Keys) == 0 { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: map must have string keys", name), - } - } - - // Get the key we're dealing with, which is the first item - keyStr := item.Keys[0].Token.Value().(string) - - // If we've already processed this key, then ignore it - if _, ok := done[keyStr]; ok { - continue - } - - // Determine the value. If we have more than one key, then we - // get the objectlist of only these keys. - itemVal := item.Val - if len(item.Keys) > 1 { - itemVal = n.Filter(keyStr) - done[keyStr] = struct{}{} - } - - // Make the field name - fieldName := fmt.Sprintf("%s.%s", name, keyStr) - - // Get the key/value as reflection values - key := reflect.ValueOf(keyStr) - val := reflect.Indirect(reflect.New(resultElemType)) - - // If we have a pre-existing value in the map, use that - oldVal := resultMap.MapIndex(key) - if oldVal.IsValid() { - val.Set(oldVal) - } - - // Decode! - if err := d.decode(fieldName, itemVal, val); err != nil { - return err - } - - // Set the value on the map - resultMap.SetMapIndex(key, val) - } - - // Set the final map if we can - set.Set(resultMap) - return nil -} - -func (d *decoder) decodePtr(name string, node ast.Node, result reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - resultType := result.Type() - resultElemType := resultType.Elem() - val := reflect.New(resultElemType) - if err := d.decode(name, node, reflect.Indirect(val)); err != nil { - return err - } - - result.Set(val) - return nil -} - -func (d *decoder) decodeSlice(name string, node ast.Node, result reflect.Value) error { - // If we have an interface, then we can address the interface, - // but not the slice itself, so get the element but set the interface - set := result - if result.Kind() == reflect.Interface { - result = result.Elem() - } - // Create the slice if it isn't nil - resultType := result.Type() - resultElemType := resultType.Elem() - if result.IsNil() { - resultSliceType := reflect.SliceOf(resultElemType) - result = reflect.MakeSlice( - resultSliceType, 0, 0) - } - - // Figure out the items we'll be copying into the slice - var items []ast.Node - switch n := node.(type) { - case *ast.ObjectList: - items = make([]ast.Node, len(n.Items)) - for i, item := range n.Items { - items[i] = item - } - case *ast.ObjectType: - items = []ast.Node{n} - case *ast.ListType: - items = n.List - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("unknown slice type: %T", node), - } - } - - for i, item := range items { - fieldName := fmt.Sprintf("%s[%d]", name, i) - - // Decode - val := reflect.Indirect(reflect.New(resultElemType)) - - // if item is an object that was decoded from ambiguous JSON and - // flattened, make sure it's expanded if it needs to decode into a - // defined structure. - item := expandObject(item, val) - - if err := d.decode(fieldName, item, val); err != nil { - return err - } - - // Append it onto the slice - result = reflect.Append(result, val) - } - - set.Set(result) - return nil -} - -// expandObject detects if an ambiguous JSON object was flattened to a List which -// should be decoded into a struct, and expands the ast to properly deocode. -func expandObject(node ast.Node, result reflect.Value) ast.Node { - item, ok := node.(*ast.ObjectItem) - if !ok { - return node - } - - elemType := result.Type() - - // our target type must be a struct - switch elemType.Kind() { - case reflect.Ptr: - switch elemType.Elem().Kind() { - case reflect.Struct: - //OK - default: - return node - } - case reflect.Struct: - //OK - default: - return node - } - - // A list value will have a key and field name. If it had more fields, - // it wouldn't have been flattened. - if len(item.Keys) != 2 { - return node - } - - keyToken := item.Keys[0].Token - item.Keys = item.Keys[1:] - - // we need to un-flatten the ast enough to decode - newNode := &ast.ObjectItem{ - Keys: []*ast.ObjectKey{ - &ast.ObjectKey{ - Token: keyToken, - }, - }, - Val: &ast.ObjectType{ - List: &ast.ObjectList{ - Items: []*ast.ObjectItem{item}, - }, - }, - } - - return newNode -} - -func (d *decoder) decodeString(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - switch n.Token.Type { - case token.NUMBER: - result.Set(reflect.ValueOf(n.Token.Text).Convert(result.Type())) - return nil - case token.STRING, token.HEREDOC: - result.Set(reflect.ValueOf(n.Token.Value()).Convert(result.Type())) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type for string %T", name, node), - } -} - -func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) error { - var item *ast.ObjectItem - if it, ok := node.(*ast.ObjectItem); ok { - item = it - node = it.Val - } - - if ot, ok := node.(*ast.ObjectType); ok { - node = ot.List - } - - // Handle the special case where the object itself is a literal. Previously - // the yacc parser would always ensure top-level elements were arrays. The new - // parser does not make the same guarantees, thus we need to convert any - // top-level literal elements into a list. - if _, ok := node.(*ast.LiteralType); ok && item != nil { - node = &ast.ObjectList{Items: []*ast.ObjectItem{item}} - } - - list, ok := node.(*ast.ObjectList) - if !ok { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: not an object type for struct (%T)", name, node), - } - } - - // This slice will keep track of all the structs we'll be decoding. - // There can be more than one struct if there are embedded structs - // that are squashed. - structs := make([]reflect.Value, 1, 5) - structs[0] = result - - // Compile the list of all the fields that we're going to be decoding - // from all the structs. - type field struct { - field reflect.StructField - val reflect.Value - } - fields := []field{} - for len(structs) > 0 { - structVal := structs[0] - structs = structs[1:] - - structType := structVal.Type() - for i := 0; i < structType.NumField(); i++ { - fieldType := structType.Field(i) - tagParts := strings.Split(fieldType.Tag.Get(tagName), ",") - - // Ignore fields with tag name "-" - if tagParts[0] == "-" { - continue - } - - if fieldType.Anonymous { - fieldKind := fieldType.Type.Kind() - if fieldKind != reflect.Struct { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unsupported type to struct: %s", - fieldType.Name, fieldKind), - } - } - - // We have an embedded field. We "squash" the fields down - // if specified in the tag. - squash := false - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - - if squash { - structs = append( - structs, result.FieldByName(fieldType.Name)) - continue - } - } - - // Normal struct field, store it away - fields = append(fields, field{fieldType, structVal.Field(i)}) - } - } - - usedKeys := make(map[string]struct{}) - decodedFields := make([]string, 0, len(fields)) - decodedFieldsVal := make([]reflect.Value, 0) - unusedKeysVal := make([]reflect.Value, 0) - for _, f := range fields { - field, fieldValue := f.field, f.val - if !fieldValue.IsValid() { - // This should never happen - panic("field is not valid") - } - - // If we can't set the field, then it is unexported or something, - // and we just continue onwards. - if !fieldValue.CanSet() { - continue - } - - fieldName := field.Name - - tagValue := field.Tag.Get(tagName) - tagParts := strings.SplitN(tagValue, ",", 2) - if len(tagParts) >= 2 { - switch tagParts[1] { - case "decodedFields": - decodedFieldsVal = append(decodedFieldsVal, fieldValue) - continue - case "key": - if item == nil { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: %s asked for 'key', impossible", - name, fieldName), - } - } - - fieldValue.SetString(item.Keys[0].Token.Value().(string)) - continue - case "unusedKeys": - unusedKeysVal = append(unusedKeysVal, fieldValue) - continue - } - } - - if tagParts[0] != "" { - fieldName = tagParts[0] - } - - // Determine the element we'll use to decode. If it is a single - // match (only object with the field), then we decode it exactly. - // If it is a prefix match, then we decode the matches. - filter := list.Filter(fieldName) - - prefixMatches := filter.Children() - matches := filter.Elem() - if len(matches.Items) == 0 && len(prefixMatches.Items) == 0 { - continue - } - - // Track the used key - usedKeys[fieldName] = struct{}{} - - // Create the field name and decode. We range over the elements - // because we actually want the value. - fieldName = fmt.Sprintf("%s.%s", name, fieldName) - if len(prefixMatches.Items) > 0 { - if err := d.decode(fieldName, prefixMatches, fieldValue); err != nil { - return err - } - } - for _, match := range matches.Items { - var decodeNode ast.Node = match.Val - if ot, ok := decodeNode.(*ast.ObjectType); ok { - decodeNode = &ast.ObjectList{Items: ot.List.Items} - } - - if err := d.decode(fieldName, decodeNode, fieldValue); err != nil { - return err - } - } - - decodedFields = append(decodedFields, field.Name) - } - - if len(decodedFieldsVal) > 0 { - // Sort it so that it is deterministic - sort.Strings(decodedFields) - - for _, v := range decodedFieldsVal { - v.Set(reflect.ValueOf(decodedFields)) - } - } - - return nil -} - -// findNodeType returns the type of ast.Node -func findNodeType() reflect.Type { - var nodeContainer struct { - Node ast.Node - } - value := reflect.ValueOf(nodeContainer).FieldByName("Node") - return value.Type() -} diff --git a/vendor/github.com/hashicorp/hcl/go.mod b/vendor/github.com/hashicorp/hcl/go.mod deleted file mode 100644 index 4debbbe3..00000000 --- a/vendor/github.com/hashicorp/hcl/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/hcl - -require github.com/davecgh/go-spew v1.1.1 diff --git a/vendor/github.com/hashicorp/hcl/go.sum b/vendor/github.com/hashicorp/hcl/go.sum deleted file mode 100644 index b5e2922e..00000000 --- a/vendor/github.com/hashicorp/hcl/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/vendor/github.com/hashicorp/hcl/hcl.go b/vendor/github.com/hashicorp/hcl/hcl.go deleted file mode 100644 index 575a20b5..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package hcl decodes HCL into usable Go structures. -// -// hcl input can come in either pure HCL format or JSON format. -// It can be parsed into an AST, and then decoded into a structure, -// or it can be decoded directly from a string into a structure. -// -// If you choose to parse HCL into a raw AST, the benefit is that you -// can write custom visitor implementations to implement custom -// semantic checks. By default, HCL does not perform any semantic -// checks. -package hcl diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go deleted file mode 100644 index 6e5ef654..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go +++ /dev/null @@ -1,219 +0,0 @@ -// Package ast declares the types used to represent syntax trees for HCL -// (HashiCorp Configuration Language) -package ast - -import ( - "fmt" - "strings" - - "github.com/hashicorp/hcl/hcl/token" -) - -// Node is an element in the abstract syntax tree. -type Node interface { - node() - Pos() token.Pos -} - -func (File) node() {} -func (ObjectList) node() {} -func (ObjectKey) node() {} -func (ObjectItem) node() {} -func (Comment) node() {} -func (CommentGroup) node() {} -func (ObjectType) node() {} -func (LiteralType) node() {} -func (ListType) node() {} - -// File represents a single HCL file -type File struct { - Node Node // usually a *ObjectList - Comments []*CommentGroup // list of all comments in the source -} - -func (f *File) Pos() token.Pos { - return f.Node.Pos() -} - -// ObjectList represents a list of ObjectItems. An HCL file itself is an -// ObjectList. -type ObjectList struct { - Items []*ObjectItem -} - -func (o *ObjectList) Add(item *ObjectItem) { - o.Items = append(o.Items, item) -} - -// Filter filters out the objects with the given key list as a prefix. -// -// The returned list of objects contain ObjectItems where the keys have -// this prefix already stripped off. This might result in objects with -// zero-length key lists if they have no children. -// -// If no matches are found, an empty ObjectList (non-nil) is returned. -func (o *ObjectList) Filter(keys ...string) *ObjectList { - var result ObjectList - for _, item := range o.Items { - // If there aren't enough keys, then ignore this - if len(item.Keys) < len(keys) { - continue - } - - match := true - for i, key := range item.Keys[:len(keys)] { - key := key.Token.Value().(string) - if key != keys[i] && !strings.EqualFold(key, keys[i]) { - match = false - break - } - } - if !match { - continue - } - - // Strip off the prefix from the children - newItem := *item - newItem.Keys = newItem.Keys[len(keys):] - result.Add(&newItem) - } - - return &result -} - -// Children returns further nested objects (key length > 0) within this -// ObjectList. This should be used with Filter to get at child items. -func (o *ObjectList) Children() *ObjectList { - var result ObjectList - for _, item := range o.Items { - if len(item.Keys) > 0 { - result.Add(item) - } - } - - return &result -} - -// Elem returns items in the list that are direct element assignments -// (key length == 0). This should be used with Filter to get at elements. -func (o *ObjectList) Elem() *ObjectList { - var result ObjectList - for _, item := range o.Items { - if len(item.Keys) == 0 { - result.Add(item) - } - } - - return &result -} - -func (o *ObjectList) Pos() token.Pos { - // always returns the uninitiliazed position - return o.Items[0].Pos() -} - -// ObjectItem represents a HCL Object Item. An item is represented with a key -// (or keys). It can be an assignment or an object (both normal and nested) -type ObjectItem struct { - // keys is only one length long if it's of type assignment. If it's a - // nested object it can be larger than one. In that case "assign" is - // invalid as there is no assignments for a nested object. - Keys []*ObjectKey - - // assign contains the position of "=", if any - Assign token.Pos - - // val is the item itself. It can be an object,list, number, bool or a - // string. If key length is larger than one, val can be only of type - // Object. - Val Node - - LeadComment *CommentGroup // associated lead comment - LineComment *CommentGroup // associated line comment -} - -func (o *ObjectItem) Pos() token.Pos { - // I'm not entirely sure what causes this, but removing this causes - // a test failure. We should investigate at some point. - if len(o.Keys) == 0 { - return token.Pos{} - } - - return o.Keys[0].Pos() -} - -// ObjectKeys are either an identifier or of type string. -type ObjectKey struct { - Token token.Token -} - -func (o *ObjectKey) Pos() token.Pos { - return o.Token.Pos -} - -// LiteralType represents a literal of basic type. Valid types are: -// token.NUMBER, token.FLOAT, token.BOOL and token.STRING -type LiteralType struct { - Token token.Token - - // comment types, only used when in a list - LeadComment *CommentGroup - LineComment *CommentGroup -} - -func (l *LiteralType) Pos() token.Pos { - return l.Token.Pos -} - -// ListStatement represents a HCL List type -type ListType struct { - Lbrack token.Pos // position of "[" - Rbrack token.Pos // position of "]" - List []Node // the elements in lexical order -} - -func (l *ListType) Pos() token.Pos { - return l.Lbrack -} - -func (l *ListType) Add(node Node) { - l.List = append(l.List, node) -} - -// ObjectType represents a HCL Object Type -type ObjectType struct { - Lbrace token.Pos // position of "{" - Rbrace token.Pos // position of "}" - List *ObjectList // the nodes in lexical order -} - -func (o *ObjectType) Pos() token.Pos { - return o.Lbrace -} - -// Comment node represents a single //, # style or /*- style commment -type Comment struct { - Start token.Pos // position of / or # - Text string -} - -func (c *Comment) Pos() token.Pos { - return c.Start -} - -// CommentGroup node represents a sequence of comments with no other tokens and -// no empty lines between. -type CommentGroup struct { - List []*Comment // len(List) > 0 -} - -func (c *CommentGroup) Pos() token.Pos { - return c.List[0].Pos() -} - -//------------------------------------------------------------------- -// GoStringer -//------------------------------------------------------------------- - -func (o *ObjectKey) GoString() string { return fmt.Sprintf("*%#v", *o) } -func (o *ObjectList) GoString() string { return fmt.Sprintf("*%#v", *o) } diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go b/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go deleted file mode 100644 index ba07ad42..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go +++ /dev/null @@ -1,52 +0,0 @@ -package ast - -import "fmt" - -// WalkFunc describes a function to be called for each node during a Walk. The -// returned node can be used to rewrite the AST. Walking stops the returned -// bool is false. -type WalkFunc func(Node) (Node, bool) - -// Walk traverses an AST in depth-first order: It starts by calling fn(node); -// node must not be nil. If fn returns true, Walk invokes fn recursively for -// each of the non-nil children of node, followed by a call of fn(nil). The -// returned node of fn can be used to rewrite the passed node to fn. -func Walk(node Node, fn WalkFunc) Node { - rewritten, ok := fn(node) - if !ok { - return rewritten - } - - switch n := node.(type) { - case *File: - n.Node = Walk(n.Node, fn) - case *ObjectList: - for i, item := range n.Items { - n.Items[i] = Walk(item, fn).(*ObjectItem) - } - case *ObjectKey: - // nothing to do - case *ObjectItem: - for i, k := range n.Keys { - n.Keys[i] = Walk(k, fn).(*ObjectKey) - } - - if n.Val != nil { - n.Val = Walk(n.Val, fn) - } - case *LiteralType: - // nothing to do - case *ListType: - for i, l := range n.List { - n.List[i] = Walk(l, fn) - } - case *ObjectType: - n.List = Walk(n.List, fn).(*ObjectList) - default: - // should we panic here? - fmt.Printf("unknown type: %T\n", n) - } - - fn(nil) - return rewritten -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error.go deleted file mode 100644 index 5c99381d..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go +++ /dev/null @@ -1,17 +0,0 @@ -package parser - -import ( - "fmt" - - "github.com/hashicorp/hcl/hcl/token" -) - -// PosError is a parse error that contains a position. -type PosError struct { - Pos token.Pos - Err error -} - -func (e *PosError) Error() string { - return fmt.Sprintf("At %s: %s", e.Pos, e.Err) -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go deleted file mode 100644 index 64c83bcf..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ /dev/null @@ -1,532 +0,0 @@ -// Package parser implements a parser for HCL (HashiCorp Configuration -// Language) -package parser - -import ( - "bytes" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/scanner" - "github.com/hashicorp/hcl/hcl/token" -) - -type Parser struct { - sc *scanner.Scanner - - // Last read token - tok token.Token - commaPrev token.Token - - comments []*ast.CommentGroup - leadComment *ast.CommentGroup // last lead comment - lineComment *ast.CommentGroup // last line comment - - enableTrace bool - indent int - n int // buffer size (max = 1) -} - -func newParser(src []byte) *Parser { - return &Parser{ - sc: scanner.New(src), - } -} - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func Parse(src []byte) (*ast.File, error) { - // normalize all line endings - // since the scanner and output only work with "\n" line endings, we may - // end up with dangling "\r" characters in the parsed data. - src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) - - p := newParser(src) - return p.Parse() -} - -var errEofToken = errors.New("EOF token found") - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func (p *Parser) Parse() (*ast.File, error) { - f := &ast.File{} - var err, scerr error - p.sc.Error = func(pos token.Pos, msg string) { - scerr = &PosError{Pos: pos, Err: errors.New(msg)} - } - - f.Node, err = p.objectList(false) - if scerr != nil { - return nil, scerr - } - if err != nil { - return nil, err - } - - f.Comments = p.comments - return f, nil -} - -// objectList parses a list of items within an object (generally k/v pairs). -// The parameter" obj" tells this whether to we are within an object (braces: -// '{', '}') or just at the top level. If we're within an object, we end -// at an RBRACE. -func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) { - defer un(trace(p, "ParseObjectList")) - node := &ast.ObjectList{} - - for { - if obj { - tok := p.scan() - p.unscan() - if tok.Type == token.RBRACE { - break - } - } - - n, err := p.objectItem() - if err == errEofToken { - break // we are finished - } - - // we don't return a nil node, because might want to use already - // collected items. - if err != nil { - return node, err - } - - node.Add(n) - - // object lists can be optionally comma-delimited e.g. when a list of maps - // is being expressed, so a comma is allowed here - it's simply consumed - tok := p.scan() - if tok.Type != token.COMMA { - p.unscan() - } - } - return node, nil -} - -func (p *Parser) consumeComment() (comment *ast.Comment, endline int) { - endline = p.tok.Pos.Line - - // count the endline if it's multiline comment, ie starting with /* - if len(p.tok.Text) > 1 && p.tok.Text[1] == '*' { - // don't use range here - no need to decode Unicode code points - for i := 0; i < len(p.tok.Text); i++ { - if p.tok.Text[i] == '\n' { - endline++ - } - } - } - - comment = &ast.Comment{Start: p.tok.Pos, Text: p.tok.Text} - p.tok = p.sc.Scan() - return -} - -func (p *Parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) { - var list []*ast.Comment - endline = p.tok.Pos.Line - - for p.tok.Type == token.COMMENT && p.tok.Pos.Line <= endline+n { - var comment *ast.Comment - comment, endline = p.consumeComment() - list = append(list, comment) - } - - // add comment group to the comments list - comments = &ast.CommentGroup{List: list} - p.comments = append(p.comments, comments) - - return -} - -// objectItem parses a single object item -func (p *Parser) objectItem() (*ast.ObjectItem, error) { - defer un(trace(p, "ParseObjectItem")) - - keys, err := p.objectKey() - if len(keys) > 0 && err == errEofToken { - // We ignore eof token here since it is an error if we didn't - // receive a value (but we did receive a key) for the item. - err = nil - } - if len(keys) > 0 && err != nil && p.tok.Type == token.RBRACE { - // This is a strange boolean statement, but what it means is: - // We have keys with no value, and we're likely in an object - // (since RBrace ends an object). For this, we set err to nil so - // we continue and get the error below of having the wrong value - // type. - err = nil - - // Reset the token type so we don't think it completed fine. See - // objectType which uses p.tok.Type to check if we're done with - // the object. - p.tok.Type = token.EOF - } - if err != nil { - return nil, err - } - - o := &ast.ObjectItem{ - Keys: keys, - } - - if p.leadComment != nil { - o.LeadComment = p.leadComment - p.leadComment = nil - } - - switch p.tok.Type { - case token.ASSIGN: - o.Assign = p.tok.Pos - o.Val, err = p.object() - if err != nil { - return nil, err - } - case token.LBRACE: - o.Val, err = p.objectType() - if err != nil { - return nil, err - } - default: - keyStr := make([]string, 0, len(keys)) - for _, k := range keys { - keyStr = append(keyStr, k.Token.Text) - } - - return nil, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf( - "key '%s' expected start of object ('{') or assignment ('=')", - strings.Join(keyStr, " ")), - } - } - - // key=#comment - // val - if p.lineComment != nil { - o.LineComment, p.lineComment = p.lineComment, nil - } - - // do a look-ahead for line comment - p.scan() - if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil { - o.LineComment = p.lineComment - p.lineComment = nil - } - p.unscan() - return o, nil -} - -// objectKey parses an object key and returns a ObjectKey AST -func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { - keyCount := 0 - keys := make([]*ast.ObjectKey, 0) - - for { - tok := p.scan() - switch tok.Type { - case token.EOF: - // It is very important to also return the keys here as well as - // the error. This is because we need to be able to tell if we - // did parse keys prior to finding the EOF, or if we just found - // a bare EOF. - return keys, errEofToken - case token.ASSIGN: - // assignment or object only, but not nested objects. this is not - // allowed: `foo bar = {}` - if keyCount > 1 { - return nil, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type), - } - } - - if keyCount == 0 { - return nil, &PosError{ - Pos: p.tok.Pos, - Err: errors.New("no object keys found!"), - } - } - - return keys, nil - case token.LBRACE: - var err error - - // If we have no keys, then it is a syntax error. i.e. {{}} is not - // allowed. - if len(keys) == 0 { - err = &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("expected: IDENT | STRING got: %s", p.tok.Type), - } - } - - // object - return keys, err - case token.IDENT, token.STRING: - keyCount++ - keys = append(keys, &ast.ObjectKey{Token: p.tok}) - case token.ILLEGAL: - return keys, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("illegal character"), - } - default: - return keys, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("expected: IDENT | STRING | ASSIGN | LBRACE got: %s", p.tok.Type), - } - } - } -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) object() (ast.Node, error) { - defer un(trace(p, "ParseType")) - tok := p.scan() - - switch tok.Type { - case token.NUMBER, token.FLOAT, token.BOOL, token.STRING, token.HEREDOC: - return p.literalType() - case token.LBRACE: - return p.objectType() - case token.LBRACK: - return p.listType() - case token.COMMENT: - // implement comment - case token.EOF: - return nil, errEofToken - } - - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("Unknown token: %+v", tok), - } -} - -// objectType parses an object type and returns a ObjectType AST -func (p *Parser) objectType() (*ast.ObjectType, error) { - defer un(trace(p, "ParseObjectType")) - - // we assume that the currently scanned token is a LBRACE - o := &ast.ObjectType{ - Lbrace: p.tok.Pos, - } - - l, err := p.objectList(true) - - // if we hit RBRACE, we are good to go (means we parsed all Items), if it's - // not a RBRACE, it's an syntax error and we just return it. - if err != nil && p.tok.Type != token.RBRACE { - return nil, err - } - - // No error, scan and expect the ending to be a brace - if tok := p.scan(); tok.Type != token.RBRACE { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("object expected closing RBRACE got: %s", tok.Type), - } - } - - o.List = l - o.Rbrace = p.tok.Pos // advanced via parseObjectList - return o, nil -} - -// listType parses a list type and returns a ListType AST -func (p *Parser) listType() (*ast.ListType, error) { - defer un(trace(p, "ParseListType")) - - // we assume that the currently scanned token is a LBRACK - l := &ast.ListType{ - Lbrack: p.tok.Pos, - } - - needComma := false - for { - tok := p.scan() - if needComma { - switch tok.Type { - case token.COMMA, token.RBRACK: - default: - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error parsing list, expected comma or list end, got: %s", - tok.Type), - } - } - } - switch tok.Type { - case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: - node, err := p.literalType() - if err != nil { - return nil, err - } - - // If there is a lead comment, apply it - if p.leadComment != nil { - node.LeadComment = p.leadComment - p.leadComment = nil - } - - l.Add(node) - needComma = true - case token.COMMA: - // get next list item or we are at the end - // do a look-ahead for line comment - p.scan() - if p.lineComment != nil && len(l.List) > 0 { - lit, ok := l.List[len(l.List)-1].(*ast.LiteralType) - if ok { - lit.LineComment = p.lineComment - l.List[len(l.List)-1] = lit - p.lineComment = nil - } - } - p.unscan() - - needComma = false - continue - case token.LBRACE: - // Looks like a nested object, so parse it out - node, err := p.objectType() - if err != nil { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error while trying to parse object within list: %s", err), - } - } - l.Add(node) - needComma = true - case token.LBRACK: - node, err := p.listType() - if err != nil { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error while trying to parse list within list: %s", err), - } - } - l.Add(node) - case token.RBRACK: - // finished - l.Rbrack = p.tok.Pos - return l, nil - default: - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("unexpected token while parsing list: %s", tok.Type), - } - } - } -} - -// literalType parses a literal type and returns a LiteralType AST -func (p *Parser) literalType() (*ast.LiteralType, error) { - defer un(trace(p, "ParseLiteral")) - - return &ast.LiteralType{ - Token: p.tok, - }, nil -} - -// scan returns the next token from the underlying scanner. If a token has -// been unscanned then read that instead. In the process, it collects any -// comment groups encountered, and remembers the last lead and line comments. -func (p *Parser) scan() token.Token { - // If we have a token on the buffer, then return it. - if p.n != 0 { - p.n = 0 - return p.tok - } - - // Otherwise read the next token from the scanner and Save it to the buffer - // in case we unscan later. - prev := p.tok - p.tok = p.sc.Scan() - - if p.tok.Type == token.COMMENT { - var comment *ast.CommentGroup - var endline int - - // fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n", - // p.tok.Pos.Line, prev.Pos.Line, endline) - if p.tok.Pos.Line == prev.Pos.Line { - // The comment is on same line as the previous token; it - // cannot be a lead comment but may be a line comment. - comment, endline = p.consumeCommentGroup(0) - if p.tok.Pos.Line != endline { - // The next token is on a different line, thus - // the last comment group is a line comment. - p.lineComment = comment - } - } - - // consume successor comments, if any - endline = -1 - for p.tok.Type == token.COMMENT { - comment, endline = p.consumeCommentGroup(1) - } - - if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE { - switch p.tok.Type { - case token.RBRACE, token.RBRACK: - // Do not count for these cases - default: - // The next token is following on the line immediately after the - // comment group, thus the last comment group is a lead comment. - p.leadComment = comment - } - } - - } - - return p.tok -} - -// unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { - p.n = 1 -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *Parser) printTrace(a ...interface{}) { - if !p.enableTrace { - return - } - - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column) - - i := 2 * p.indent - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *Parser, msg string) *Parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *Parser) { - p.indent-- - p.printTrace(")") -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go deleted file mode 100644 index 624a18fe..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go +++ /dev/null @@ -1,652 +0,0 @@ -// Package scanner implements a scanner for HCL (HashiCorp Configuration -// Language) source text. -package scanner - -import ( - "bytes" - "fmt" - "os" - "regexp" - "unicode" - "unicode/utf8" - - "github.com/hashicorp/hcl/hcl/token" -) - -// eof represents a marker rune for the end of the reader. -const eof = rune(0) - -// Scanner defines a lexical scanner -type Scanner struct { - buf *bytes.Buffer // Source buffer for advancing and scanning - src []byte // Source buffer for immutable access - - // Source Position - srcPos token.Pos // current position - prevPos token.Pos // previous position, used for peek() method - - lastCharLen int // length of last character in bytes - lastLineLen int // length of last line in characters (for correct column reporting) - - tokStart int // token text start position - tokEnd int // token text end position - - // Error is called for each error encountered. If no Error - // function is set, the error is reported to os.Stderr. - Error func(pos token.Pos, msg string) - - // ErrorCount is incremented by one for each error encountered. - ErrorCount int - - // tokPos is the start position of most recently scanned token; set by - // Scan. The Filename field is always left untouched by the Scanner. If - // an error is reported (via Error) and Position is invalid, the scanner is - // not inside a token. - tokPos token.Pos -} - -// New creates and initializes a new instance of Scanner using src as -// its source content. -func New(src []byte) *Scanner { - // even though we accept a src, we read from a io.Reader compatible type - // (*bytes.Buffer). So in the future we might easily change it to streaming - // read. - b := bytes.NewBuffer(src) - s := &Scanner{ - buf: b, - src: src, - } - - // srcPosition always starts with 1 - s.srcPos.Line = 1 - return s -} - -// next reads the next rune from the bufferred reader. Returns the rune(0) if -// an error occurs (or io.EOF is returned). -func (s *Scanner) next() rune { - ch, size, err := s.buf.ReadRune() - if err != nil { - // advance for error reporting - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - return eof - } - - // remember last position - s.prevPos = s.srcPos - - s.srcPos.Column++ - s.lastCharLen = size - s.srcPos.Offset += size - - if ch == utf8.RuneError && size == 1 { - s.err("illegal UTF-8 encoding") - return ch - } - - if ch == '\n' { - s.srcPos.Line++ - s.lastLineLen = s.srcPos.Column - s.srcPos.Column = 0 - } - - if ch == '\x00' { - s.err("unexpected null character (0x00)") - return eof - } - - if ch == '\uE123' { - s.err("unicode code point U+E123 reserved for internal use") - return utf8.RuneError - } - - // debug - // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) - return ch -} - -// unread unreads the previous read Rune and updates the source position -func (s *Scanner) unread() { - if err := s.buf.UnreadRune(); err != nil { - panic(err) // this is user fault, we should catch it - } - s.srcPos = s.prevPos // put back last position -} - -// peek returns the next rune without advancing the reader. -func (s *Scanner) peek() rune { - peek, _, err := s.buf.ReadRune() - if err != nil { - return eof - } - - s.buf.UnreadRune() - return peek -} - -// Scan scans the next token and returns the token. -func (s *Scanner) Scan() token.Token { - ch := s.next() - - // skip white space - for isWhitespace(ch) { - ch = s.next() - } - - var tok token.Type - - // token text markings - s.tokStart = s.srcPos.Offset - s.lastCharLen - - // token position, initial next() is moving the offset by one(size of rune - // actually), though we are interested with the starting point - s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen - if s.srcPos.Column > 0 { - // common case: last character was not a '\n' - s.tokPos.Line = s.srcPos.Line - s.tokPos.Column = s.srcPos.Column - } else { - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - s.tokPos.Line = s.srcPos.Line - 1 - s.tokPos.Column = s.lastLineLen - } - - switch { - case isLetter(ch): - tok = token.IDENT - lit := s.scanIdentifier() - if lit == "true" || lit == "false" { - tok = token.BOOL - } - case isDecimal(ch): - tok = s.scanNumber(ch) - default: - switch ch { - case eof: - tok = token.EOF - case '"': - tok = token.STRING - s.scanString() - case '#', '/': - tok = token.COMMENT - s.scanComment(ch) - case '.': - tok = token.PERIOD - ch = s.peek() - if isDecimal(ch) { - tok = token.FLOAT - ch = s.scanMantissa(ch) - ch = s.scanExponent(ch) - } - case '<': - tok = token.HEREDOC - s.scanHeredoc() - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case '{': - tok = token.LBRACE - case '}': - tok = token.RBRACE - case ',': - tok = token.COMMA - case '=': - tok = token.ASSIGN - case '+': - tok = token.ADD - case '-': - if isDecimal(s.peek()) { - ch := s.next() - tok = s.scanNumber(ch) - } else { - tok = token.SUB - } - default: - s.err("illegal char") - } - } - - // finish token ending - s.tokEnd = s.srcPos.Offset - - // create token literal - var tokenText string - if s.tokStart >= 0 { - tokenText = string(s.src[s.tokStart:s.tokEnd]) - } - s.tokStart = s.tokEnd // ensure idempotency of tokenText() call - - return token.Token{ - Type: tok, - Pos: s.tokPos, - Text: tokenText, - } -} - -func (s *Scanner) scanComment(ch rune) { - // single line comments - if ch == '#' || (ch == '/' && s.peek() != '*') { - if ch == '/' && s.peek() != '/' { - s.err("expected '/' for comment") - return - } - - ch = s.next() - for ch != '\n' && ch >= 0 && ch != eof { - ch = s.next() - } - if ch != eof && ch >= 0 { - s.unread() - } - return - } - - // be sure we get the character after /* This allows us to find comment's - // that are not erminated - if ch == '/' { - s.next() - ch = s.next() // read character after "/*" - } - - // look for /* - style comments - for { - if ch < 0 || ch == eof { - s.err("comment not terminated") - break - } - - ch0 := ch - ch = s.next() - if ch0 == '*' && ch == '/' { - break - } - } -} - -// scanNumber scans a HCL number definition starting with the given rune -func (s *Scanner) scanNumber(ch rune) token.Type { - if ch == '0' { - // check for hexadecimal, octal or float - ch = s.next() - if ch == 'x' || ch == 'X' { - // hexadecimal - ch = s.next() - found := false - for isHexadecimal(ch) { - ch = s.next() - found = true - } - - if !found { - s.err("illegal hexadecimal number") - } - - if ch != eof { - s.unread() - } - - return token.NUMBER - } - - // now it's either something like: 0421(octal) or 0.1231(float) - illegalOctal := false - for isDecimal(ch) { - ch = s.next() - if ch == '8' || ch == '9' { - // this is just a possibility. For example 0159 is illegal, but - // 0159.23 is valid. So we mark a possible illegal octal. If - // the next character is not a period, we'll print the error. - illegalOctal = true - } - } - - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if illegalOctal { - s.err("illegal octal number") - } - - if ch != eof { - s.unread() - } - return token.NUMBER - } - - s.scanMantissa(ch) - ch = s.next() // seek forward - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if ch != eof { - s.unread() - } - return token.NUMBER -} - -// scanMantissa scans the mantissa beginning from the rune. It returns the next -// non decimal rune. It's used to determine wheter it's a fraction or exponent. -func (s *Scanner) scanMantissa(ch rune) rune { - scanned := false - for isDecimal(ch) { - ch = s.next() - scanned = true - } - - if scanned && ch != eof { - s.unread() - } - return ch -} - -// scanFraction scans the fraction after the '.' rune -func (s *Scanner) scanFraction(ch rune) rune { - if ch == '.' { - ch = s.peek() // we peek just to see if we can move forward - ch = s.scanMantissa(ch) - } - return ch -} - -// scanExponent scans the remaining parts of an exponent after the 'e' or 'E' -// rune. -func (s *Scanner) scanExponent(ch rune) rune { - if ch == 'e' || ch == 'E' { - ch = s.next() - if ch == '-' || ch == '+' { - ch = s.next() - } - ch = s.scanMantissa(ch) - } - return ch -} - -// scanHeredoc scans a heredoc string -func (s *Scanner) scanHeredoc() { - // Scan the second '<' in example: '<= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) { - break - } - - // Not an anchor match, record the start of a new line - lineStart = s.srcPos.Offset - } - - if ch == eof { - s.err("heredoc not terminated") - return - } - } - - return -} - -// scanString scans a quoted string -func (s *Scanner) scanString() { - braces := 0 - for { - // '"' opening already consumed - // read character after quote - ch := s.next() - - if (ch == '\n' && braces == 0) || ch < 0 || ch == eof { - s.err("literal not terminated") - return - } - - if ch == '"' && braces == 0 { - break - } - - // If we're going into a ${} then we can ignore quotes for awhile - if braces == 0 && ch == '$' && s.peek() == '{' { - braces++ - s.next() - } else if braces > 0 && ch == '{' { - braces++ - } - if braces > 0 && ch == '}' { - braces-- - } - - if ch == '\\' { - s.scanEscape() - } - } - - return -} - -// scanEscape scans an escape sequence -func (s *Scanner) scanEscape() rune { - // http://en.cppreference.com/w/cpp/language/escape - ch := s.next() // read character after '/' - switch ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': - // nothing to do - case '0', '1', '2', '3', '4', '5', '6', '7': - // octal notation - ch = s.scanDigits(ch, 8, 3) - case 'x': - // hexademical notation - ch = s.scanDigits(s.next(), 16, 2) - case 'u': - // universal character name - ch = s.scanDigits(s.next(), 16, 4) - case 'U': - // universal character name - ch = s.scanDigits(s.next(), 16, 8) - default: - s.err("illegal char escape") - } - return ch -} - -// scanDigits scans a rune with the given base for n times. For example an -// octal notation \184 would yield in scanDigits(ch, 8, 3) -func (s *Scanner) scanDigits(ch rune, base, n int) rune { - start := n - for n > 0 && digitVal(ch) < base { - ch = s.next() - if ch == eof { - // If we see an EOF, we halt any more scanning of digits - // immediately. - break - } - - n-- - } - if n > 0 { - s.err("illegal char escape") - } - - if n != start && ch != eof { - // we scanned all digits, put the last non digit char back, - // only if we read anything at all - s.unread() - } - - return ch -} - -// scanIdentifier scans an identifier and returns the literal string -func (s *Scanner) scanIdentifier() string { - offs := s.srcPos.Offset - s.lastCharLen - ch := s.next() - for isLetter(ch) || isDigit(ch) || ch == '-' || ch == '.' { - ch = s.next() - } - - if ch != eof { - s.unread() // we got identifier, put back latest char - } - - return string(s.src[offs:s.srcPos.Offset]) -} - -// recentPosition returns the position of the character immediately after the -// character or token returned by the last call to Scan. -func (s *Scanner) recentPosition() (pos token.Pos) { - pos.Offset = s.srcPos.Offset - s.lastCharLen - switch { - case s.srcPos.Column > 0: - // common case: last character was not a '\n' - pos.Line = s.srcPos.Line - pos.Column = s.srcPos.Column - case s.lastLineLen > 0: - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - pos.Line = s.srcPos.Line - 1 - pos.Column = s.lastLineLen - default: - // at the beginning of the source - pos.Line = 1 - pos.Column = 1 - } - return -} - -// err prints the error of any scanning to s.Error function. If the function is -// not defined, by default it prints them to os.Stderr -func (s *Scanner) err(msg string) { - s.ErrorCount++ - pos := s.recentPosition() - - if s.Error != nil { - s.Error(pos, msg) - return - } - - fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) -} - -// isHexadecimal returns true if the given rune is a letter -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - -// isDigit returns true if the given rune is a decimal digit -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -// isDecimal returns true if the given rune is a decimal number -func isDecimal(ch rune) bool { - return '0' <= ch && ch <= '9' -} - -// isHexadecimal returns true if the given rune is an hexadecimal number -func isHexadecimal(ch rune) bool { - return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F' -} - -// isWhitespace returns true if the rune is a space, tab, newline or carriage return -func isWhitespace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' -} - -// digitVal returns the integer value of a given octal,decimal or hexadecimal rune -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go deleted file mode 100644 index 5f981eaa..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go +++ /dev/null @@ -1,241 +0,0 @@ -package strconv - -import ( - "errors" - "unicode/utf8" -) - -// ErrSyntax indicates that a value does not have the right syntax for the target type. -var ErrSyntax = errors.New("invalid syntax") - -// Unquote interprets s as a single-quoted, double-quoted, -// or backquoted Go string literal, returning the string value -// that s quotes. (If s is single-quoted, it would be a Go -// character literal; Unquote returns the corresponding -// one-character string.) -func Unquote(s string) (t string, err error) { - n := len(s) - if n < 2 { - return "", ErrSyntax - } - quote := s[0] - if quote != s[n-1] { - return "", ErrSyntax - } - s = s[1 : n-1] - - if quote != '"' { - return "", ErrSyntax - } - if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') { - return "", ErrSyntax - } - - // Is it trivial? Avoid allocation. - if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') { - switch quote { - case '"': - return s, nil - case '\'': - r, size := utf8.DecodeRuneInString(s) - if size == len(s) && (r != utf8.RuneError || size != 1) { - return s, nil - } - } - } - - var runeTmp [utf8.UTFMax]byte - buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations. - for len(s) > 0 { - // If we're starting a '${}' then let it through un-unquoted. - // Specifically: we don't unquote any characters within the `${}` - // section. - if s[0] == '$' && len(s) > 1 && s[1] == '{' { - buf = append(buf, '$', '{') - s = s[2:] - - // Continue reading until we find the closing brace, copying as-is - braces := 1 - for len(s) > 0 && braces > 0 { - r, size := utf8.DecodeRuneInString(s) - if r == utf8.RuneError { - return "", ErrSyntax - } - - s = s[size:] - - n := utf8.EncodeRune(runeTmp[:], r) - buf = append(buf, runeTmp[:n]...) - - switch r { - case '{': - braces++ - case '}': - braces-- - } - } - if braces != 0 { - return "", ErrSyntax - } - if len(s) == 0 { - // If there's no string left, we're done! - break - } else { - // If there's more left, we need to pop back up to the top of the loop - // in case there's another interpolation in this string. - continue - } - } - - if s[0] == '\n' { - return "", ErrSyntax - } - - c, multibyte, ss, err := unquoteChar(s, quote) - if err != nil { - return "", err - } - s = ss - if c < utf8.RuneSelf || !multibyte { - buf = append(buf, byte(c)) - } else { - n := utf8.EncodeRune(runeTmp[:], c) - buf = append(buf, runeTmp[:n]...) - } - if quote == '\'' && len(s) != 0 { - // single-quoted must be single character - return "", ErrSyntax - } - } - return string(buf), nil -} - -// contains reports whether the string contains the byte c. -func contains(s string, c byte) bool { - for i := 0; i < len(s); i++ { - if s[i] == c { - return true - } - } - return false -} - -func unhex(b byte) (v rune, ok bool) { - c := rune(b) - switch { - case '0' <= c && c <= '9': - return c - '0', true - case 'a' <= c && c <= 'f': - return c - 'a' + 10, true - case 'A' <= c && c <= 'F': - return c - 'A' + 10, true - } - return -} - -func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) { - // easy cases - switch c := s[0]; { - case c == quote && (quote == '\'' || quote == '"'): - err = ErrSyntax - return - case c >= utf8.RuneSelf: - r, size := utf8.DecodeRuneInString(s) - return r, true, s[size:], nil - case c != '\\': - return rune(s[0]), false, s[1:], nil - } - - // hard case: c is backslash - if len(s) <= 1 { - err = ErrSyntax - return - } - c := s[1] - s = s[2:] - - switch c { - case 'a': - value = '\a' - case 'b': - value = '\b' - case 'f': - value = '\f' - case 'n': - value = '\n' - case 'r': - value = '\r' - case 't': - value = '\t' - case 'v': - value = '\v' - case 'x', 'u', 'U': - n := 0 - switch c { - case 'x': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - var v rune - if len(s) < n { - err = ErrSyntax - return - } - for j := 0; j < n; j++ { - x, ok := unhex(s[j]) - if !ok { - err = ErrSyntax - return - } - v = v<<4 | x - } - s = s[n:] - if c == 'x' { - // single-byte string, possibly not UTF-8 - value = v - break - } - if v > utf8.MaxRune { - err = ErrSyntax - return - } - value = v - multibyte = true - case '0', '1', '2', '3', '4', '5', '6', '7': - v := rune(c) - '0' - if len(s) < 2 { - err = ErrSyntax - return - } - for j := 0; j < 2; j++ { // one digit already; two more - x := rune(s[j]) - '0' - if x < 0 || x > 7 { - err = ErrSyntax - return - } - v = (v << 3) | x - } - s = s[2:] - if v > 255 { - err = ErrSyntax - return - } - value = v - case '\\': - value = '\\' - case '\'', '"': - if c != quote { - err = ErrSyntax - return - } - value = rune(c) - default: - err = ErrSyntax - return - } - tail = s - return -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/position.go b/vendor/github.com/hashicorp/hcl/hcl/token/position.go deleted file mode 100644 index 59c1bb72..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/token/position.go +++ /dev/null @@ -1,46 +0,0 @@ -package token - -import "fmt" - -// Pos describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -type Pos struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (p *Pos) IsValid() bool { return p.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -func (p Pos) String() string { - s := p.Filename - if p.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", p.Line, p.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Before reports whether the position p is before u. -func (p Pos) Before(u Pos) bool { - return u.Offset > p.Offset || u.Line > p.Line -} - -// After reports whether the position p is after u. -func (p Pos) After(u Pos) bool { - return u.Offset < p.Offset || u.Line < p.Line -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/token.go b/vendor/github.com/hashicorp/hcl/hcl/token/token.go deleted file mode 100644 index e37c0664..00000000 --- a/vendor/github.com/hashicorp/hcl/hcl/token/token.go +++ /dev/null @@ -1,219 +0,0 @@ -// Package token defines constants representing the lexical tokens for HCL -// (HashiCorp Configuration Language) -package token - -import ( - "fmt" - "strconv" - "strings" - - hclstrconv "github.com/hashicorp/hcl/hcl/strconv" -) - -// Token defines a single HCL token which can be obtained via the Scanner -type Token struct { - Type Type - Pos Pos - Text string - JSON bool -} - -// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) -type Type int - -const ( - // Special tokens - ILLEGAL Type = iota - EOF - COMMENT - - identifier_beg - IDENT // literals - literal_beg - NUMBER // 12345 - FLOAT // 123.45 - BOOL // true,false - STRING // "abc" - HEREDOC // < 0 { - // Pop the current item - n := len(frontier) - item := frontier[n-1] - frontier = frontier[:n-1] - - switch v := item.Val.(type) { - case *ast.ObjectType: - items, frontier = flattenObjectType(v, item, items, frontier) - case *ast.ListType: - items, frontier = flattenListType(v, item, items, frontier) - default: - items = append(items, item) - } - } - - // Reverse the list since the frontier model runs things backwards - for i := len(items)/2 - 1; i >= 0; i-- { - opp := len(items) - 1 - i - items[i], items[opp] = items[opp], items[i] - } - - // Done! Set the original items - list.Items = items - return n, true - }) -} - -func flattenListType( - ot *ast.ListType, - item *ast.ObjectItem, - items []*ast.ObjectItem, - frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { - // If the list is empty, keep the original list - if len(ot.List) == 0 { - items = append(items, item) - return items, frontier - } - - // All the elements of this object must also be objects! - for _, subitem := range ot.List { - if _, ok := subitem.(*ast.ObjectType); !ok { - items = append(items, item) - return items, frontier - } - } - - // Great! We have a match go through all the items and flatten - for _, elem := range ot.List { - // Add it to the frontier so that we can recurse - frontier = append(frontier, &ast.ObjectItem{ - Keys: item.Keys, - Assign: item.Assign, - Val: elem, - LeadComment: item.LeadComment, - LineComment: item.LineComment, - }) - } - - return items, frontier -} - -func flattenObjectType( - ot *ast.ObjectType, - item *ast.ObjectItem, - items []*ast.ObjectItem, - frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { - // If the list has no items we do not have to flatten anything - if ot.List.Items == nil { - items = append(items, item) - return items, frontier - } - - // All the elements of this object must also be objects! - for _, subitem := range ot.List.Items { - if _, ok := subitem.Val.(*ast.ObjectType); !ok { - items = append(items, item) - return items, frontier - } - } - - // Great! We have a match go through all the items and flatten - for _, subitem := range ot.List.Items { - // Copy the new key - keys := make([]*ast.ObjectKey, len(item.Keys)+len(subitem.Keys)) - copy(keys, item.Keys) - copy(keys[len(item.Keys):], subitem.Keys) - - // Add it to the frontier so that we can recurse - frontier = append(frontier, &ast.ObjectItem{ - Keys: keys, - Assign: item.Assign, - Val: subitem.Val, - LeadComment: item.LeadComment, - LineComment: item.LineComment, - }) - } - - return items, frontier -} diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go deleted file mode 100644 index 125a5f07..00000000 --- a/vendor/github.com/hashicorp/hcl/json/parser/parser.go +++ /dev/null @@ -1,313 +0,0 @@ -package parser - -import ( - "errors" - "fmt" - - "github.com/hashicorp/hcl/hcl/ast" - hcltoken "github.com/hashicorp/hcl/hcl/token" - "github.com/hashicorp/hcl/json/scanner" - "github.com/hashicorp/hcl/json/token" -) - -type Parser struct { - sc *scanner.Scanner - - // Last read token - tok token.Token - commaPrev token.Token - - enableTrace bool - indent int - n int // buffer size (max = 1) -} - -func newParser(src []byte) *Parser { - return &Parser{ - sc: scanner.New(src), - } -} - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func Parse(src []byte) (*ast.File, error) { - p := newParser(src) - return p.Parse() -} - -var errEofToken = errors.New("EOF token found") - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func (p *Parser) Parse() (*ast.File, error) { - f := &ast.File{} - var err, scerr error - p.sc.Error = func(pos token.Pos, msg string) { - scerr = fmt.Errorf("%s: %s", pos, msg) - } - - // The root must be an object in JSON - object, err := p.object() - if scerr != nil { - return nil, scerr - } - if err != nil { - return nil, err - } - - // We make our final node an object list so it is more HCL compatible - f.Node = object.List - - // Flatten it, which finds patterns and turns them into more HCL-like - // AST trees. - flattenObjects(f.Node) - - return f, nil -} - -func (p *Parser) objectList() (*ast.ObjectList, error) { - defer un(trace(p, "ParseObjectList")) - node := &ast.ObjectList{} - - for { - n, err := p.objectItem() - if err == errEofToken { - break // we are finished - } - - // we don't return a nil node, because might want to use already - // collected items. - if err != nil { - return node, err - } - - node.Add(n) - - // Check for a followup comma. If it isn't a comma, then we're done - if tok := p.scan(); tok.Type != token.COMMA { - break - } - } - - return node, nil -} - -// objectItem parses a single object item -func (p *Parser) objectItem() (*ast.ObjectItem, error) { - defer un(trace(p, "ParseObjectItem")) - - keys, err := p.objectKey() - if err != nil { - return nil, err - } - - o := &ast.ObjectItem{ - Keys: keys, - } - - switch p.tok.Type { - case token.COLON: - pos := p.tok.Pos - o.Assign = hcltoken.Pos{ - Filename: pos.Filename, - Offset: pos.Offset, - Line: pos.Line, - Column: pos.Column, - } - - o.Val, err = p.objectValue() - if err != nil { - return nil, err - } - } - - return o, nil -} - -// objectKey parses an object key and returns a ObjectKey AST -func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { - keyCount := 0 - keys := make([]*ast.ObjectKey, 0) - - for { - tok := p.scan() - switch tok.Type { - case token.EOF: - return nil, errEofToken - case token.STRING: - keyCount++ - keys = append(keys, &ast.ObjectKey{ - Token: p.tok.HCLToken(), - }) - case token.COLON: - // If we have a zero keycount it means that we never got - // an object key, i.e. `{ :`. This is a syntax error. - if keyCount == 0 { - return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type) - } - - // Done - return keys, nil - case token.ILLEGAL: - return nil, errors.New("illegal") - default: - return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type) - } - } -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) objectValue() (ast.Node, error) { - defer un(trace(p, "ParseObjectValue")) - tok := p.scan() - - switch tok.Type { - case token.NUMBER, token.FLOAT, token.BOOL, token.NULL, token.STRING: - return p.literalType() - case token.LBRACE: - return p.objectType() - case token.LBRACK: - return p.listType() - case token.EOF: - return nil, errEofToken - } - - return nil, fmt.Errorf("Expected object value, got unknown token: %+v", tok) -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) object() (*ast.ObjectType, error) { - defer un(trace(p, "ParseType")) - tok := p.scan() - - switch tok.Type { - case token.LBRACE: - return p.objectType() - case token.EOF: - return nil, errEofToken - } - - return nil, fmt.Errorf("Expected object, got unknown token: %+v", tok) -} - -// objectType parses an object type and returns a ObjectType AST -func (p *Parser) objectType() (*ast.ObjectType, error) { - defer un(trace(p, "ParseObjectType")) - - // we assume that the currently scanned token is a LBRACE - o := &ast.ObjectType{} - - l, err := p.objectList() - - // if we hit RBRACE, we are good to go (means we parsed all Items), if it's - // not a RBRACE, it's an syntax error and we just return it. - if err != nil && p.tok.Type != token.RBRACE { - return nil, err - } - - o.List = l - return o, nil -} - -// listType parses a list type and returns a ListType AST -func (p *Parser) listType() (*ast.ListType, error) { - defer un(trace(p, "ParseListType")) - - // we assume that the currently scanned token is a LBRACK - l := &ast.ListType{} - - for { - tok := p.scan() - switch tok.Type { - case token.NUMBER, token.FLOAT, token.STRING: - node, err := p.literalType() - if err != nil { - return nil, err - } - - l.Add(node) - case token.COMMA: - continue - case token.LBRACE: - node, err := p.objectType() - if err != nil { - return nil, err - } - - l.Add(node) - case token.BOOL: - // TODO(arslan) should we support? not supported by HCL yet - case token.LBRACK: - // TODO(arslan) should we support nested lists? Even though it's - // written in README of HCL, it's not a part of the grammar - // (not defined in parse.y) - case token.RBRACK: - // finished - return l, nil - default: - return nil, fmt.Errorf("unexpected token while parsing list: %s", tok.Type) - } - - } -} - -// literalType parses a literal type and returns a LiteralType AST -func (p *Parser) literalType() (*ast.LiteralType, error) { - defer un(trace(p, "ParseLiteral")) - - return &ast.LiteralType{ - Token: p.tok.HCLToken(), - }, nil -} - -// scan returns the next token from the underlying scanner. If a token has -// been unscanned then read that instead. -func (p *Parser) scan() token.Token { - // If we have a token on the buffer, then return it. - if p.n != 0 { - p.n = 0 - return p.tok - } - - p.tok = p.sc.Scan() - return p.tok -} - -// unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { - p.n = 1 -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *Parser) printTrace(a ...interface{}) { - if !p.enableTrace { - return - } - - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column) - - i := 2 * p.indent - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *Parser, msg string) *Parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *Parser) { - p.indent-- - p.printTrace(")") -} diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go deleted file mode 100644 index fe3f0f09..00000000 --- a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go +++ /dev/null @@ -1,451 +0,0 @@ -package scanner - -import ( - "bytes" - "fmt" - "os" - "unicode" - "unicode/utf8" - - "github.com/hashicorp/hcl/json/token" -) - -// eof represents a marker rune for the end of the reader. -const eof = rune(0) - -// Scanner defines a lexical scanner -type Scanner struct { - buf *bytes.Buffer // Source buffer for advancing and scanning - src []byte // Source buffer for immutable access - - // Source Position - srcPos token.Pos // current position - prevPos token.Pos // previous position, used for peek() method - - lastCharLen int // length of last character in bytes - lastLineLen int // length of last line in characters (for correct column reporting) - - tokStart int // token text start position - tokEnd int // token text end position - - // Error is called for each error encountered. If no Error - // function is set, the error is reported to os.Stderr. - Error func(pos token.Pos, msg string) - - // ErrorCount is incremented by one for each error encountered. - ErrorCount int - - // tokPos is the start position of most recently scanned token; set by - // Scan. The Filename field is always left untouched by the Scanner. If - // an error is reported (via Error) and Position is invalid, the scanner is - // not inside a token. - tokPos token.Pos -} - -// New creates and initializes a new instance of Scanner using src as -// its source content. -func New(src []byte) *Scanner { - // even though we accept a src, we read from a io.Reader compatible type - // (*bytes.Buffer). So in the future we might easily change it to streaming - // read. - b := bytes.NewBuffer(src) - s := &Scanner{ - buf: b, - src: src, - } - - // srcPosition always starts with 1 - s.srcPos.Line = 1 - return s -} - -// next reads the next rune from the bufferred reader. Returns the rune(0) if -// an error occurs (or io.EOF is returned). -func (s *Scanner) next() rune { - ch, size, err := s.buf.ReadRune() - if err != nil { - // advance for error reporting - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - return eof - } - - if ch == utf8.RuneError && size == 1 { - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - s.err("illegal UTF-8 encoding") - return ch - } - - // remember last position - s.prevPos = s.srcPos - - s.srcPos.Column++ - s.lastCharLen = size - s.srcPos.Offset += size - - if ch == '\n' { - s.srcPos.Line++ - s.lastLineLen = s.srcPos.Column - s.srcPos.Column = 0 - } - - // debug - // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) - return ch -} - -// unread unreads the previous read Rune and updates the source position -func (s *Scanner) unread() { - if err := s.buf.UnreadRune(); err != nil { - panic(err) // this is user fault, we should catch it - } - s.srcPos = s.prevPos // put back last position -} - -// peek returns the next rune without advancing the reader. -func (s *Scanner) peek() rune { - peek, _, err := s.buf.ReadRune() - if err != nil { - return eof - } - - s.buf.UnreadRune() - return peek -} - -// Scan scans the next token and returns the token. -func (s *Scanner) Scan() token.Token { - ch := s.next() - - // skip white space - for isWhitespace(ch) { - ch = s.next() - } - - var tok token.Type - - // token text markings - s.tokStart = s.srcPos.Offset - s.lastCharLen - - // token position, initial next() is moving the offset by one(size of rune - // actually), though we are interested with the starting point - s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen - if s.srcPos.Column > 0 { - // common case: last character was not a '\n' - s.tokPos.Line = s.srcPos.Line - s.tokPos.Column = s.srcPos.Column - } else { - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - s.tokPos.Line = s.srcPos.Line - 1 - s.tokPos.Column = s.lastLineLen - } - - switch { - case isLetter(ch): - lit := s.scanIdentifier() - if lit == "true" || lit == "false" { - tok = token.BOOL - } else if lit == "null" { - tok = token.NULL - } else { - s.err("illegal char") - } - case isDecimal(ch): - tok = s.scanNumber(ch) - default: - switch ch { - case eof: - tok = token.EOF - case '"': - tok = token.STRING - s.scanString() - case '.': - tok = token.PERIOD - ch = s.peek() - if isDecimal(ch) { - tok = token.FLOAT - ch = s.scanMantissa(ch) - ch = s.scanExponent(ch) - } - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case '{': - tok = token.LBRACE - case '}': - tok = token.RBRACE - case ',': - tok = token.COMMA - case ':': - tok = token.COLON - case '-': - if isDecimal(s.peek()) { - ch := s.next() - tok = s.scanNumber(ch) - } else { - s.err("illegal char") - } - default: - s.err("illegal char: " + string(ch)) - } - } - - // finish token ending - s.tokEnd = s.srcPos.Offset - - // create token literal - var tokenText string - if s.tokStart >= 0 { - tokenText = string(s.src[s.tokStart:s.tokEnd]) - } - s.tokStart = s.tokEnd // ensure idempotency of tokenText() call - - return token.Token{ - Type: tok, - Pos: s.tokPos, - Text: tokenText, - } -} - -// scanNumber scans a HCL number definition starting with the given rune -func (s *Scanner) scanNumber(ch rune) token.Type { - zero := ch == '0' - pos := s.srcPos - - s.scanMantissa(ch) - ch = s.next() // seek forward - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if ch != eof { - s.unread() - } - - // If we have a larger number and this is zero, error - if zero && pos != s.srcPos { - s.err("numbers cannot start with 0") - } - - return token.NUMBER -} - -// scanMantissa scans the mantissa beginning from the rune. It returns the next -// non decimal rune. It's used to determine wheter it's a fraction or exponent. -func (s *Scanner) scanMantissa(ch rune) rune { - scanned := false - for isDecimal(ch) { - ch = s.next() - scanned = true - } - - if scanned && ch != eof { - s.unread() - } - return ch -} - -// scanFraction scans the fraction after the '.' rune -func (s *Scanner) scanFraction(ch rune) rune { - if ch == '.' { - ch = s.peek() // we peek just to see if we can move forward - ch = s.scanMantissa(ch) - } - return ch -} - -// scanExponent scans the remaining parts of an exponent after the 'e' or 'E' -// rune. -func (s *Scanner) scanExponent(ch rune) rune { - if ch == 'e' || ch == 'E' { - ch = s.next() - if ch == '-' || ch == '+' { - ch = s.next() - } - ch = s.scanMantissa(ch) - } - return ch -} - -// scanString scans a quoted string -func (s *Scanner) scanString() { - braces := 0 - for { - // '"' opening already consumed - // read character after quote - ch := s.next() - - if ch == '\n' || ch < 0 || ch == eof { - s.err("literal not terminated") - return - } - - if ch == '"' { - break - } - - // If we're going into a ${} then we can ignore quotes for awhile - if braces == 0 && ch == '$' && s.peek() == '{' { - braces++ - s.next() - } else if braces > 0 && ch == '{' { - braces++ - } - if braces > 0 && ch == '}' { - braces-- - } - - if ch == '\\' { - s.scanEscape() - } - } - - return -} - -// scanEscape scans an escape sequence -func (s *Scanner) scanEscape() rune { - // http://en.cppreference.com/w/cpp/language/escape - ch := s.next() // read character after '/' - switch ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': - // nothing to do - case '0', '1', '2', '3', '4', '5', '6', '7': - // octal notation - ch = s.scanDigits(ch, 8, 3) - case 'x': - // hexademical notation - ch = s.scanDigits(s.next(), 16, 2) - case 'u': - // universal character name - ch = s.scanDigits(s.next(), 16, 4) - case 'U': - // universal character name - ch = s.scanDigits(s.next(), 16, 8) - default: - s.err("illegal char escape") - } - return ch -} - -// scanDigits scans a rune with the given base for n times. For example an -// octal notation \184 would yield in scanDigits(ch, 8, 3) -func (s *Scanner) scanDigits(ch rune, base, n int) rune { - for n > 0 && digitVal(ch) < base { - ch = s.next() - n-- - } - if n > 0 { - s.err("illegal char escape") - } - - // we scanned all digits, put the last non digit char back - s.unread() - return ch -} - -// scanIdentifier scans an identifier and returns the literal string -func (s *Scanner) scanIdentifier() string { - offs := s.srcPos.Offset - s.lastCharLen - ch := s.next() - for isLetter(ch) || isDigit(ch) || ch == '-' { - ch = s.next() - } - - if ch != eof { - s.unread() // we got identifier, put back latest char - } - - return string(s.src[offs:s.srcPos.Offset]) -} - -// recentPosition returns the position of the character immediately after the -// character or token returned by the last call to Scan. -func (s *Scanner) recentPosition() (pos token.Pos) { - pos.Offset = s.srcPos.Offset - s.lastCharLen - switch { - case s.srcPos.Column > 0: - // common case: last character was not a '\n' - pos.Line = s.srcPos.Line - pos.Column = s.srcPos.Column - case s.lastLineLen > 0: - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - pos.Line = s.srcPos.Line - 1 - pos.Column = s.lastLineLen - default: - // at the beginning of the source - pos.Line = 1 - pos.Column = 1 - } - return -} - -// err prints the error of any scanning to s.Error function. If the function is -// not defined, by default it prints them to os.Stderr -func (s *Scanner) err(msg string) { - s.ErrorCount++ - pos := s.recentPosition() - - if s.Error != nil { - s.Error(pos, msg) - return - } - - fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) -} - -// isHexadecimal returns true if the given rune is a letter -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - -// isHexadecimal returns true if the given rune is a decimal digit -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -// isHexadecimal returns true if the given rune is a decimal number -func isDecimal(ch rune) bool { - return '0' <= ch && ch <= '9' -} - -// isHexadecimal returns true if the given rune is an hexadecimal number -func isHexadecimal(ch rune) bool { - return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F' -} - -// isWhitespace returns true if the rune is a space, tab, newline or carriage return -func isWhitespace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' -} - -// digitVal returns the integer value of a given octal,decimal or hexadecimal rune -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} diff --git a/vendor/github.com/hashicorp/hcl/json/token/position.go b/vendor/github.com/hashicorp/hcl/json/token/position.go deleted file mode 100644 index 59c1bb72..00000000 --- a/vendor/github.com/hashicorp/hcl/json/token/position.go +++ /dev/null @@ -1,46 +0,0 @@ -package token - -import "fmt" - -// Pos describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -type Pos struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (p *Pos) IsValid() bool { return p.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -func (p Pos) String() string { - s := p.Filename - if p.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", p.Line, p.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Before reports whether the position p is before u. -func (p Pos) Before(u Pos) bool { - return u.Offset > p.Offset || u.Line > p.Line -} - -// After reports whether the position p is after u. -func (p Pos) After(u Pos) bool { - return u.Offset < p.Offset || u.Line < p.Line -} diff --git a/vendor/github.com/hashicorp/hcl/json/token/token.go b/vendor/github.com/hashicorp/hcl/json/token/token.go deleted file mode 100644 index 95a0c3ee..00000000 --- a/vendor/github.com/hashicorp/hcl/json/token/token.go +++ /dev/null @@ -1,118 +0,0 @@ -package token - -import ( - "fmt" - "strconv" - - hcltoken "github.com/hashicorp/hcl/hcl/token" -) - -// Token defines a single HCL token which can be obtained via the Scanner -type Token struct { - Type Type - Pos Pos - Text string -} - -// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) -type Type int - -const ( - // Special tokens - ILLEGAL Type = iota - EOF - - identifier_beg - literal_beg - NUMBER // 12345 - FLOAT // 123.45 - BOOL // true,false - STRING // "abc" - NULL // null - literal_end - identifier_end - - operator_beg - LBRACK // [ - LBRACE // { - COMMA // , - PERIOD // . - COLON // : - - RBRACK // ] - RBRACE // } - - operator_end -) - -var tokens = [...]string{ - ILLEGAL: "ILLEGAL", - - EOF: "EOF", - - NUMBER: "NUMBER", - FLOAT: "FLOAT", - BOOL: "BOOL", - STRING: "STRING", - NULL: "NULL", - - LBRACK: "LBRACK", - LBRACE: "LBRACE", - COMMA: "COMMA", - PERIOD: "PERIOD", - COLON: "COLON", - - RBRACK: "RBRACK", - RBRACE: "RBRACE", -} - -// String returns the string corresponding to the token tok. -func (t Type) String() string { - s := "" - if 0 <= t && t < Type(len(tokens)) { - s = tokens[t] - } - if s == "" { - s = "token(" + strconv.Itoa(int(t)) + ")" - } - return s -} - -// IsIdentifier returns true for tokens corresponding to identifiers and basic -// type literals; it returns false otherwise. -func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end } - -// IsLiteral returns true for tokens corresponding to basic type literals; it -// returns false otherwise. -func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end } - -// IsOperator returns true for tokens corresponding to operators and -// delimiters; it returns false otherwise. -func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end } - -// String returns the token's literal text. Note that this is only -// applicable for certain token types, such as token.IDENT, -// token.STRING, etc.. -func (t Token) String() string { - return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text) -} - -// HCLToken converts this token to an HCL token. -// -// The token type must be a literal type or this will panic. -func (t Token) HCLToken() hcltoken.Token { - switch t.Type { - case BOOL: - return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text} - case FLOAT: - return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text} - case NULL: - return hcltoken.Token{Type: hcltoken.STRING, Text: ""} - case NUMBER: - return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text} - case STRING: - return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true} - default: - panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type)) - } -} diff --git a/vendor/github.com/hashicorp/hcl/lex.go b/vendor/github.com/hashicorp/hcl/lex.go deleted file mode 100644 index d9993c29..00000000 --- a/vendor/github.com/hashicorp/hcl/lex.go +++ /dev/null @@ -1,38 +0,0 @@ -package hcl - -import ( - "unicode" - "unicode/utf8" -) - -type lexModeValue byte - -const ( - lexModeUnknown lexModeValue = iota - lexModeHcl - lexModeJson -) - -// lexMode returns whether we're going to be parsing in JSON -// mode or HCL mode. -func lexMode(v []byte) lexModeValue { - var ( - r rune - w int - offset int - ) - - for { - r, w = utf8.DecodeRune(v[offset:]) - offset += w - if unicode.IsSpace(r) { - continue - } - if r == '{' { - return lexModeJson - } - break - } - - return lexModeHcl -} diff --git a/vendor/github.com/hashicorp/hcl/parse.go b/vendor/github.com/hashicorp/hcl/parse.go deleted file mode 100644 index 1fca53c4..00000000 --- a/vendor/github.com/hashicorp/hcl/parse.go +++ /dev/null @@ -1,39 +0,0 @@ -package hcl - -import ( - "fmt" - - "github.com/hashicorp/hcl/hcl/ast" - hclParser "github.com/hashicorp/hcl/hcl/parser" - jsonParser "github.com/hashicorp/hcl/json/parser" -) - -// ParseBytes accepts as input byte slice and returns ast tree. -// -// Input can be either JSON or HCL -func ParseBytes(in []byte) (*ast.File, error) { - return parse(in) -} - -// ParseString accepts input as a string and returns ast tree. -func ParseString(input string) (*ast.File, error) { - return parse([]byte(input)) -} - -func parse(in []byte) (*ast.File, error) { - switch lexMode(in) { - case lexModeHcl: - return hclParser.Parse(in) - case lexModeJson: - return jsonParser.Parse(in) - } - - return nil, fmt.Errorf("unknown config format") -} - -// Parse parses the given input and returns the root object. -// -// The input format can be either HCL or JSON. -func Parse(input string) (*ast.File, error) { - return parse([]byte(input)) -} diff --git a/vendor/github.com/hashicorp/vault/LICENSE b/vendor/github.com/hashicorp/vault/LICENSE deleted file mode 100644 index e87a115e..00000000 --- a/vendor/github.com/hashicorp/vault/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/vault/api/auth.go b/vendor/github.com/hashicorp/vault/api/auth.go deleted file mode 100644 index da870c11..00000000 --- a/vendor/github.com/hashicorp/vault/api/auth.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Auth is used to perform credential backend related operations. -type Auth struct { - c *Client -} - -// Auth is used to return the client for credential-backend API calls. -func (c *Client) Auth() *Auth { - return &Auth{c: c} -} diff --git a/vendor/github.com/hashicorp/vault/api/auth_token.go b/vendor/github.com/hashicorp/vault/api/auth_token.go deleted file mode 100644 index ed594eee..00000000 --- a/vendor/github.com/hashicorp/vault/api/auth_token.go +++ /dev/null @@ -1,275 +0,0 @@ -package api - -import "context" - -// TokenAuth is used to perform token backend operations on Vault -type TokenAuth struct { - c *Client -} - -// Token is used to return the client for token-backend API calls -func (a *Auth) Token() *TokenAuth { - return &TokenAuth{c: a.c} -} - -func (c *TokenAuth) Create(opts *TokenCreateRequest) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) CreateOrphan(opts *TokenCreateRequest) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create-orphan") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) CreateWithRole(opts *TokenCreateRequest, roleName string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create/"+roleName) - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) Lookup(token string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/lookup") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) LookupAccessor(accessor string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/lookup-accessor") - if err := r.SetJSONBody(map[string]interface{}{ - "accessor": accessor, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) LookupSelf() (*Secret, error) { - r := c.c.NewRequest("GET", "/v1/auth/token/lookup-self") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) Renew(token string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - "increment": increment, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) RenewSelf(increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew-self") - - body := map[string]interface{}{"increment": increment} - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// RenewTokenAsSelf behaves like renew-self, but authenticates using a provided -// token instead of the token attached to the client. -func (c *TokenAuth) RenewTokenAsSelf(token string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew-self") - r.ClientToken = token - - body := map[string]interface{}{"increment": increment} - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// RevokeAccessor revokes a token associated with the given accessor -// along with all the child tokens. -func (c *TokenAuth) RevokeAccessor(accessor string) error { - r := c.c.NewRequest("POST", "/v1/auth/token/revoke-accessor") - if err := r.SetJSONBody(map[string]interface{}{ - "accessor": accessor, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeOrphan revokes a token without revoking the tree underneath it (so -// child tokens are orphaned rather than revoked) -func (c *TokenAuth) RevokeOrphan(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke-orphan") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeSelf revokes the token making the call. The `token` parameter is kept -// for backwards compatibility but is ignored; only the client's set token has -// an effect. -func (c *TokenAuth) RevokeSelf(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke-self") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeTree is the "normal" revoke operation that revokes the given token and -// the entire tree underneath -- all of its child tokens, their child tokens, -// etc. -func (c *TokenAuth) RevokeTree(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// TokenCreateRequest is the options structure for creating a token. -type TokenCreateRequest struct { - ID string `json:"id,omitempty"` - Policies []string `json:"policies,omitempty"` - Metadata map[string]string `json:"meta,omitempty"` - Lease string `json:"lease,omitempty"` - TTL string `json:"ttl,omitempty"` - ExplicitMaxTTL string `json:"explicit_max_ttl,omitempty"` - Period string `json:"period,omitempty"` - NoParent bool `json:"no_parent,omitempty"` - NoDefaultPolicy bool `json:"no_default_policy,omitempty"` - DisplayName string `json:"display_name"` - NumUses int `json:"num_uses"` - Renewable *bool `json:"renewable,omitempty"` - Type string `json:"type"` -} diff --git a/vendor/github.com/hashicorp/vault/api/client.go b/vendor/github.com/hashicorp/vault/api/client.go deleted file mode 100644 index d3acaea9..00000000 --- a/vendor/github.com/hashicorp/vault/api/client.go +++ /dev/null @@ -1,763 +0,0 @@ -package api - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/url" - "os" - "path" - "strconv" - "strings" - "sync" - "time" - "unicode" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-retryablehttp" - "github.com/hashicorp/go-rootcerts" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/parseutil" - "golang.org/x/net/http2" - "golang.org/x/time/rate" -) - -const EnvVaultAddress = "VAULT_ADDR" -const EnvVaultCACert = "VAULT_CACERT" -const EnvVaultCAPath = "VAULT_CAPATH" -const EnvVaultClientCert = "VAULT_CLIENT_CERT" -const EnvVaultClientKey = "VAULT_CLIENT_KEY" -const EnvVaultClientTimeout = "VAULT_CLIENT_TIMEOUT" -const EnvVaultInsecure = "VAULT_SKIP_VERIFY" -const EnvVaultTLSServerName = "VAULT_TLS_SERVER_NAME" -const EnvVaultWrapTTL = "VAULT_WRAP_TTL" -const EnvVaultMaxRetries = "VAULT_MAX_RETRIES" -const EnvVaultToken = "VAULT_TOKEN" -const EnvVaultMFA = "VAULT_MFA" -const EnvRateLimit = "VAULT_RATE_LIMIT" - -// WrappingLookupFunc is a function that, given an HTTP verb and a path, -// returns an optional string duration to be used for response wrapping (e.g. -// "15s", or simply "15"). The path will not begin with "/v1/" or "v1/" or "/", -// however, end-of-path forward slashes are not trimmed, so must match your -// called path precisely. -type WrappingLookupFunc func(operation, path string) string - -// Config is used to configure the creation of the client. -type Config struct { - modifyLock sync.RWMutex - - // Address is the address of the Vault server. This should be a complete - // URL such as "http://vault.example.com". If you need a custom SSL - // cert or want to enable insecure mode, you need to specify a custom - // HttpClient. - Address string - - // HttpClient is the HTTP client to use. Vault sets sane defaults for the - // http.Client and its associated http.Transport created in DefaultConfig. - // If you must modify Vault's defaults, it is suggested that you start with - // that client and modify as needed rather than start with an empty client - // (or http.DefaultClient). - HttpClient *http.Client - - // MaxRetries controls the maximum number of times to retry when a 5xx - // error occurs. Set to 0 to disable retrying. Defaults to 2 (for a total - // of three tries). - MaxRetries int - - // Timeout is for setting custom timeout parameter in the HttpClient - Timeout time.Duration - - // If there is an error when creating the configuration, this will be the - // error - Error error - - // The Backoff function to use; a default is used if not provided - Backoff retryablehttp.Backoff - - // Limiter is the rate limiter used by the client. - // If this pointer is nil, then there will be no limit set. - // In contrast, if this pointer is set, even to an empty struct, - // then that limiter will be used. Note that an empty Limiter - // is equivalent blocking all events. - Limiter *rate.Limiter -} - -// TLSConfig contains the parameters needed to configure TLS on the HTTP client -// used to communicate with Vault. -type TLSConfig struct { - // CACert is the path to a PEM-encoded CA cert file to use to verify the - // Vault server SSL certificate. - CACert string - - // CAPath is the path to a directory of PEM-encoded CA cert files to verify - // the Vault server SSL certificate. - CAPath string - - // ClientCert is the path to the certificate for Vault communication - ClientCert string - - // ClientKey is the path to the private key for Vault communication - ClientKey string - - // TLSServerName, if set, is used to set the SNI host when connecting via - // TLS. - TLSServerName string - - // Insecure enables or disables SSL verification - Insecure bool -} - -// DefaultConfig returns a default configuration for the client. It is -// safe to modify the return value of this function. -// -// The default Address is https://127.0.0.1:8200, but this can be overridden by -// setting the `VAULT_ADDR` environment variable. -// -// If an error is encountered, this will return nil. -func DefaultConfig() *Config { - config := &Config{ - Address: "https://127.0.0.1:8200", - HttpClient: cleanhttp.DefaultPooledClient(), - } - config.HttpClient.Timeout = time.Second * 60 - - transport := config.HttpClient.Transport.(*http.Transport) - transport.TLSHandshakeTimeout = 10 * time.Second - transport.TLSClientConfig = &tls.Config{ - MinVersion: tls.VersionTLS12, - } - if err := http2.ConfigureTransport(transport); err != nil { - config.Error = err - return config - } - - if err := config.ReadEnvironment(); err != nil { - config.Error = err - return config - } - - // Ensure redirects are not automatically followed - // Note that this is sane for the API client as it has its own - // redirect handling logic (and thus also for command/meta), - // but in e.g. http_test actual redirect handling is necessary - config.HttpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { - // Returning this value causes the Go net library to not close the - // response body and to nil out the error. Otherwise retry clients may - // try three times on every redirect because it sees an error from this - // function (to prevent redirects) passing through to it. - return http.ErrUseLastResponse - } - - config.Backoff = retryablehttp.LinearJitterBackoff - config.MaxRetries = 2 - - return config -} - -// ConfigureTLS takes a set of TLS configurations and applies those to the the -// HTTP client. -func (c *Config) ConfigureTLS(t *TLSConfig) error { - if c.HttpClient == nil { - c.HttpClient = DefaultConfig().HttpClient - } - clientTLSConfig := c.HttpClient.Transport.(*http.Transport).TLSClientConfig - - var clientCert tls.Certificate - foundClientCert := false - - switch { - case t.ClientCert != "" && t.ClientKey != "": - var err error - clientCert, err = tls.LoadX509KeyPair(t.ClientCert, t.ClientKey) - if err != nil { - return err - } - foundClientCert = true - case t.ClientCert != "" || t.ClientKey != "": - return fmt.Errorf("both client cert and client key must be provided") - } - - if t.CACert != "" || t.CAPath != "" { - rootConfig := &rootcerts.Config{ - CAFile: t.CACert, - CAPath: t.CAPath, - } - if err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil { - return err - } - } - - if t.Insecure { - clientTLSConfig.InsecureSkipVerify = true - } - - if foundClientCert { - // We use this function to ignore the server's preferential list of - // CAs, otherwise any CA used for the cert auth backend must be in the - // server's CA pool - clientTLSConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { - return &clientCert, nil - } - } - - if t.TLSServerName != "" { - clientTLSConfig.ServerName = t.TLSServerName - } - - return nil -} - -// ReadEnvironment reads configuration information from the environment. If -// there is an error, no configuration value is updated. -func (c *Config) ReadEnvironment() error { - var envAddress string - var envCACert string - var envCAPath string - var envClientCert string - var envClientKey string - var envClientTimeout time.Duration - var envInsecure bool - var envTLSServerName string - var envMaxRetries *uint64 - var limit *rate.Limiter - - // Parse the environment variables - if v := os.Getenv(EnvVaultAddress); v != "" { - envAddress = v - } - if v := os.Getenv(EnvVaultMaxRetries); v != "" { - maxRetries, err := strconv.ParseUint(v, 10, 32) - if err != nil { - return err - } - envMaxRetries = &maxRetries - } - if v := os.Getenv(EnvVaultCACert); v != "" { - envCACert = v - } - if v := os.Getenv(EnvVaultCAPath); v != "" { - envCAPath = v - } - if v := os.Getenv(EnvVaultClientCert); v != "" { - envClientCert = v - } - if v := os.Getenv(EnvVaultClientKey); v != "" { - envClientKey = v - } - if v := os.Getenv(EnvRateLimit); v != "" { - rateLimit, burstLimit, err := parseRateLimit(v) - if err != nil { - return err - } - limit = rate.NewLimiter(rate.Limit(rateLimit), burstLimit) - } - if t := os.Getenv(EnvVaultClientTimeout); t != "" { - clientTimeout, err := parseutil.ParseDurationSecond(t) - if err != nil { - return fmt.Errorf("could not parse %q", EnvVaultClientTimeout) - } - envClientTimeout = clientTimeout - } - if v := os.Getenv(EnvVaultInsecure); v != "" { - var err error - envInsecure, err = strconv.ParseBool(v) - if err != nil { - return fmt.Errorf("could not parse VAULT_SKIP_VERIFY") - } - } - if v := os.Getenv(EnvVaultTLSServerName); v != "" { - envTLSServerName = v - } - - // Configure the HTTP clients TLS configuration. - t := &TLSConfig{ - CACert: envCACert, - CAPath: envCAPath, - ClientCert: envClientCert, - ClientKey: envClientKey, - TLSServerName: envTLSServerName, - Insecure: envInsecure, - } - - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.Limiter = limit - - if err := c.ConfigureTLS(t); err != nil { - return err - } - - if envAddress != "" { - c.Address = envAddress - } - - if envMaxRetries != nil { - c.MaxRetries = int(*envMaxRetries) - } - - if envClientTimeout != 0 { - c.Timeout = envClientTimeout - } - - return nil -} - -func parseRateLimit(val string) (rate float64, burst int, err error) { - - _, err = fmt.Sscanf(val, "%f:%d", &rate, &burst) - if err != nil { - rate, err = strconv.ParseFloat(val, 64) - if err != nil { - err = fmt.Errorf("%v was provided but incorrectly formatted", EnvRateLimit) - } - burst = int(rate) - } - - return rate, burst, err - -} - -// Client is the client to the Vault API. Create a client with NewClient. -type Client struct { - modifyLock sync.RWMutex - addr *url.URL - config *Config - token string - headers http.Header - wrappingLookupFunc WrappingLookupFunc - mfaCreds []string - policyOverride bool -} - -// NewClient returns a new client for the given configuration. -// -// If the configuration is nil, Vault will use configuration from -// DefaultConfig(), which is the recommended starting configuration. -// -// If the environment variable `VAULT_TOKEN` is present, the token will be -// automatically added to the client. Otherwise, you must manually call -// `SetToken()`. -func NewClient(c *Config) (*Client, error) { - def := DefaultConfig() - if def == nil { - return nil, fmt.Errorf("could not create/read default configuration") - } - if def.Error != nil { - return nil, errwrap.Wrapf("error encountered setting up default configuration: {{err}}", def.Error) - } - - if c == nil { - c = def - } - - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - u, err := url.Parse(c.Address) - if err != nil { - return nil, err - } - - if c.HttpClient == nil { - c.HttpClient = def.HttpClient - } - if c.HttpClient.Transport == nil { - c.HttpClient.Transport = def.HttpClient.Transport - } - - client := &Client{ - addr: u, - config: c, - } - - if token := os.Getenv(EnvVaultToken); token != "" { - client.token = token - } - - return client, nil -} - -// Sets the address of Vault in the client. The format of address should be -// "://:". Setting this on a client will override the -// value of VAULT_ADDR environment variable. -func (c *Client) SetAddress(addr string) error { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - parsedAddr, err := url.Parse(addr) - if err != nil { - return errwrap.Wrapf("failed to set address: {{err}}", err) - } - - c.addr = parsedAddr - return nil -} - -// Address returns the Vault URL the client is configured to connect to -func (c *Client) Address() string { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.addr.String() -} - -// SetLimiter will set the rate limiter for this client. -// This method is thread-safe. -// rateLimit and burst are specified according to https://godoc.org/golang.org/x/time/rate#NewLimiter -func (c *Client) SetLimiter(rateLimit float64, burst int) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Limiter = rate.NewLimiter(rate.Limit(rateLimit), burst) -} - -// SetMaxRetries sets the number of retries that will be used in the case of certain errors -func (c *Client) SetMaxRetries(retries int) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.MaxRetries = retries -} - -// SetClientTimeout sets the client request timeout -func (c *Client) SetClientTimeout(timeout time.Duration) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Timeout = timeout -} - -// CurrentWrappingLookupFunc sets a lookup function that returns desired wrap TTLs -// for a given operation and path -func (c *Client) CurrentWrappingLookupFunc() WrappingLookupFunc { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.wrappingLookupFunc -} - -// SetWrappingLookupFunc sets a lookup function that returns desired wrap TTLs -// for a given operation and path -func (c *Client) SetWrappingLookupFunc(lookupFunc WrappingLookupFunc) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.wrappingLookupFunc = lookupFunc -} - -// SetMFACreds sets the MFA credentials supplied either via the environment -// variable or via the command line. -func (c *Client) SetMFACreds(creds []string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.mfaCreds = creds -} - -// SetNamespace sets the namespace supplied either via the environment -// variable or via the command line. -func (c *Client) SetNamespace(namespace string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - if c.headers == nil { - c.headers = make(http.Header) - } - - c.headers.Set(consts.NamespaceHeaderName, namespace) -} - -// Token returns the access token being used by this client. It will -// return the empty string if there is no token set. -func (c *Client) Token() string { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.token -} - -// SetToken sets the token directly. This won't perform any auth -// verification, it simply sets the token properly for future requests. -func (c *Client) SetToken(v string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.token = v -} - -// ClearToken deletes the token if it is set or does nothing otherwise. -func (c *Client) ClearToken() { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.token = "" -} - -// Headers gets the current set of headers used for requests. This returns a -// copy; to modify it make modifications locally and use SetHeaders. -func (c *Client) Headers() http.Header { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - if c.headers == nil { - return nil - } - - ret := make(http.Header) - for k, v := range c.headers { - for _, val := range v { - ret[k] = append(ret[k], val) - } - } - - return ret -} - -// SetHeaders sets the headers to be used for future requests. -func (c *Client) SetHeaders(headers http.Header) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.headers = headers -} - -// SetBackoff sets the backoff function to be used for future requests. -func (c *Client) SetBackoff(backoff retryablehttp.Backoff) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Backoff = backoff -} - -// Clone creates a new client with the same configuration. Note that the same -// underlying http.Client is used; modifying the client from more than one -// goroutine at once may not be safe, so modify the client as needed and then -// clone. -// -// Also, only the client's config is currently copied; this means items not in -// the api.Config struct, such as policy override and wrapping function -// behavior, must currently then be set as desired on the new client. -func (c *Client) Clone() (*Client, error) { - c.modifyLock.RLock() - c.config.modifyLock.RLock() - config := c.config - c.modifyLock.RUnlock() - - newConfig := &Config{ - Address: config.Address, - HttpClient: config.HttpClient, - MaxRetries: config.MaxRetries, - Timeout: config.Timeout, - Backoff: config.Backoff, - Limiter: config.Limiter, - } - config.modifyLock.RUnlock() - - return NewClient(newConfig) -} - -// SetPolicyOverride sets whether requests should be sent with the policy -// override flag to request overriding soft-mandatory Sentinel policies (both -// RGPs and EGPs) -func (c *Client) SetPolicyOverride(override bool) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.policyOverride = override -} - -// NewRequest creates a new raw request object to query the Vault server -// configured for this client. This is an advanced method and generally -// doesn't need to be called externally. -func (c *Client) NewRequest(method, requestPath string) *Request { - c.modifyLock.RLock() - addr := c.addr - token := c.token - mfaCreds := c.mfaCreds - wrappingLookupFunc := c.wrappingLookupFunc - headers := c.headers - policyOverride := c.policyOverride - c.modifyLock.RUnlock() - - // if SRV records exist (see https://tools.ietf.org/html/draft-andrews-http-srv-02), lookup the SRV - // record and take the highest match; this is not designed for high-availability, just discovery - var host string = addr.Host - if addr.Port() == "" { - // Internet Draft specifies that the SRV record is ignored if a port is given - _, addrs, err := net.LookupSRV("http", "tcp", addr.Hostname()) - if err == nil && len(addrs) > 0 { - host = fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port) - } - } - - req := &Request{ - Method: method, - URL: &url.URL{ - User: addr.User, - Scheme: addr.Scheme, - Host: host, - Path: path.Join(addr.Path, requestPath), - }, - ClientToken: token, - Params: make(map[string][]string), - } - - var lookupPath string - switch { - case strings.HasPrefix(requestPath, "/v1/"): - lookupPath = strings.TrimPrefix(requestPath, "/v1/") - case strings.HasPrefix(requestPath, "v1/"): - lookupPath = strings.TrimPrefix(requestPath, "v1/") - default: - lookupPath = requestPath - } - - req.MFAHeaderVals = mfaCreds - - if wrappingLookupFunc != nil { - req.WrapTTL = wrappingLookupFunc(method, lookupPath) - } else { - req.WrapTTL = DefaultWrappingLookupFunc(method, lookupPath) - } - - if headers != nil { - req.Headers = headers - } - - req.PolicyOverride = policyOverride - - return req -} - -// RawRequest performs the raw request given. This request may be against -// a Vault server not configured with this client. This is an advanced operation -// that generally won't need to be called externally. -func (c *Client) RawRequest(r *Request) (*Response, error) { - return c.RawRequestWithContext(context.Background(), r) -} - -// RawRequestWithContext performs the raw request given. This request may be against -// a Vault server not configured with this client. This is an advanced operation -// that generally won't need to be called externally. -func (c *Client) RawRequestWithContext(ctx context.Context, r *Request) (*Response, error) { - c.modifyLock.RLock() - token := c.token - - c.config.modifyLock.RLock() - limiter := c.config.Limiter - maxRetries := c.config.MaxRetries - backoff := c.config.Backoff - httpClient := c.config.HttpClient - timeout := c.config.Timeout - c.config.modifyLock.RUnlock() - - c.modifyLock.RUnlock() - - if limiter != nil { - limiter.Wait(ctx) - } - - // Sanity check the token before potentially erroring from the API - idx := strings.IndexFunc(token, func(c rune) bool { - return !unicode.IsPrint(c) - }) - if idx != -1 { - return nil, fmt.Errorf("configured Vault token contains non-printable characters and cannot be used") - } - - redirectCount := 0 -START: - req, err := r.toRetryableHTTP() - if err != nil { - return nil, err - } - if req == nil { - return nil, fmt.Errorf("nil request created") - } - - if timeout != 0 { - ctx, _ = context.WithTimeout(ctx, timeout) - } - req.Request = req.Request.WithContext(ctx) - - if backoff == nil { - backoff = retryablehttp.LinearJitterBackoff - } - - client := &retryablehttp.Client{ - HTTPClient: httpClient, - RetryWaitMin: 1000 * time.Millisecond, - RetryWaitMax: 1500 * time.Millisecond, - RetryMax: maxRetries, - CheckRetry: retryablehttp.DefaultRetryPolicy, - Backoff: backoff, - ErrorHandler: retryablehttp.PassthroughErrorHandler, - } - - var result *Response - resp, err := client.Do(req) - if resp != nil { - result = &Response{Response: resp} - } - if err != nil { - if strings.Contains(err.Error(), "tls: oversized") { - err = errwrap.Wrapf( - "{{err}}\n\n"+ - "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"+ - " vault -address http://

\n\n"+ - "You can also set the VAULT_ADDR environment variable:\n\n\n"+ - " VAULT_ADDR=http://
vault \n\n"+ - "where
is replaced by the actual address to the server.", - err) - } - return result, err - } - - // Check for a redirect, only allowing for a single redirect - if (resp.StatusCode == 301 || resp.StatusCode == 302 || resp.StatusCode == 307) && redirectCount == 0 { - // Parse the updated location - respLoc, err := resp.Location() - if err != nil { - return result, err - } - - // Ensure a protocol downgrade doesn't happen - if req.URL.Scheme == "https" && respLoc.Scheme != "https" { - return result, fmt.Errorf("redirect would cause protocol downgrade") - } - - // Update the request - r.URL = respLoc - - // Reset the request body if any - if err := r.ResetJSONBody(); err != nil { - return result, err - } - - // Retry the request - redirectCount++ - goto START - } - - if err := result.Error(); err != nil { - return result, err - } - - return result, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/help.go b/vendor/github.com/hashicorp/vault/api/help.go deleted file mode 100644 index 472ca039..00000000 --- a/vendor/github.com/hashicorp/vault/api/help.go +++ /dev/null @@ -1,29 +0,0 @@ -package api - -import ( - "context" - "fmt" -) - -// Help reads the help information for the given path. -func (c *Client) Help(path string) (*Help, error) { - r := c.NewRequest("GET", fmt.Sprintf("/v1/%s", path)) - r.Params.Add("help", "1") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result Help - err = resp.DecodeJSON(&result) - return &result, err -} - -type Help struct { - Help string `json:"help"` - SeeAlso []string `json:"see_also"` -} diff --git a/vendor/github.com/hashicorp/vault/api/logical.go b/vendor/github.com/hashicorp/vault/api/logical.go deleted file mode 100644 index d13daac6..00000000 --- a/vendor/github.com/hashicorp/vault/api/logical.go +++ /dev/null @@ -1,267 +0,0 @@ -package api - -import ( - "bytes" - "context" - "fmt" - "io" - "net/url" - "os" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" -) - -const ( - wrappedResponseLocation = "cubbyhole/response" -) - -var ( - // The default TTL that will be used with `sys/wrapping/wrap`, can be - // changed - DefaultWrappingTTL = "5m" - - // The default function used if no other function is set, which honors the - // env var and wraps `sys/wrapping/wrap` - DefaultWrappingLookupFunc = func(operation, path string) string { - if os.Getenv(EnvVaultWrapTTL) != "" { - return os.Getenv(EnvVaultWrapTTL) - } - - if (operation == "PUT" || operation == "POST") && path == "sys/wrapping/wrap" { - return DefaultWrappingTTL - } - - return "" - } -) - -// Logical is used to perform logical backend operations on Vault. -type Logical struct { - c *Client -} - -// Logical is used to return the client for logical-backend API calls. -func (c *Client) Logical() *Logical { - return &Logical{c: c} -} - -func (c *Logical) Read(path string) (*Secret, error) { - return c.ReadWithData(path, nil) -} - -func (c *Logical) ReadWithData(path string, data map[string][]string) (*Secret, error) { - r := c.c.NewRequest("GET", "/v1/"+path) - - var values url.Values - for k, v := range data { - if values == nil { - values = make(url.Values) - } - for _, val := range v { - values.Add(k, val) - } - } - - if values != nil { - r.Params = values - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - return nil, nil - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) List(path string) (*Secret, error) { - r := c.c.NewRequest("LIST", "/v1/"+path) - // Set this for broader compatibility, but we use LIST above to be able to - // handle the wrapping lookup function - r.Method = "GET" - r.Params.Set("list", "true") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - return nil, nil - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Write(path string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/"+path) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, err - } - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Delete(path string) (*Secret, error) { - r := c.c.NewRequest("DELETE", "/v1/"+path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, err - } - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Unwrap(wrappingToken string) (*Secret, error) { - var data map[string]interface{} - if wrappingToken != "" { - if c.c.Token() == "" { - c.c.SetToken(wrappingToken) - } else if wrappingToken != c.c.Token() { - data = map[string]interface{}{ - "token": wrappingToken, - } - } - } - - r := c.c.NewRequest("PUT", "/v1/sys/wrapping/unwrap") - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp == nil || resp.StatusCode != 404 { - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - return ParseSecret(resp.Body) - } - - // In the 404 case this may actually be a wrapped 404 error - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - - // Otherwise this might be an old-style wrapping token so attempt the old - // method - if wrappingToken != "" { - origToken := c.c.Token() - defer c.c.SetToken(origToken) - c.c.SetToken(wrappingToken) - } - - secret, err = c.Read(wrappedResponseLocation) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error reading %q: {{err}}", wrappedResponseLocation), err) - } - if secret == nil { - return nil, fmt.Errorf("no value found at %q", wrappedResponseLocation) - } - if secret.Data == nil { - return nil, fmt.Errorf("\"data\" not found in wrapping response") - } - if _, ok := secret.Data["response"]; !ok { - return nil, fmt.Errorf("\"response\" not found in wrapping response \"data\" map") - } - - wrappedSecret := new(Secret) - buf := bytes.NewBufferString(secret.Data["response"].(string)) - if err := jsonutil.DecodeJSONFromReader(buf, wrappedSecret); err != nil { - return nil, errwrap.Wrapf("error unmarshalling wrapped secret: {{err}}", err) - } - - return wrappedSecret, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/renewer.go b/vendor/github.com/hashicorp/vault/api/renewer.go deleted file mode 100644 index 1d37a193..00000000 --- a/vendor/github.com/hashicorp/vault/api/renewer.go +++ /dev/null @@ -1,349 +0,0 @@ -package api - -import ( - "errors" - "math/rand" - "sync" - "time" -) - -var ( - ErrRenewerMissingInput = errors.New("missing input to renewer") - ErrRenewerMissingSecret = errors.New("missing secret to renew") - ErrRenewerNotRenewable = errors.New("secret is not renewable") - ErrRenewerNoSecretData = errors.New("returned empty secret data") - - // DefaultRenewerRenewBuffer is the default size of the buffer for renew - // messages on the channel. - DefaultRenewerRenewBuffer = 5 -) - -// Renewer is a process for renewing a secret. -// -// renewer, err := client.NewRenewer(&RenewerInput{ -// Secret: mySecret, -// }) -// go renewer.Renew() -// defer renewer.Stop() -// -// for { -// select { -// case err := <-renewer.DoneCh(): -// if err != nil { -// log.Fatal(err) -// } -// -// // Renewal is now over -// case renewal := <-renewer.RenewCh(): -// log.Printf("Successfully renewed: %#v", renewal) -// } -// } -// -// -// The `DoneCh` will return if renewal fails or if the remaining lease duration -// after a renewal is less than or equal to the grace (in number of seconds). In -// both cases, the caller should attempt a re-read of the secret. Clients should -// check the return value of the channel to see if renewal was successful. -type Renewer struct { - l sync.Mutex - - client *Client - secret *Secret - grace time.Duration - random *rand.Rand - increment int - doneCh chan error - renewCh chan *RenewOutput - - stopped bool - stopCh chan struct{} -} - -// RenewerInput is used as input to the renew function. -type RenewerInput struct { - // Secret is the secret to renew - Secret *Secret - - // DEPRECATED: this does not do anything. - Grace time.Duration - - // Rand is the randomizer to use for underlying randomization. If not - // provided, one will be generated and seeded automatically. If provided, it - // is assumed to have already been seeded. - Rand *rand.Rand - - // RenewBuffer is the size of the buffered channel where renew messages are - // dispatched. - RenewBuffer int - - // The new TTL, in seconds, that should be set on the lease. The TTL set - // here may or may not be honored by the vault server, based on Vault - // configuration or any associated max TTL values. - Increment int -} - -// RenewOutput is the metadata returned to the client (if it's listening) to -// renew messages. -type RenewOutput struct { - // RenewedAt is the timestamp when the renewal took place (UTC). - RenewedAt time.Time - - // Secret is the underlying renewal data. It's the same struct as all data - // that is returned from Vault, but since this is renewal data, it will not - // usually include the secret itself. - Secret *Secret -} - -// NewRenewer creates a new renewer from the given input. -func (c *Client) NewRenewer(i *RenewerInput) (*Renewer, error) { - if i == nil { - return nil, ErrRenewerMissingInput - } - - secret := i.Secret - if secret == nil { - return nil, ErrRenewerMissingSecret - } - - random := i.Rand - if random == nil { - random = rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) - } - - renewBuffer := i.RenewBuffer - if renewBuffer == 0 { - renewBuffer = DefaultRenewerRenewBuffer - } - - return &Renewer{ - client: c, - secret: secret, - increment: i.Increment, - random: random, - doneCh: make(chan error, 1), - renewCh: make(chan *RenewOutput, renewBuffer), - - stopped: false, - stopCh: make(chan struct{}), - }, nil -} - -// DoneCh returns the channel where the renewer will publish when renewal stops. -// If there is an error, this will be an error. -func (r *Renewer) DoneCh() <-chan error { - return r.doneCh -} - -// RenewCh is a channel that receives a message when a successful renewal takes -// place and includes metadata about the renewal. -func (r *Renewer) RenewCh() <-chan *RenewOutput { - return r.renewCh -} - -// Stop stops the renewer. -func (r *Renewer) Stop() { - r.l.Lock() - if !r.stopped { - close(r.stopCh) - r.stopped = true - } - r.l.Unlock() -} - -// Renew starts a background process for renewing this secret. When the secret -// has auth data, this attempts to renew the auth (token). When the secret has -// a lease, this attempts to renew the lease. -func (r *Renewer) Renew() { - var result error - if r.secret.Auth != nil { - result = r.renewAuth() - } else { - result = r.renewLease() - } - - r.doneCh <- result -} - -// renewAuth is a helper for renewing authentication. -func (r *Renewer) renewAuth() error { - if !r.secret.Auth.Renewable || r.secret.Auth.ClientToken == "" { - return ErrRenewerNotRenewable - } - - priorDuration := time.Duration(r.secret.Auth.LeaseDuration) * time.Second - r.calculateGrace(priorDuration) - - client, token := r.client, r.secret.Auth.ClientToken - - for { - // Check if we are stopped. - select { - case <-r.stopCh: - return nil - default: - } - - // Renew the auth. - renewal, err := client.Auth().Token().RenewTokenAsSelf(token, r.increment) - if err != nil { - return err - } - - // Push a message that a renewal took place. - select { - case r.renewCh <- &RenewOutput{time.Now().UTC(), renewal}: - default: - } - - // Somehow, sometimes, this happens. - if renewal == nil || renewal.Auth == nil { - return ErrRenewerNoSecretData - } - - // Do nothing if we are not renewable - if !renewal.Auth.Renewable { - return ErrRenewerNotRenewable - } - - // Grab the lease duration - leaseDuration := time.Duration(renewal.Auth.LeaseDuration) * time.Second - - // 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 leaseDuration > priorDuration { - r.calculateGrace(leaseDuration) - } - priorDuration = leaseDuration - - // 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(leaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) - - // 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 - // seconds, a grace period of 3 seconds, and end up sleeping for more - // than three of those seconds and having a very small budget of time - // to renew. - if leaseDuration <= r.grace || leaseDuration-sleepDuration <= r.grace { - return nil - } - - select { - case <-r.stopCh: - return nil - case <-time.After(sleepDuration): - continue - } - } -} - -// renewLease is a helper for renewing a lease. -func (r *Renewer) renewLease() error { - if !r.secret.Renewable || r.secret.LeaseID == "" { - return ErrRenewerNotRenewable - } - - priorDuration := time.Duration(r.secret.LeaseDuration) * time.Second - r.calculateGrace(priorDuration) - - client, leaseID := r.client, r.secret.LeaseID - - for { - // Check if we are stopped. - select { - case <-r.stopCh: - return nil - default: - } - - // Renew the lease. - renewal, err := client.Sys().Renew(leaseID, r.increment) - if err != nil { - return err - } - - // Push a message that a renewal took place. - select { - case r.renewCh <- &RenewOutput{time.Now().UTC(), renewal}: - default: - } - - // Somehow, sometimes, this happens. - if renewal == nil { - return ErrRenewerNoSecretData - } - - // Do nothing if we are not renewable - if !renewal.Renewable { - return ErrRenewerNotRenewable - } - - // Grab the lease duration - leaseDuration := time.Duration(renewal.LeaseDuration) * time.Second - - // 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 leaseDuration > priorDuration { - r.calculateGrace(leaseDuration) - } - priorDuration = leaseDuration - - // 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(leaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) - - // 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 - // seconds, a grace period of 3 seconds, and end up sleeping for more - // than three of those seconds and having a very small budget of time - // to renew. - if leaseDuration <= r.grace || leaseDuration-sleepDuration <= r.grace { - return nil - } - - select { - case <-r.stopCh: - return nil - case <-time.After(sleepDuration): - continue - } - } -} - -// sleepDuration calculates the time to sleep given the base lease duration. The -// base is the resulting lease duration. It will be reduced to 1/3 and -// multiplied by a random float between 0.0 and 1.0. This extra randomness -// prevents multiple clients from all trying to renew simultaneously. -func (r *Renewer) sleepDuration(base time.Duration) time.Duration { - sleep := float64(base) - - // Renew at 1/3 the remaining lease. This will give us an opportunity to retry - // at least one more time should the first renewal fail. - sleep = sleep / 3.0 - - // Use a randomness so many clients do not hit Vault simultaneously. - sleep = sleep * (r.random.Float64() + 1) / 2.0 - - return time.Duration(sleep) -} - -// calculateGrace calculates the grace period based on a reasonable set of -// assumptions given the total lease time; it also adds some jitter to not have -// clients be in sync. -func (r *Renewer) calculateGrace(leaseDuration time.Duration) { - if leaseDuration == 0 { - r.grace = 0 - return - } - - leaseNanos := float64(leaseDuration.Nanoseconds()) - jitterMax := 0.1 * leaseNanos - - // For a given lease duration, we want to allow 80-90% of that to elapse, - // so the remaining amount is the grace period - r.grace = time.Duration(jitterMax) + time.Duration(uint64(r.random.Int63())%uint64(jitterMax)) -} diff --git a/vendor/github.com/hashicorp/vault/api/request.go b/vendor/github.com/hashicorp/vault/api/request.go deleted file mode 100644 index 4efa2aa8..00000000 --- a/vendor/github.com/hashicorp/vault/api/request.go +++ /dev/null @@ -1,147 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "net/url" - - "github.com/hashicorp/vault/helper/consts" - - retryablehttp "github.com/hashicorp/go-retryablehttp" -) - -// Request is a raw request configuration structure used to initiate -// API requests to the Vault server. -type Request struct { - Method string - URL *url.URL - Params url.Values - Headers http.Header - ClientToken string - MFAHeaderVals []string - WrapTTL string - Obj interface{} - - // When possible, use BodyBytes as it is more efficient due to how the - // retry logic works - BodyBytes []byte - - // Fallback - Body io.Reader - BodySize int64 - - // Whether to request overriding soft-mandatory Sentinel policies (RGPs and - // EGPs). If set, the override flag will take effect for all policies - // evaluated during the request. - PolicyOverride bool -} - -// SetJSONBody is used to set a request body that is a JSON-encoded value. -func (r *Request) SetJSONBody(val interface{}) error { - buf, err := json.Marshal(val) - if err != nil { - return err - } - - r.Obj = val - r.BodyBytes = buf - return nil -} - -// ResetJSONBody is used to reset the body for a redirect -func (r *Request) ResetJSONBody() error { - if r.BodyBytes == nil { - return nil - } - return r.SetJSONBody(r.Obj) -} - -// DEPRECATED: ToHTTP turns this request into a valid *http.Request for use -// with the net/http package. -func (r *Request) ToHTTP() (*http.Request, error) { - req, err := r.toRetryableHTTP() - if err != nil { - return nil, err - } - - switch { - case r.BodyBytes == nil && r.Body == nil: - // No body - - case r.BodyBytes != nil: - req.Request.Body = ioutil.NopCloser(bytes.NewReader(r.BodyBytes)) - - default: - if c, ok := r.Body.(io.ReadCloser); ok { - req.Request.Body = c - } else { - req.Request.Body = ioutil.NopCloser(r.Body) - } - } - - return req.Request, nil -} - -func (r *Request) toRetryableHTTP() (*retryablehttp.Request, error) { - // Encode the query parameters - r.URL.RawQuery = r.Params.Encode() - - // Create the HTTP request, defaulting to retryable - var req *retryablehttp.Request - - var err error - var body interface{} - - switch { - case r.BodyBytes == nil && r.Body == nil: - // No body - - case r.BodyBytes != nil: - // Use bytes, it's more efficient - body = r.BodyBytes - - default: - body = r.Body - } - - req, err = retryablehttp.NewRequest(r.Method, r.URL.RequestURI(), body) - if err != nil { - return nil, err - } - - req.URL.User = r.URL.User - req.URL.Scheme = r.URL.Scheme - req.URL.Host = r.URL.Host - req.Host = r.URL.Host - - if r.Headers != nil { - for header, vals := range r.Headers { - for _, val := range vals { - req.Header.Add(header, val) - } - } - } - - if len(r.ClientToken) != 0 { - req.Header.Set(consts.AuthHeaderName, r.ClientToken) - } - - if len(r.WrapTTL) != 0 { - req.Header.Set("X-Vault-Wrap-TTL", r.WrapTTL) - } - - if len(r.MFAHeaderVals) != 0 { - for _, mfaHeaderVal := range r.MFAHeaderVals { - req.Header.Add("X-Vault-MFA", mfaHeaderVal) - } - } - - if r.PolicyOverride { - req.Header.Set("X-Vault-Policy-Override", "true") - } - - return req, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/response.go b/vendor/github.com/hashicorp/vault/api/response.go deleted file mode 100644 index 053a2772..00000000 --- a/vendor/github.com/hashicorp/vault/api/response.go +++ /dev/null @@ -1,77 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - - "github.com/hashicorp/vault/helper/jsonutil" -) - -// Response is a raw response that wraps an HTTP response. -type Response struct { - *http.Response -} - -// DecodeJSON will decode the response body to a JSON structure. This -// 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) -} - -// Error returns an error response if there is one. If there is an error, -// this will fully consume the response body, but will not close it. The -// body must still be closed manually. -func (r *Response) Error() error { - // 200 to 399 are okay status codes. 429 is the code for health status of - // standby nodes. - if (r.StatusCode >= 200 && r.StatusCode < 400) || r.StatusCode == 429 { - return nil - } - - // We have an error. Let's copy the body into our own buffer first, - // so that if we can't decode JSON, we can at least copy it raw. - bodyBuf := &bytes.Buffer{} - if _, err := io.Copy(bodyBuf, r.Body); err != nil { - return err - } - - r.Body.Close() - r.Body = ioutil.NopCloser(bodyBuf) - - // Decode the error response if we can. Note that we wrap the bodyBuf - // 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 { - // Ignore the decoding error and just drop the raw response - return fmt.Errorf( - "Error making API request.\n\n"+ - "URL: %s %s\n"+ - "Code: %d. Raw Message:\n\n%s", - r.Request.Method, r.Request.URL.String(), - r.StatusCode, bodyBuf.String()) - } - - var errBody bytes.Buffer - errBody.WriteString(fmt.Sprintf( - "Error making API request.\n\n"+ - "URL: %s %s\n"+ - "Code: %d. Errors:\n\n", - r.Request.Method, r.Request.URL.String(), - r.StatusCode)) - for _, err := range resp.Errors { - errBody.WriteString(fmt.Sprintf("* %s", err)) - } - - return fmt.Errorf(errBody.String()) -} - -// ErrorResponse is the raw structure of errors when they're returned by the -// HTTP API. -type ErrorResponse struct { - Errors []string -} diff --git a/vendor/github.com/hashicorp/vault/api/secret.go b/vendor/github.com/hashicorp/vault/api/secret.go deleted file mode 100644 index e2596260..00000000 --- a/vendor/github.com/hashicorp/vault/api/secret.go +++ /dev/null @@ -1,320 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" -) - -// Secret is the structure returned for every secret within Vault. -type Secret struct { - // The request ID that generated this response - RequestID string `json:"request_id"` - - LeaseID string `json:"lease_id"` - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` - - // Data is the actual contents of the secret. The format of the data - // is arbitrary and up to the secret backend. - Data map[string]interface{} `json:"data"` - - // Warnings contains any warnings related to the operation. These - // are not issues that caused the command to fail, but that the - // client should be aware of. - Warnings []string `json:"warnings"` - - // Auth, if non-nil, means that there was authentication information - // attached to this response. - Auth *SecretAuth `json:"auth,omitempty"` - - // WrapInfo, if non-nil, means that the initial response was wrapped in the - // cubbyhole of the given token (which has a TTL of the given number of - // seconds) - WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"` -} - -// TokenID returns the standardized token ID (token) for the given secret. -func (s *Secret) TokenID() (string, error) { - if s == nil { - return "", nil - } - - if s.Auth != nil && len(s.Auth.ClientToken) > 0 { - return s.Auth.ClientToken, nil - } - - if s.Data == nil || s.Data["id"] == nil { - return "", nil - } - - id, ok := s.Data["id"].(string) - if !ok { - return "", fmt.Errorf("token found but in the wrong format") - } - - return id, nil -} - -// TokenAccessor returns the standardized token accessor for the given secret. -// If the secret is nil or does not contain an accessor, this returns the empty -// string. -func (s *Secret) TokenAccessor() (string, error) { - if s == nil { - return "", nil - } - - if s.Auth != nil && len(s.Auth.Accessor) > 0 { - return s.Auth.Accessor, nil - } - - if s.Data == nil || s.Data["accessor"] == nil { - return "", nil - } - - accessor, ok := s.Data["accessor"].(string) - if !ok { - return "", fmt.Errorf("token found but in the wrong format") - } - - return accessor, nil -} - -// TokenRemainingUses returns the standardized remaining uses for the given -// secret. If the secret is nil or does not contain the "num_uses", this -// returns -1. On error, this will return -1 and a non-nil error. -func (s *Secret) TokenRemainingUses() (int, error) { - if s == nil || s.Data == nil || s.Data["num_uses"] == nil { - return -1, nil - } - - uses, err := parseutil.ParseInt(s.Data["num_uses"]) - if err != nil { - return 0, err - } - - return int(uses), nil -} - -// TokenPolicies returns the standardized list of policies for the given secret. -// If the secret is nil or does not contain any policies, this returns nil. It -// also populates the secret's Auth info with identity/token policy info. -func (s *Secret) TokenPolicies() ([]string, error) { - if s == nil { - return nil, nil - } - - if s.Auth != nil && len(s.Auth.Policies) > 0 { - return s.Auth.Policies, nil - } - - if s.Data == nil || s.Data["policies"] == nil { - return nil, nil - } - - var tokenPolicies []string - - // Token policies - { - _, ok := s.Data["policies"] - if !ok { - goto TOKEN_DONE - } - - sList, ok := s.Data["policies"].([]string) - if ok { - tokenPolicies = sList - goto TOKEN_DONE - } - - list, ok := s.Data["policies"].([]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert token policies to expected format") - } - for _, v := range list { - p, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert policy %v to string", v) - } - tokenPolicies = append(tokenPolicies, p) - } - } - -TOKEN_DONE: - var identityPolicies []string - - // Identity policies - { - _, ok := s.Data["identity_policies"] - if !ok { - goto DONE - } - - sList, ok := s.Data["identity_policies"].([]string) - if ok { - identityPolicies = sList - goto DONE - } - - list, ok := s.Data["identity_policies"].([]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert identity policies to expected format") - } - for _, v := range list { - p, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert policy %v to string", v) - } - identityPolicies = append(identityPolicies, p) - } - } - -DONE: - - if s.Auth == nil { - s.Auth = &SecretAuth{} - } - - policies := append(tokenPolicies, identityPolicies...) - - s.Auth.TokenPolicies = tokenPolicies - s.Auth.IdentityPolicies = identityPolicies - s.Auth.Policies = policies - - return policies, nil -} - -// TokenMetadata returns the map of metadata associated with this token, if any -// exists. If the secret is nil or does not contain the "metadata" key, this -// returns nil. -func (s *Secret) TokenMetadata() (map[string]string, error) { - if s == nil { - return nil, nil - } - - if s.Auth != nil && len(s.Auth.Metadata) > 0 { - return s.Auth.Metadata, nil - } - - if s.Data == nil || (s.Data["metadata"] == nil && s.Data["meta"] == nil) { - return nil, nil - } - - data, ok := s.Data["metadata"].(map[string]interface{}) - if !ok { - data, ok = s.Data["meta"].(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert metadata field to expected format") - } - } - - metadata := make(map[string]string, len(data)) - for k, v := range data { - typed, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert metadata value %v to string", v) - } - metadata[k] = typed - } - - return metadata, nil -} - -// TokenIsRenewable returns the standardized token renewability for the given -// secret. If the secret is nil or does not contain the "renewable" key, this -// returns false. -func (s *Secret) TokenIsRenewable() (bool, error) { - if s == nil { - return false, nil - } - - if s.Auth != nil && s.Auth.Renewable { - return s.Auth.Renewable, nil - } - - if s.Data == nil || s.Data["renewable"] == nil { - return false, nil - } - - renewable, err := parseutil.ParseBool(s.Data["renewable"]) - if err != nil { - return false, errwrap.Wrapf("could not convert renewable value to a boolean: {{err}}", err) - } - - return renewable, nil -} - -// TokenTTL returns the standardized remaining token TTL for the given secret. -// If the secret is nil or does not contain a TTL, this returns 0. -func (s *Secret) TokenTTL() (time.Duration, error) { - if s == nil { - return 0, nil - } - - if s.Auth != nil && s.Auth.LeaseDuration > 0 { - return time.Duration(s.Auth.LeaseDuration) * time.Second, nil - } - - if s.Data == nil || s.Data["ttl"] == nil { - return 0, nil - } - - ttl, err := parseutil.ParseDurationSecond(s.Data["ttl"]) - if err != nil { - return 0, err - } - - return ttl, nil -} - -// SecretWrapInfo contains wrapping information if we have it. If what is -// contained is an authentication token, the accessor for the token will be -// available in WrappedAccessor. -type SecretWrapInfo struct { - Token string `json:"token"` - Accessor string `json:"accessor"` - TTL int `json:"ttl"` - CreationTime time.Time `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor"` -} - -// SecretAuth is the structure containing auth information if we have it. -type SecretAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies"` - IdentityPolicies []string `json:"identity_policies"` - Metadata map[string]string `json:"metadata"` - - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` -} - -// ParseSecret is used to parse a secret value from JSON from an io.Reader. -func ParseSecret(r io.Reader) (*Secret, error) { - // First read the data into a buffer. Not super efficient but we want to - // know if we actually have a body or not. - var buf bytes.Buffer - _, err := buf.ReadFrom(r) - if err != nil { - return nil, err - } - if buf.Len() == 0 { - return nil, nil - } - - // First decode the JSON into a map[string]interface{} - var secret Secret - if err := jsonutil.DecodeJSONFromReader(&buf, &secret); err != nil { - return nil, err - } - - return &secret, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/ssh.go b/vendor/github.com/hashicorp/vault/api/ssh.go deleted file mode 100644 index 837eac4f..00000000 --- a/vendor/github.com/hashicorp/vault/api/ssh.go +++ /dev/null @@ -1,62 +0,0 @@ -package api - -import ( - "context" - "fmt" -) - -// SSH is used to return a client to invoke operations on SSH backend. -type SSH struct { - c *Client - MountPoint string -} - -// SSH returns the client for logical-backend API calls. -func (c *Client) SSH() *SSH { - return c.SSHWithMountPoint(SSHHelperDefaultMountPoint) -} - -// SSHWithMountPoint returns the client with specific SSH mount point. -func (c *Client) SSHWithMountPoint(mountPoint string) *SSH { - return &SSH{ - c: c, - MountPoint: mountPoint, - } -} - -// Credential invokes the SSH backend API to create a credential to establish an SSH session. -func (c *SSH) Credential(role string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/creds/%s", c.MountPoint, role)) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// SignKey signs the given public key and returns a signed public key to pass -// along with the SSH request. -func (c *SSH) SignKey(role string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/sign/%s", c.MountPoint, role)) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} diff --git a/vendor/github.com/hashicorp/vault/api/ssh_agent.go b/vendor/github.com/hashicorp/vault/api/ssh_agent.go deleted file mode 100644 index 1dd681a5..00000000 --- a/vendor/github.com/hashicorp/vault/api/ssh_agent.go +++ /dev/null @@ -1,234 +0,0 @@ -package api - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "os" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-rootcerts" - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/helper/hclutil" - "github.com/mitchellh/mapstructure" -) - -const ( - // SSHHelperDefaultMountPoint is the default path at which SSH backend will be - // mounted in the Vault server. - SSHHelperDefaultMountPoint = "ssh" - - // VerifyEchoRequest is the echo request message sent as OTP by the helper. - VerifyEchoRequest = "verify-echo-request" - - // VerifyEchoResponse is the echo response message sent as a response to OTP - // matching echo request. - VerifyEchoResponse = "verify-echo-response" -) - -// SSHHelper is a structure representing a vault-ssh-helper which can talk to vault server -// in order to verify the OTP entered by the user. It contains the path at which -// SSH backend is mounted at the server. -type SSHHelper struct { - c *Client - MountPoint string -} - -// SSHVerifyResponse is a structure representing the fields in Vault server's -// response. -type SSHVerifyResponse struct { - // Usually empty. If the request OTP is echo request message, this will - // be set to the corresponding echo response message. - Message string `json:"message" mapstructure:"message"` - - // Username associated with the OTP - Username string `json:"username" mapstructure:"username"` - - // IP associated with the OTP - IP string `json:"ip" mapstructure:"ip"` - - // Name of the role against which the OTP was issued - RoleName string `json:"role_name" mapstructure:"role_name"` -} - -// SSHHelperConfig is a structure which represents the entries from the vault-ssh-helper's configuration file. -type SSHHelperConfig struct { - VaultAddr string `hcl:"vault_addr"` - SSHMountPoint string `hcl:"ssh_mount_point"` - CACert string `hcl:"ca_cert"` - CAPath string `hcl:"ca_path"` - AllowedCidrList string `hcl:"allowed_cidr_list"` - AllowedRoles string `hcl:"allowed_roles"` - TLSSkipVerify bool `hcl:"tls_skip_verify"` - TLSServerName string `hcl:"tls_server_name"` -} - -// SetTLSParameters sets the TLS parameters for this SSH agent. -func (c *SSHHelperConfig) SetTLSParameters(clientConfig *Config, certPool *x509.CertPool) { - tlsConfig := &tls.Config{ - InsecureSkipVerify: c.TLSSkipVerify, - MinVersion: tls.VersionTLS12, - RootCAs: certPool, - ServerName: c.TLSServerName, - } - - transport := cleanhttp.DefaultTransport() - transport.TLSClientConfig = tlsConfig - clientConfig.HttpClient.Transport = transport -} - -// Returns true if any of the following conditions are true: -// * CA cert is configured -// * CA path is configured -// * configured to skip certificate verification -// * TLS server name is configured -// -func (c *SSHHelperConfig) shouldSetTLSParameters() bool { - return c.CACert != "" || c.CAPath != "" || c.TLSServerName != "" || c.TLSSkipVerify -} - -// NewClient returns a new client for the configuration. This client will be used by the -// vault-ssh-helper to communicate with Vault server and verify the OTP entered by user. -// If the configuration supplies Vault SSL certificates, then the client will -// have TLS configured in its transport. -func (c *SSHHelperConfig) NewClient() (*Client, error) { - // Creating a default client configuration for communicating with vault server. - clientConfig := DefaultConfig() - - // Pointing the client to the actual address of vault server. - clientConfig.Address = c.VaultAddr - - // Check if certificates are provided via config file. - if c.shouldSetTLSParameters() { - rootConfig := &rootcerts.Config{ - CAFile: c.CACert, - CAPath: c.CAPath, - } - certPool, err := rootcerts.LoadCACerts(rootConfig) - if err != nil { - return nil, err - } - // Enable TLS on the HTTP client information - c.SetTLSParameters(clientConfig, certPool) - } - - // Creating the client object for the given configuration - client, err := NewClient(clientConfig) - if err != nil { - return nil, err - } - - return client, nil -} - -// LoadSSHHelperConfig loads ssh-helper's configuration from the file and populates the corresponding -// in-memory structure. -// -// Vault address is a required parameter. -// Mount point defaults to "ssh". -func LoadSSHHelperConfig(path string) (*SSHHelperConfig, error) { - contents, err := ioutil.ReadFile(path) - if err != nil && !os.IsNotExist(err) { - return nil, multierror.Prefix(err, "ssh_helper:") - } - return ParseSSHHelperConfig(string(contents)) -} - -// ParseSSHHelperConfig parses the given contents as a string for the SSHHelper -// configuration. -func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { - root, err := hcl.Parse(string(contents)) - if err != nil { - return nil, errwrap.Wrapf("error parsing config: {{err}}", err) - } - - list, ok := root.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("error parsing config: file doesn't contain a root object") - } - - valid := []string{ - "vault_addr", - "ssh_mount_point", - "ca_cert", - "ca_path", - "allowed_cidr_list", - "allowed_roles", - "tls_skip_verify", - "tls_server_name", - } - if err := hclutil.CheckHCLKeys(list, valid); err != nil { - return nil, multierror.Prefix(err, "ssh_helper:") - } - - var c SSHHelperConfig - c.SSHMountPoint = SSHHelperDefaultMountPoint - if err := hcl.DecodeObject(&c, list); err != nil { - return nil, multierror.Prefix(err, "ssh_helper:") - } - - if c.VaultAddr == "" { - return nil, fmt.Errorf(`missing config "vault_addr"`) - } - return &c, nil -} - -// SSHHelper creates an SSHHelper object which can talk to Vault server with SSH backend -// mounted at default path ("ssh"). -func (c *Client) SSHHelper() *SSHHelper { - return c.SSHHelperWithMountPoint(SSHHelperDefaultMountPoint) -} - -// SSHHelperWithMountPoint creates an SSHHelper object which can talk to Vault server with SSH backend -// mounted at a specific mount point. -func (c *Client) SSHHelperWithMountPoint(mountPoint string) *SSHHelper { - return &SSHHelper{ - c: c, - MountPoint: mountPoint, - } -} - -// Verify verifies if the key provided by user is present in Vault server. The response -// will contain the IP address and username associated with the OTP. In case the -// OTP matches the echo request message, instead of searching an entry for the OTP, -// an echo response message is returned. This feature is used by ssh-helper to verify if -// its configured correctly. -func (c *SSHHelper) Verify(otp string) (*SSHVerifyResponse, error) { - data := map[string]interface{}{ - "otp": otp, - } - verifyPath := fmt.Sprintf("/v1/%s/verify", c.MountPoint) - r := c.c.NewRequest("PUT", verifyPath) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - - if secret.Data == nil { - return nil, nil - } - - var verifyResp SSHVerifyResponse - err = mapstructure.Decode(secret.Data, &verifyResp) - if err != nil { - return nil, err - } - return &verifyResp, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/sys.go b/vendor/github.com/hashicorp/vault/api/sys.go deleted file mode 100644 index 5fb11188..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Sys is used to perform system-related operations on Vault. -type Sys struct { - c *Client -} - -// Sys is used to return the client for sys-related API calls. -func (c *Client) Sys() *Sys { - return &Sys{c: c} -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_audit.go b/vendor/github.com/hashicorp/vault/api/sys_audit.go deleted file mode 100644 index 2448c036..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_audit.go +++ /dev/null @@ -1,136 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) AuditHash(path string, input string) (string, error) { - body := map[string]interface{}{ - "input": input, - } - - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit-hash/%s", path)) - if err := r.SetJSONBody(body); err != nil { - return "", err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return "", err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return "", err - } - if secret == nil || secret.Data == nil { - return "", errors.New("data from server response is empty") - } - - hash, ok := secret.Data["hash"] - if !ok { - return "", errors.New("hash not found in response data") - } - hashStr, ok := hash.(string) - if !ok { - return "", errors.New("could not parse hash in response data") - } - - return hashStr, nil -} - -func (c *Sys) ListAudit() (map[string]*Audit, error) { - r := c.c.NewRequest("GET", "/v1/sys/audit") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*Audit{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -// DEPRECATED: Use EnableAuditWithOptions instead -func (c *Sys) EnableAudit( - path string, auditType string, desc string, opts map[string]string) error { - return c.EnableAuditWithOptions(path, &EnableAuditOptions{ - Type: auditType, - Description: desc, - Options: opts, - }) -} - -func (c *Sys) EnableAuditWithOptions(path string, options *EnableAuditOptions) error { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit/%s", path)) - if err := r.SetJSONBody(options); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DisableAudit(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/audit/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err == nil { - defer resp.Body.Close() - } - return err -} - -// Structures for the requests/resposne are all down here. They aren't -// individually documented because the map almost directly to the raw HTTP API -// documentation. Please refer to that documentation for more details. - -type EnableAuditOptions struct { - Type string `json:"type" mapstructure:"type"` - Description string `json:"description" mapstructure:"description"` - Options map[string]string `json:"options" mapstructure:"options"` - Local bool `json:"local" mapstructure:"local"` -} - -type Audit struct { - Type string `json:"type" mapstructure:"type"` - Description string `json:"description" mapstructure:"description"` - Options map[string]string `json:"options" mapstructure:"options"` - Local bool `json:"local" mapstructure:"local"` - Path string `json:"path" mapstructure:"path"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_auth.go b/vendor/github.com/hashicorp/vault/api/sys_auth.go deleted file mode 100644 index e7a9c222..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_auth.go +++ /dev/null @@ -1,80 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListAuth() (map[string]*AuthMount, error) { - r := c.c.NewRequest("GET", "/v1/sys/auth") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*AuthMount{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -// DEPRECATED: Use EnableAuthWithOptions instead -func (c *Sys) EnableAuth(path, authType, desc string) error { - return c.EnableAuthWithOptions(path, &EnableAuthOptions{ - Type: authType, - Description: desc, - }) -} - -func (c *Sys) EnableAuthWithOptions(path string, options *EnableAuthOptions) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/auth/%s", path)) - if err := r.SetJSONBody(options); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DisableAuth(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/auth/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -// Rather than duplicate, we can use modern Go's type aliasing -type EnableAuthOptions = MountInput -type AuthConfigInput = MountConfigInput -type AuthMount = MountOutput -type AuthConfigOutput = MountConfigOutput diff --git a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go b/vendor/github.com/hashicorp/vault/api/sys_capabilities.go deleted file mode 100644 index 64b3951d..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go +++ /dev/null @@ -1,64 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) CapabilitiesSelf(path string) ([]string, error) { - return c.Capabilities(c.c.Token(), path) -} - -func (c *Sys) Capabilities(token, path string) ([]string, error) { - body := map[string]string{ - "token": token, - "path": path, - } - - reqPath := "/v1/sys/capabilities" - if token == c.c.Token() { - reqPath = fmt.Sprintf("%s-self", reqPath) - } - - r := c.c.NewRequest("POST", reqPath) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var res []string - err = mapstructure.Decode(secret.Data[path], &res) - if err != nil { - return nil, err - } - - if len(res) == 0 { - _, ok := secret.Data["capabilities"] - if ok { - err = mapstructure.Decode(secret.Data["capabilities"], &res) - if err != nil { - return nil, err - } - } - } - - return res, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go b/vendor/github.com/hashicorp/vault/api/sys_config_cors.go deleted file mode 100644 index d153a47c..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go +++ /dev/null @@ -1,105 +0,0 @@ -package api - -import ( - "context" - "errors" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) CORSStatus() (*CORSResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/config/cors") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) ConfigureCORS(req *CORSRequest) (*CORSResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/config/cors") - if err := r.SetJSONBody(req); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) DisableCORS() (*CORSResponse, error) { - r := c.c.NewRequest("DELETE", "/v1/sys/config/cors") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -type CORSRequest struct { - AllowedOrigins string `json:"allowed_origins" mapstructure:"allowed_origins"` - Enabled bool `json:"enabled" mapstructure:"enabled"` -} - -type CORSResponse struct { - AllowedOrigins string `json:"allowed_origins" mapstructure:"allowed_origins"` - Enabled bool `json:"enabled" mapstructure:"enabled"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go b/vendor/github.com/hashicorp/vault/api/sys_generate_root.go deleted file mode 100644 index 66f72dff..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go +++ /dev/null @@ -1,124 +0,0 @@ -package api - -import "context" - -func (c *Sys) GenerateRootStatus() (*GenerateRootStatusResponse, error) { - return c.generateRootStatusCommon("/v1/sys/generate-root/attempt") -} - -func (c *Sys) GenerateDROperationTokenStatus() (*GenerateRootStatusResponse, error) { - return c.generateRootStatusCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt") -} - -func (c *Sys) generateRootStatusCommon(path string) (*GenerateRootStatusResponse, error) { - r := c.c.NewRequest("GET", path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) GenerateRootInit(otp, pgpKey string) (*GenerateRootStatusResponse, error) { - return c.generateRootInitCommon("/v1/sys/generate-root/attempt", otp, pgpKey) -} - -func (c *Sys) GenerateDROperationTokenInit(otp, pgpKey string) (*GenerateRootStatusResponse, error) { - return c.generateRootInitCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt", otp, pgpKey) -} - -func (c *Sys) generateRootInitCommon(path, otp, pgpKey string) (*GenerateRootStatusResponse, error) { - body := map[string]interface{}{ - "otp": otp, - "pgp_key": pgpKey, - } - - r := c.c.NewRequest("PUT", path) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) GenerateRootCancel() error { - return c.generateRootCancelCommon("/v1/sys/generate-root/attempt") -} - -func (c *Sys) GenerateDROperationTokenCancel() error { - return c.generateRootCancelCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt") -} - -func (c *Sys) generateRootCancelCommon(path string) error { - r := c.c.NewRequest("DELETE", path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) GenerateRootUpdate(shard, nonce string) (*GenerateRootStatusResponse, error) { - return c.generateRootUpdateCommon("/v1/sys/generate-root/update", shard, nonce) -} - -func (c *Sys) GenerateDROperationTokenUpdate(shard, nonce string) (*GenerateRootStatusResponse, error) { - return c.generateRootUpdateCommon("/v1/sys/replication/dr/secondary/generate-operation-token/update", shard, nonce) -} - -func (c *Sys) generateRootUpdateCommon(path, shard, nonce string) (*GenerateRootStatusResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", path) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type GenerateRootStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - Progress int `json:"progress"` - Required int `json:"required"` - Complete bool `json:"complete"` - EncodedToken string `json:"encoded_token"` - EncodedRootToken string `json:"encoded_root_token"` - PGPFingerprint string `json:"pgp_fingerprint"` - OTP string `json:"otp"` - OTPLength int `json:"otp_length"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_health.go b/vendor/github.com/hashicorp/vault/api/sys_health.go deleted file mode 100644 index e4c60d44..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_health.go +++ /dev/null @@ -1,40 +0,0 @@ -package api - -import "context" - -func (c *Sys) Health() (*HealthResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/health") - // If the code is 400 or above it will automatically turn into an error, - // but the sys/health API defaults to returning 5xx when not sealed or - // inited, so we force this code to be something else so we parse correctly - r.Params.Add("uninitcode", "299") - r.Params.Add("sealedcode", "299") - r.Params.Add("standbycode", "299") - r.Params.Add("drsecondarycode", "299") - r.Params.Add("performancestandbycode", "299") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result HealthResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type HealthResponse struct { - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - Standby bool `json:"standby"` - ReplicationPerformanceMode string `json:"replication_performance_mode"` - ReplicationDRMode string `json:"replication_dr_mode"` - ServerTimeUTC int64 `json:"server_time_utc"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` - LastWAL uint64 `json:"last_wal,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_init.go b/vendor/github.com/hashicorp/vault/api/sys_init.go deleted file mode 100644 index 0e499c6e..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_init.go +++ /dev/null @@ -1,61 +0,0 @@ -package api - -import "context" - -func (c *Sys) InitStatus() (bool, error) { - r := c.c.NewRequest("GET", "/v1/sys/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return false, err - } - defer resp.Body.Close() - - var result InitStatusResponse - err = resp.DecodeJSON(&result) - return result.Initialized, err -} - -func (c *Sys) Init(opts *InitRequest) (*InitResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/init") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result InitResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type InitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - RecoveryShares int `json:"recovery_shares"` - RecoveryThreshold int `json:"recovery_threshold"` - RecoveryPGPKeys []string `json:"recovery_pgp_keys"` - RootTokenPGPKey string `json:"root_token_pgp_key"` -} - -type InitStatusResponse struct { - Initialized bool -} - -type InitResponse struct { - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - RecoveryKeys []string `json:"recovery_keys"` - RecoveryKeysB64 []string `json:"recovery_keys_base64"` - RootToken string `json:"root_token"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_leader.go b/vendor/github.com/hashicorp/vault/api/sys_leader.go deleted file mode 100644 index 8846dcdf..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_leader.go +++ /dev/null @@ -1,29 +0,0 @@ -package api - -import "context" - -func (c *Sys) Leader() (*LeaderResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/leader") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result LeaderResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type LeaderResponse struct { - HAEnabled bool `json:"ha_enabled"` - IsSelf bool `json:"is_self"` - LeaderAddress string `json:"leader_address"` - LeaderClusterAddress string `json:"leader_cluster_address"` - PerfStandby bool `json:"performance_standby"` - PerfStandbyLastRemoteWAL uint64 `json:"performance_standby_last_remote_wal"` - LastWAL uint64 `json:"last_wal"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_leases.go b/vendor/github.com/hashicorp/vault/api/sys_leases.go deleted file mode 100644 index 09c9642a..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_leases.go +++ /dev/null @@ -1,105 +0,0 @@ -package api - -import ( - "context" - "errors" -) - -func (c *Sys) Renew(id string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/sys/leases/renew") - - body := map[string]interface{}{ - "increment": increment, - "lease_id": id, - } - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *Sys) Revoke(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokePrefix(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke-prefix/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokeForce(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke-force/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokeWithOptions(opts *RevokeOptions) error { - if opts == nil { - return errors.New("nil options provided") - } - - // Construct path - path := "/v1/sys/leases/revoke/" - switch { - case opts.Force: - path = "/v1/sys/leases/revoke-force/" - case opts.Prefix: - path = "/v1/sys/leases/revoke-prefix/" - } - path += opts.LeaseID - - r := c.c.NewRequest("PUT", path) - if !opts.Force { - body := map[string]interface{}{ - "sync": opts.Sync, - } - if err := r.SetJSONBody(body); err != nil { - return err - } - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -type RevokeOptions struct { - LeaseID string - Force bool - Prefix bool - Sync bool -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_mounts.go b/vendor/github.com/hashicorp/vault/api/sys_mounts.go deleted file mode 100644 index f5993c70..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_mounts.go +++ /dev/null @@ -1,182 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListMounts() (map[string]*MountOutput, error) { - r := c.c.NewRequest("GET", "/v1/sys/mounts") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*MountOutput{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -func (c *Sys) Mount(path string, mountInfo *MountInput) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s", path)) - if err := r.SetJSONBody(mountInfo); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) Unmount(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/mounts/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) Remount(from, to string) error { - body := map[string]interface{}{ - "from": from, - "to": to, - } - - r := c.c.NewRequest("POST", "/v1/sys/remount") - if err := r.SetJSONBody(body); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) TuneMount(path string, config MountConfigInput) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) - if err := r.SetJSONBody(config); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) MountConfig(path string) (*MountConfigOutput, error) { - r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result MountConfigOutput - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -type MountInput struct { - Type string `json:"type"` - Description string `json:"description"` - Config MountConfigInput `json:"config"` - Local bool `json:"local"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` - Options map[string]string `json:"options"` - - // Deprecated: Newer server responses should be returning this information in the - // Type field (json: "type") instead. - PluginName string `json:"plugin_name,omitempty"` -} - -type MountConfigInput struct { - Options map[string]string `json:"options" mapstructure:"options"` - DefaultLeaseTTL string `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - Description *string `json:"description,omitempty" mapstructure:"description"` - MaxLeaseTTL string `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" mapstructure:"force_no_cache"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` - TokenType string `json:"token_type,omitempty" mapstructure:"token_type"` - - // Deprecated: This field will always be blank for newer server responses. - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` -} - -type MountOutput struct { - Type string `json:"type"` - Description string `json:"description"` - Accessor string `json:"accessor"` - Config MountConfigOutput `json:"config"` - Options map[string]string `json:"options"` - Local bool `json:"local"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` -} - -type MountConfigOutput struct { - DefaultLeaseTTL int `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL int `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" mapstructure:"force_no_cache"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` - TokenType string `json:"token_type,omitempty" mapstructure:"token_type"` - - // Deprecated: This field will always be blank for newer server responses. - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_plugins.go b/vendor/github.com/hashicorp/vault/api/sys_plugins.go deleted file mode 100644 index d15165ee..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_plugins.go +++ /dev/null @@ -1,228 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/vault/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"` -} - -// 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"` - - // Names is the list of names of the plugins. - // - // Deprecated: Newer server responses should be returning PluginsByType (json: - // "types") instead. - Names []string `json:"names"` -} - -// ListPlugins lists all plugins in the catalog and returns their names as a -// list of strings. -func (c *Sys) ListPlugins(i *ListPluginsInput) (*ListPluginsResponse, error) { - path := "" - method := "" - if i.Type == consts.PluginTypeUnknown { - path = "/v1/sys/plugins/catalog" - method = "GET" - } else { - path = fmt.Sprintf("/v1/sys/plugins/catalog/%s", i.Type) - method = "LIST" - } - - req := c.c.NewRequest(method, path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - if resp.StatusCode == 405 && req.Method == "GET" { - // We received an Unsupported Operation response from Vault, indicating - // Vault of an older version that doesn't support the READ method yet. - req.Method = "LIST" - resp, err := c.c.RawRequestWithContext(ctx, req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var result struct { - Data struct { - Keys []string `json:"keys"` - } `json:"data"` - } - if err := resp.DecodeJSON(&result); err != nil { - return nil, err - } - return &ListPluginsResponse{Names: result.Data.Keys}, nil - } - - result := &ListPluginsResponse{ - PluginsByType: make(map[consts.PluginType][]string), - } - if i.Type == consts.PluginTypeUnknown { - for pluginTypeStr, pluginsRaw := range secret.Data { - pluginType, err := consts.ParsePluginType(pluginTypeStr) - if err != nil { - return nil, err - } - - pluginsIfc, ok := pluginsRaw.([]interface{}) - if !ok { - return nil, fmt.Errorf("unable to parse plugins for %q type", pluginTypeStr) - } - - plugins := make([]string, len(pluginsIfc)) - for i, nameIfc := range pluginsIfc { - name, ok := nameIfc.(string) - if !ok { - - } - plugins[i] = name - } - result.PluginsByType[pluginType] = plugins - } - } else { - var respKeys []string - if err := mapstructure.Decode(secret.Data["keys"], &respKeys); err != nil { - return nil, err - } - result.PluginsByType[i.Type] = respKeys - } - - return result, nil -} - -// GetPluginInput is used as input to the GetPlugin function. -type GetPluginInput struct { - Name string `json:"-"` - - // Type of the plugin. Required. - Type consts.PluginType `json:"type"` -} - -// GetPluginResponse is the response from the GetPlugin call. -type GetPluginResponse struct { - Args []string `json:"args"` - Builtin bool `json:"builtin"` - Command string `json:"command"` - Name string `json:"name"` - SHA256 string `json:"sha256"` -} - -// GetPlugin retrieves information about the plugin. -func (c *Sys) GetPlugin(i *GetPluginInput) (*GetPluginResponse, error) { - path := catalogPathByType(i.Type, i.Name) - req := c.c.NewRequest(http.MethodGet, path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result struct { - Data *GetPluginResponse - } - err = resp.DecodeJSON(&result) - if err != nil { - return nil, err - } - return result.Data, err -} - -// RegisterPluginInput is used as input to the RegisterPlugin function. -type RegisterPluginInput struct { - // Name is the name of the plugin. Required. - Name string `json:"-"` - - // Type of the plugin. Required. - Type consts.PluginType `json:"type"` - - // Args is the list of args to spawn the process with. - Args []string `json:"args,omitempty"` - - // Command is the command to run. - Command string `json:"command,omitempty"` - - // SHA256 is the shasum of the plugin. - SHA256 string `json:"sha256,omitempty"` -} - -// RegisterPlugin registers the plugin with the given information. -func (c *Sys) RegisterPlugin(i *RegisterPluginInput) error { - path := catalogPathByType(i.Type, i.Name) - req := c.c.NewRequest(http.MethodPut, path) - - if err := req.SetJSONBody(i); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err == nil { - defer resp.Body.Close() - } - return err -} - -// DeregisterPluginInput is used as input to the DeregisterPlugin function. -type DeregisterPluginInput struct { - // Name is the name of the plugin. Required. - Name string `json:"-"` - - // Type of the plugin. Required. - Type consts.PluginType `json:"type"` -} - -// DeregisterPlugin removes the plugin with the given name from the plugin -// catalog. -func (c *Sys) DeregisterPlugin(i *DeregisterPluginInput) error { - path := catalogPathByType(i.Type, i.Name) - req := c.c.NewRequest(http.MethodDelete, path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err == nil { - defer resp.Body.Close() - } - return err -} - -// catalogPathByType is a helper to construct the proper API path by plugin type -func catalogPathByType(pluginType consts.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 { - path = fmt.Sprintf("/v1/sys/plugins/catalog/%s", name) - } - - return path -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_policy.go b/vendor/github.com/hashicorp/vault/api/sys_policy.go deleted file mode 100644 index cdbb3f75..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_policy.go +++ /dev/null @@ -1,109 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListPolicies() ([]string, error) { - r := c.c.NewRequest("LIST", "/v1/sys/policies/acl") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result []string - err = mapstructure.Decode(secret.Data["keys"], &result) - if err != nil { - return nil, err - } - - return result, err -} - -func (c *Sys) GetPolicy(name string) (string, error) { - r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/policies/acl/%s", name)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - if resp.StatusCode == 404 { - return "", nil - } - } - if err != nil { - return "", err - } - - secret, err := ParseSecret(resp.Body) - if err != nil { - return "", err - } - if secret == nil || secret.Data == nil { - return "", errors.New("data from server response is empty") - } - - if policyRaw, ok := secret.Data["policy"]; ok { - return policyRaw.(string), nil - } - - return "", fmt.Errorf("no policy found in response") -} - -func (c *Sys) PutPolicy(name, rules string) error { - body := map[string]string{ - "policy": rules, - } - - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/policies/acl/%s", name)) - if err := r.SetJSONBody(body); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DeletePolicy(name string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/policies/acl/%s", name)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -type getPoliciesResp struct { - Rules string `json:"rules"` -} - -type listPoliciesResp struct { - Policies []string `json:"policies"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_rekey.go b/vendor/github.com/hashicorp/vault/api/sys_rekey.go deleted file mode 100644 index 55f1a703..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_rekey.go +++ /dev/null @@ -1,388 +0,0 @@ -package api - -import ( - "context" - "errors" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) RekeyStatus() (*RekeyStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyStatus() (*RekeyStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey-recovery-key/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyVerificationStatus() (*RekeyVerificationStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyVerificationStatus() (*RekeyVerificationStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey-recovery-key/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyInit(config *RekeyInitRequest) (*RekeyStatusResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/rekey/init") - if err := r.SetJSONBody(config); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyInit(config *RekeyInitRequest) (*RekeyStatusResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/init") - if err := r.SetJSONBody(config); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyRecoveryKeyCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey-recovery-key/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyVerificationCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyRecoveryKeyVerificationCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey-recovery-key/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyUpdate(shard, nonce string) (*RekeyUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey/update") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyUpdate(shard, nonce string) (*RekeyUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/update") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRetrieveBackup() (*RekeyRetrieveResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result RekeyRetrieveResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) RekeyRetrieveRecoveryBackup() (*RekeyRetrieveResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/recovery-backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result RekeyRetrieveResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) RekeyDeleteBackup() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - - return err -} - -func (c *Sys) RekeyDeleteRecoveryBackup() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/recovery-backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - - return err -} - -func (c *Sys) RekeyVerificationUpdate(shard, nonce string) (*RekeyVerificationUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey/verify") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyVerificationUpdate(shard, nonce string) (*RekeyVerificationUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/verify") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type RekeyInitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - Backup bool - RequireVerification bool `json:"require_verification"` -} - -type RekeyStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Required int `json:"required"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce"` -} - -type RekeyUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyRetrieveResponse struct { - Nonce string `json:"nonce" mapstructure:"nonce"` - Keys map[string][]string `json:"keys" mapstructure:"keys"` - KeysB64 map[string][]string `json:"keys_base64" mapstructure:"keys_base64"` -} - -type RekeyVerificationStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` -} - -type RekeyVerificationUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_rotate.go b/vendor/github.com/hashicorp/vault/api/sys_rotate.go deleted file mode 100644 index c525feb0..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_rotate.go +++ /dev/null @@ -1,77 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "time" -) - -func (c *Sys) Rotate() error { - r := c.c.NewRequest("POST", "/v1/sys/rotate") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) KeyStatus() (*KeyStatus, error) { - r := c.c.NewRequest("GET", "/v1/sys/key-status") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result KeyStatus - - termRaw, ok := secret.Data["term"] - if !ok { - return nil, errors.New("term not found in response") - } - term, ok := termRaw.(json.Number) - if !ok { - return nil, errors.New("could not convert term to a number") - } - term64, err := term.Int64() - if err != nil { - return nil, err - } - result.Term = int(term64) - - installTimeRaw, ok := secret.Data["install_time"] - if !ok { - return nil, errors.New("install_time not found in response") - } - installTimeStr, ok := installTimeRaw.(string) - if !ok { - return nil, errors.New("could not convert install_time to a string") - } - installTime, err := time.Parse(time.RFC3339Nano, installTimeStr) - if err != nil { - return nil, err - } - result.InstallTime = installTime - - return &result, err -} - -type KeyStatus struct { - Term int `json:"term"` - InstallTime time.Time `json:"install_time"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_seal.go b/vendor/github.com/hashicorp/vault/api/sys_seal.go deleted file mode 100644 index 301d3f26..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_seal.go +++ /dev/null @@ -1,86 +0,0 @@ -package api - -import "context" - -func (c *Sys) SealStatus() (*SealStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/seal-status") - return sealStatusRequest(c, r) -} - -func (c *Sys) Seal() error { - r := c.c.NewRequest("PUT", "/v1/sys/seal") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) ResetUnsealProcess() (*SealStatusResponse, error) { - body := map[string]interface{}{"reset": true} - - r := c.c.NewRequest("PUT", "/v1/sys/unseal") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - return sealStatusRequest(c, r) -} - -func (c *Sys) Unseal(shard string) (*SealStatusResponse, error) { - body := map[string]interface{}{"key": shard} - - r := c.c.NewRequest("PUT", "/v1/sys/unseal") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - return sealStatusRequest(c, r) -} - -func (c *Sys) UnsealWithOptions(opts *UnsealOpts) (*SealStatusResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/unseal") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - return sealStatusRequest(c, r) -} - -func sealStatusRequest(c *Sys, r *Request) (*SealStatusResponse, error) { - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result SealStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type SealStatusResponse struct { - Type string `json:"type"` - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Nonce string `json:"nonce"` - Version string `json:"version"` - Migration bool `json:"migration"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` - RecoverySeal bool `json:"recovery_seal"` -} - -type UnsealOpts struct { - Key string `json:"key"` - Reset bool `json:"reset"` - Migrate bool `json:"migrate"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go b/vendor/github.com/hashicorp/vault/api/sys_stepdown.go deleted file mode 100644 index 55dc6fbc..00000000 --- a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go +++ /dev/null @@ -1,15 +0,0 @@ -package api - -import "context" - -func (c *Sys) StepDown() error { - r := c.c.NewRequest("PUT", "/v1/sys/step-down") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil && resp.Body != nil { - resp.Body.Close() - } - return err -} diff --git a/vendor/github.com/hashicorp/vault/audit/audit.go b/vendor/github.com/hashicorp/vault/audit/audit.go deleted file mode 100644 index fed70335..00000000 --- a/vendor/github.com/hashicorp/vault/audit/audit.go +++ /dev/null @@ -1,63 +0,0 @@ -package audit - -import ( - "context" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -// Backend interface must be implemented for an audit -// mechanism to be made available. Audit backends can be enabled to -// sink information to different backends such as logs, file, databases, -// or other external services. -type Backend interface { - // LogRequest is used to synchronously log a request. This is done after the - // request is authorized but before the request is executed. The arguments - // MUST not be modified in anyway. They should be deep copied if this is - // a possibility. - LogRequest(context.Context, *LogInput) error - - // LogResponse is used to synchronously log a response. This is done after - // the request is processed but before the response is sent. The arguments - // MUST not be modified in anyway. They should be deep copied if this is - // a possibility. - LogResponse(context.Context, *LogInput) error - - // GetHash is used to return the given data with the backend's hash, - // so that a caller can determine if a value in the audit log matches - // an expected plaintext value - GetHash(context.Context, string) (string, error) - - // Reload is called on SIGHUP for supporting backends. - Reload(context.Context) error - - // Invalidate is called for path invalidation - Invalidate(context.Context) -} - -// LogInput contains the input parameters passed into LogRequest and LogResponse -type LogInput struct { - Auth *logical.Auth - Request *logical.Request - Response *logical.Response - OuterErr error - NonHMACReqDataKeys []string - NonHMACRespDataKeys []string -} - -// BackendConfig contains configuration parameters used in the factory func to -// instantiate audit backends -type BackendConfig struct { - // The view to store the salt - SaltView logical.Storage - - // The salt config that should be used for any secret obfuscation - SaltConfig *salt.Config - - // Config is the opaque user configuration provided when mounting - Config map[string]string -} - -// Factory is the factory function to create an audit backend. -type Factory func(context.Context, *BackendConfig) (Backend, error) diff --git a/vendor/github.com/hashicorp/vault/audit/format.go b/vendor/github.com/hashicorp/vault/audit/format.go deleted file mode 100644 index 76f81bf2..00000000 --- a/vendor/github.com/hashicorp/vault/audit/format.go +++ /dev/null @@ -1,488 +0,0 @@ -package audit - -import ( - "context" - "fmt" - "io" - "strings" - "time" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -type AuditFormatWriter interface { - WriteRequest(io.Writer, *AuditRequestEntry) error - WriteResponse(io.Writer, *AuditResponseEntry) error - Salt(context.Context) (*salt.Salt, error) -} - -// AuditFormatter implements the Formatter interface, and allows the underlying -// marshaller to be swapped out -type AuditFormatter struct { - AuditFormatWriter -} - -var _ Formatter = (*AuditFormatter)(nil) - -func (f *AuditFormatter) FormatRequest(ctx context.Context, w io.Writer, config FormatterConfig, in *LogInput) error { - if in == nil || in.Request == nil { - return fmt.Errorf("request to request-audit a nil request") - } - - if w == nil { - return fmt.Errorf("writer for audit request is nil") - } - - if f.AuditFormatWriter == nil { - return fmt.Errorf("no format writer specified") - } - - salt, err := f.Salt(ctx) - if err != nil { - return errwrap.Wrapf("error fetching salt: {{err}}", err) - } - - // Set these to the input values at first - auth := in.Auth - req := in.Request - - if !config.Raw { - // Before we copy the structure we must nil out some data - // otherwise we will cause reflection to panic and die - if in.Request.Connection != nil && in.Request.Connection.ConnState != nil { - origState := in.Request.Connection.ConnState - in.Request.Connection.ConnState = nil - defer func() { - in.Request.Connection.ConnState = origState - }() - } - - // Copy the auth structure - if in.Auth != nil { - cp, err := copystructure.Copy(in.Auth) - if err != nil { - return err - } - auth = cp.(*logical.Auth) - } - - cp, err := copystructure.Copy(in.Request) - if err != nil { - return err - } - req = cp.(*logical.Request) - - // Hash any sensitive information - if auth != nil { - // Cache and restore accessor in the auth - var authAccessor string - if !config.HMACAccessor && auth.Accessor != "" { - authAccessor = auth.Accessor - } - if err := Hash(salt, auth, nil); err != nil { - return err - } - if authAccessor != "" { - auth.Accessor = authAccessor - } - } - - // Cache and restore accessor in the request - var clientTokenAccessor string - if !config.HMACAccessor && req != nil && req.ClientTokenAccessor != "" { - clientTokenAccessor = req.ClientTokenAccessor - } - if err := Hash(salt, req, in.NonHMACReqDataKeys); err != nil { - return err - } - if clientTokenAccessor != "" { - req.ClientTokenAccessor = clientTokenAccessor - } - } - - // If auth is nil, make an empty one - if auth == nil { - auth = new(logical.Auth) - } - var errString string - if in.OuterErr != nil { - errString = in.OuterErr.Error() - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - reqEntry := &AuditRequestEntry{ - Type: "request", - Error: errString, - - Auth: AuditAuth{ - ClientToken: auth.ClientToken, - Accessor: auth.Accessor, - DisplayName: auth.DisplayName, - Policies: auth.Policies, - TokenPolicies: auth.TokenPolicies, - IdentityPolicies: auth.IdentityPolicies, - ExternalNamespacePolicies: auth.ExternalNamespacePolicies, - Metadata: auth.Metadata, - EntityID: auth.EntityID, - RemainingUses: req.ClientTokenRemainingUses, - TokenType: auth.TokenType.String(), - }, - - Request: AuditRequest{ - ID: req.ID, - ClientToken: req.ClientToken, - ClientTokenAccessor: req.ClientTokenAccessor, - Operation: req.Operation, - Namespace: AuditNamespace{ - ID: ns.ID, - Path: ns.Path, - }, - Path: req.Path, - Data: req.Data, - PolicyOverride: req.PolicyOverride, - RemoteAddr: getRemoteAddr(req), - ReplicationCluster: req.ReplicationCluster, - Headers: req.Headers, - }, - } - - if req.WrapInfo != nil { - reqEntry.Request.WrapTTL = int(req.WrapInfo.TTL / time.Second) - } - - if !config.OmitTime { - reqEntry.Time = time.Now().UTC().Format(time.RFC3339Nano) - } - - return f.AuditFormatWriter.WriteRequest(w, reqEntry) -} - -func (f *AuditFormatter) FormatResponse(ctx context.Context, w io.Writer, config FormatterConfig, in *LogInput) error { - if in == nil || in.Request == nil { - return fmt.Errorf("request to response-audit a nil request") - } - - if w == nil { - return fmt.Errorf("writer for audit request is nil") - } - - if f.AuditFormatWriter == nil { - return fmt.Errorf("no format writer specified") - } - - salt, err := f.Salt(ctx) - if err != nil { - return errwrap.Wrapf("error fetching salt: {{err}}", err) - } - - // Set these to the input values at first - auth := in.Auth - req := in.Request - resp := in.Response - - if !config.Raw { - // Before we copy the structure we must nil out some data - // otherwise we will cause reflection to panic and die - if in.Request.Connection != nil && in.Request.Connection.ConnState != nil { - origState := in.Request.Connection.ConnState - in.Request.Connection.ConnState = nil - defer func() { - in.Request.Connection.ConnState = origState - }() - } - - // Copy the auth structure - if in.Auth != nil { - cp, err := copystructure.Copy(in.Auth) - if err != nil { - return err - } - auth = cp.(*logical.Auth) - } - - cp, err := copystructure.Copy(in.Request) - if err != nil { - return err - } - req = cp.(*logical.Request) - - if in.Response != nil { - cp, err := copystructure.Copy(in.Response) - if err != nil { - return err - } - resp = cp.(*logical.Response) - } - - // Hash any sensitive information - - // Cache and restore accessor in the auth - if auth != nil { - var accessor string - if !config.HMACAccessor && auth.Accessor != "" { - accessor = auth.Accessor - } - if err := Hash(salt, auth, nil); err != nil { - return err - } - if accessor != "" { - auth.Accessor = accessor - } - } - - // Cache and restore accessor in the request - var clientTokenAccessor string - if !config.HMACAccessor && req != nil && req.ClientTokenAccessor != "" { - clientTokenAccessor = req.ClientTokenAccessor - } - if err := Hash(salt, req, in.NonHMACReqDataKeys); err != nil { - return err - } - if clientTokenAccessor != "" { - req.ClientTokenAccessor = clientTokenAccessor - } - - // Cache and restore accessor in the response - if resp != nil { - var accessor, wrappedAccessor, wrappingAccessor string - if !config.HMACAccessor && resp != nil && resp.Auth != nil && resp.Auth.Accessor != "" { - accessor = resp.Auth.Accessor - } - if !config.HMACAccessor && resp != nil && resp.WrapInfo != nil && resp.WrapInfo.WrappedAccessor != "" { - wrappedAccessor = resp.WrapInfo.WrappedAccessor - wrappingAccessor = resp.WrapInfo.Accessor - } - if err := Hash(salt, resp, in.NonHMACRespDataKeys); err != nil { - return err - } - if accessor != "" { - resp.Auth.Accessor = accessor - } - if wrappedAccessor != "" { - resp.WrapInfo.WrappedAccessor = wrappedAccessor - } - if wrappingAccessor != "" { - resp.WrapInfo.Accessor = wrappingAccessor - } - } - } - - // If things are nil, make empty to avoid panics - if auth == nil { - auth = new(logical.Auth) - } - if resp == nil { - resp = new(logical.Response) - } - var errString string - if in.OuterErr != nil { - errString = in.OuterErr.Error() - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - var respAuth *AuditAuth - if resp.Auth != nil { - respAuth = &AuditAuth{ - ClientToken: resp.Auth.ClientToken, - Accessor: resp.Auth.Accessor, - DisplayName: resp.Auth.DisplayName, - Policies: resp.Auth.Policies, - TokenPolicies: resp.Auth.TokenPolicies, - IdentityPolicies: resp.Auth.IdentityPolicies, - ExternalNamespacePolicies: resp.Auth.ExternalNamespacePolicies, - Metadata: resp.Auth.Metadata, - NumUses: resp.Auth.NumUses, - EntityID: resp.Auth.EntityID, - TokenType: resp.Auth.TokenType.String(), - } - } - - var respSecret *AuditSecret - if resp.Secret != nil { - respSecret = &AuditSecret{ - LeaseID: resp.Secret.LeaseID, - } - } - - var respWrapInfo *AuditResponseWrapInfo - if resp.WrapInfo != nil { - token := resp.WrapInfo.Token - if jwtToken := parseVaultTokenFromJWT(token); jwtToken != nil { - token = *jwtToken - } - respWrapInfo = &AuditResponseWrapInfo{ - TTL: int(resp.WrapInfo.TTL / time.Second), - Token: token, - Accessor: resp.WrapInfo.Accessor, - CreationTime: resp.WrapInfo.CreationTime.UTC().Format(time.RFC3339Nano), - CreationPath: resp.WrapInfo.CreationPath, - WrappedAccessor: resp.WrapInfo.WrappedAccessor, - } - } - - respEntry := &AuditResponseEntry{ - Type: "response", - Error: errString, - Auth: AuditAuth{ - ClientToken: auth.ClientToken, - Accessor: auth.Accessor, - DisplayName: auth.DisplayName, - Policies: auth.Policies, - TokenPolicies: auth.TokenPolicies, - IdentityPolicies: auth.IdentityPolicies, - ExternalNamespacePolicies: auth.ExternalNamespacePolicies, - Metadata: auth.Metadata, - RemainingUses: req.ClientTokenRemainingUses, - EntityID: auth.EntityID, - TokenType: auth.TokenType.String(), - }, - - Request: AuditRequest{ - ID: req.ID, - ClientToken: req.ClientToken, - ClientTokenAccessor: req.ClientTokenAccessor, - Operation: req.Operation, - Namespace: AuditNamespace{ - ID: ns.ID, - Path: ns.Path, - }, - Path: req.Path, - Data: req.Data, - PolicyOverride: req.PolicyOverride, - RemoteAddr: getRemoteAddr(req), - ReplicationCluster: req.ReplicationCluster, - Headers: req.Headers, - }, - - Response: AuditResponse{ - Auth: respAuth, - Secret: respSecret, - Data: resp.Data, - Redirect: resp.Redirect, - WrapInfo: respWrapInfo, - }, - } - - if req.WrapInfo != nil { - respEntry.Request.WrapTTL = int(req.WrapInfo.TTL / time.Second) - } - - if !config.OmitTime { - respEntry.Time = time.Now().UTC().Format(time.RFC3339Nano) - } - - return f.AuditFormatWriter.WriteResponse(w, respEntry) -} - -// AuditRequestEntry is the structure of a request audit log entry in Audit. -type AuditRequestEntry struct { - Time string `json:"time,omitempty"` - Type string `json:"type"` - Auth AuditAuth `json:"auth"` - Request AuditRequest `json:"request"` - Error string `json:"error"` -} - -// AuditResponseEntry is the structure of a response audit log entry in Audit. -type AuditResponseEntry struct { - Time string `json:"time,omitempty"` - Type string `json:"type"` - Auth AuditAuth `json:"auth"` - Request AuditRequest `json:"request"` - Response AuditResponse `json:"response"` - Error string `json:"error"` -} - -type AuditRequest struct { - ID string `json:"id"` - ReplicationCluster string `json:"replication_cluster,omitempty"` - Operation logical.Operation `json:"operation"` - ClientToken string `json:"client_token"` - ClientTokenAccessor string `json:"client_token_accessor"` - Namespace AuditNamespace `json:"namespace"` - Path string `json:"path"` - Data map[string]interface{} `json:"data"` - PolicyOverride bool `json:"policy_override"` - RemoteAddr string `json:"remote_address"` - WrapTTL int `json:"wrap_ttl"` - Headers map[string][]string `json:"headers"` -} - -type AuditResponse struct { - Auth *AuditAuth `json:"auth,omitempty"` - Secret *AuditSecret `json:"secret,omitempty"` - Data map[string]interface{} `json:"data,omitempty"` - Redirect string `json:"redirect,omitempty"` - WrapInfo *AuditResponseWrapInfo `json:"wrap_info,omitempty"` -} - -type AuditAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - DisplayName string `json:"display_name"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies,omitempty"` - IdentityPolicies []string `json:"identity_policies,omitempty"` - ExternalNamespacePolicies map[string][]string `json:"external_namespace_policies,omitempty"` - Metadata map[string]string `json:"metadata"` - NumUses int `json:"num_uses,omitempty"` - RemainingUses int `json:"remaining_uses,omitempty"` - EntityID string `json:"entity_id"` - TokenType string `json:"token_type"` -} - -type AuditSecret struct { - LeaseID string `json:"lease_id"` -} - -type AuditResponseWrapInfo struct { - TTL int `json:"ttl"` - Token string `json:"token"` - Accessor string `json:"accessor"` - CreationTime string `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor,omitempty"` -} - -type AuditNamespace struct { - ID string `json:"id"` - Path string `json:"path"` -} - -// getRemoteAddr safely gets the remote address avoiding a nil pointer -func getRemoteAddr(req *logical.Request) string { - if req != nil && req.Connection != nil { - return req.Connection.RemoteAddr - } - return "" -} - -// parseVaultTokenFromJWT returns a string iff the token was a JWT and we could -// extract the original token ID from inside -func parseVaultTokenFromJWT(token string) *string { - if strings.Count(token, ".") != 2 { - return nil - } - - wt, err := jws.ParseJWT([]byte(token)) - if err != nil || wt == nil { - return nil - } - - result, _ := wt.Claims().JWTID() - - return &result -} diff --git a/vendor/github.com/hashicorp/vault/audit/format_json.go b/vendor/github.com/hashicorp/vault/audit/format_json.go deleted file mode 100644 index f42ab20d..00000000 --- a/vendor/github.com/hashicorp/vault/audit/format_json.go +++ /dev/null @@ -1,53 +0,0 @@ -package audit - -import ( - "context" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/vault/helper/salt" -) - -// JSONFormatWriter is an AuditFormatWriter implementation that structures data into -// a JSON format. -type JSONFormatWriter struct { - Prefix string - SaltFunc func(context.Context) (*salt.Salt, error) -} - -func (f *JSONFormatWriter) WriteRequest(w io.Writer, req *AuditRequestEntry) error { - if req == nil { - return fmt.Errorf("request entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - enc := json.NewEncoder(w) - return enc.Encode(req) -} - -func (f *JSONFormatWriter) WriteResponse(w io.Writer, resp *AuditResponseEntry) error { - if resp == nil { - return fmt.Errorf("response entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - enc := json.NewEncoder(w) - return enc.Encode(resp) -} - -func (f *JSONFormatWriter) Salt(ctx context.Context) (*salt.Salt, error) { - return f.SaltFunc(ctx) -} diff --git a/vendor/github.com/hashicorp/vault/audit/format_jsonx.go b/vendor/github.com/hashicorp/vault/audit/format_jsonx.go deleted file mode 100644 index 30937464..00000000 --- a/vendor/github.com/hashicorp/vault/audit/format_jsonx.go +++ /dev/null @@ -1,74 +0,0 @@ -package audit - -import ( - "context" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/vault/helper/salt" - "github.com/jefferai/jsonx" -) - -// JSONxFormatWriter is an AuditFormatWriter implementation that structures data into -// a XML format. -type JSONxFormatWriter struct { - Prefix string - SaltFunc func(context.Context) (*salt.Salt, error) -} - -func (f *JSONxFormatWriter) WriteRequest(w io.Writer, req *AuditRequestEntry) error { - if req == nil { - return fmt.Errorf("request entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - jsonBytes, err := json.Marshal(req) - if err != nil { - return err - } - - xmlBytes, err := jsonx.EncodeJSONBytes(jsonBytes) - if err != nil { - return err - } - - _, err = w.Write(xmlBytes) - return err -} - -func (f *JSONxFormatWriter) WriteResponse(w io.Writer, resp *AuditResponseEntry) error { - if resp == nil { - return fmt.Errorf("response entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - jsonBytes, err := json.Marshal(resp) - if err != nil { - return err - } - - xmlBytes, err := jsonx.EncodeJSONBytes(jsonBytes) - if err != nil { - return err - } - - _, err = w.Write(xmlBytes) - return err -} - -func (f *JSONxFormatWriter) Salt(ctx context.Context) (*salt.Salt, error) { - return f.SaltFunc(ctx) -} diff --git a/vendor/github.com/hashicorp/vault/audit/formatter.go b/vendor/github.com/hashicorp/vault/audit/formatter.go deleted file mode 100644 index 7702a1ee..00000000 --- a/vendor/github.com/hashicorp/vault/audit/formatter.go +++ /dev/null @@ -1,24 +0,0 @@ -package audit - -import ( - "context" - "io" -) - -// Formatter is an interface that is responsible for formating a -// request/response into some format. Formatters write their output -// to an io.Writer. -// -// It is recommended that you pass data through Hash prior to formatting it. -type Formatter interface { - FormatRequest(context.Context, io.Writer, FormatterConfig, *LogInput) error - FormatResponse(context.Context, io.Writer, FormatterConfig, *LogInput) error -} - -type FormatterConfig struct { - Raw bool - HMACAccessor bool - - // This should only ever be used in a testing context - OmitTime bool -} diff --git a/vendor/github.com/hashicorp/vault/audit/hashstructure.go b/vendor/github.com/hashicorp/vault/audit/hashstructure.go deleted file mode 100644 index be1aad97..00000000 --- a/vendor/github.com/hashicorp/vault/audit/hashstructure.go +++ /dev/null @@ -1,319 +0,0 @@ -package audit - -import ( - "errors" - "reflect" - "strings" - "time" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" - "github.com/mitchellh/reflectwalk" -) - -// HashString hashes the given opaque string and returns it -func HashString(salter *salt.Salt, data string) string { - return salter.GetIdentifiedHMAC(data) -} - -// Hash will hash the given type. This has built-in support for auth, -// requests, and responses. If it is a type that isn't recognized, then -// it will be passed through. -// -// The structure is modified in-place. -func Hash(salter *salt.Salt, raw interface{}, nonHMACDataKeys []string) error { - fn := salter.GetIdentifiedHMAC - - switch s := raw.(type) { - case *logical.Auth: - if s == nil { - return nil - } - if s.ClientToken != "" { - s.ClientToken = fn(s.ClientToken) - } - if s.Accessor != "" { - s.Accessor = fn(s.Accessor) - } - - case *logical.Request: - if s == nil { - return nil - } - if s.Auth != nil { - if err := Hash(salter, s.Auth, nil); err != nil { - return err - } - } - - if s.ClientToken != "" { - s.ClientToken = fn(s.ClientToken) - } - - if s.ClientTokenAccessor != "" { - s.ClientTokenAccessor = fn(s.ClientTokenAccessor) - } - - data, err := HashStructure(s.Data, fn, nonHMACDataKeys) - if err != nil { - return err - } - - s.Data = data.(map[string]interface{}) - - case *logical.Response: - if s == nil { - return nil - } - - if s.Auth != nil { - if err := Hash(salter, s.Auth, nil); err != nil { - return err - } - } - - if s.WrapInfo != nil { - if err := Hash(salter, s.WrapInfo, nil); err != nil { - return err - } - } - - data, err := HashStructure(s.Data, fn, nonHMACDataKeys) - if err != nil { - return err - } - - s.Data = data.(map[string]interface{}) - - case *wrapping.ResponseWrapInfo: - if s == nil { - return nil - } - - s.Token = fn(s.Token) - s.Accessor = fn(s.Accessor) - - if s.WrappedAccessor != "" { - s.WrappedAccessor = fn(s.WrappedAccessor) - } - } - - return nil -} - -// HashStructure takes an interface and hashes all the values within -// the structure. Only _values_ are hashed: keys of objects are not. -// -// For the HashCallback, see the built-in HashCallbacks below. -func HashStructure(s interface{}, cb HashCallback, ignoredKeys []string) (interface{}, error) { - s, err := copystructure.Copy(s) - if err != nil { - return nil, err - } - - walker := &hashWalker{Callback: cb, IgnoredKeys: ignoredKeys} - if err := reflectwalk.Walk(s, walker); err != nil { - return nil, err - } - - return s, nil -} - -// HashCallback is the callback called for HashStructure to hash -// a value. -type HashCallback func(string) string - -// hashWalker implements interfaces for the reflectwalk package -// (github.com/mitchellh/reflectwalk) that can be used to automatically -// replace primitives with a hashed value. -type hashWalker struct { - // Callback is the function to call with the primitive that is - // to be hashed. If there is an error, walking will be halted - // immediately and the error returned. - Callback HashCallback - - // IgnoreKeys are the keys that wont have the HashCallback applied - IgnoredKeys []string - - key []string - lastValue reflect.Value - loc reflectwalk.Location - cs []reflect.Value - csKey []reflect.Value - csData interface{} - sliceIndex int - unknownKeys []string -} - -// hashTimeType stores a pre-computed reflect.Type for a time.Time so -// we can quickly compare in hashWalker.Struct. We create an empty/invalid -// time.Time{} so we don't need to incur any additional startup cost vs. -// Now() or Unix(). -var hashTimeType = reflect.TypeOf(time.Time{}) - -func (w *hashWalker) Enter(loc reflectwalk.Location) error { - w.loc = loc - return nil -} - -func (w *hashWalker) Exit(loc reflectwalk.Location) error { - w.loc = reflectwalk.None - - switch loc { - case reflectwalk.Map: - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.MapValue: - w.key = w.key[:len(w.key)-1] - w.csKey = w.csKey[:len(w.csKey)-1] - case reflectwalk.Slice: - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.SliceElem: - w.csKey = w.csKey[:len(w.csKey)-1] - } - - return nil -} - -func (w *hashWalker) Map(m reflect.Value) error { - w.cs = append(w.cs, m) - return nil -} - -func (w *hashWalker) MapElem(m, k, v reflect.Value) error { - w.csData = k - w.csKey = append(w.csKey, k) - w.key = append(w.key, k.String()) - w.lastValue = v - return nil -} - -func (w *hashWalker) Slice(s reflect.Value) error { - w.cs = append(w.cs, s) - return nil -} - -func (w *hashWalker) SliceElem(i int, elem reflect.Value) error { - w.csKey = append(w.csKey, reflect.ValueOf(i)) - w.sliceIndex = i - return nil -} - -func (w *hashWalker) Struct(v reflect.Value) error { - // We are looking for time values. If it isn't one, ignore it. - if v.Type() != hashTimeType { - return nil - } - - // If we aren't in a map value, return an error to prevent a panic - if v.Interface() != w.lastValue.Interface() { - return errors.New("time.Time value in a non map key cannot be hashed for audits") - } - - // Create a string value of the time. IMPORTANT: this must never change - // across Vault versions or the hash value of equivalent time.Time will - // change. - strVal := v.Interface().(time.Time).Format(time.RFC3339Nano) - - // Set the map value to the string instead of the time.Time object - m := w.cs[len(w.cs)-1] - mk := w.csData.(reflect.Value) - m.SetMapIndex(mk, reflect.ValueOf(strVal)) - - // Skip this entry so that we don't walk the struct. - return reflectwalk.SkipEntry -} - -func (w *hashWalker) StructField(reflect.StructField, reflect.Value) error { - return nil -} - -func (w *hashWalker) Primitive(v reflect.Value) error { - if w.Callback == nil { - return nil - } - - // We don't touch map keys - if w.loc == reflectwalk.MapKey { - return nil - } - - setV := v - - // We only care about strings - if v.Kind() == reflect.Interface { - setV = v - v = v.Elem() - } - if v.Kind() != reflect.String { - return nil - } - - // See if the current key is part of the ignored keys - currentKey := w.key[len(w.key)-1] - if strutil.StrListContains(w.IgnoredKeys, currentKey) { - return nil - } - - replaceVal := w.Callback(v.String()) - - resultVal := reflect.ValueOf(replaceVal) - switch w.loc { - case reflectwalk.MapKey: - m := w.cs[len(w.cs)-1] - - // Delete the old value - var zero reflect.Value - m.SetMapIndex(w.csData.(reflect.Value), zero) - - // Set the new key with the existing value - m.SetMapIndex(resultVal, w.lastValue) - - // Set the key to be the new key - w.csData = resultVal - case reflectwalk.MapValue: - // If we're in a map, then the only way to set a map value is - // to set it directly. - m := w.cs[len(w.cs)-1] - mk := w.csData.(reflect.Value) - m.SetMapIndex(mk, resultVal) - default: - // Otherwise, we should be addressable - setV.Set(resultVal) - } - - return nil -} - -func (w *hashWalker) removeCurrent() { - // Append the key to the unknown keys - w.unknownKeys = append(w.unknownKeys, strings.Join(w.key, ".")) - - for i := 1; i <= len(w.cs); i++ { - c := w.cs[len(w.cs)-i] - switch c.Kind() { - case reflect.Map: - // Zero value so that we delete the map key - var val reflect.Value - - // Get the key and delete it - k := w.csData.(reflect.Value) - c.SetMapIndex(k, val) - return - } - } - - panic("No container found for removeCurrent") -} - -func (w *hashWalker) replaceCurrent(v reflect.Value) { - c := w.cs[len(w.cs)-2] - switch c.Kind() { - case reflect.Map: - // Get the key and delete it - k := w.csKey[len(w.csKey)-1] - c.SetMapIndex(k, v) - } -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/client.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/client.go deleted file mode 100644 index ea71a6f7..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/client.go +++ /dev/null @@ -1,91 +0,0 @@ -package dbplugin - -import ( - "context" - "errors" - "sync" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" -) - -// DatabasePluginClient embeds a databasePluginRPCClient and wraps it's Close -// method to also call Kill() on the plugin.Client. -type DatabasePluginClient struct { - client *plugin.Client - sync.Mutex - - Database -} - -// This wraps the Close call and ensures we both close the database connection -// and kill the plugin. -func (dc *DatabasePluginClient) Close() error { - err := dc.Database.Close() - dc.client.Kill() - - return err -} - -// NewPluginClient returns a databaseRPCClient with a connection to a running -// plugin. The client is wrapped in a DatabasePluginClient object to ensure the -// plugin is killed on call of Close(). -func NewPluginClient(ctx context.Context, sys pluginutil.RunnerUtil, pluginRunner *pluginutil.PluginRunner, logger log.Logger, isMetadataMode bool) (Database, error) { - - // pluginSets is the map of plugins we can dispense. - pluginSets := map[int]plugin.PluginSet{ - // Version 3 supports both protocols - 3: plugin.PluginSet{ - "database": &DatabasePlugin{ - GRPCDatabasePlugin: new(GRPCDatabasePlugin), - }, - }, - // Version 4 only supports gRPC - 4: plugin.PluginSet{ - "database": new(GRPCDatabasePlugin), - }, - } - - var client *plugin.Client - var err error - if isMetadataMode { - client, err = pluginRunner.RunMetadataMode(ctx, sys, pluginSets, handshakeConfig, []string{}, logger) - } else { - client, err = pluginRunner.Run(ctx, sys, pluginSets, handshakeConfig, []string{}, logger) - } - if err != nil { - return nil, err - } - - // Connect via RPC - rpcClient, err := client.Client() - if err != nil { - return nil, err - } - - // Request the plugin - raw, err := rpcClient.Dispense("database") - if err != nil { - return nil, err - } - - // We should have a database type now. This feels like a normal interface - // implementation but is in fact over an RPC connection. - var db Database - switch raw.(type) { - case *gRPCClient: - db = raw.(*gRPCClient) - case *databasePluginRPCClient: - logger.Warn("plugin is using deprecated netRPC transport, recompile plugin to upgrade to gRPC", "plugin", pluginRunner.Name) - db = raw.(*databasePluginRPCClient) - default: - return nil, errors.New("unsupported client type") - } - - // Wrap RPC implementation in DatabasePluginClient - return &DatabasePluginClient{ - client: client, - Database: db, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.pb.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.pb.go deleted file mode 100644 index 3da44217..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.pb.go +++ /dev/null @@ -1,1037 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: builtin/logical/database/dbplugin/database.proto - -package dbplugin - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - timestamp "github.com/golang/protobuf/ptypes/timestamp" - 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 - -// Deprecated: Do not use. -type InitializeRequest struct { - Config []byte `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - VerifyConnection bool `protobuf:"varint,2,opt,name=verify_connection,json=verifyConnection,proto3" json:"verify_connection,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitializeRequest) Reset() { *m = InitializeRequest{} } -func (m *InitializeRequest) String() string { return proto.CompactTextString(m) } -func (*InitializeRequest) ProtoMessage() {} -func (*InitializeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{0} -} - -func (m *InitializeRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitializeRequest.Unmarshal(m, b) -} -func (m *InitializeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitializeRequest.Marshal(b, m, deterministic) -} -func (m *InitializeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitializeRequest.Merge(m, src) -} -func (m *InitializeRequest) XXX_Size() int { - return xxx_messageInfo_InitializeRequest.Size(m) -} -func (m *InitializeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitializeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitializeRequest proto.InternalMessageInfo - -func (m *InitializeRequest) GetConfig() []byte { - if m != nil { - return m.Config - } - return nil -} - -func (m *InitializeRequest) GetVerifyConnection() bool { - if m != nil { - return m.VerifyConnection - } - return false -} - -type InitRequest struct { - Config []byte `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - VerifyConnection bool `protobuf:"varint,2,opt,name=verify_connection,json=verifyConnection,proto3" json:"verify_connection,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitRequest) Reset() { *m = InitRequest{} } -func (m *InitRequest) String() string { return proto.CompactTextString(m) } -func (*InitRequest) ProtoMessage() {} -func (*InitRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{1} -} - -func (m *InitRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitRequest.Unmarshal(m, b) -} -func (m *InitRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitRequest.Marshal(b, m, deterministic) -} -func (m *InitRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitRequest.Merge(m, src) -} -func (m *InitRequest) XXX_Size() int { - return xxx_messageInfo_InitRequest.Size(m) -} -func (m *InitRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitRequest proto.InternalMessageInfo - -func (m *InitRequest) GetConfig() []byte { - if m != nil { - return m.Config - } - return nil -} - -func (m *InitRequest) GetVerifyConnection() bool { - if m != nil { - return m.VerifyConnection - } - return false -} - -type CreateUserRequest struct { - Statements *Statements `protobuf:"bytes,1,opt,name=statements,proto3" json:"statements,omitempty"` - UsernameConfig *UsernameConfig `protobuf:"bytes,2,opt,name=username_config,json=usernameConfig,proto3" json:"username_config,omitempty"` - Expiration *timestamp.Timestamp `protobuf:"bytes,3,opt,name=expiration,proto3" json:"expiration,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateUserRequest) Reset() { *m = CreateUserRequest{} } -func (m *CreateUserRequest) String() string { return proto.CompactTextString(m) } -func (*CreateUserRequest) ProtoMessage() {} -func (*CreateUserRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{2} -} - -func (m *CreateUserRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateUserRequest.Unmarshal(m, b) -} -func (m *CreateUserRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateUserRequest.Marshal(b, m, deterministic) -} -func (m *CreateUserRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateUserRequest.Merge(m, src) -} -func (m *CreateUserRequest) XXX_Size() int { - return xxx_messageInfo_CreateUserRequest.Size(m) -} -func (m *CreateUserRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CreateUserRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateUserRequest proto.InternalMessageInfo - -func (m *CreateUserRequest) GetStatements() *Statements { - if m != nil { - return m.Statements - } - return nil -} - -func (m *CreateUserRequest) GetUsernameConfig() *UsernameConfig { - if m != nil { - return m.UsernameConfig - } - return nil -} - -func (m *CreateUserRequest) GetExpiration() *timestamp.Timestamp { - if m != nil { - return m.Expiration - } - return nil -} - -type RenewUserRequest struct { - Statements *Statements `protobuf:"bytes,1,opt,name=statements,proto3" json:"statements,omitempty"` - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - Expiration *timestamp.Timestamp `protobuf:"bytes,3,opt,name=expiration,proto3" json:"expiration,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RenewUserRequest) Reset() { *m = RenewUserRequest{} } -func (m *RenewUserRequest) String() string { return proto.CompactTextString(m) } -func (*RenewUserRequest) ProtoMessage() {} -func (*RenewUserRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{3} -} - -func (m *RenewUserRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RenewUserRequest.Unmarshal(m, b) -} -func (m *RenewUserRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RenewUserRequest.Marshal(b, m, deterministic) -} -func (m *RenewUserRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RenewUserRequest.Merge(m, src) -} -func (m *RenewUserRequest) XXX_Size() int { - return xxx_messageInfo_RenewUserRequest.Size(m) -} -func (m *RenewUserRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RenewUserRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RenewUserRequest proto.InternalMessageInfo - -func (m *RenewUserRequest) GetStatements() *Statements { - if m != nil { - return m.Statements - } - return nil -} - -func (m *RenewUserRequest) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *RenewUserRequest) GetExpiration() *timestamp.Timestamp { - if m != nil { - return m.Expiration - } - return nil -} - -type RevokeUserRequest struct { - Statements *Statements `protobuf:"bytes,1,opt,name=statements,proto3" json:"statements,omitempty"` - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RevokeUserRequest) Reset() { *m = RevokeUserRequest{} } -func (m *RevokeUserRequest) String() string { return proto.CompactTextString(m) } -func (*RevokeUserRequest) ProtoMessage() {} -func (*RevokeUserRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{4} -} - -func (m *RevokeUserRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RevokeUserRequest.Unmarshal(m, b) -} -func (m *RevokeUserRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RevokeUserRequest.Marshal(b, m, deterministic) -} -func (m *RevokeUserRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RevokeUserRequest.Merge(m, src) -} -func (m *RevokeUserRequest) XXX_Size() int { - return xxx_messageInfo_RevokeUserRequest.Size(m) -} -func (m *RevokeUserRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RevokeUserRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RevokeUserRequest proto.InternalMessageInfo - -func (m *RevokeUserRequest) GetStatements() *Statements { - if m != nil { - return m.Statements - } - return nil -} - -func (m *RevokeUserRequest) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -type RotateRootCredentialsRequest struct { - Statements []string `protobuf:"bytes,1,rep,name=statements,proto3" json:"statements,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RotateRootCredentialsRequest) Reset() { *m = RotateRootCredentialsRequest{} } -func (m *RotateRootCredentialsRequest) String() string { return proto.CompactTextString(m) } -func (*RotateRootCredentialsRequest) ProtoMessage() {} -func (*RotateRootCredentialsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{5} -} - -func (m *RotateRootCredentialsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RotateRootCredentialsRequest.Unmarshal(m, b) -} -func (m *RotateRootCredentialsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RotateRootCredentialsRequest.Marshal(b, m, deterministic) -} -func (m *RotateRootCredentialsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RotateRootCredentialsRequest.Merge(m, src) -} -func (m *RotateRootCredentialsRequest) XXX_Size() int { - return xxx_messageInfo_RotateRootCredentialsRequest.Size(m) -} -func (m *RotateRootCredentialsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RotateRootCredentialsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RotateRootCredentialsRequest proto.InternalMessageInfo - -func (m *RotateRootCredentialsRequest) GetStatements() []string { - if m != nil { - return m.Statements - } - return nil -} - -type Statements struct { - // DEPRECATED, will be removed in 0.12 - CreationStatements string `protobuf:"bytes,1,opt,name=creation_statements,json=creationStatements,proto3" json:"creation_statements,omitempty"` // Deprecated: Do not use. - // DEPRECATED, will be removed in 0.12 - RevocationStatements string `protobuf:"bytes,2,opt,name=revocation_statements,json=revocationStatements,proto3" json:"revocation_statements,omitempty"` // Deprecated: Do not use. - // DEPRECATED, will be removed in 0.12 - RollbackStatements string `protobuf:"bytes,3,opt,name=rollback_statements,json=rollbackStatements,proto3" json:"rollback_statements,omitempty"` // Deprecated: Do not use. - // DEPRECATED, will be removed in 0.12 - RenewStatements string `protobuf:"bytes,4,opt,name=renew_statements,json=renewStatements,proto3" json:"renew_statements,omitempty"` // Deprecated: Do not use. - Creation []string `protobuf:"bytes,5,rep,name=creation,proto3" json:"creation,omitempty"` - Revocation []string `protobuf:"bytes,6,rep,name=revocation,proto3" json:"revocation,omitempty"` - Rollback []string `protobuf:"bytes,7,rep,name=rollback,proto3" json:"rollback,omitempty"` - Renewal []string `protobuf:"bytes,8,rep,name=renewal,proto3" json:"renewal,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Statements) Reset() { *m = Statements{} } -func (m *Statements) String() string { return proto.CompactTextString(m) } -func (*Statements) ProtoMessage() {} -func (*Statements) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{6} -} - -func (m *Statements) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Statements.Unmarshal(m, b) -} -func (m *Statements) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Statements.Marshal(b, m, deterministic) -} -func (m *Statements) XXX_Merge(src proto.Message) { - xxx_messageInfo_Statements.Merge(m, src) -} -func (m *Statements) XXX_Size() int { - return xxx_messageInfo_Statements.Size(m) -} -func (m *Statements) XXX_DiscardUnknown() { - xxx_messageInfo_Statements.DiscardUnknown(m) -} - -var xxx_messageInfo_Statements proto.InternalMessageInfo - -// Deprecated: Do not use. -func (m *Statements) GetCreationStatements() string { - if m != nil { - return m.CreationStatements - } - return "" -} - -// Deprecated: Do not use. -func (m *Statements) GetRevocationStatements() string { - if m != nil { - return m.RevocationStatements - } - return "" -} - -// Deprecated: Do not use. -func (m *Statements) GetRollbackStatements() string { - if m != nil { - return m.RollbackStatements - } - return "" -} - -// Deprecated: Do not use. -func (m *Statements) GetRenewStatements() string { - if m != nil { - return m.RenewStatements - } - return "" -} - -func (m *Statements) GetCreation() []string { - if m != nil { - return m.Creation - } - return nil -} - -func (m *Statements) GetRevocation() []string { - if m != nil { - return m.Revocation - } - return nil -} - -func (m *Statements) GetRollback() []string { - if m != nil { - return m.Rollback - } - return nil -} - -func (m *Statements) GetRenewal() []string { - if m != nil { - return m.Renewal - } - return nil -} - -type UsernameConfig struct { - DisplayName string `protobuf:"bytes,1,opt,name=DisplayName,proto3" json:"DisplayName,omitempty"` - RoleName string `protobuf:"bytes,2,opt,name=RoleName,proto3" json:"RoleName,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UsernameConfig) Reset() { *m = UsernameConfig{} } -func (m *UsernameConfig) String() string { return proto.CompactTextString(m) } -func (*UsernameConfig) ProtoMessage() {} -func (*UsernameConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{7} -} - -func (m *UsernameConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UsernameConfig.Unmarshal(m, b) -} -func (m *UsernameConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UsernameConfig.Marshal(b, m, deterministic) -} -func (m *UsernameConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_UsernameConfig.Merge(m, src) -} -func (m *UsernameConfig) XXX_Size() int { - return xxx_messageInfo_UsernameConfig.Size(m) -} -func (m *UsernameConfig) XXX_DiscardUnknown() { - xxx_messageInfo_UsernameConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_UsernameConfig proto.InternalMessageInfo - -func (m *UsernameConfig) GetDisplayName() string { - if m != nil { - return m.DisplayName - } - return "" -} - -func (m *UsernameConfig) GetRoleName() string { - if m != nil { - return m.RoleName - } - return "" -} - -type InitResponse struct { - Config []byte `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitResponse) Reset() { *m = InitResponse{} } -func (m *InitResponse) String() string { return proto.CompactTextString(m) } -func (*InitResponse) ProtoMessage() {} -func (*InitResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{8} -} - -func (m *InitResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitResponse.Unmarshal(m, b) -} -func (m *InitResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitResponse.Marshal(b, m, deterministic) -} -func (m *InitResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitResponse.Merge(m, src) -} -func (m *InitResponse) XXX_Size() int { - return xxx_messageInfo_InitResponse.Size(m) -} -func (m *InitResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InitResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InitResponse proto.InternalMessageInfo - -func (m *InitResponse) GetConfig() []byte { - if m != nil { - return m.Config - } - return nil -} - -type CreateUserResponse struct { - Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` - Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateUserResponse) Reset() { *m = CreateUserResponse{} } -func (m *CreateUserResponse) String() string { return proto.CompactTextString(m) } -func (*CreateUserResponse) ProtoMessage() {} -func (*CreateUserResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{9} -} - -func (m *CreateUserResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateUserResponse.Unmarshal(m, b) -} -func (m *CreateUserResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateUserResponse.Marshal(b, m, deterministic) -} -func (m *CreateUserResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateUserResponse.Merge(m, src) -} -func (m *CreateUserResponse) XXX_Size() int { - return xxx_messageInfo_CreateUserResponse.Size(m) -} -func (m *CreateUserResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CreateUserResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateUserResponse proto.InternalMessageInfo - -func (m *CreateUserResponse) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *CreateUserResponse) GetPassword() string { - if m != nil { - return m.Password - } - return "" -} - -type TypeResponse struct { - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TypeResponse) Reset() { *m = TypeResponse{} } -func (m *TypeResponse) String() string { return proto.CompactTextString(m) } -func (*TypeResponse) ProtoMessage() {} -func (*TypeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{10} -} - -func (m *TypeResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TypeResponse.Unmarshal(m, b) -} -func (m *TypeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TypeResponse.Marshal(b, m, deterministic) -} -func (m *TypeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TypeResponse.Merge(m, src) -} -func (m *TypeResponse) XXX_Size() int { - return xxx_messageInfo_TypeResponse.Size(m) -} -func (m *TypeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TypeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TypeResponse proto.InternalMessageInfo - -func (m *TypeResponse) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -type RotateRootCredentialsResponse struct { - Config []byte `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RotateRootCredentialsResponse) Reset() { *m = RotateRootCredentialsResponse{} } -func (m *RotateRootCredentialsResponse) String() string { return proto.CompactTextString(m) } -func (*RotateRootCredentialsResponse) ProtoMessage() {} -func (*RotateRootCredentialsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7bf7b4c7fef2f66e, []int{11} -} - -func (m *RotateRootCredentialsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RotateRootCredentialsResponse.Unmarshal(m, b) -} -func (m *RotateRootCredentialsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RotateRootCredentialsResponse.Marshal(b, m, deterministic) -} -func (m *RotateRootCredentialsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_RotateRootCredentialsResponse.Merge(m, src) -} -func (m *RotateRootCredentialsResponse) XXX_Size() int { - return xxx_messageInfo_RotateRootCredentialsResponse.Size(m) -} -func (m *RotateRootCredentialsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_RotateRootCredentialsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_RotateRootCredentialsResponse proto.InternalMessageInfo - -func (m *RotateRootCredentialsResponse) GetConfig() []byte { - if m != nil { - return m.Config - } - return nil -} - -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_7bf7b4c7fef2f66e, []int{12} -} - -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 (m *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(m, 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((*InitializeRequest)(nil), "dbplugin.InitializeRequest") - proto.RegisterType((*InitRequest)(nil), "dbplugin.InitRequest") - proto.RegisterType((*CreateUserRequest)(nil), "dbplugin.CreateUserRequest") - proto.RegisterType((*RenewUserRequest)(nil), "dbplugin.RenewUserRequest") - proto.RegisterType((*RevokeUserRequest)(nil), "dbplugin.RevokeUserRequest") - proto.RegisterType((*RotateRootCredentialsRequest)(nil), "dbplugin.RotateRootCredentialsRequest") - proto.RegisterType((*Statements)(nil), "dbplugin.Statements") - proto.RegisterType((*UsernameConfig)(nil), "dbplugin.UsernameConfig") - proto.RegisterType((*InitResponse)(nil), "dbplugin.InitResponse") - proto.RegisterType((*CreateUserResponse)(nil), "dbplugin.CreateUserResponse") - proto.RegisterType((*TypeResponse)(nil), "dbplugin.TypeResponse") - proto.RegisterType((*RotateRootCredentialsResponse)(nil), "dbplugin.RotateRootCredentialsResponse") - proto.RegisterType((*Empty)(nil), "dbplugin.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 - -// DatabaseClient is the client API for Database service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type DatabaseClient interface { - Type(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TypeResponse, error) - CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) - RenewUser(ctx context.Context, in *RenewUserRequest, opts ...grpc.CallOption) (*Empty, error) - RevokeUser(ctx context.Context, in *RevokeUserRequest, opts ...grpc.CallOption) (*Empty, error) - RotateRootCredentials(ctx context.Context, in *RotateRootCredentialsRequest, opts ...grpc.CallOption) (*RotateRootCredentialsResponse, error) - Init(ctx context.Context, in *InitRequest, opts ...grpc.CallOption) (*InitResponse, error) - Close(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - Initialize(ctx context.Context, in *InitializeRequest, opts ...grpc.CallOption) (*Empty, error) -} - -type databaseClient struct { - cc *grpc.ClientConn -} - -func NewDatabaseClient(cc *grpc.ClientConn) DatabaseClient { - return &databaseClient{cc} -} - -func (c *databaseClient) Type(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TypeResponse, error) { - out := new(TypeResponse) - err := c.cc.Invoke(ctx, "/dbplugin.Database/Type", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) { - out := new(CreateUserResponse) - err := c.cc.Invoke(ctx, "/dbplugin.Database/CreateUser", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) RenewUser(ctx context.Context, in *RenewUserRequest, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/dbplugin.Database/RenewUser", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) RevokeUser(ctx context.Context, in *RevokeUserRequest, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/dbplugin.Database/RevokeUser", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) RotateRootCredentials(ctx context.Context, in *RotateRootCredentialsRequest, opts ...grpc.CallOption) (*RotateRootCredentialsResponse, error) { - out := new(RotateRootCredentialsResponse) - err := c.cc.Invoke(ctx, "/dbplugin.Database/RotateRootCredentials", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) Init(ctx context.Context, in *InitRequest, opts ...grpc.CallOption) (*InitResponse, error) { - out := new(InitResponse) - err := c.cc.Invoke(ctx, "/dbplugin.Database/Init", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *databaseClient) Close(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/dbplugin.Database/Close", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Deprecated: Do not use. -func (c *databaseClient) Initialize(ctx context.Context, in *InitializeRequest, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/dbplugin.Database/Initialize", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// DatabaseServer is the server API for Database service. -type DatabaseServer interface { - Type(context.Context, *Empty) (*TypeResponse, error) - CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) - RenewUser(context.Context, *RenewUserRequest) (*Empty, error) - RevokeUser(context.Context, *RevokeUserRequest) (*Empty, error) - RotateRootCredentials(context.Context, *RotateRootCredentialsRequest) (*RotateRootCredentialsResponse, error) - Init(context.Context, *InitRequest) (*InitResponse, error) - Close(context.Context, *Empty) (*Empty, error) - Initialize(context.Context, *InitializeRequest) (*Empty, error) -} - -func RegisterDatabaseServer(s *grpc.Server, srv DatabaseServer) { - s.RegisterService(&_Database_serviceDesc, srv) -} - -func _Database_Type_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.(DatabaseServer).Type(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/Type", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).Type(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_CreateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).CreateUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/CreateUser", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).CreateUser(ctx, req.(*CreateUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_RenewUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RenewUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).RenewUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/RenewUser", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).RenewUser(ctx, req.(*RenewUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_RevokeUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RevokeUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).RevokeUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/RevokeUser", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).RevokeUser(ctx, req.(*RevokeUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_RotateRootCredentials_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RotateRootCredentialsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).RotateRootCredentials(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/RotateRootCredentials", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).RotateRootCredentials(ctx, req.(*RotateRootCredentialsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_Init_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InitRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).Init(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/Init", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).Init(ctx, req.(*InitRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_Close_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.(DatabaseServer).Close(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/Close", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).Close(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _Database_Initialize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InitializeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DatabaseServer).Initialize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/dbplugin.Database/Initialize", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DatabaseServer).Initialize(ctx, req.(*InitializeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Database_serviceDesc = grpc.ServiceDesc{ - ServiceName: "dbplugin.Database", - HandlerType: (*DatabaseServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Type", - Handler: _Database_Type_Handler, - }, - { - MethodName: "CreateUser", - Handler: _Database_CreateUser_Handler, - }, - { - MethodName: "RenewUser", - Handler: _Database_RenewUser_Handler, - }, - { - MethodName: "RevokeUser", - Handler: _Database_RevokeUser_Handler, - }, - { - MethodName: "RotateRootCredentials", - Handler: _Database_RotateRootCredentials_Handler, - }, - { - MethodName: "Init", - Handler: _Database_Init_Handler, - }, - { - MethodName: "Close", - Handler: _Database_Close_Handler, - }, - { - MethodName: "Initialize", - Handler: _Database_Initialize_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "builtin/logical/database/dbplugin/database.proto", -} - -func init() { - proto.RegisterFile("builtin/logical/database/dbplugin/database.proto", fileDescriptor_7bf7b4c7fef2f66e) -} - -var fileDescriptor_7bf7b4c7fef2f66e = []byte{ - // 724 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0xd1, 0x4e, 0xdb, 0x4a, - 0x10, 0x95, 0x93, 0x00, 0xc9, 0x80, 0x80, 0xec, 0x05, 0x64, 0xf9, 0x72, 0x6f, 0x91, 0x1f, 0x28, - 0x55, 0xd5, 0xb8, 0x82, 0x56, 0x54, 0xa8, 0xa2, 0x2a, 0xa1, 0xaa, 0x2a, 0x55, 0x3c, 0x2c, 0xf0, - 0x52, 0x55, 0x42, 0x1b, 0x67, 0x49, 0x56, 0x38, 0x5e, 0xd7, 0xbb, 0x0e, 0x4d, 0x7f, 0xa0, 0xfd, - 0x8c, 0x7e, 0x4e, 0x1f, 0xfb, 0x49, 0x95, 0x37, 0x59, 0xef, 0x26, 0x86, 0xf2, 0x40, 0xfb, 0xe6, - 0xd9, 0x99, 0x33, 0x73, 0xe6, 0x78, 0x76, 0x16, 0x9e, 0x76, 0x32, 0x16, 0x49, 0x16, 0x07, 0x11, - 0xef, 0xb1, 0x90, 0x44, 0x41, 0x97, 0x48, 0xd2, 0x21, 0x82, 0x06, 0xdd, 0x4e, 0x12, 0x65, 0x3d, - 0x16, 0x17, 0x27, 0xad, 0x24, 0xe5, 0x92, 0xa3, 0xba, 0x76, 0x78, 0x0f, 0x7a, 0x9c, 0xf7, 0x22, - 0x1a, 0xa8, 0xf3, 0x4e, 0x76, 0x19, 0x48, 0x36, 0xa0, 0x42, 0x92, 0x41, 0x32, 0x0e, 0xf5, 0x3f, - 0x42, 0xf3, 0x5d, 0xcc, 0x24, 0x23, 0x11, 0xfb, 0x42, 0x31, 0xfd, 0x94, 0x51, 0x21, 0xd1, 0x06, - 0xcc, 0x87, 0x3c, 0xbe, 0x64, 0x3d, 0xd7, 0xd9, 0x72, 0x76, 0x96, 0xf0, 0xc4, 0x42, 0x8f, 0xa1, - 0x39, 0xa4, 0x29, 0xbb, 0x1c, 0x5d, 0x84, 0x3c, 0x8e, 0x69, 0x28, 0x19, 0x8f, 0xdd, 0xca, 0x96, - 0xb3, 0x53, 0xc7, 0xab, 0x63, 0x47, 0xbb, 0x38, 0x3f, 0xa8, 0xb8, 0x8e, 0x8f, 0x61, 0x31, 0xcf, - 0xfe, 0x27, 0xf3, 0xfa, 0x3f, 0x1c, 0x68, 0xb6, 0x53, 0x4a, 0x24, 0x3d, 0x17, 0x34, 0xd5, 0xa9, - 0x9f, 0x01, 0x08, 0x49, 0x24, 0x1d, 0xd0, 0x58, 0x0a, 0x95, 0x7e, 0x71, 0x77, 0xad, 0xa5, 0x75, - 0x68, 0x9d, 0x16, 0x3e, 0x6c, 0xc5, 0xa1, 0xd7, 0xb0, 0x92, 0x09, 0x9a, 0xc6, 0x64, 0x40, 0x2f, - 0x26, 0xcc, 0x2a, 0x0a, 0xea, 0x1a, 0xe8, 0xf9, 0x24, 0xa0, 0xad, 0xfc, 0x78, 0x39, 0x9b, 0xb2, - 0xd1, 0x01, 0x00, 0xfd, 0x9c, 0xb0, 0x94, 0x28, 0xd2, 0x55, 0x85, 0xf6, 0x5a, 0x63, 0xd9, 0x5b, - 0x5a, 0xf6, 0xd6, 0x99, 0x96, 0x1d, 0x5b, 0xd1, 0xfe, 0x77, 0x07, 0x56, 0x31, 0x8d, 0xe9, 0xf5, - 0xfd, 0x3b, 0xf1, 0xa0, 0xae, 0x89, 0xa9, 0x16, 0x1a, 0xb8, 0xb0, 0xef, 0x45, 0x91, 0x42, 0x13, - 0xd3, 0x21, 0xbf, 0xa2, 0x7f, 0x95, 0xa2, 0x7f, 0x08, 0x9b, 0x98, 0xe7, 0xa1, 0x98, 0x73, 0xd9, - 0x4e, 0x69, 0x97, 0xc6, 0xf9, 0x4c, 0x0a, 0x5d, 0xf1, 0xff, 0x99, 0x8a, 0xd5, 0x9d, 0x86, 0x9d, - 0xdb, 0xff, 0x59, 0x01, 0x30, 0x65, 0xd1, 0x1e, 0xfc, 0x13, 0xe6, 0x23, 0xc2, 0x78, 0x7c, 0x31, - 0xc3, 0xb4, 0x71, 0x54, 0x71, 0x1d, 0x8c, 0xb4, 0xdb, 0x02, 0xed, 0xc3, 0x7a, 0x4a, 0x87, 0x3c, - 0x2c, 0xc1, 0x2a, 0x05, 0x6c, 0xcd, 0x04, 0x4c, 0x57, 0x4b, 0x79, 0x14, 0x75, 0x48, 0x78, 0x65, - 0xc3, 0xaa, 0xa6, 0x9a, 0x76, 0x5b, 0xa0, 0x27, 0xb0, 0x9a, 0xe6, 0xbf, 0xde, 0x46, 0xd4, 0x0a, - 0xc4, 0x8a, 0xf2, 0x9d, 0x4e, 0x89, 0xa7, 0x29, 0xbb, 0x73, 0xaa, 0xfd, 0xc2, 0xce, 0xc5, 0x31, - 0xbc, 0xdc, 0xf9, 0xb1, 0x38, 0xe6, 0x24, 0xc7, 0x6a, 0x02, 0xee, 0xc2, 0x18, 0xab, 0x6d, 0xe4, - 0xc2, 0x82, 0x2a, 0x45, 0x22, 0xb7, 0xae, 0x5c, 0xda, 0xf4, 0x4f, 0x60, 0x79, 0x7a, 0xf4, 0xd1, - 0x16, 0x2c, 0x1e, 0x33, 0x91, 0x44, 0x64, 0x74, 0x92, 0xff, 0x43, 0xa5, 0x26, 0xb6, 0x8f, 0xf2, - 0x4a, 0x98, 0x47, 0xf4, 0xc4, 0xfa, 0xc5, 0xda, 0xf6, 0xb7, 0x61, 0x69, 0xbc, 0x0b, 0x44, 0xc2, - 0x63, 0x41, 0x6f, 0x5b, 0x06, 0xfe, 0x7b, 0x40, 0xf6, 0xf5, 0x9e, 0x44, 0xdb, 0xc3, 0xe3, 0xcc, - 0xcc, 0xb7, 0x07, 0xf5, 0x84, 0x08, 0x71, 0xcd, 0xd3, 0xae, 0xae, 0xaa, 0x6d, 0xdf, 0x87, 0xa5, - 0xb3, 0x51, 0x42, 0x8b, 0x3c, 0x08, 0x6a, 0x72, 0x94, 0xe8, 0x1c, 0xea, 0xdb, 0xdf, 0x87, 0xff, - 0x6e, 0x19, 0xbe, 0x3b, 0xa8, 0x2e, 0xc0, 0xdc, 0x9b, 0x41, 0x22, 0x47, 0xbb, 0x5f, 0x6b, 0x50, - 0x3f, 0x9e, 0xec, 0x60, 0x14, 0x40, 0x2d, 0x2f, 0x89, 0x56, 0xcc, 0x8d, 0x50, 0x51, 0xde, 0x86, - 0x39, 0x98, 0xe2, 0xf4, 0x16, 0xc0, 0x74, 0x8c, 0xfe, 0x35, 0x51, 0xa5, 0x35, 0xe7, 0x6d, 0xde, - 0xec, 0x9c, 0x24, 0x7a, 0x01, 0x8d, 0x62, 0x9d, 0x20, 0xcf, 0x84, 0xce, 0xee, 0x18, 0x6f, 0x96, - 0x5a, 0xbe, 0x22, 0xcc, 0x35, 0xb7, 0x29, 0x94, 0x2e, 0x7f, 0x19, 0xdb, 0x87, 0xf5, 0x1b, 0xe5, - 0x43, 0xdb, 0x56, 0x9a, 0xdf, 0x5c, 0x6e, 0xef, 0xe1, 0x9d, 0x71, 0x93, 0xfe, 0x9e, 0x43, 0x2d, - 0x1f, 0x21, 0xb4, 0x6e, 0x00, 0xd6, 0xf3, 0x62, 0xeb, 0x3b, 0x35, 0x69, 0x8f, 0x60, 0xae, 0x1d, - 0x71, 0x71, 0xc3, 0x1f, 0x29, 0xf5, 0xf2, 0x0a, 0xc0, 0x3c, 0x87, 0xb6, 0x0e, 0xa5, 0x47, 0xb2, - 0x84, 0xf5, 0xab, 0xdf, 0x2a, 0xce, 0xd1, 0xe1, 0x87, 0x97, 0x3d, 0x26, 0xfb, 0x59, 0xa7, 0x15, - 0xf2, 0x41, 0xd0, 0x27, 0xa2, 0xcf, 0x42, 0x9e, 0x26, 0xc1, 0x90, 0x64, 0x91, 0x0c, 0xee, 0x7c, - 0xc9, 0x3b, 0xf3, 0x6a, 0x1f, 0xef, 0xfd, 0x0a, 0x00, 0x00, 0xff, 0xff, 0x9c, 0x49, 0x0b, 0x5b, - 0xf5, 0x07, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.proto b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.proto deleted file mode 100644 index 7873792e..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/database.proto +++ /dev/null @@ -1,93 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/builtin/logical/database/dbplugin"; - -package dbplugin; - -import "google/protobuf/timestamp.proto"; - -message InitializeRequest { - option deprecated = true; - bytes config = 1; - bool verify_connection = 2; -} - -message InitRequest { - bytes config = 1; - bool verify_connection = 2; -} - -message CreateUserRequest { - Statements statements = 1; - UsernameConfig username_config = 2; - google.protobuf.Timestamp expiration = 3; -} - -message RenewUserRequest { - Statements statements = 1; - string username = 2; - google.protobuf.Timestamp expiration = 3; -} - -message RevokeUserRequest { - Statements statements = 1; - string username = 2; -} - -message RotateRootCredentialsRequest { - repeated string statements = 1; -} - -message Statements { - // DEPRECATED, will be removed in 0.12 - string creation_statements = 1 [deprecated=true]; - // DEPRECATED, will be removed in 0.12 - string revocation_statements = 2 [deprecated=true]; - // DEPRECATED, will be removed in 0.12 - string rollback_statements = 3 [deprecated=true]; - // DEPRECATED, will be removed in 0.12 - string renew_statements = 4 [deprecated=true]; - - repeated string creation = 5; - repeated string revocation = 6; - repeated string rollback = 7; - repeated string renewal = 8; -} - -message UsernameConfig { - string DisplayName = 1; - string RoleName = 2; -} - -message InitResponse { - bytes config = 1; -} - -message CreateUserResponse { - string username = 1; - string password = 2; -} - -message TypeResponse { - string type = 1; -} - -message RotateRootCredentialsResponse { - bytes config = 1; -} - -message Empty {} - -service Database { - rpc Type(Empty) returns (TypeResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); - rpc RenewUser(RenewUserRequest) returns (Empty); - rpc RevokeUser(RevokeUserRequest) returns (Empty); - rpc RotateRootCredentials(RotateRootCredentialsRequest) returns (RotateRootCredentialsResponse); - rpc Init(InitRequest) returns (InitResponse); - rpc Close(Empty) returns (Empty); - - rpc Initialize(InitializeRequest) returns (Empty) { - option deprecated = true; - }; -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/databasemiddleware.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/databasemiddleware.go deleted file mode 100644 index ba2dd4e5..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/databasemiddleware.go +++ /dev/null @@ -1,275 +0,0 @@ -package dbplugin - -import ( - "context" - "errors" - "net/url" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - - metrics "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" -) - -// ---- Tracing Middleware Domain ---- - -// databaseTracingMiddleware wraps a implementation of Database and executes -// trace logging on function call. -type databaseTracingMiddleware struct { - next Database - logger log.Logger -} - -func (mw *databaseTracingMiddleware) Type() (string, error) { - return mw.next.Type() -} - -func (mw *databaseTracingMiddleware) CreateUser(ctx context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) { - defer func(then time.Time) { - mw.logger.Trace("create user", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("create user", "status", "started") - return mw.next.CreateUser(ctx, statements, usernameConfig, expiration) -} - -func (mw *databaseTracingMiddleware) RenewUser(ctx context.Context, statements Statements, username string, expiration time.Time) (err error) { - defer func(then time.Time) { - mw.logger.Trace("renew user", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("renew user", "status", "started") - return mw.next.RenewUser(ctx, statements, username, expiration) -} - -func (mw *databaseTracingMiddleware) RevokeUser(ctx context.Context, statements Statements, username string) (err error) { - defer func(then time.Time) { - mw.logger.Trace("revoke user", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("revoke user", "status", "started") - return mw.next.RevokeUser(ctx, statements, username) -} - -func (mw *databaseTracingMiddleware) RotateRootCredentials(ctx context.Context, statements []string) (conf map[string]interface{}, err error) { - defer func(then time.Time) { - mw.logger.Trace("rotate root credentials", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("rotate root credentials", "status", "started") - return mw.next.RotateRootCredentials(ctx, statements) -} - -func (mw *databaseTracingMiddleware) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := mw.Init(ctx, conf, verifyConnection) - return err -} - -func (mw *databaseTracingMiddleware) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (saveConf map[string]interface{}, err error) { - defer func(then time.Time) { - mw.logger.Trace("initialize", "status", "finished", "verify", verifyConnection, "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("initialize", "status", "started") - return mw.next.Init(ctx, conf, verifyConnection) -} - -func (mw *databaseTracingMiddleware) Close() (err error) { - defer func(then time.Time) { - mw.logger.Trace("close", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - mw.logger.Trace("close", "status", "started") - return mw.next.Close() -} - -// ---- Metrics Middleware Domain ---- - -// databaseMetricsMiddleware wraps an implementation of Databases and on -// function call logs metrics about this instance. -type databaseMetricsMiddleware struct { - next Database - - typeStr string -} - -func (mw *databaseMetricsMiddleware) Type() (string, error) { - return mw.next.Type() -} - -func (mw *databaseMetricsMiddleware) CreateUser(ctx context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "CreateUser"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "CreateUser"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "CreateUser", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "CreateUser", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "CreateUser"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "CreateUser"}, 1) - return mw.next.CreateUser(ctx, statements, usernameConfig, expiration) -} - -func (mw *databaseMetricsMiddleware) RenewUser(ctx context.Context, statements Statements, username string, expiration time.Time) (err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "RenewUser"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "RenewUser"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "RenewUser", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RenewUser", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "RenewUser"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RenewUser"}, 1) - return mw.next.RenewUser(ctx, statements, username, expiration) -} - -func (mw *databaseMetricsMiddleware) RevokeUser(ctx context.Context, statements Statements, username string) (err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "RevokeUser"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "RevokeUser"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "RevokeUser", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RevokeUser", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "RevokeUser"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RevokeUser"}, 1) - return mw.next.RevokeUser(ctx, statements, username) -} - -func (mw *databaseMetricsMiddleware) RotateRootCredentials(ctx context.Context, statements []string) (conf map[string]interface{}, err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "RotateRootCredentials"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "RotateRootCredentials"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "RotateRootCredentials", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RotateRootCredentials", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "RotateRootCredentials"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "RotateRootCredentials"}, 1) - return mw.next.RotateRootCredentials(ctx, statements) -} - -func (mw *databaseMetricsMiddleware) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := mw.Init(ctx, conf, verifyConnection) - return err -} - -func (mw *databaseMetricsMiddleware) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (saveConf map[string]interface{}, err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "Initialize"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "Initialize"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "Initialize", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "Initialize", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "Initialize"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "Initialize"}, 1) - return mw.next.Init(ctx, conf, verifyConnection) -} - -func (mw *databaseMetricsMiddleware) Close() (err error) { - defer func(now time.Time) { - metrics.MeasureSince([]string{"database", "Close"}, now) - metrics.MeasureSince([]string{"database", mw.typeStr, "Close"}, now) - - if err != nil { - metrics.IncrCounter([]string{"database", "Close", "error"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "Close", "error"}, 1) - } - }(time.Now()) - - metrics.IncrCounter([]string{"database", "Close"}, 1) - metrics.IncrCounter([]string{"database", mw.typeStr, "Close"}, 1) - return mw.next.Close() -} - -// ---- Error Sanitizer Middleware Domain ---- - -// DatabaseErrorSanitizerMiddleware wraps an implementation of Databases and -// sanitizes returned error messages -type DatabaseErrorSanitizerMiddleware struct { - l sync.RWMutex - next Database - secretsFn func() map[string]interface{} -} - -func NewDatabaseErrorSanitizerMiddleware(next Database, secretsFn func() map[string]interface{}) *DatabaseErrorSanitizerMiddleware { - return &DatabaseErrorSanitizerMiddleware{ - next: next, - secretsFn: secretsFn, - } -} - -func (mw *DatabaseErrorSanitizerMiddleware) Type() (string, error) { - dbType, err := mw.next.Type() - return dbType, mw.sanitize(err) -} - -func (mw *DatabaseErrorSanitizerMiddleware) CreateUser(ctx context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) { - username, password, err = mw.next.CreateUser(ctx, statements, usernameConfig, expiration) - return username, password, mw.sanitize(err) -} - -func (mw *DatabaseErrorSanitizerMiddleware) RenewUser(ctx context.Context, statements Statements, username string, expiration time.Time) (err error) { - return mw.sanitize(mw.next.RenewUser(ctx, statements, username, expiration)) -} - -func (mw *DatabaseErrorSanitizerMiddleware) RevokeUser(ctx context.Context, statements Statements, username string) (err error) { - return mw.sanitize(mw.next.RevokeUser(ctx, statements, username)) -} - -func (mw *DatabaseErrorSanitizerMiddleware) RotateRootCredentials(ctx context.Context, statements []string) (conf map[string]interface{}, err error) { - conf, err = mw.next.RotateRootCredentials(ctx, statements) - return conf, mw.sanitize(err) -} - -func (mw *DatabaseErrorSanitizerMiddleware) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := mw.Init(ctx, conf, verifyConnection) - return err -} - -func (mw *DatabaseErrorSanitizerMiddleware) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (saveConf map[string]interface{}, err error) { - saveConf, err = mw.next.Init(ctx, conf, verifyConnection) - return saveConf, mw.sanitize(err) -} - -func (mw *DatabaseErrorSanitizerMiddleware) Close() (err error) { - return mw.sanitize(mw.next.Close()) -} - -// sanitize -func (mw *DatabaseErrorSanitizerMiddleware) sanitize(err error) error { - if err == nil { - return nil - } - if errwrap.ContainsType(err, new(url.Error)) { - return errors.New("unable to parse connection url") - } - if mw.secretsFn != nil { - for k, v := range mw.secretsFn() { - if k == "" { - continue - } - err = errors.New(strings.Replace(err.Error(), k, v.(string), -1)) - } - } - return err -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/grpc_transport.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/grpc_transport.go deleted file mode 100644 index 1b5267e8..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/grpc_transport.go +++ /dev/null @@ -1,285 +0,0 @@ -package dbplugin - -import ( - "context" - "encoding/json" - "errors" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/pluginutil" -) - -var ( - ErrPluginShutdown = errors.New("plugin shutdown") -) - -// ---- gRPC Server domain ---- - -type gRPCServer struct { - impl Database -} - -func (s *gRPCServer) Type(context.Context, *Empty) (*TypeResponse, error) { - t, err := s.impl.Type() - if err != nil { - return nil, err - } - - return &TypeResponse{ - Type: t, - }, nil -} - -func (s *gRPCServer) CreateUser(ctx context.Context, req *CreateUserRequest) (*CreateUserResponse, error) { - e, err := ptypes.Timestamp(req.Expiration) - if err != nil { - return nil, err - } - - u, p, err := s.impl.CreateUser(ctx, *req.Statements, *req.UsernameConfig, e) - - return &CreateUserResponse{ - Username: u, - Password: p, - }, err -} - -func (s *gRPCServer) RenewUser(ctx context.Context, req *RenewUserRequest) (*Empty, error) { - e, err := ptypes.Timestamp(req.Expiration) - if err != nil { - return nil, err - } - err = s.impl.RenewUser(ctx, *req.Statements, req.Username, e) - return &Empty{}, err -} - -func (s *gRPCServer) RevokeUser(ctx context.Context, req *RevokeUserRequest) (*Empty, error) { - err := s.impl.RevokeUser(ctx, *req.Statements, req.Username) - return &Empty{}, err -} - -func (s *gRPCServer) RotateRootCredentials(ctx context.Context, req *RotateRootCredentialsRequest) (*RotateRootCredentialsResponse, error) { - - resp, err := s.impl.RotateRootCredentials(ctx, req.Statements) - if err != nil { - return nil, err - } - - respConfig, err := json.Marshal(resp) - if err != nil { - return nil, err - } - - return &RotateRootCredentialsResponse{ - Config: respConfig, - }, err -} - -func (s *gRPCServer) Initialize(ctx context.Context, req *InitializeRequest) (*Empty, error) { - _, err := s.Init(ctx, &InitRequest{ - Config: req.Config, - VerifyConnection: req.VerifyConnection, - }) - return &Empty{}, err -} - -func (s *gRPCServer) Init(ctx context.Context, req *InitRequest) (*InitResponse, error) { - config := map[string]interface{}{} - err := json.Unmarshal(req.Config, &config) - if err != nil { - return nil, err - } - - resp, err := s.impl.Init(ctx, config, req.VerifyConnection) - if err != nil { - return nil, err - } - - respConfig, err := json.Marshal(resp) - if err != nil { - return nil, err - } - - return &InitResponse{ - Config: respConfig, - }, err -} - -func (s *gRPCServer) Close(_ context.Context, _ *Empty) (*Empty, error) { - s.impl.Close() - return &Empty{}, nil -} - -// ---- gRPC client domain ---- - -type gRPCClient struct { - client DatabaseClient - clientConn *grpc.ClientConn - - doneCtx context.Context -} - -func (c *gRPCClient) Type() (string, error) { - resp, err := c.client.Type(c.doneCtx, &Empty{}) - if err != nil { - return "", err - } - - return resp.Type, err -} - -func (c *gRPCClient) CreateUser(ctx context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) { - t, err := ptypes.TimestampProto(expiration) - if err != nil { - return "", "", err - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, c.doneCtx) - defer close(quitCh) - defer cancel() - - resp, err := c.client.CreateUser(ctx, &CreateUserRequest{ - Statements: &statements, - UsernameConfig: &usernameConfig, - Expiration: t, - }) - if err != nil { - if c.doneCtx.Err() != nil { - return "", "", ErrPluginShutdown - } - - return "", "", err - } - - return resp.Username, resp.Password, err -} - -func (c *gRPCClient) RenewUser(ctx context.Context, statements Statements, username string, expiration time.Time) error { - t, err := ptypes.TimestampProto(expiration) - if err != nil { - return err - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, c.doneCtx) - defer close(quitCh) - defer cancel() - - _, err = c.client.RenewUser(ctx, &RenewUserRequest{ - Statements: &statements, - Username: username, - Expiration: t, - }) - if err != nil { - if c.doneCtx.Err() != nil { - return ErrPluginShutdown - } - - return err - } - - return nil -} - -func (c *gRPCClient) RevokeUser(ctx context.Context, statements Statements, username string) error { - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, c.doneCtx) - defer close(quitCh) - defer cancel() - - _, err := c.client.RevokeUser(ctx, &RevokeUserRequest{ - Statements: &statements, - Username: username, - }) - - if err != nil { - if c.doneCtx.Err() != nil { - return ErrPluginShutdown - } - - return err - } - - return nil -} - -func (c *gRPCClient) RotateRootCredentials(ctx context.Context, statements []string) (conf map[string]interface{}, err error) { - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, c.doneCtx) - defer close(quitCh) - defer cancel() - - resp, err := c.client.RotateRootCredentials(ctx, &RotateRootCredentialsRequest{ - Statements: statements, - }) - - if err != nil { - if c.doneCtx.Err() != nil { - return nil, ErrPluginShutdown - } - - return nil, err - } - - if err := json.Unmarshal(resp.Config, &conf); err != nil { - return nil, err - } - - return conf, nil -} - -func (c *gRPCClient) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := c.Init(ctx, conf, verifyConnection) - return err -} - -func (c *gRPCClient) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) { - configRaw, err := json.Marshal(conf) - if err != nil { - return nil, err - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, c.doneCtx) - defer close(quitCh) - defer cancel() - - resp, err := c.client.Init(ctx, &InitRequest{ - Config: configRaw, - VerifyConnection: verifyConnection, - }) - if err != nil { - // Fall back to old call if not implemented - grpcStatus, ok := status.FromError(err) - if ok && grpcStatus.Code() == codes.Unimplemented { - _, err = c.client.Initialize(ctx, &InitializeRequest{ - Config: configRaw, - VerifyConnection: verifyConnection, - }) - if err == nil { - return conf, nil - } - } - - if c.doneCtx.Err() != nil { - return nil, ErrPluginShutdown - } - return nil, err - } - - if err := json.Unmarshal(resp.Config, &conf); err != nil { - return nil, err - } - return conf, nil -} - -func (c *gRPCClient) Close() error { - _, err := c.client.Close(c.doneCtx, &Empty{}) - return err -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/netrpc_transport.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/netrpc_transport.go deleted file mode 100644 index 25cbc979..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/netrpc_transport.go +++ /dev/null @@ -1,197 +0,0 @@ -package dbplugin - -import ( - "context" - "encoding/json" - "fmt" - "net/rpc" - "strings" - "time" -) - -// ---- RPC server domain ---- - -// databasePluginRPCServer implements an RPC version of Database and is run -// inside a plugin. It wraps an underlying implementation of Database. -type databasePluginRPCServer struct { - impl Database -} - -func (ds *databasePluginRPCServer) Type(_ struct{}, resp *string) error { - var err error - *resp, err = ds.impl.Type() - return err -} - -func (ds *databasePluginRPCServer) CreateUser(args *CreateUserRequestRPC, resp *CreateUserResponse) error { - var err error - resp.Username, resp.Password, err = ds.impl.CreateUser(context.Background(), args.Statements, args.UsernameConfig, args.Expiration) - return err -} - -func (ds *databasePluginRPCServer) RenewUser(args *RenewUserRequestRPC, _ *struct{}) error { - err := ds.impl.RenewUser(context.Background(), args.Statements, args.Username, args.Expiration) - return err -} - -func (ds *databasePluginRPCServer) RevokeUser(args *RevokeUserRequestRPC, _ *struct{}) error { - err := ds.impl.RevokeUser(context.Background(), args.Statements, args.Username) - return err -} - -func (ds *databasePluginRPCServer) RotateRootCredentials(args *RotateRootCredentialsRequestRPC, resp *RotateRootCredentialsResponse) error { - config, err := ds.impl.RotateRootCredentials(context.Background(), args.Statements) - if err != nil { - return err - } - resp.Config, err = json.Marshal(config) - return err -} - -func (ds *databasePluginRPCServer) Initialize(args *InitializeRequestRPC, _ *struct{}) error { - return ds.Init(&InitRequestRPC{ - Config: args.Config, - VerifyConnection: args.VerifyConnection, - }, &InitResponse{}) -} - -func (ds *databasePluginRPCServer) Init(args *InitRequestRPC, resp *InitResponse) error { - config, err := ds.impl.Init(context.Background(), args.Config, args.VerifyConnection) - if err != nil { - return err - } - resp.Config, err = json.Marshal(config) - return err -} - -func (ds *databasePluginRPCServer) Close(_ struct{}, _ *struct{}) error { - ds.impl.Close() - return nil -} - -// ---- RPC client domain ---- -// databasePluginRPCClient implements Database and is used on the client to -// make RPC calls to a plugin. -type databasePluginRPCClient struct { - client *rpc.Client -} - -func (dr *databasePluginRPCClient) Type() (string, error) { - var dbType string - err := dr.client.Call("Plugin.Type", struct{}{}, &dbType) - - return fmt.Sprintf("plugin-%s", dbType), err -} - -func (dr *databasePluginRPCClient) CreateUser(_ context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) { - req := CreateUserRequestRPC{ - Statements: statements, - UsernameConfig: usernameConfig, - Expiration: expiration, - } - - var resp CreateUserResponse - err = dr.client.Call("Plugin.CreateUser", req, &resp) - - return resp.Username, resp.Password, err -} - -func (dr *databasePluginRPCClient) RenewUser(_ context.Context, statements Statements, username string, expiration time.Time) error { - req := RenewUserRequestRPC{ - Statements: statements, - Username: username, - Expiration: expiration, - } - - return dr.client.Call("Plugin.RenewUser", req, &struct{}{}) -} - -func (dr *databasePluginRPCClient) RevokeUser(_ context.Context, statements Statements, username string) error { - req := RevokeUserRequestRPC{ - Statements: statements, - Username: username, - } - - return dr.client.Call("Plugin.RevokeUser", req, &struct{}{}) -} - -func (dr *databasePluginRPCClient) RotateRootCredentials(_ context.Context, statements []string) (saveConf map[string]interface{}, err error) { - req := RotateRootCredentialsRequestRPC{ - Statements: statements, - } - - var resp RotateRootCredentialsResponse - err = dr.client.Call("Plugin.RotateRootCredentials", req, &resp) - - err = json.Unmarshal(resp.Config, &saveConf) - return saveConf, err -} - -func (dr *databasePluginRPCClient) Initialize(_ context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := dr.Init(nil, conf, verifyConnection) - return err -} - -func (dr *databasePluginRPCClient) Init(_ context.Context, conf map[string]interface{}, verifyConnection bool) (saveConf map[string]interface{}, err error) { - req := InitRequestRPC{ - Config: conf, - VerifyConnection: verifyConnection, - } - - var resp InitResponse - err = dr.client.Call("Plugin.Init", req, &resp) - if err != nil { - if strings.Contains(err.Error(), "can't find method Plugin.Init") { - req := InitializeRequestRPC{ - Config: conf, - VerifyConnection: verifyConnection, - } - - err = dr.client.Call("Plugin.Initialize", req, &struct{}{}) - if err == nil { - return conf, nil - } - } - return nil, err - } - - err = json.Unmarshal(resp.Config, &saveConf) - return saveConf, err -} - -func (dr *databasePluginRPCClient) Close() error { - return dr.client.Call("Plugin.Close", struct{}{}, &struct{}{}) -} - -// ---- RPC Request Args Domain ---- - -type InitializeRequestRPC struct { - Config map[string]interface{} - VerifyConnection bool -} - -type InitRequestRPC struct { - Config map[string]interface{} - VerifyConnection bool -} - -type CreateUserRequestRPC struct { - Statements Statements - UsernameConfig UsernameConfig - Expiration time.Time -} - -type RenewUserRequestRPC struct { - Statements Statements - Username string - Expiration time.Time -} - -type RevokeUserRequestRPC struct { - Statements Statements - Username string -} - -type RotateRootCredentialsRequestRPC struct { - Statements []string -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/plugin.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/plugin.go deleted file mode 100644 index 918b98b3..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/plugin.go +++ /dev/null @@ -1,159 +0,0 @@ -package dbplugin - -import ( - "context" - "fmt" - "net/rpc" - "time" - - "google.golang.org/grpc" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" -) - -// Database is the interface that all database objects must implement. -type Database interface { - Type() (string, error) - CreateUser(ctx context.Context, statements Statements, usernameConfig UsernameConfig, expiration time.Time) (username string, password string, err error) - RenewUser(ctx context.Context, statements Statements, username string, expiration time.Time) error - RevokeUser(ctx context.Context, statements Statements, username string) error - - RotateRootCredentials(ctx context.Context, statements []string) (config map[string]interface{}, err error) - - Init(ctx context.Context, config map[string]interface{}, verifyConnection bool) (saveConfig map[string]interface{}, err error) - Close() error - - // DEPRECATED, will be removed in 0.13 - Initialize(ctx context.Context, config map[string]interface{}, verifyConnection bool) (err error) -} - -// PluginFactory is used to build plugin database types. It wraps the database -// object in a logging and metrics middleware. -func PluginFactory(ctx context.Context, pluginName string, sys pluginutil.LookRunnerUtil, logger log.Logger) (Database, error) { - // Look for plugin in the plugin catalog - pluginRunner, err := sys.LookupPlugin(ctx, pluginName, consts.PluginTypeDatabase) - if err != nil { - return nil, err - } - - namedLogger := logger.Named(pluginName) - - var transport string - var db Database - if pluginRunner.Builtin { - // Plugin is builtin so we can retrieve an instance of the interface - // from the pluginRunner. Then cast it to a Database. - dbRaw, err := pluginRunner.BuiltinFactory() - if err != nil { - return nil, errwrap.Wrapf("error initializing plugin: {{err}}", err) - } - - var ok bool - db, ok = dbRaw.(Database) - if !ok { - return nil, fmt.Errorf("unsupported database type: %q", pluginName) - } - - transport = "builtin" - - } else { - // create a DatabasePluginClient instance - db, err = NewPluginClient(ctx, sys, pluginRunner, namedLogger, false) - if err != nil { - return nil, err - } - - // Switch on the underlying database client type to get the transport - // method. - switch db.(*DatabasePluginClient).Database.(type) { - case *gRPCClient: - transport = "gRPC" - case *databasePluginRPCClient: - transport = "netRPC" - } - - } - - typeStr, err := db.Type() - if err != nil { - return nil, errwrap.Wrapf("error getting plugin type: {{err}}", err) - } - - // Wrap with metrics middleware - db = &databaseMetricsMiddleware{ - next: db, - typeStr: typeStr, - } - - // Wrap with tracing middleware - if namedLogger.IsTrace() { - db = &databaseTracingMiddleware{ - next: db, - logger: namedLogger.With("transport", transport), - } - } - - return db, nil -} - -// handshakeConfigs are used to just do a basic handshake between -// a plugin and host. If the handshake fails, a user friendly error is shown. -// This prevents users from executing bad plugins or executing a plugin -// directory. It is a UX feature, not a security feature. -var handshakeConfig = plugin.HandshakeConfig{ - ProtocolVersion: 4, - MagicCookieKey: "VAULT_DATABASE_PLUGIN", - MagicCookieValue: "926a0820-aea2-be28-51d6-83cdf00e8edb", -} - -var _ plugin.Plugin = &DatabasePlugin{} -var _ plugin.GRPCPlugin = &DatabasePlugin{} -var _ plugin.Plugin = &GRPCDatabasePlugin{} -var _ plugin.GRPCPlugin = &GRPCDatabasePlugin{} - -// DatabasePlugin implements go-plugin's Plugin interface. It has methods for -// retrieving a server and a client instance of the plugin. -type DatabasePlugin struct { - *GRPCDatabasePlugin -} - -// GRPCDatabasePlugin is the plugin.Plugin implementation that only supports GRPC -// transport -type GRPCDatabasePlugin struct { - Impl Database - - // Embeding this will disable the netRPC protocol - plugin.NetRPCUnsupportedPlugin -} - -func (d DatabasePlugin) Server(*plugin.MuxBroker) (interface{}, error) { - impl := &DatabaseErrorSanitizerMiddleware{ - next: d.Impl, - } - return &databasePluginRPCServer{impl: impl}, nil -} - -func (DatabasePlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { - return &databasePluginRPCClient{client: c}, nil -} - -func (d GRPCDatabasePlugin) GRPCServer(_ *plugin.GRPCBroker, s *grpc.Server) error { - impl := &DatabaseErrorSanitizerMiddleware{ - next: d.Impl, - } - - RegisterDatabaseServer(s, &gRPCServer{impl: impl}) - return nil -} - -func (GRPCDatabasePlugin) GRPCClient(doneCtx context.Context, _ *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - return &gRPCClient{ - client: NewDatabaseClient(c), - clientConn: c, - doneCtx: doneCtx, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/server.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/server.go deleted file mode 100644 index 9f170493..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/dbplugin/server.go +++ /dev/null @@ -1,49 +0,0 @@ -package dbplugin - -import ( - "crypto/tls" - - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" -) - -// Serve is called from within a plugin and wraps the provided -// Database implementation in a databasePluginRPCServer object and starts a -// RPC server. -func Serve(db Database, tlsProvider func() (*tls.Config, error)) { - plugin.Serve(ServeConfig(db, tlsProvider)) -} - -func ServeConfig(db Database, tlsProvider func() (*tls.Config, error)) *plugin.ServeConfig { - // pluginSets is the map of plugins we can dispense. - pluginSets := map[int]plugin.PluginSet{ - 3: plugin.PluginSet{ - "database": &DatabasePlugin{ - GRPCDatabasePlugin: &GRPCDatabasePlugin{ - Impl: db, - }, - }, - }, - 4: plugin.PluginSet{ - "database": &GRPCDatabasePlugin{ - Impl: db, - }, - }, - } - - conf := &plugin.ServeConfig{ - HandshakeConfig: handshakeConfig, - VersionedPlugins: pluginSets, - TLSProvider: tlsProvider, - GRPCServer: plugin.DefaultGRPCServer, - } - - // If we do not have gRPC support fallback to version 3 - // Remove this block in 0.13 - if !pluginutil.GRPCSupport() { - conf.GRPCServer = nil - delete(conf.VersionedPlugins, 4) - } - - return conf -} diff --git a/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go b/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go deleted file mode 100644 index 34f0512e..00000000 --- a/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go +++ /dev/null @@ -1,239 +0,0 @@ -package plugin - -import ( - "context" - "fmt" - "net/rpc" - "reflect" - "sync" - - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - bplugin "github.com/hashicorp/vault/logical/plugin" -) - -var ( - ErrMismatchType = fmt.Errorf("mismatch on mounted backend and plugin backend type") - ErrMismatchPaths = fmt.Errorf("mismatch on mounted backend and plugin backend special paths") -) - -// Factory returns a configured plugin logical.Backend. -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - _, ok := conf.Config["plugin_name"] - if !ok { - return nil, fmt.Errorf("plugin_name not provided") - } - b, err := Backend(ctx, conf) - if err != nil { - return nil, err - } - - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Backend returns an instance of the backend, either as a plugin if external -// or as a concrete implementation if builtin, casted as logical.Backend. -func Backend(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - var b PluginBackend - - name := conf.Config["plugin_name"] - pluginType, err := consts.ParsePluginType(conf.Config["plugin_type"]) - if err != nil { - return nil, err - } - - sys := conf.System - - // NewBackend with isMetadataMode set to true - raw, err := bplugin.NewBackend(ctx, name, pluginType, sys, conf, true) - if err != nil { - return nil, err - } - err = raw.Setup(ctx, conf) - if err != nil { - return nil, err - } - // Get SpecialPaths and BackendType - paths := raw.SpecialPaths() - btype := raw.Type() - - // Cleanup meta plugin backend - raw.Cleanup(ctx) - - // Initialize b.Backend with dummy backend since plugin - // backends will need to be lazy loaded. - b.Backend = &framework.Backend{ - PathsSpecial: paths, - BackendType: btype, - } - - b.config = conf - - return &b, nil -} - -// PluginBackend is a thin wrapper around plugin.BackendPluginClient -type PluginBackend struct { - logical.Backend - sync.RWMutex - - config *logical.BackendConfig - - // Used to detect if we already reloaded - canary string - - // Used to detect if plugin is set - loaded bool -} - -func (b *PluginBackend) reloadBackend(ctx context.Context) error { - b.Logger().Debug("reloading plugin backend", "plugin", b.config.Config["plugin_name"]) - return b.startBackend(ctx) -} - -// startBackend starts a plugin backend -func (b *PluginBackend) startBackend(ctx context.Context) error { - pluginName := b.config.Config["plugin_name"] - pluginType, err := consts.ParsePluginType(b.config.Config["plugin_type"]) - if err != nil { - return err - } - - // Ensure proper cleanup of the backend (i.e. call client.Kill()) - b.Backend.Cleanup(ctx) - - nb, err := bplugin.NewBackend(ctx, pluginName, pluginType, b.config.System, b.config, false) - if err != nil { - return err - } - err = nb.Setup(ctx, b.config) - if err != nil { - return err - } - - // If the backend has not been loaded (i.e. still in metadata mode), - // check if type and special paths still matches - if !b.loaded { - if b.Backend.Type() != nb.Type() { - nb.Cleanup(ctx) - b.Logger().Warn("failed to start plugin process", "plugin", b.config.Config["plugin_name"], "error", ErrMismatchType) - return ErrMismatchType - } - if !reflect.DeepEqual(b.Backend.SpecialPaths(), nb.SpecialPaths()) { - nb.Cleanup(ctx) - b.Logger().Warn("failed to start plugin process", "plugin", b.config.Config["plugin_name"], "error", ErrMismatchPaths) - return ErrMismatchPaths - } - } - - b.Backend = nb - b.loaded = true - - return nil -} - -// HandleRequest is a thin wrapper implementation of HandleRequest that includes automatic plugin reload. -func (b *PluginBackend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - b.RLock() - canary := b.canary - - // Lazy-load backend - if !b.loaded { - // Upgrade lock - b.RUnlock() - b.Lock() - // Check once more after lock swap - if !b.loaded { - err := b.startBackend(ctx) - if err != nil { - b.Unlock() - return nil, err - } - } - b.Unlock() - b.RLock() - } - resp, err := b.Backend.HandleRequest(ctx, req) - b.RUnlock() - // Need to compare string value for case were err comes from plugin RPC - // and is returned as plugin.BasicError type. - if err != nil && - (err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) { - // Reload plugin if it's an rpc.ErrShutdown - b.Lock() - if b.canary == canary { - err := b.reloadBackend(ctx) - if err != nil { - b.Unlock() - return nil, err - } - b.canary, err = uuid.GenerateUUID() - if err != nil { - b.Unlock() - return nil, err - } - } - b.Unlock() - - // Try request once more - b.RLock() - defer b.RUnlock() - return b.Backend.HandleRequest(ctx, req) - } - return resp, err -} - -// HandleExistenceCheck is a thin wrapper implementation of HandleRequest that includes automatic plugin reload. -func (b *PluginBackend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - b.RLock() - canary := b.canary - - // Lazy-load backend - if !b.loaded { - // Upgrade lock - b.RUnlock() - b.Lock() - // Check once more after lock swap - if !b.loaded { - err := b.startBackend(ctx) - if err != nil { - b.Unlock() - return false, false, err - } - } - b.Unlock() - b.RLock() - } - - checkFound, exists, err := b.Backend.HandleExistenceCheck(ctx, req) - b.RUnlock() - if err != nil && - (err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) { - // Reload plugin if it's an rpc.ErrShutdown - b.Lock() - if b.canary == canary { - err := b.reloadBackend(ctx) - if err != nil { - b.Unlock() - return false, false, err - } - b.canary, err = uuid.GenerateUUID() - if err != nil { - b.Unlock() - return false, false, err - } - } - b.Unlock() - - // Try request once more - b.RLock() - defer b.RUnlock() - return b.Backend.HandleExistenceCheck(ctx, req) - } - return checkFound, exists, err -} diff --git a/vendor/github.com/hashicorp/vault/helper/base62/base62.go b/vendor/github.com/hashicorp/vault/helper/base62/base62.go deleted file mode 100644 index 6130deda..00000000 --- a/vendor/github.com/hashicorp/vault/helper/base62/base62.go +++ /dev/null @@ -1,59 +0,0 @@ -// Package base62 provides utilities for working with base62 strings. -// base62 strings will only contain characters: 0-9, a-z, A-Z -package base62 - -import ( - "math/big" - - uuid "github.com/hashicorp/go-uuid" -) - -// Encode converts buf into a base62 string -// -// Note: this should only be used for reducing a string's character set range. -// It is not for use with arbitrary data since leading 0 bytes will be dropped. -func Encode(buf []byte) string { - var encoder big.Int - - encoder.SetBytes(buf) - return encoder.Text(62) -} - -// Decode converts input from base62 to its byte representation -// If the decoding fails, an empty slice is returned. -func Decode(input string) []byte { - var decoder big.Int - - decoder.SetString(input, 62) - return decoder.Bytes() -} - -// Random generates a random base62-encoded string. -// If truncate is true, the result will be a string of the requested length. -// Otherwise, it will be the encoded result of length bytes of random data. -func Random(length int, truncate bool) (string, error) { - bytesNeeded := length - - // ~0.74 bytes are needed per output character in truncate mode. We'll - // ask for just a little more than that. - if truncate { - bytesNeeded = (bytesNeeded * 3 / 4) + 1 - } - - for { - buf, err := uuid.GenerateRandomBytes(bytesNeeded) - if err != nil { - return "", err - } - - result := Encode(buf) - - if truncate { - if len(result) < length { - continue - } - result = result[:length] - } - return result, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go b/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go deleted file mode 100644 index 7c665194..00000000 --- a/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go +++ /dev/null @@ -1,301 +0,0 @@ -package certutil - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "math/big" - "strconv" - "strings" - - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/mitchellh/mapstructure" -) - -// 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 int64 - inBytes := strings.Split(in, sep) - for _, inByte := range inBytes { - if inBits, err = strconv.ParseInt(inByte, 16, 8); err != nil { - return nil - } - ret.WriteByte(byte(inBits)) - } - return ret.Bytes() -} - -// GetSubjKeyID returns the subject key ID, e.g. the SHA1 sum -// of the marshaled public key -func GetSubjKeyID(privateKey crypto.Signer) ([]byte, error) { - if privateKey == nil { - return nil, errutil.InternalError{Err: "passed-in private key is nil"} - } - - marshaledKey, err := x509.MarshalPKIXPublicKey(privateKey.Public()) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error marshalling public key: %s", err)} - } - - subjKeyID := sha1.Sum(marshaledKey) - - return subjKeyID[:], 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"} -} - -// 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, err := x509.ParseECPrivateKey(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 = ECBlock - parsedBundle.PrivateKeyType = ECPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKey = signer - - } else if signer, err := x509.ParsePKCS1PrivateKey(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.PrivateKeyType = RSAPrivateKey - parsedBundle.PrivateKeyFormat = PKCS1Block - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKey = signer - } else if signer, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes); err == nil { - parsedBundle.PrivateKeyFormat = PKCS8Block - - if parsedBundle.PrivateKeyType != UnknownPrivateKey { - return nil, errutil.UserError{Err: "More than one private key given; provide only one private key in the bundle"} - } - switch signer := signer.(type) { - case *rsa.PrivateKey: - parsedBundle.PrivateKey = signer - parsedBundle.PrivateKeyType = RSAPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - case *ecdsa.PrivateKey: - parsedBundle.PrivateKey = signer - parsedBundle.PrivateKeyType = ECPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - } - } else if certificates, err := x509.ParseCertificates(pemBlock.Bytes); err == nil { - certPath = append(certPath, &CertBlock{ - Certificate: certificates[0], - Bytes: pemBlock.Bytes, - }) - } - } - - 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 { - var err error - var privateKeyType PrivateKeyType - var privateKeyBytes []byte - var privateKey crypto.Signer - - switch keyType { - case "rsa": - privateKeyType = RSAPrivateKey - privateKey, err = rsa.GenerateKey(rand.Reader, 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, rand.Reader) - 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)} - } - 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) { - serial, err := rand.Int(rand.Reader, (&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 -} - -// ComparePublicKeys compares two public keys and returns true if they match -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 - - default: - return false, fmt.Errorf("cannot compare key with type %T", key1Iface) - } -} - -// PasrsePublicKeyPEM 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 { - 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 - } - } - - if rsaPublicKey, ok := rawKey.(*rsa.PublicKey); ok { - return rsaPublicKey, nil - } - if ecPublicKey, ok := rawKey.(*ecdsa.PublicKey); ok { - return ecPublicKey, nil - } - } - - return nil, errors.New("data does not contain any valid RSA or ECDSA public keys") -} diff --git a/vendor/github.com/hashicorp/vault/helper/certutil/types.go b/vendor/github.com/hashicorp/vault/helper/certutil/types.go deleted file mode 100644 index 9a27a6fb..00000000 --- a/vendor/github.com/hashicorp/vault/helper/certutil/types.go +++ /dev/null @@ -1,591 +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/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" -) - -// 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" -) - -// 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 ( - 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 -} - -// 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) { - result := &ParsedCertBundle{} - 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 - result.PrivateKeyFormat = BlockType(strings.TrimSpace(pemBlock.Type)) - - switch result.PrivateKeyFormat { - case ECBlock: - result.PrivateKeyType, c.PrivateKeyType = ECPrivateKey, ECPrivateKey - case PKCS1Block: - c.PrivateKeyType, result.PrivateKeyType = RSAPrivateKey, RSAPrivateKey - case PKCS8Block: - t, err := getPKCS8Type(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting key type from pkcs#8: %v", err)} - } - result.PrivateKeyType = t - switch t { - case ECPrivateKey: - c.PrivateKeyType = ECPrivateKey - case RSAPrivateKey: - c.PrivateKeyType = RSAPrivateKey - } - default: - return nil, errutil.UserError{Err: fmt.Sprintf("Unsupported key block type: %s", pemBlock.Type)} - } - - result.PrivateKey, err = result.getSigner() - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", 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 -} - -// 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) - } - } - - 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)", - i+1, certPath[i].Certificate.Subject.CommonName, caCert.Certificate.Subject.CommonName) - } - } - } - - 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: - 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 - 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 { - 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" - 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)} - } - - 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 *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} - tlsConfig.BuildNameToCertificate() - } - - 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"` -} diff --git a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go b/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go deleted file mode 100644 index 356d4548..00000000 --- a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go +++ /dev/null @@ -1,207 +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) { - var err error - var reader io.ReadCloser - 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)) - - 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) - - case CompressionCanarySnappy: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: snappy.NewReader(bytes.NewReader(cData)), - } - - case CompressionCanaryLZ4: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: lz4.NewReader(bytes.NewReader(cData)), - } - - 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(), false, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/consts/consts.go b/vendor/github.com/hashicorp/vault/helper/consts/consts.go deleted file mode 100644 index 972a69f4..00000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/consts.go +++ /dev/null @@ -1,14 +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" -) diff --git a/vendor/github.com/hashicorp/vault/helper/consts/error.go b/vendor/github.com/hashicorp/vault/helper/consts/error.go deleted file mode 100644 index 06977d5d..00000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/error.go +++ /dev/null @@ -1,16 +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") - - // 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") - - // Used when .. is used in a path - ErrPathContainsParentReferences = errors.New("path cannot contain parent references") -) diff --git a/vendor/github.com/hashicorp/vault/helper/consts/plugin_types.go b/vendor/github.com/hashicorp/vault/helper/consts/plugin_types.go deleted file mode 100644 index e0a00e48..00000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/plugin_types.go +++ /dev/null @@ -1,59 +0,0 @@ -package consts - -import "fmt" - -var PluginTypes = []PluginType{ - PluginTypeUnknown, - PluginTypeCredential, - PluginTypeDatabase, - PluginTypeSecrets, -} - -type PluginType uint32 - -// This is a list of PluginTypes used by Vault. -// If we need to add any in the future, it would -// be best to add them to the _end_ of the list below -// because they resolve to incrementing numbers, -// which may be saved in state somewhere. Thus if -// the name for one of those numbers changed because -// a value were added to the middle, that could cause -// the wrong plugin types to be read from storage -// for a given underlying number. Example of the problem -// here: https://play.golang.org/p/YAaPw5ww3er -const ( - PluginTypeUnknown PluginType = iota - PluginTypeCredential - PluginTypeDatabase - PluginTypeSecrets -) - -func (p PluginType) String() string { - switch p { - case PluginTypeUnknown: - return "unknown" - case PluginTypeCredential: - return "auth" - case PluginTypeDatabase: - return "database" - case PluginTypeSecrets: - return "secret" - default: - return "unsupported" - } -} - -func ParsePluginType(pluginType string) (PluginType, error) { - switch pluginType { - case "unknown": - return PluginTypeUnknown, nil - case "auth": - return PluginTypeCredential, nil - case "database": - return PluginTypeDatabase, nil - case "secret": - return PluginTypeSecrets, nil - default: - return PluginTypeUnknown, fmt.Errorf("%q is not a supported plugin type", pluginType) - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/consts/replication.go b/vendor/github.com/hashicorp/vault/helper/consts/replication.go deleted file mode 100644 index bdad1552..00000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/replication.go +++ /dev/null @@ -1,87 +0,0 @@ -package consts - -import "time" - -type ReplicationState uint32 - -var ReplicationStaleReadTimeout = 2 * time.Second - -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 - ReplicationPerformanceSecondary - OldSplitReplicationBootstrapping - ReplicationDRPrimary - ReplicationDRSecondary - ReplicationPerformanceBootstrapping - ReplicationDRBootstrapping - ReplicationPerformanceDisabled - ReplicationDRDisabled - ReplicationPerformanceStandby -) - -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) 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) 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 } diff --git a/vendor/github.com/hashicorp/vault/helper/dbtxn/dbtxn.go b/vendor/github.com/hashicorp/vault/helper/dbtxn/dbtxn.go deleted file mode 100644 index 3337bd97..00000000 --- a/vendor/github.com/hashicorp/vault/helper/dbtxn/dbtxn.go +++ /dev/null @@ -1,63 +0,0 @@ -package dbtxn - -import ( - "context" - "database/sql" - "fmt" - "strings" -) - -// ExecuteDBQuery handles executing one single statement, while properly releasing its resources. -// - ctx: Required -// - db: Required -// - config: Optional, may be nil -// - query: Required -func ExecuteDBQuery(ctx context.Context, db *sql.DB, params map[string]string, query string) error { - - parsedQuery := parseQuery(params, query) - - stmt, err := db.PrepareContext(ctx, parsedQuery) - if err != nil { - return err - } - defer stmt.Close() - - return execute(ctx, stmt) -} - -// ExecuteTxQuery handles executing one single statement, while properly releasing its resources. -// - ctx: Required -// - tx: Required -// - config: Optional, may be nil -// - query: Required -func ExecuteTxQuery(ctx context.Context, tx *sql.Tx, params map[string]string, query string) error { - - parsedQuery := parseQuery(params, query) - - stmt, err := tx.PrepareContext(ctx, parsedQuery) - if err != nil { - return err - } - defer stmt.Close() - - return execute(ctx, stmt) -} - -func execute(ctx context.Context, stmt *sql.Stmt) error { - if _, err := stmt.ExecContext(ctx); err != nil { - return err - } - return nil -} - -func parseQuery(m map[string]string, tpl string) string { - - if m == nil || len(m) <= 0 { - return tpl - } - - for k, v := range m { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - return tpl -} diff --git a/vendor/github.com/hashicorp/vault/helper/errutil/error.go b/vendor/github.com/hashicorp/vault/helper/errutil/error.go deleted file mode 100644 index 0b95efb4..00000000 --- a/vendor/github.com/hashicorp/vault/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/helper/forwarding/types.pb.go b/vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go deleted file mode 100644 index e7b104c6..00000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go +++ /dev/null @@ -1,357 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/forwarding/types.proto - -package forwarding - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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 Request struct { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - // uint64 id = 1; - Method string `protobuf:"bytes,2,opt,name=method,proto3" json:"method,omitempty"` - Url *URL `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` - HeaderEntries map[string]*HeaderEntry `protobuf:"bytes,4,rep,name=header_entries,json=headerEntries,proto3" json:"header_entries,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Body []byte `protobuf:"bytes,5,opt,name=body,proto3" json:"body,omitempty"` - Host string `protobuf:"bytes,6,opt,name=host,proto3" json:"host,omitempty"` - RemoteAddr string `protobuf:"bytes,7,opt,name=remote_addr,json=remoteAddr,proto3" json:"remote_addr,omitempty"` - PeerCertificates [][]byte `protobuf:"bytes,8,rep,name=peer_certificates,json=peerCertificates,proto3" json:"peer_certificates,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_e38697de88a2f47c, []int{0} -} - -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (m *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(m, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -func (m *Request) GetMethod() string { - if m != nil { - return m.Method - } - return "" -} - -func (m *Request) GetUrl() *URL { - if m != nil { - return m.Url - } - return nil -} - -func (m *Request) GetHeaderEntries() map[string]*HeaderEntry { - if m != nil { - return m.HeaderEntries - } - return nil -} - -func (m *Request) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func (m *Request) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *Request) GetRemoteAddr() string { - if m != nil { - return m.RemoteAddr - } - return "" -} - -func (m *Request) GetPeerCertificates() [][]byte { - if m != nil { - return m.PeerCertificates - } - return nil -} - -type URL struct { - Scheme string `protobuf:"bytes,1,opt,name=scheme,proto3" json:"scheme,omitempty"` - Opaque string `protobuf:"bytes,2,opt,name=opaque,proto3" json:"opaque,omitempty"` - // This isn't needed now but might be in the future, so we'll skip the - // number to keep the ordering in net/url - // UserInfo user = 3; - Host string `protobuf:"bytes,4,opt,name=host,proto3" json:"host,omitempty"` - Path string `protobuf:"bytes,5,opt,name=path,proto3" json:"path,omitempty"` - RawPath string `protobuf:"bytes,6,opt,name=raw_path,json=rawPath,proto3" json:"raw_path,omitempty"` - // This also isn't needed right now, but we'll reserve the number - // bool force_query = 7; - RawQuery string `protobuf:"bytes,8,opt,name=raw_query,json=rawQuery,proto3" json:"raw_query,omitempty"` - Fragment string `protobuf:"bytes,9,opt,name=fragment,proto3" json:"fragment,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *URL) Reset() { *m = URL{} } -func (m *URL) String() string { return proto.CompactTextString(m) } -func (*URL) ProtoMessage() {} -func (*URL) Descriptor() ([]byte, []int) { - return fileDescriptor_e38697de88a2f47c, []int{1} -} - -func (m *URL) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_URL.Unmarshal(m, b) -} -func (m *URL) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_URL.Marshal(b, m, deterministic) -} -func (m *URL) XXX_Merge(src proto.Message) { - xxx_messageInfo_URL.Merge(m, src) -} -func (m *URL) XXX_Size() int { - return xxx_messageInfo_URL.Size(m) -} -func (m *URL) XXX_DiscardUnknown() { - xxx_messageInfo_URL.DiscardUnknown(m) -} - -var xxx_messageInfo_URL proto.InternalMessageInfo - -func (m *URL) GetScheme() string { - if m != nil { - return m.Scheme - } - return "" -} - -func (m *URL) GetOpaque() string { - if m != nil { - return m.Opaque - } - return "" -} - -func (m *URL) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *URL) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *URL) GetRawPath() string { - if m != nil { - return m.RawPath - } - return "" -} - -func (m *URL) GetRawQuery() string { - if m != nil { - return m.RawQuery - } - return "" -} - -func (m *URL) GetFragment() string { - if m != nil { - return m.Fragment - } - return "" -} - -type HeaderEntry struct { - Values []string `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HeaderEntry) Reset() { *m = HeaderEntry{} } -func (m *HeaderEntry) String() string { return proto.CompactTextString(m) } -func (*HeaderEntry) ProtoMessage() {} -func (*HeaderEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_e38697de88a2f47c, []int{2} -} - -func (m *HeaderEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HeaderEntry.Unmarshal(m, b) -} -func (m *HeaderEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HeaderEntry.Marshal(b, m, deterministic) -} -func (m *HeaderEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_HeaderEntry.Merge(m, src) -} -func (m *HeaderEntry) XXX_Size() int { - return xxx_messageInfo_HeaderEntry.Size(m) -} -func (m *HeaderEntry) XXX_DiscardUnknown() { - xxx_messageInfo_HeaderEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_HeaderEntry proto.InternalMessageInfo - -func (m *HeaderEntry) GetValues() []string { - if m != nil { - return m.Values - } - return nil -} - -type Response struct { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - // uint64 id = 1; - StatusCode uint32 `protobuf:"varint,2,opt,name=status_code,json=statusCode,proto3" json:"status_code,omitempty"` - Body []byte `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"` - // Added in 0.6.2 to ensure that the content-type is set appropriately, as - // well as any other information - HeaderEntries map[string]*HeaderEntry `protobuf:"bytes,4,rep,name=header_entries,json=headerEntries,proto3" json:"header_entries,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - LastRemoteWal uint64 `protobuf:"varint,5,opt,name=last_remote_wal,json=lastRemoteWal,proto3" json:"last_remote_wal,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_e38697de88a2f47c, []int{3} -} - -func (m *Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Response.Unmarshal(m, b) -} -func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Response.Marshal(b, m, deterministic) -} -func (m *Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Response.Merge(m, src) -} -func (m *Response) XXX_Size() int { - return xxx_messageInfo_Response.Size(m) -} -func (m *Response) XXX_DiscardUnknown() { - xxx_messageInfo_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Response proto.InternalMessageInfo - -func (m *Response) GetStatusCode() uint32 { - if m != nil { - return m.StatusCode - } - return 0 -} - -func (m *Response) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func (m *Response) GetHeaderEntries() map[string]*HeaderEntry { - if m != nil { - return m.HeaderEntries - } - return nil -} - -func (m *Response) GetLastRemoteWal() uint64 { - if m != nil { - return m.LastRemoteWal - } - return 0 -} - -func init() { - proto.RegisterType((*Request)(nil), "forwarding.Request") - proto.RegisterMapType((map[string]*HeaderEntry)(nil), "forwarding.Request.HeaderEntriesEntry") - proto.RegisterType((*URL)(nil), "forwarding.URL") - proto.RegisterType((*HeaderEntry)(nil), "forwarding.HeaderEntry") - proto.RegisterType((*Response)(nil), "forwarding.Response") - proto.RegisterMapType((map[string]*HeaderEntry)(nil), "forwarding.Response.HeaderEntriesEntry") -} - -func init() { proto.RegisterFile("helper/forwarding/types.proto", fileDescriptor_e38697de88a2f47c) } - -var fileDescriptor_e38697de88a2f47c = []byte{ - // 497 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x53, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0x95, 0xe3, 0xb4, 0x49, 0x26, 0x0d, 0x2d, 0x7b, 0x80, 0xa5, 0x08, 0x61, 0x22, 0x51, 0x22, - 0x01, 0x8e, 0x14, 0x2e, 0x88, 0x1b, 0x54, 0x48, 0x1c, 0x0a, 0x82, 0x95, 0x2a, 0x04, 0x17, 0x6b, - 0xe3, 0x9d, 0x64, 0x2d, 0xec, 0xac, 0xb3, 0xbb, 0x6e, 0xe4, 0xdf, 0xe0, 0x4f, 0xf8, 0x27, 0x3e, - 0x04, 0xed, 0xda, 0x34, 0x46, 0x15, 0x12, 0x17, 0x4e, 0x99, 0xf7, 0xde, 0x64, 0x3c, 0x6f, 0x66, - 0x16, 0x1e, 0x48, 0xcc, 0x4b, 0xd4, 0xf3, 0x95, 0xd2, 0x3b, 0xae, 0x45, 0xb6, 0x59, 0xcf, 0x6d, - 0x5d, 0xa2, 0x89, 0x4b, 0xad, 0xac, 0x22, 0xb0, 0xe7, 0xa7, 0x3f, 0x7b, 0x30, 0x60, 0xb8, 0xad, - 0xd0, 0x58, 0x72, 0x07, 0x0e, 0x0b, 0xb4, 0x52, 0x09, 0xda, 0x8b, 0x82, 0xd9, 0x88, 0xb5, 0x88, - 0x3c, 0x82, 0xb0, 0xd2, 0x39, 0x0d, 0xa3, 0x60, 0x36, 0x5e, 0x1c, 0xc7, 0xfb, 0x7f, 0xc7, 0x97, - 0xec, 0x82, 0x39, 0x8d, 0xbc, 0x87, 0x5b, 0x12, 0xb9, 0x40, 0x9d, 0xe0, 0xc6, 0xea, 0x0c, 0x0d, - 0xed, 0x47, 0xe1, 0x6c, 0xbc, 0x38, 0xeb, 0x66, 0xb7, 0xdf, 0x89, 0xdf, 0xf9, 0xcc, 0xb7, 0x4d, - 0xa2, 0xfb, 0xa9, 0xd9, 0x44, 0x76, 0x39, 0x42, 0xa0, 0xbf, 0x54, 0xa2, 0xa6, 0x07, 0x51, 0x30, - 0x3b, 0x62, 0x3e, 0x76, 0x9c, 0x54, 0xc6, 0xd2, 0x43, 0xdf, 0x9b, 0x8f, 0xc9, 0x43, 0x18, 0x6b, - 0x2c, 0x94, 0xc5, 0x84, 0x0b, 0xa1, 0xe9, 0xc0, 0x4b, 0xd0, 0x50, 0xaf, 0x85, 0xd0, 0xe4, 0x29, - 0xdc, 0x2e, 0x11, 0x75, 0x92, 0xa2, 0xb6, 0xd9, 0x2a, 0x4b, 0xb9, 0x45, 0x43, 0x87, 0x51, 0x38, - 0x3b, 0x62, 0x27, 0x4e, 0x38, 0xef, 0xf0, 0xa7, 0x5f, 0x80, 0xdc, 0x6c, 0x8d, 0x9c, 0x40, 0xf8, - 0x0d, 0x6b, 0x1a, 0xf8, 0xda, 0x2e, 0x24, 0xcf, 0xe1, 0xe0, 0x8a, 0xe7, 0x15, 0xfa, 0x31, 0x8d, - 0x17, 0x77, 0xbb, 0x1e, 0xf7, 0x05, 0x6a, 0xd6, 0x64, 0xbd, 0xea, 0xbd, 0x0c, 0xa6, 0x3f, 0x02, - 0x08, 0x2f, 0xd9, 0x85, 0x1b, 0xb1, 0x49, 0x25, 0x16, 0xd8, 0xd6, 0x6b, 0x91, 0xe3, 0x55, 0xc9, - 0xb7, 0x6d, 0xcd, 0x11, 0x6b, 0xd1, 0xb5, 0xe9, 0x7e, 0xc7, 0x34, 0x81, 0x7e, 0xc9, 0xad, 0xf4, - 0xc3, 0x19, 0x31, 0x1f, 0x93, 0x7b, 0x30, 0xd4, 0x7c, 0x97, 0x78, 0xbe, 0x19, 0xd0, 0x40, 0xf3, - 0xdd, 0x47, 0x27, 0xdd, 0x87, 0x91, 0x93, 0xb6, 0x15, 0xea, 0x9a, 0x0e, 0xbd, 0xe6, 0x72, 0x3f, - 0x39, 0x4c, 0x4e, 0x61, 0xb8, 0xd2, 0x7c, 0x5d, 0xe0, 0xc6, 0xd2, 0x51, 0xa3, 0xfd, 0xc6, 0xd3, - 0xc7, 0x30, 0xee, 0xb8, 0x71, 0x2d, 0x7a, 0x3f, 0x86, 0x06, 0x51, 0xe8, 0x5a, 0x6c, 0xd0, 0xf4, - 0x7b, 0x0f, 0x86, 0x0c, 0x4d, 0xa9, 0x36, 0x06, 0xdd, 0x42, 0x8c, 0xe5, 0xb6, 0x32, 0x49, 0xaa, - 0x44, 0x63, 0x66, 0xc2, 0xa0, 0xa1, 0xce, 0x95, 0xc0, 0xeb, 0xcd, 0x86, 0x9d, 0xcd, 0x7e, 0xf8, - 0xcb, 0xf1, 0x3c, 0xf9, 0xf3, 0x78, 0x9a, 0x4f, 0xfc, 0xc3, 0xf5, 0x9c, 0xc1, 0x71, 0xce, 0x8d, - 0x4d, 0xda, 0xd3, 0xd8, 0xf1, 0xdc, 0xcf, 0xaa, 0xcf, 0x26, 0x8e, 0x66, 0x9e, 0xfd, 0xcc, 0xf3, - 0xff, 0xb8, 0xef, 0x37, 0xf1, 0xd7, 0x67, 0xeb, 0xcc, 0xca, 0x6a, 0x19, 0xa7, 0xaa, 0x98, 0x4b, - 0x6e, 0x64, 0x96, 0x2a, 0x5d, 0xce, 0xaf, 0x78, 0x95, 0xdb, 0xf9, 0x8d, 0xe7, 0xb9, 0x3c, 0xf4, - 0x2f, 0xf3, 0xc5, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfd, 0xbd, 0xb1, 0xfc, 0xba, 0x03, 0x00, - 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto b/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto deleted file mode 100644 index 8f1376a1..00000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto +++ /dev/null @@ -1,49 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/forwarding"; - -package forwarding; - -message Request { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - //uint64 id = 1; - string method = 2; - URL url = 3; - map header_entries = 4; - bytes body = 5; - string host = 6; - string remote_addr = 7; - repeated bytes peer_certificates = 8; -} - -message URL { - string scheme = 1; - string opaque = 2; - // This isn't needed now but might be in the future, so we'll skip the - // number to keep the ordering in net/url - //UserInfo user = 3; - string host = 4; - string path = 5; - string raw_path = 6; - // This also isn't needed right now, but we'll reserve the number - //bool force_query = 7; - string raw_query = 8; - string fragment = 9; -} - -message HeaderEntry { - repeated string values = 1; -} - -message Response { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - //uint64 id = 1; - uint32 status_code = 2; - bytes body = 3; - // Added in 0.6.2 to ensure that the content-type is set appropriately, as - // well as any other information - map header_entries = 4; - uint64 last_remote_wal = 5; -} diff --git a/vendor/github.com/hashicorp/vault/helper/forwarding/util.go b/vendor/github.com/hashicorp/vault/helper/forwarding/util.go deleted file mode 100644 index d33e7e04..00000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/util.go +++ /dev/null @@ -1,218 +0,0 @@ -package forwarding - -import ( - "bytes" - "crypto/tls" - "crypto/x509" - "errors" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - - "github.com/golang/protobuf/proto" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/jsonutil" -) - -type bufCloser struct { - *bytes.Buffer -} - -func (b bufCloser) Close() error { - b.Reset() - return nil -} - -// GenerateForwardedRequest generates a new http.Request that contains the -// original requests's information in the new request's body. -func GenerateForwardedHTTPRequest(req *http.Request, addr string) (*http.Request, error) { - fq, err := GenerateForwardedRequest(req) - if err != nil { - return nil, err - } - - var newBody []byte - switch os.Getenv("VAULT_MESSAGE_TYPE") { - case "json": - newBody, err = jsonutil.EncodeJSON(fq) - case "json_compress": - newBody, err = jsonutil.EncodeJSONAndCompress(fq, &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeLZW, - }) - case "proto3": - fallthrough - default: - newBody, err = proto.Marshal(fq) - } - if err != nil { - return nil, err - } - - ret, err := http.NewRequest("POST", addr, bytes.NewBuffer(newBody)) - if err != nil { - return nil, err - } - - return ret, nil -} - -func GenerateForwardedRequest(req *http.Request) (*Request, error) { - var reader io.Reader = req.Body - ctx := req.Context() - maxRequestSize := ctx.Value("max_request_size") - if maxRequestSize != nil { - max, ok := maxRequestSize.(int64) - if !ok { - return nil, errors.New("could not parse max_request_size from request context") - } - if max > 0 { - reader = io.LimitReader(req.Body, max) - } - } - - body, err := ioutil.ReadAll(reader) - if err != nil { - return nil, err - } - - fq := Request{ - Method: req.Method, - HeaderEntries: make(map[string]*HeaderEntry, len(req.Header)), - Host: req.Host, - RemoteAddr: req.RemoteAddr, - Body: body, - } - - reqURL := req.URL - fq.Url = &URL{ - Scheme: reqURL.Scheme, - Opaque: reqURL.Opaque, - Host: reqURL.Host, - Path: reqURL.Path, - RawPath: reqURL.RawPath, - RawQuery: reqURL.RawQuery, - Fragment: reqURL.Fragment, - } - - for k, v := range req.Header { - fq.HeaderEntries[k] = &HeaderEntry{ - Values: v, - } - } - - if req.TLS != nil && req.TLS.PeerCertificates != nil && len(req.TLS.PeerCertificates) > 0 { - fq.PeerCertificates = make([][]byte, len(req.TLS.PeerCertificates)) - for i, cert := range req.TLS.PeerCertificates { - fq.PeerCertificates[i] = cert.Raw - } - } - - return &fq, nil -} - -// ParseForwardedRequest generates a new http.Request that is comprised of the -// values in the given request's body, assuming it correctly parses into a -// ForwardedRequest. -func ParseForwardedHTTPRequest(req *http.Request) (*http.Request, error) { - buf := bytes.NewBuffer(nil) - _, err := buf.ReadFrom(req.Body) - if err != nil { - return nil, err - } - - fq := new(Request) - switch os.Getenv("VAULT_MESSAGE_TYPE") { - case "json", "json_compress": - err = jsonutil.DecodeJSON(buf.Bytes(), fq) - default: - err = proto.Unmarshal(buf.Bytes(), fq) - } - if err != nil { - return nil, err - } - - return ParseForwardedRequest(fq) -} - -func ParseForwardedRequest(fq *Request) (*http.Request, error) { - buf := bufCloser{ - Buffer: bytes.NewBuffer(fq.Body), - } - - ret := &http.Request{ - Method: fq.Method, - Header: make(map[string][]string, len(fq.HeaderEntries)), - Body: buf, - Host: fq.Host, - RemoteAddr: fq.RemoteAddr, - } - - ret.URL = &url.URL{ - Scheme: fq.Url.Scheme, - Opaque: fq.Url.Opaque, - Host: fq.Url.Host, - Path: fq.Url.Path, - RawPath: fq.Url.RawPath, - RawQuery: fq.Url.RawQuery, - Fragment: fq.Url.Fragment, - } - - for k, v := range fq.HeaderEntries { - ret.Header[k] = v.Values - } - - if fq.PeerCertificates != nil && len(fq.PeerCertificates) > 0 { - ret.TLS = &tls.ConnectionState{ - PeerCertificates: make([]*x509.Certificate, len(fq.PeerCertificates)), - } - for i, certBytes := range fq.PeerCertificates { - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, err - } - ret.TLS.PeerCertificates[i] = cert - } - } - - return ret, nil -} - -type RPCResponseWriter struct { - statusCode int - header http.Header - body *bytes.Buffer -} - -// NewRPCResponseWriter returns an initialized RPCResponseWriter -func NewRPCResponseWriter() *RPCResponseWriter { - w := &RPCResponseWriter{ - header: make(http.Header), - body: new(bytes.Buffer), - statusCode: 200, - } - //w.header.Set("Content-Type", "application/octet-stream") - return w -} - -func (w *RPCResponseWriter) Header() http.Header { - return w.header -} - -func (w *RPCResponseWriter) Write(buf []byte) (int, error) { - w.body.Write(buf) - return len(buf), nil -} - -func (w *RPCResponseWriter) WriteHeader(code int) { - w.statusCode = code -} - -func (w *RPCResponseWriter) StatusCode() int { - return w.statusCode -} - -func (w *RPCResponseWriter) Body() *bytes.Buffer { - return w.body -} diff --git a/vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go b/vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go deleted file mode 100644 index 0b120367..00000000 --- a/vendor/github.com/hashicorp/vault/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/helper/identity/identity.go b/vendor/github.com/hashicorp/vault/helper/identity/identity.go deleted file mode 100644 index 46789c03..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/identity.go +++ /dev/null @@ -1,65 +0,0 @@ -package identity - -import ( - "fmt" - - proto "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" -) - -func (g *Group) Clone() (*Group, error) { - if g == nil { - return nil, fmt.Errorf("nil group") - } - - marshaledGroup, err := proto.Marshal(g) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal group: {{err}}", err) - } - - var clonedGroup Group - err = proto.Unmarshal(marshaledGroup, &clonedGroup) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal group: {{err}}", err) - } - - return &clonedGroup, nil -} - -func (e *Entity) Clone() (*Entity, error) { - if e == nil { - return nil, fmt.Errorf("nil entity") - } - - marshaledEntity, err := proto.Marshal(e) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal entity: {{err}}", err) - } - - var clonedEntity Entity - err = proto.Unmarshal(marshaledEntity, &clonedEntity) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal entity: {{err}}", err) - } - - return &clonedEntity, nil -} - -func (p *Alias) Clone() (*Alias, error) { - if p == nil { - return nil, fmt.Errorf("nil alias") - } - - marshaledAlias, err := proto.Marshal(p) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal alias: {{err}}", err) - } - - var clonedAlias Alias - err = proto.Unmarshal(marshaledAlias, &clonedAlias) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal alias: {{err}}", err) - } - - return &clonedAlias, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.pb.go b/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.pb.go deleted file mode 100644 index 5c1855e7..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.pb.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build !enterprise -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/identity/mfa/types.proto - -package mfa - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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 Secret struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Secret) Reset() { *m = Secret{} } -func (m *Secret) String() string { return proto.CompactTextString(m) } -func (*Secret) ProtoMessage() {} -func (*Secret) Descriptor() ([]byte, []int) { - return fileDescriptor_2eb73493aac0ba29, []int{0} -} - -func (m *Secret) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Secret.Unmarshal(m, b) -} -func (m *Secret) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Secret.Marshal(b, m, deterministic) -} -func (m *Secret) XXX_Merge(src proto.Message) { - xxx_messageInfo_Secret.Merge(m, src) -} -func (m *Secret) XXX_Size() int { - return xxx_messageInfo_Secret.Size(m) -} -func (m *Secret) XXX_DiscardUnknown() { - xxx_messageInfo_Secret.DiscardUnknown(m) -} - -var xxx_messageInfo_Secret proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Secret)(nil), "mfa.Secret") -} - -func init() { proto.RegisterFile("helper/identity/mfa/types.proto", fileDescriptor_2eb73493aac0ba29) } - -var fileDescriptor_2eb73493aac0ba29 = []byte{ - // 111 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x48, 0xcd, 0x29, - 0x48, 0x2d, 0xd2, 0xcf, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xa9, 0xd4, 0xcf, 0x4d, 0x4b, 0xd4, - 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0xce, 0x4d, 0x4b, - 0x54, 0xe2, 0xe0, 0x62, 0x0b, 0x4e, 0x4d, 0x2e, 0x4a, 0x2d, 0x71, 0x32, 0x88, 0xd2, 0x4b, 0xcf, - 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0xcf, 0x48, 0x2c, 0xce, 0xc8, 0x4c, 0xce, - 0x2f, 0x2a, 0xd0, 0x2f, 0x4b, 0x2c, 0xcd, 0x29, 0xd1, 0xc7, 0x62, 0x58, 0x12, 0x1b, 0xd8, 0x1c, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa9, 0xc9, 0x73, 0x5e, 0x6a, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.proto b/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.proto deleted file mode 100644 index ab908072..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/mfa/types.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/identity/mfa"; - -package mfa; - -message Secret {} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go b/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go deleted file mode 100644 index bf3cfff5..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go +++ /dev/null @@ -1,125 +0,0 @@ -package identity - -import "github.com/golang/protobuf/ptypes" - -func (e *Entity) SentinelGet(key string) (interface{}, error) { - if e == nil { - return nil, nil - } - switch key { - case "aliases": - return e.Aliases, nil - case "id": - return e.ID, nil - case "meta", "metadata": - return e.Metadata, nil - case "name": - return e.Name, nil - case "creation_time": - return ptypes.TimestampString(e.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(e.LastUpdateTime), nil - case "merged_entity_ids": - return e.MergedEntityIDs, nil - case "policies": - return e.Policies, nil - } - - return nil, nil -} - -func (e *Entity) SentinelKeys() []string { - return []string{ - "id", - "aliases", - "metadata", - "meta", - "name", - "creation_time", - "last_update_time", - "merged_entity_ids", - "policies", - } -} - -func (p *Alias) SentinelGet(key string) (interface{}, error) { - if p == nil { - return nil, nil - } - switch key { - case "id": - return p.ID, nil - case "mount_type": - return p.MountType, nil - case "mount_accessor": - return p.MountAccessor, nil - case "mount_path": - return p.MountPath, nil - case "meta", "metadata": - return p.Metadata, nil - case "name": - return p.Name, nil - case "creation_time": - return ptypes.TimestampString(p.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(p.LastUpdateTime), nil - case "merged_from_entity_ids": - return p.MergedFromCanonicalIDs, nil - } - - return nil, nil -} - -func (a *Alias) SentinelKeys() []string { - return []string{ - "id", - "mount_type", - "mount_path", - "meta", - "metadata", - "name", - "creation_time", - "last_update_time", - "merged_from_entity_ids", - } -} - -func (g *Group) SentinelGet(key string) (interface{}, error) { - if g == nil { - return nil, nil - } - switch key { - case "id": - return g.ID, nil - case "name": - return g.Name, nil - case "policies": - return g.Policies, nil - case "parent_group_ids": - return g.ParentGroupIDs, nil - case "member_entity_ids": - return g.MemberEntityIDs, nil - case "meta", "metadata": - return g.Metadata, nil - case "creation_time": - return ptypes.TimestampString(g.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(g.LastUpdateTime), nil - } - - return nil, nil -} - -func (g *Group) SentinelKeys() []string { - return []string{ - "id", - "name", - "policies", - "parent_group_ids", - "member_entity_ids", - "metadata", - "meta", - "creation_time", - "last_update_time", - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/templating.go b/vendor/github.com/hashicorp/vault/helper/identity/templating.go deleted file mode 100644 index 0d739c83..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/templating.go +++ /dev/null @@ -1,214 +0,0 @@ -package identity - -import ( - "errors" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/namespace" -) - -var ( - ErrUnbalancedTemplatingCharacter = errors.New("unbalanced templating characters") - ErrNoEntityAttachedToToken = errors.New("string contains entity template directives but no entity was provided") - ErrNoGroupsAttachedToToken = errors.New("string contains groups template directives but no groups were provided") - ErrTemplateValueNotFound = errors.New("no value could be found for one of the template directives") -) - -type PopulateStringInput struct { - ValidityCheckOnly bool - String string - Entity *Entity - Groups []*Group - Namespace *namespace.Namespace -} - -func PopulateString(p *PopulateStringInput) (bool, string, error) { - if p == nil { - return false, "", errors.New("nil input") - } - - if p.String == "" { - return false, "", nil - } - - var subst bool - splitStr := strings.Split(p.String, "{{") - - if len(splitStr) >= 1 { - if strings.Contains(splitStr[0], "}}") { - return false, "", ErrUnbalancedTemplatingCharacter - } - if len(splitStr) == 1 { - return false, p.String, nil - } - } - - var b strings.Builder - if !p.ValidityCheckOnly { - b.Grow(2 * len(p.String)) - } - - for i, str := range splitStr { - if i == 0 { - if !p.ValidityCheckOnly { - b.WriteString(str) - } - continue - } - splitPiece := strings.Split(str, "}}") - switch len(splitPiece) { - case 2: - subst = true - if !p.ValidityCheckOnly { - tmplStr, err := performTemplating(p.Namespace, strings.TrimSpace(splitPiece[0]), p.Entity, p.Groups) - if err != nil { - return false, "", err - } - b.WriteString(tmplStr) - b.WriteString(splitPiece[1]) - } - default: - return false, "", ErrUnbalancedTemplatingCharacter - } - } - - return subst, b.String(), nil -} - -func performTemplating(ns *namespace.Namespace, input string, entity *Entity, groups []*Group) (string, error) { - performAliasTemplating := func(trimmed string, alias *Alias) (string, error) { - switch { - case trimmed == "id": - return alias.ID, nil - case trimmed == "name": - if alias.Name == "" { - return "", ErrTemplateValueNotFound - } - return alias.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := alias.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - } - - return "", ErrTemplateValueNotFound - } - - performEntityTemplating := func(trimmed string) (string, error) { - switch { - case trimmed == "id": - return entity.ID, nil - case trimmed == "name": - if entity.Name == "" { - return "", ErrTemplateValueNotFound - } - return entity.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := entity.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - case strings.HasPrefix(trimmed, "aliases."): - split := strings.SplitN(strings.TrimPrefix(trimmed, "aliases."), ".", 2) - if len(split) != 2 { - return "", errors.New("invalid alias selector") - } - var found *Alias - for _, alias := range entity.Aliases { - if split[0] == alias.MountAccessor { - found = alias - break - } - } - if found == nil { - return "", errors.New("alias not found") - } - return performAliasTemplating(split[1], found) - } - - return "", ErrTemplateValueNotFound - } - - performGroupsTemplating := func(trimmed string) (string, error) { - var ids bool - - selectorSplit := strings.SplitN(trimmed, ".", 2) - switch { - case len(selectorSplit) != 2: - return "", errors.New("invalid groups selector") - case selectorSplit[0] == "ids": - ids = true - case selectorSplit[0] == "names": - default: - return "", errors.New("invalid groups selector") - } - trimmed = selectorSplit[1] - - accessorSplit := strings.SplitN(trimmed, ".", 2) - if len(accessorSplit) != 2 { - return "", errors.New("invalid groups accessor") - } - var found *Group - for _, group := range groups { - var compare string - if ids { - compare = group.ID - } else { - if ns != nil && group.NamespaceID == ns.ID { - compare = group.Name - } else { - continue - } - } - - if compare == accessorSplit[0] { - found = group - break - } - } - - if found == nil { - return "", fmt.Errorf("entity is not a member of group %q", accessorSplit[0]) - } - - trimmed = accessorSplit[1] - - switch { - case trimmed == "id": - return found.ID, nil - case trimmed == "name": - if found.Name == "" { - return "", ErrTemplateValueNotFound - } - return found.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := found.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - } - - return "", ErrTemplateValueNotFound - } - - switch { - case strings.HasPrefix(input, "identity.entity."): - if entity == nil { - return "", ErrNoEntityAttachedToToken - } - return performEntityTemplating(strings.TrimPrefix(input, "identity.entity.")) - - case strings.HasPrefix(input, "identity.groups."): - if len(groups) == 0 { - return "", ErrNoGroupsAttachedToToken - } - return performGroupsTemplating(strings.TrimPrefix(input, "identity.groups.")) - } - - return "", ErrTemplateValueNotFound -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go b/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go deleted file mode 100644 index 28263c89..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go +++ /dev/null @@ -1,796 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/identity/types.proto - -package identity - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - timestamp "github.com/golang/protobuf/ptypes/timestamp" - mfa "github.com/hashicorp/vault/helper/identity/mfa" - math "math" -) - -// 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 - -// Group represents an identity group. -type Group struct { - // ID is the unique identifier for this group - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // Name is the unique name for this group - Name string `sentinel:"" protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Policies are the vault policies to be granted to members of this group - Policies []string `sentinel:"" protobuf:"bytes,3,rep,name=policies,proto3" json:"policies,omitempty"` - // ParentGroupIDs are the identifiers of those groups to which this group is a - // member of. These will serve as references to the parent group in the - // hierarchy. - ParentGroupIDs []string `sentinel:"" protobuf:"bytes,4,rep,name=parent_group_ids,json=parentGroupIds,proto3" json:"parent_group_ids,omitempty"` - // MemberEntityIDs are the identifiers of entities which are members of this - // group - MemberEntityIDs []string `sentinel:"" protobuf:"bytes,5,rep,name=member_entity_ids,json=memberEntityIDs,proto3" json:"member_entity_ids,omitempty"` - // Metadata represents the custom data tied with this group - Metadata map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // CreationTime is the time at which this group was created - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,7,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the time at which this group was last modified - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,8,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // ModifyIndex tracks the number of updates to the group. It is useful to detect - // updates to the groups. - ModifyIndex uint64 `sentinel:"" protobuf:"varint,9,opt,name=modify_index,json=modifyIndex,proto3" json:"modify_index,omitempty"` - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // group is stored in the underlying storage. This is useful to find all - // the groups belonging to a particular bucket during invalidation of the - // storage key. - BucketKeyHash string `sentinel:"" protobuf:"bytes,10,opt,name=bucket_key_hash,json=bucketKeyHash,proto3" json:"bucket_key_hash,omitempty"` - // Alias is used to mark this group as an internal mapping of a group that - // is external to the identity store. Alias can only be set if the 'type' - // is set to 'external'. - Alias *Alias `sentinel:"" protobuf:"bytes,11,opt,name=alias,proto3" json:"alias,omitempty"` - // Type indicates if this group is an internal group or an external group. - // Memberships of the internal groups can be managed over the API whereas - // the memberships on the external group --for which a corresponding alias - // will be set-- will be managed automatically. - Type string `sentinel:"" protobuf:"bytes,12,opt,name=type,proto3" json:"type,omitempty"` - // NamespaceID is the identifier of the namespace to which this group - // belongs to. Do not return this value over the API when reading the - // group. - NamespaceID string `sentinel:"" protobuf:"bytes,13,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Group) Reset() { *m = Group{} } -func (m *Group) String() string { return proto.CompactTextString(m) } -func (*Group) ProtoMessage() {} -func (*Group) Descriptor() ([]byte, []int) { - return fileDescriptor_319efdc71a5d7416, []int{0} -} - -func (m *Group) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Group.Unmarshal(m, b) -} -func (m *Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Group.Marshal(b, m, deterministic) -} -func (m *Group) XXX_Merge(src proto.Message) { - xxx_messageInfo_Group.Merge(m, src) -} -func (m *Group) XXX_Size() int { - return xxx_messageInfo_Group.Size(m) -} -func (m *Group) XXX_DiscardUnknown() { - xxx_messageInfo_Group.DiscardUnknown(m) -} - -var xxx_messageInfo_Group proto.InternalMessageInfo - -func (m *Group) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Group) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Group) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *Group) GetParentGroupIDs() []string { - if m != nil { - return m.ParentGroupIDs - } - return nil -} - -func (m *Group) GetMemberEntityIDs() []string { - if m != nil { - return m.MemberEntityIDs - } - return nil -} - -func (m *Group) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Group) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Group) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Group) GetModifyIndex() uint64 { - if m != nil { - return m.ModifyIndex - } - return 0 -} - -func (m *Group) GetBucketKeyHash() string { - if m != nil { - return m.BucketKeyHash - } - return "" -} - -func (m *Group) GetAlias() *Alias { - if m != nil { - return m.Alias - } - return nil -} - -func (m *Group) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Group) GetNamespaceID() string { - if m != nil { - return m.NamespaceID - } - return "" -} - -// Entity represents an entity that gets persisted and indexed. -// Entity is fundamentally composed of zero or many aliases. -type Entity struct { - // Aliases are the identities that this entity is made of. This can be - // empty as well to favor being able to create the entity first and then - // incrementally adding aliases. - Aliases []*Alias `sentinel:"" protobuf:"bytes,1,rep,name=aliases,proto3" json:"aliases,omitempty"` - // ID is the unique identifier of the entity which always be a UUID. This - // should never be allowed to be updated. - ID string `sentinel:"" protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - // Name is a unique identifier of the entity which is intended to be - // human-friendly. The default name might not be human friendly since it - // gets suffixed by a UUID, but it can optionally be updated, unlike the ID - // field. - Name string `sentinel:"" protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the explicit metadata which is set by the - // clients. This is useful to tie any information pertaining to the - // aliases. This is a non-unique field of entity, meaning multiple - // entities can have the same metadata set. Entities will be indexed based - // on this explicit metadata. This enables virtual groupings of entities - // based on its metadata. - Metadata map[string]string `sentinel:"" 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"` - // CreationTime is the time at which this entity is first created. - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,5,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the most recent time at which the properties of this - // entity got modified. This is helpful in filtering out entities based on - // its age and to take action on them, if desired. - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,6,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // MergedEntityIDs are the entities which got merged to this one. Entities - // will be indexed based on all the entities that got merged into it. This - // helps to apply the actions on this entity on the tokens that are merged - // to the merged entities. Merged entities will be deleted entirely and - // this is the only trackable trail of its earlier presence. - MergedEntityIDs []string `sentinel:"" protobuf:"bytes,7,rep,name=merged_entity_ids,json=mergedEntityIDs,proto3" json:"merged_entity_ids,omitempty"` - // Policies the entity is entitled to - Policies []string `sentinel:"" protobuf:"bytes,8,rep,name=policies,proto3" json:"policies,omitempty"` - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // entity is stored in the underlying storage. This is useful to find all - // the entities belonging to a particular bucket during invalidation of the - // storage key. - BucketKeyHash string `sentinel:"" protobuf:"bytes,9,opt,name=bucket_key_hash,json=bucketKeyHash,proto3" json:"bucket_key_hash,omitempty"` - // MFASecrets holds the MFA secrets indexed by the identifier of the MFA - // method configuration. - MFASecrets map[string]*mfa.Secret `sentinel:"" protobuf:"bytes,10,rep,name=mfa_secrets,json=mfaSecrets,proto3" json:"mfa_secrets,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Disabled indicates whether tokens associated with the account should not - // be able to be used - Disabled bool `sentinel:"" protobuf:"varint,11,opt,name=disabled,proto3" json:"disabled,omitempty"` - // NamespaceID is the identifier of the namespace to which this entity - // belongs to. Do not return this value over the API when reading the - // entity. - NamespaceID string `sentinel:"" protobuf:"bytes,12,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Entity) Reset() { *m = Entity{} } -func (m *Entity) String() string { return proto.CompactTextString(m) } -func (*Entity) ProtoMessage() {} -func (*Entity) Descriptor() ([]byte, []int) { - return fileDescriptor_319efdc71a5d7416, []int{1} -} - -func (m *Entity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Entity.Unmarshal(m, b) -} -func (m *Entity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Entity.Marshal(b, m, deterministic) -} -func (m *Entity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Entity.Merge(m, src) -} -func (m *Entity) XXX_Size() int { - return xxx_messageInfo_Entity.Size(m) -} -func (m *Entity) XXX_DiscardUnknown() { - xxx_messageInfo_Entity.DiscardUnknown(m) -} - -var xxx_messageInfo_Entity proto.InternalMessageInfo - -func (m *Entity) GetAliases() []*Alias { - if m != nil { - return m.Aliases - } - return nil -} - -func (m *Entity) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Entity) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Entity) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Entity) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Entity) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Entity) GetMergedEntityIDs() []string { - if m != nil { - return m.MergedEntityIDs - } - return nil -} - -func (m *Entity) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *Entity) GetBucketKeyHash() string { - if m != nil { - return m.BucketKeyHash - } - return "" -} - -func (m *Entity) GetMFASecrets() map[string]*mfa.Secret { - if m != nil { - return m.MFASecrets - } - return nil -} - -func (m *Entity) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -func (m *Entity) GetNamespaceID() string { - if m != nil { - return m.NamespaceID - } - return "" -} - -// Alias represents the alias that gets stored inside of the -// entity object in storage and also represents in an in-memory index of an -// alias object. -type Alias struct { - // ID is the unique identifier that represents this alias - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // CanonicalID is the entity identifier to which this alias belongs to - CanonicalID string `sentinel:"" protobuf:"bytes,2,opt,name=canonical_id,json=canonicalId,proto3" json:"canonical_id,omitempty"` - // MountType is the backend mount's type to which this alias belongs to. - // This enables categorically querying aliases of specific backend types. - MountType string `sentinel:"" protobuf:"bytes,3,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - // MountAccessor is the backend mount's accessor to which this alias - // belongs to. - MountAccessor string `sentinel:"" protobuf:"bytes,4,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - // MountPath is the backend mount's path to which the Maccessor belongs to. This - // field is not used for any operational purposes. This is only returned when - // alias is read, only as a nicety. - MountPath string `sentinel:"" protobuf:"bytes,5,opt,name=mount_path,json=mountPath,proto3" json:"mount_path,omitempty"` - // Metadata is the explicit metadata that clients set against an entity - // which enables virtual grouping of aliases. Aliases will be indexed - // against their metadata. - Metadata map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Name is the identifier of this alias in its authentication source. - // This does not uniquely identify an alias in Vault. This in conjunction - // with MountAccessor form to be the factors that represent an alias in a - // unique way. Aliases will be indexed based on this combined uniqueness - // factor. - Name string `sentinel:"" protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` - // CreationTime is the time at which this alias was first created - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,8,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the most recent time at which the properties of this - // alias got modified. This is helpful in filtering out aliases based - // on its age and to take action on them, if desired. - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,9,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // MergedFromCanonicalIDs is the FIFO history of merging activity - MergedFromCanonicalIDs []string `sentinel:"" protobuf:"bytes,10,rep,name=merged_from_canonical_ids,json=mergedFromCanonicalIds,proto3" json:"merged_from_canonical_ids,omitempty"` - // NamespaceID is the identifier of the namespace to which this alias - // belongs. - NamespaceID string `sentinel:"" protobuf:"bytes,11,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Alias) Reset() { *m = Alias{} } -func (m *Alias) String() string { return proto.CompactTextString(m) } -func (*Alias) ProtoMessage() {} -func (*Alias) Descriptor() ([]byte, []int) { - return fileDescriptor_319efdc71a5d7416, []int{2} -} - -func (m *Alias) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Alias.Unmarshal(m, b) -} -func (m *Alias) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Alias.Marshal(b, m, deterministic) -} -func (m *Alias) XXX_Merge(src proto.Message) { - xxx_messageInfo_Alias.Merge(m, src) -} -func (m *Alias) XXX_Size() int { - return xxx_messageInfo_Alias.Size(m) -} -func (m *Alias) XXX_DiscardUnknown() { - xxx_messageInfo_Alias.DiscardUnknown(m) -} - -var xxx_messageInfo_Alias proto.InternalMessageInfo - -func (m *Alias) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Alias) GetCanonicalID() string { - if m != nil { - return m.CanonicalID - } - return "" -} - -func (m *Alias) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *Alias) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *Alias) GetMountPath() string { - if m != nil { - return m.MountPath - } - return "" -} - -func (m *Alias) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Alias) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Alias) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Alias) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Alias) GetMergedFromCanonicalIDs() []string { - if m != nil { - return m.MergedFromCanonicalIDs - } - return nil -} - -func (m *Alias) GetNamespaceID() string { - if m != nil { - return m.NamespaceID - } - return "" -} - -// Deprecated. Retained for backwards compatibility. -type EntityStorageEntry struct { - Personas []*PersonaIndexEntry `sentinel:"" protobuf:"bytes,1,rep,name=personas,proto3" json:"personas,omitempty"` - ID string `sentinel:"" protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - Name string `sentinel:"" protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - Metadata map[string]string `sentinel:"" 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"` - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,5,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,6,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - MergedEntityIDs []string `sentinel:"" protobuf:"bytes,7,rep,name=merged_entity_ids,json=mergedEntityIDs,proto3" json:"merged_entity_ids,omitempty"` - Policies []string `sentinel:"" protobuf:"bytes,8,rep,name=policies,proto3" json:"policies,omitempty"` - BucketKeyHash string `sentinel:"" protobuf:"bytes,9,opt,name=bucket_key_hash,json=bucketKeyHash,proto3" json:"bucket_key_hash,omitempty"` - MFASecrets map[string]*mfa.Secret `sentinel:"" protobuf:"bytes,10,rep,name=mfa_secrets,json=mfaSecrets,proto3" json:"mfa_secrets,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EntityStorageEntry) Reset() { *m = EntityStorageEntry{} } -func (m *EntityStorageEntry) String() string { return proto.CompactTextString(m) } -func (*EntityStorageEntry) ProtoMessage() {} -func (*EntityStorageEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_319efdc71a5d7416, []int{3} -} - -func (m *EntityStorageEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EntityStorageEntry.Unmarshal(m, b) -} -func (m *EntityStorageEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EntityStorageEntry.Marshal(b, m, deterministic) -} -func (m *EntityStorageEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_EntityStorageEntry.Merge(m, src) -} -func (m *EntityStorageEntry) XXX_Size() int { - return xxx_messageInfo_EntityStorageEntry.Size(m) -} -func (m *EntityStorageEntry) XXX_DiscardUnknown() { - xxx_messageInfo_EntityStorageEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_EntityStorageEntry proto.InternalMessageInfo - -func (m *EntityStorageEntry) GetPersonas() []*PersonaIndexEntry { - if m != nil { - return m.Personas - } - return nil -} - -func (m *EntityStorageEntry) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *EntityStorageEntry) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *EntityStorageEntry) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *EntityStorageEntry) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *EntityStorageEntry) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *EntityStorageEntry) GetMergedEntityIDs() []string { - if m != nil { - return m.MergedEntityIDs - } - return nil -} - -func (m *EntityStorageEntry) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *EntityStorageEntry) GetBucketKeyHash() string { - if m != nil { - return m.BucketKeyHash - } - return "" -} - -func (m *EntityStorageEntry) GetMFASecrets() map[string]*mfa.Secret { - if m != nil { - return m.MFASecrets - } - return nil -} - -// Deprecated. Retained for backwards compatibility. -type PersonaIndexEntry struct { - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - EntityID string `sentinel:"" protobuf:"bytes,2,opt,name=entity_id,json=entityId,proto3" json:"entity_id,omitempty"` - MountType string `sentinel:"" protobuf:"bytes,3,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - MountAccessor string `sentinel:"" protobuf:"bytes,4,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - MountPath string `sentinel:"" protobuf:"bytes,5,opt,name=mount_path,json=mountPath,proto3" json:"mount_path,omitempty"` - Metadata map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Name string `sentinel:"" protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,8,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,9,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - MergedFromEntityIDs []string `sentinel:"" protobuf:"bytes,10,rep,name=merged_from_entity_ids,json=mergedFromEntityIDs,proto3" json:"merged_from_entity_ids,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PersonaIndexEntry) Reset() { *m = PersonaIndexEntry{} } -func (m *PersonaIndexEntry) String() string { return proto.CompactTextString(m) } -func (*PersonaIndexEntry) ProtoMessage() {} -func (*PersonaIndexEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_319efdc71a5d7416, []int{4} -} - -func (m *PersonaIndexEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PersonaIndexEntry.Unmarshal(m, b) -} -func (m *PersonaIndexEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PersonaIndexEntry.Marshal(b, m, deterministic) -} -func (m *PersonaIndexEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_PersonaIndexEntry.Merge(m, src) -} -func (m *PersonaIndexEntry) XXX_Size() int { - return xxx_messageInfo_PersonaIndexEntry.Size(m) -} -func (m *PersonaIndexEntry) XXX_DiscardUnknown() { - xxx_messageInfo_PersonaIndexEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_PersonaIndexEntry proto.InternalMessageInfo - -func (m *PersonaIndexEntry) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *PersonaIndexEntry) GetEntityID() string { - if m != nil { - return m.EntityID - } - return "" -} - -func (m *PersonaIndexEntry) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *PersonaIndexEntry) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *PersonaIndexEntry) GetMountPath() string { - if m != nil { - return m.MountPath - } - return "" -} - -func (m *PersonaIndexEntry) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *PersonaIndexEntry) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PersonaIndexEntry) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *PersonaIndexEntry) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *PersonaIndexEntry) GetMergedFromEntityIDs() []string { - if m != nil { - return m.MergedFromEntityIDs - } - return nil -} - -func init() { - proto.RegisterType((*Group)(nil), "identity.Group") - proto.RegisterMapType((map[string]string)(nil), "identity.Group.MetadataEntry") - proto.RegisterType((*Entity)(nil), "identity.Entity") - proto.RegisterMapType((map[string]string)(nil), "identity.Entity.MetadataEntry") - proto.RegisterMapType((map[string]*mfa.Secret)(nil), "identity.Entity.MFASecretsEntry") - proto.RegisterType((*Alias)(nil), "identity.Alias") - proto.RegisterMapType((map[string]string)(nil), "identity.Alias.MetadataEntry") - proto.RegisterType((*EntityStorageEntry)(nil), "identity.EntityStorageEntry") - proto.RegisterMapType((map[string]string)(nil), "identity.EntityStorageEntry.MetadataEntry") - proto.RegisterMapType((map[string]*mfa.Secret)(nil), "identity.EntityStorageEntry.MFASecretsEntry") - proto.RegisterType((*PersonaIndexEntry)(nil), "identity.PersonaIndexEntry") - proto.RegisterMapType((map[string]string)(nil), "identity.PersonaIndexEntry.MetadataEntry") -} - -func init() { proto.RegisterFile("helper/identity/types.proto", fileDescriptor_319efdc71a5d7416) } - -var fileDescriptor_319efdc71a5d7416 = []byte{ - // 861 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x96, 0xcf, 0x8f, 0xdb, 0x44, - 0x14, 0xc7, 0x95, 0x1f, 0x4e, 0xec, 0xe7, 0xfc, 0xd8, 0x0e, 0xa8, 0x32, 0x59, 0x95, 0x66, 0x2b, - 0x15, 0xa5, 0xab, 0xca, 0x91, 0xb6, 0x07, 0x68, 0x39, 0xa0, 0x05, 0xb6, 0x10, 0x50, 0xa5, 0xca, - 0x2d, 0x17, 0x2e, 0xd6, 0xc4, 0x9e, 0x24, 0xa3, 0xb5, 0x3d, 0x96, 0x67, 0x5c, 0x91, 0xff, 0x80, - 0x23, 0x17, 0xfe, 0x24, 0xfe, 0x28, 0x6e, 0x68, 0x66, 0x6c, 0xc7, 0x8d, 0xd3, 0xa5, 0x2b, 0x22, - 0x04, 0x52, 0x6f, 0xf6, 0x77, 0xde, 0xbc, 0x3c, 0xbf, 0xf7, 0x79, 0x5f, 0x05, 0x4e, 0x37, 0x24, - 0x4a, 0x49, 0x36, 0xa7, 0x21, 0x49, 0x04, 0x15, 0xdb, 0xb9, 0xd8, 0xa6, 0x84, 0xbb, 0x69, 0xc6, - 0x04, 0x43, 0x66, 0xa9, 0x4e, 0xee, 0xaf, 0x19, 0x5b, 0x47, 0x64, 0xae, 0xf4, 0x65, 0xbe, 0x9a, - 0x0b, 0x1a, 0x13, 0x2e, 0x70, 0x9c, 0xea, 0xd0, 0xc9, 0xfd, 0xfd, 0x3c, 0xf1, 0x0a, 0xd7, 0x73, - 0x3d, 0xf8, 0xa3, 0x0b, 0xc6, 0x77, 0x19, 0xcb, 0x53, 0x34, 0x82, 0x36, 0x0d, 0x9d, 0xd6, 0xb4, - 0x35, 0xb3, 0xbc, 0x36, 0x0d, 0x11, 0x82, 0x6e, 0x82, 0x63, 0xe2, 0xb4, 0x95, 0xa2, 0x9e, 0xd1, - 0x04, 0xcc, 0x94, 0x45, 0x34, 0xa0, 0x84, 0x3b, 0x9d, 0x69, 0x67, 0x66, 0x79, 0xd5, 0x3b, 0x9a, - 0xc1, 0x49, 0x8a, 0x33, 0x92, 0x08, 0x7f, 0x2d, 0xf3, 0xf9, 0x34, 0xe4, 0x4e, 0x57, 0xc5, 0x8c, - 0xb4, 0xae, 0x7e, 0x66, 0x11, 0x72, 0x74, 0x0e, 0x77, 0x62, 0x12, 0x2f, 0x49, 0xe6, 0xeb, 0xa2, - 0x54, 0xa8, 0xa1, 0x42, 0xc7, 0xfa, 0xe0, 0x4a, 0xe9, 0x32, 0xf6, 0x29, 0x98, 0x31, 0x11, 0x38, - 0xc4, 0x02, 0x3b, 0xbd, 0x69, 0x67, 0x66, 0x5f, 0xdc, 0x73, 0xcb, 0x8f, 0x71, 0x55, 0x46, 0xf7, - 0x45, 0x71, 0x7e, 0x95, 0x88, 0x6c, 0xeb, 0x55, 0xe1, 0xe8, 0x2b, 0x18, 0x06, 0x19, 0xc1, 0x82, - 0xb2, 0xc4, 0x97, 0x7d, 0x71, 0xfa, 0xd3, 0xd6, 0xcc, 0xbe, 0x98, 0xb8, 0xba, 0x69, 0x6e, 0xd9, - 0x34, 0xf7, 0x75, 0xd9, 0x34, 0x6f, 0x50, 0x5e, 0x90, 0x12, 0xfa, 0x16, 0x4e, 0x22, 0xcc, 0x85, - 0x9f, 0xa7, 0x21, 0x16, 0x44, 0xe7, 0x30, 0xff, 0x36, 0xc7, 0x48, 0xde, 0xf9, 0x49, 0x5d, 0x51, - 0x59, 0xce, 0x60, 0x10, 0xb3, 0x90, 0xae, 0xb6, 0x3e, 0x4d, 0x42, 0xf2, 0x8b, 0x63, 0x4d, 0x5b, - 0xb3, 0xae, 0x67, 0x6b, 0x6d, 0x21, 0x25, 0xf4, 0x19, 0x8c, 0x97, 0x79, 0x70, 0x4d, 0x84, 0x7f, - 0x4d, 0xb6, 0xfe, 0x06, 0xf3, 0x8d, 0x03, 0xaa, 0xeb, 0x43, 0x2d, 0xff, 0x48, 0xb6, 0xdf, 0x63, - 0xbe, 0x41, 0x0f, 0xc1, 0xc0, 0x11, 0xc5, 0xdc, 0xb1, 0x55, 0x15, 0xe3, 0x5d, 0x27, 0x2e, 0xa5, - 0xec, 0xe9, 0x53, 0x39, 0x39, 0x39, 0x62, 0x67, 0xa0, 0x27, 0x27, 0x9f, 0x65, 0x15, 0x72, 0x82, - 0x3c, 0xc5, 0x01, 0xf1, 0x69, 0xe8, 0x0c, 0xd5, 0x99, 0x5d, 0x69, 0x8b, 0x70, 0xf2, 0x25, 0x0c, - 0xdf, 0x6a, 0x25, 0x3a, 0x81, 0xce, 0x35, 0xd9, 0x16, 0x48, 0xc8, 0x47, 0xf4, 0x31, 0x18, 0x6f, - 0x70, 0x94, 0x97, 0x50, 0xe8, 0x97, 0x67, 0xed, 0x2f, 0x5a, 0x0f, 0x7e, 0x37, 0xa0, 0xa7, 0xa7, - 0x86, 0x1e, 0x41, 0x5f, 0xd5, 0x41, 0xb8, 0xd3, 0x52, 0x13, 0x6b, 0xd4, 0x59, 0x9e, 0x17, 0xcc, - 0xb5, 0x1b, 0xcc, 0x75, 0x6a, 0xcc, 0x3d, 0xab, 0x11, 0xd0, 0x55, 0xf9, 0x3e, 0xdd, 0xe5, 0xd3, - 0x3f, 0xf9, 0xfe, 0x08, 0x18, 0x47, 0x40, 0xa0, 0x77, 0x6b, 0x04, 0x14, 0xf0, 0xd9, 0x9a, 0x84, - 0x75, 0xe0, 0xfb, 0x25, 0xf0, 0xf2, 0x60, 0x07, 0x7c, 0x7d, 0xc5, 0xcc, 0xbd, 0x15, 0x3b, 0xc0, - 0x89, 0x75, 0x88, 0x93, 0x4b, 0xb0, 0xe3, 0x15, 0xf6, 0x39, 0x09, 0x32, 0x22, 0xb8, 0x03, 0xaa, - 0x6b, 0xd3, 0x66, 0xd7, 0x56, 0xf8, 0x95, 0x0e, 0xd1, 0x7d, 0x83, 0xb8, 0x12, 0x64, 0x19, 0x21, - 0xe5, 0x78, 0x19, 0x91, 0x50, 0xd1, 0x66, 0x7a, 0xd5, 0x7b, 0x83, 0xa5, 0xc1, 0x71, 0x59, 0x9a, - 0xfc, 0x00, 0xe3, 0xbd, 0xd2, 0x0e, 0x5c, 0x3f, 0xab, 0x5f, 0xb7, 0x2f, 0x6c, 0x37, 0x5e, 0x61, - 0x57, 0xdf, 0xa9, 0x73, 0xf9, 0x5b, 0x17, 0x0c, 0x05, 0x5d, 0xc3, 0xdf, 0xce, 0x60, 0x10, 0xe0, - 0x84, 0x25, 0x34, 0xc0, 0x91, 0x5f, 0x51, 0x68, 0x57, 0xda, 0x22, 0x44, 0xf7, 0x00, 0x62, 0x96, - 0x27, 0xc2, 0x57, 0xeb, 0xa4, 0xa1, 0xb4, 0x94, 0xf2, 0x5a, 0xee, 0xd4, 0x43, 0x18, 0xe9, 0x63, - 0x1c, 0x04, 0x84, 0x73, 0x96, 0x39, 0x5d, 0x3d, 0x0d, 0xa5, 0x5e, 0x16, 0xe2, 0x2e, 0x4b, 0x8a, - 0xc5, 0x46, 0x11, 0x58, 0x66, 0x79, 0x89, 0xc5, 0xe6, 0x66, 0x87, 0x53, 0xa5, 0xbf, 0x13, 0xef, - 0x72, 0x5d, 0xfa, 0xb5, 0x75, 0x69, 0x20, 0x6f, 0x1e, 0x01, 0x79, 0xeb, 0xd6, 0xc8, 0x3f, 0x85, - 0x4f, 0x0a, 0xe4, 0x57, 0x19, 0x8b, 0xfd, 0x7a, 0xa7, 0x35, 0x90, 0x96, 0x77, 0x57, 0x07, 0x3c, - 0xcf, 0x58, 0xfc, 0xcd, 0xae, 0xe9, 0xbc, 0x81, 0x97, 0x7d, 0x64, 0xab, 0xfa, 0xd5, 0x00, 0xa4, - 0x37, 0xe0, 0x95, 0x60, 0x19, 0x5e, 0x13, 0x9d, 0xe2, 0x73, 0x30, 0x53, 0x92, 0x71, 0x96, 0xe0, - 0xd2, 0xb7, 0x4e, 0x77, 0x73, 0x78, 0xa9, 0x4f, 0x94, 0x5d, 0x17, 0x53, 0x28, 0x83, 0xdf, 0xcb, - 0xc4, 0x9e, 0x37, 0x4c, 0xec, 0x7c, 0x7f, 0x1d, 0xeb, 0xc5, 0x7c, 0x30, 0xb4, 0xb7, 0x0d, 0xed, - 0xc5, 0x21, 0x43, 0x7b, 0x7c, 0x73, 0x07, 0xdf, 0x6d, 0x6e, 0xff, 0x1d, 0x77, 0xfa, 0xb3, 0x03, - 0x77, 0x1a, 0x68, 0x35, 0x9c, 0xea, 0x14, 0xac, 0xaa, 0xcd, 0x45, 0x3d, 0x26, 0x29, 0xfa, 0xfb, - 0xef, 0x78, 0xd4, 0x55, 0xc3, 0xa3, 0x1e, 0xdd, 0xb0, 0x1b, 0xff, 0x47, 0xbf, 0x7a, 0x02, 0x77, - 0xeb, 0x7e, 0x55, 0xc3, 0x5a, 0x9b, 0xd5, 0x47, 0x3b, 0xb3, 0xaa, 0xd0, 0xfe, 0x47, 0x1c, 0x7d, - 0xfd, 0xf8, 0xe7, 0xf3, 0x35, 0x15, 0x9b, 0x7c, 0xe9, 0x06, 0x2c, 0x9e, 0x4b, 0xf6, 0x69, 0xc0, - 0xb2, 0x74, 0xfe, 0x06, 0xe7, 0x91, 0x98, 0xef, 0xfd, 0x6f, 0x5f, 0xf6, 0xd4, 0x37, 0x3c, 0xf9, - 0x2b, 0x00, 0x00, 0xff, 0xff, 0x66, 0xa2, 0xa4, 0x7e, 0x19, 0x0c, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/types.proto b/vendor/github.com/hashicorp/vault/helper/identity/types.proto deleted file mode 100644 index c604bb04..00000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/types.proto +++ /dev/null @@ -1,207 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/identity"; - -package identity; - -import "google/protobuf/timestamp.proto"; -import "helper/identity/mfa/types.proto"; - -// Group represents an identity group. -message Group { - // ID is the unique identifier for this group - string id = 1; - - // Name is the unique name for this group - string name = 2; - - // Policies are the vault policies to be granted to members of this group - repeated string policies = 3; - - // ParentGroupIDs are the identifiers of those groups to which this group is a - // member of. These will serve as references to the parent group in the - // hierarchy. - repeated string parent_group_ids = 4; - - // MemberEntityIDs are the identifiers of entities which are members of this - // group - repeated string member_entity_ids = 5; - - // Metadata represents the custom data tied with this group - map metadata = 6; - - // CreationTime is the time at which this group was created - google.protobuf.Timestamp creation_time = 7; - - // LastUpdateTime is the time at which this group was last modified - google.protobuf.Timestamp last_update_time= 8; - - // ModifyIndex tracks the number of updates to the group. It is useful to detect - // updates to the groups. - uint64 modify_index = 9; - - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // group is stored in the underlying storage. This is useful to find all - // the groups belonging to a particular bucket during invalidation of the - // storage key. - string bucket_key_hash = 10; - - // Alias is used to mark this group as an internal mapping of a group that - // is external to the identity store. Alias can only be set if the 'type' - // is set to 'external'. - Alias alias = 11; - - // Type indicates if this group is an internal group or an external group. - // Memberships of the internal groups can be managed over the API whereas - // the memberships on the external group --for which a corresponding alias - // will be set-- will be managed automatically. - string type = 12; - - // NamespaceID is the identifier of the namespace to which this group - // belongs to. Do not return this value over the API when reading the - // group. - string namespace_id = 13; -} - -// Entity represents an entity that gets persisted and indexed. -// Entity is fundamentally composed of zero or many aliases. -message Entity { - // Aliases are the identities that this entity is made of. This can be - // empty as well to favor being able to create the entity first and then - // incrementally adding aliases. - repeated Alias aliases = 1; - - // ID is the unique identifier of the entity which always be a UUID. This - // should never be allowed to be updated. - string id = 2; - - // Name is a unique identifier of the entity which is intended to be - // human-friendly. The default name might not be human friendly since it - // gets suffixed by a UUID, but it can optionally be updated, unlike the ID - // field. - string name = 3; - - // Metadata represents the explicit metadata which is set by the - // clients. This is useful to tie any information pertaining to the - // aliases. This is a non-unique field of entity, meaning multiple - // entities can have the same metadata set. Entities will be indexed based - // on this explicit metadata. This enables virtual groupings of entities - // based on its metadata. - map metadata = 4; - - // CreationTime is the time at which this entity is first created. - google.protobuf.Timestamp creation_time = 5; - - // LastUpdateTime is the most recent time at which the properties of this - // entity got modified. This is helpful in filtering out entities based on - // its age and to take action on them, if desired. - google.protobuf.Timestamp last_update_time= 6; - - // MergedEntityIDs are the entities which got merged to this one. Entities - // will be indexed based on all the entities that got merged into it. This - // helps to apply the actions on this entity on the tokens that are merged - // to the merged entities. Merged entities will be deleted entirely and - // this is the only trackable trail of its earlier presence. - repeated string merged_entity_ids = 7; - - // Policies the entity is entitled to - repeated string policies = 8; - - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // entity is stored in the underlying storage. This is useful to find all - // the entities belonging to a particular bucket during invalidation of the - // storage key. - string bucket_key_hash = 9; - - // MFASecrets holds the MFA secrets indexed by the identifier of the MFA - // method configuration. - map mfa_secrets = 10; - - // Disabled indicates whether tokens associated with the account should not - // be able to be used - bool disabled = 11; - - // NamespaceID is the identifier of the namespace to which this entity - // belongs to. Do not return this value over the API when reading the - // entity. - string namespace_id = 12; -} - -// Alias represents the alias that gets stored inside of the -// entity object in storage and also represents in an in-memory index of an -// alias object. -message Alias { - // ID is the unique identifier that represents this alias - string id = 1; - - // CanonicalID is the entity identifier to which this alias belongs to - string canonical_id = 2; - - // MountType is the backend mount's type to which this alias belongs to. - // This enables categorically querying aliases of specific backend types. - string mount_type = 3; - - // MountAccessor is the backend mount's accessor to which this alias - // belongs to. - string mount_accessor = 4; - - // MountPath is the backend mount's path to which the Maccessor belongs to. This - // field is not used for any operational purposes. This is only returned when - // alias is read, only as a nicety. - string mount_path = 5; - - // Metadata is the explicit metadata that clients set against an entity - // which enables virtual grouping of aliases. Aliases will be indexed - // against their metadata. - map metadata = 6; - - // Name is the identifier of this alias in its authentication source. - // This does not uniquely identify an alias in Vault. This in conjunction - // with MountAccessor form to be the factors that represent an alias in a - // unique way. Aliases will be indexed based on this combined uniqueness - // factor. - string name = 7; - - // CreationTime is the time at which this alias was first created - google.protobuf.Timestamp creation_time = 8; - - // LastUpdateTime is the most recent time at which the properties of this - // alias got modified. This is helpful in filtering out aliases based - // on its age and to take action on them, if desired. - google.protobuf.Timestamp last_update_time = 9; - - // MergedFromCanonicalIDs is the FIFO history of merging activity - repeated string merged_from_canonical_ids = 10; - - // NamespaceID is the identifier of the namespace to which this alias - // belongs. - string namespace_id = 11; -} - -// Deprecated. Retained for backwards compatibility. -message EntityStorageEntry { - repeated PersonaIndexEntry personas = 1; - string id = 2; - string name = 3; - map metadata = 4; - google.protobuf.Timestamp creation_time = 5; - google.protobuf.Timestamp last_update_time= 6; - repeated string merged_entity_ids = 7; - repeated string policies = 8; - string bucket_key_hash = 9; - map mfa_secrets = 10; -} - -// Deprecated. Retained for backwards compatibility. -message PersonaIndexEntry { - string id = 1; - string entity_id = 2; - string mount_type = 3; - string mount_accessor = 4; - string mount_path = 5; - map metadata = 6; - string name = 7; - google.protobuf.Timestamp creation_time = 8; - google.protobuf.Timestamp last_update_time = 9; - repeated string merged_from_entity_ids = 10; -} diff --git a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go b/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go deleted file mode 100644 index d03ddef5..00000000 --- a/vendor/github.com/hashicorp/vault/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/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/helper/license/feature.go b/vendor/github.com/hashicorp/vault/helper/license/feature.go deleted file mode 100644 index 98e83c61..00000000 --- a/vendor/github.com/hashicorp/vault/helper/license/feature.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !enterprise - -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/helper/locksutil/locks.go b/vendor/github.com/hashicorp/vault/helper/locksutil/locks.go deleted file mode 100644 index e0c2fcdd..00000000 --- a/vendor/github.com/hashicorp/vault/helper/locksutil/locks.go +++ /dev/null @@ -1,60 +0,0 @@ -package locksutil - -import ( - "crypto/md5" - "sync" -) - -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 { - hf := md5.New() - hf.Write([]byte(key)) - return uint8(hf.Sum(nil)[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/helper/logging/vault.go b/vendor/github.com/hashicorp/vault/helper/logging/vault.go deleted file mode 100644 index 3e7e4766..00000000 --- a/vendor/github.com/hashicorp/vault/helper/logging/vault.go +++ /dev/null @@ -1,39 +0,0 @@ -package logging - -import ( - "io" - "os" - "strings" - - log "github.com/hashicorp/go-hclog" -) - -// 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, - Output: w, - JSONFormat: useJson(), - } - return log.New(opts) -} - -func useJson() bool { - logFormat := os.Getenv("VAULT_LOG_FORMAT") - if logFormat == "" { - logFormat = os.Getenv("LOGXI_FORMAT") - } - switch strings.ToLower(logFormat) { - case "json", "vault_json", "vault-json", "vaultjson": - return true - default: - return false - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/mlock/mlock.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock.go deleted file mode 100644 index 1675633d..00000000 --- a/vendor/github.com/hashicorp/vault/helper/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/vault/helper/mlock/mlock_unavail.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go deleted file mode 100644 index 8084963f..00000000 --- a/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build android 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/vault/helper/mlock/mlock_unix.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go deleted file mode 100644 index af0a69d4..00000000 --- a/vendor/github.com/hashicorp/vault/helper/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/vault/helper/namespace/namespace.go b/vendor/github.com/hashicorp/vault/helper/namespace/namespace.go deleted file mode 100644 index e47a27f3..00000000 --- a/vendor/github.com/hashicorp/vault/helper/namespace/namespace.go +++ /dev/null @@ -1,127 +0,0 @@ -package namespace - -import ( - "context" - "errors" - "strings" -) - -type contextValues struct{} - -type Namespace struct { - ID string `json:"id"` - Path string `json:"path"` -} - -const ( - RootNamespaceID = "root" -) - -var ( - contextNamespace contextValues = struct{}{} - ErrNoNamespace error = errors.New("no namespace") - RootNamespace *Namespace = &Namespace{ - ID: RootNamespaceID, - Path: "", - } -) - -func (n *Namespace) HasParent(possibleParent *Namespace) bool { - switch { - case n.Path == "": - return false - case possibleParent.Path == "": - return true - default: - return strings.HasPrefix(n.Path, possibleParent.Path) - } -} - -func (n *Namespace) TrimmedPath(path string) string { - return strings.TrimPrefix(path, n.Path) -} - -func ContextWithNamespace(ctx context.Context, ns *Namespace) context.Context { - return context.WithValue(ctx, contextNamespace, ns) -} - -func RootContext(ctx context.Context) context.Context { - if ctx == nil { - return ContextWithNamespace(context.Background(), RootNamespace) - } - return ContextWithNamespace(ctx, RootNamespace) -} - -// This function caches the ns to avoid doing a .Value lookup over and over, -// because it's called a *lot* in the request critical path. .Value is -// concurrency-safe so uses some kind of locking/atomicity, but it should never -// be read before first write, plus we don't believe this will be called from -// different goroutines, so it should be safe. -func FromContext(ctx context.Context) (*Namespace, error) { - if ctx == nil { - return nil, errors.New("context was nil") - } - - nsRaw := ctx.Value(contextNamespace) - if nsRaw == nil { - return nil, ErrNoNamespace - } - - ns := nsRaw.(*Namespace) - if ns == nil { - return nil, ErrNoNamespace - } - - return ns, nil -} - -// Canonicalize trims any prefix '/' and adds a trailing '/' to the -// provided string -func Canonicalize(nsPath string) string { - if nsPath == "" { - return "" - } - - // Canonicalize the path to not have a '/' prefix - nsPath = strings.TrimPrefix(nsPath, "/") - - // Canonicalize the path to always having a '/' suffix - if !strings.HasSuffix(nsPath, "/") { - nsPath += "/" - } - - return nsPath -} - -func SplitIDFromString(input string) (string, string) { - prefix := "" - slashIdx := strings.LastIndex(input, "/") - - switch { - case strings.HasPrefix(input, "b."): - prefix = "b." - input = input[2:] - - case strings.HasPrefix(input, "s."): - prefix = "s." - input = input[2:] - - case slashIdx > 0: - // Leases will never have a b./s. to start - if slashIdx == len(input)-1 { - return input, "" - } - prefix = input[:slashIdx+1] - input = input[slashIdx+1:] - } - - idx := strings.LastIndex(input, ".") - if idx == -1 { - return prefix + input, "" - } - if idx == len(input)-1 { - return prefix + input, "" - } - - return prefix + input[:idx], input[idx+1:] -} diff --git a/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go b/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go deleted file mode 100644 index 9b32bf7d..00000000 --- a/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go +++ /dev/null @@ -1,163 +0,0 @@ -package parseutil - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/strutil" - "github.com/mitchellh/mapstructure" -) - -func ParseDurationSecond(in interface{}) (time.Duration, error) { - var dur time.Duration - jsonIn, ok := in.(json.Number) - if ok { - in = jsonIn.String() - } - switch in.(type) { - case string: - inp := in.(string) - if inp == "" { - return time.Duration(0), nil - } - var err error - // Look for a suffix otherwise its a plain second value - if strings.HasSuffix(inp, "s") || strings.HasSuffix(inp, "m") || strings.HasSuffix(inp, "h") || strings.HasSuffix(inp, "ms") { - dur, err = time.ParseDuration(inp) - if err != nil { - return dur, err - } - } else { - // Plain integer - secs, err := strconv.ParseInt(inp, 10, 64) - if err != nil { - return dur, err - } - dur = time.Duration(secs) * time.Second - } - case int: - dur = time.Duration(in.(int)) * time.Second - case int32: - dur = time.Duration(in.(int32)) * time.Second - case int64: - dur = time.Duration(in.(int64)) * time.Second - case uint: - dur = time.Duration(in.(uint)) * time.Second - case uint32: - dur = time.Duration(in.(uint32)) * time.Second - case uint64: - dur = time.Duration(in.(uint64)) * time.Second - default: - return 0, errors.New("could not parse duration from input") - } - - return dur, nil -} - -func ParseInt(in interface{}) (int64, error) { - var ret int64 - jsonIn, ok := in.(json.Number) - if ok { - in = jsonIn.String() - } - switch in.(type) { - case string: - inp := in.(string) - if inp == "" { - return 0, nil - } - var err error - left, err := strconv.ParseInt(inp, 10, 64) - if err != nil { - return ret, err - } - ret = left - case int: - ret = int64(in.(int)) - case int32: - ret = int64(in.(int32)) - case int64: - ret = in.(int64) - case uint: - ret = int64(in.(uint)) - case uint32: - ret = int64(in.(uint32)) - case uint64: - ret = int64(in.(uint64)) - default: - return 0, errors.New("could not parse value from input") - } - - return ret, nil -} - -func ParseBool(in interface{}) (bool, error) { - var result bool - if err := mapstructure.WeakDecode(in, &result); err != nil { - return false, err - } - return result, nil -} - -func ParseCommaStringSlice(in interface{}) ([]string, error) { - var result []string - config := &mapstructure.DecoderConfig{ - Result: &result, - WeaklyTypedInput: true, - DecodeHook: mapstructure.StringToSliceHookFunc(","), - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - if err := decoder.Decode(in); err != nil { - return nil, err - } - return strutil.TrimStrings(result), nil -} - -func ParseAddrs(addrs interface{}) ([]*sockaddr.SockAddrMarshaler, error) { - out := make([]*sockaddr.SockAddrMarshaler, 0) - stringAddrs := make([]string, 0) - - switch addrs.(type) { - case string: - stringAddrs = strutil.ParseArbitraryStringSlice(addrs.(string), ",") - if len(stringAddrs) == 0 { - return nil, fmt.Errorf("unable to parse addresses from %v", addrs) - } - - case []string: - stringAddrs = addrs.([]string) - - case []interface{}: - for _, v := range addrs.([]interface{}) { - stringAddr, ok := v.(string) - if !ok { - return nil, fmt.Errorf("error parsing %v as string", v) - } - stringAddrs = append(stringAddrs, stringAddr) - } - - default: - return nil, fmt.Errorf("unknown address input type %T", addrs) - } - - for _, addr := range stringAddrs { - sa, err := sockaddr.NewSockAddr(addr) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing address %q: {{err}}", addr), err) - } - out = append(out, &sockaddr.SockAddrMarshaler{ - SockAddr: sa, - }) - } - - return out, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go b/vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go deleted file mode 100644 index e0e39445..00000000 --- a/vendor/github.com/hashicorp/vault/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/helper/pgpkeys/encrypt_decrypt.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go deleted file mode 100644 index eef4c5ed..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go +++ /dev/null @@ -1,118 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// EncryptShares takes an ordered set of byte slices to encrypt and the -// corresponding base64-encoded public keys to encrypt them with, encrypts each -// byte slice with the corresponding public key. -// -// Note: There is no corresponding test function; this functionality is -// thoroughly tested in the init and rekey command unit tests -func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { - if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") - } - encryptedShares := make([][]byte, 0, len(pgpKeys)) - entities, err := GetEntities(pgpKeys) - if err != nil { - return nil, nil, err - } - for i, entity := range entities { - ctBuf := bytes.NewBuffer(nil) - pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) - if err != nil { - return nil, nil, errwrap.Wrapf("error setting up encryption for PGP message: {{err}}", err) - } - _, err = pt.Write(input[i]) - if err != nil { - return nil, nil, errwrap.Wrapf("error encrypting PGP message: {{err}}", err) - } - pt.Close() - encryptedShares = append(encryptedShares, ctBuf.Bytes()) - } - - fingerprints, err := GetFingerprints(nil, entities) - if err != nil { - return nil, nil, err - } - - return fingerprints, encryptedShares, nil -} - -// GetFingerprints takes in a list of openpgp Entities and returns the -// fingerprints. If entities is nil, it will instead parse both entities and -// fingerprints from the pgpKeys string slice. -func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, error) { - if entities == nil { - var err error - entities, err = GetEntities(pgpKeys) - - if err != nil { - return nil, err - } - } - ret := make([]string, 0, len(entities)) - for _, entity := range entities { - ret = append(ret, fmt.Sprintf("%x", entity.PrimaryKey.Fingerprint)) - } - return ret, nil -} - -// GetEntities takes in a string array of base64-encoded PGP keys and returns -// the openpgp Entities -func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { - ret := make([]*openpgp.Entity, 0, len(pgpKeys)) - for _, keystring := range pgpKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return nil, errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return nil, errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - ret = append(ret, entity) - } - return ret, nil -} - -// DecryptBytes takes in base64-encoded encrypted bytes and the base64-encoded -// private key and decrypts it. A bytes.Buffer is returned to allow the caller -// to do useful thing with it (get it as a []byte, get it as a string, use it -// as an io.Reader, etc), and also because this function doesn't know if what -// comes out is binary data or a string, so let the caller decide. -func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) { - privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 private key: {{err}}", err) - } - - cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 crypted bytes: {{err}}", err) - } - - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes))) - if err != nil { - return nil, errwrap.Wrapf("error parsing private key: {{err}}", err) - } - - entityList := &openpgp.EntityList{entity} - md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil) - if err != nil { - return nil, errwrap.Wrapf("error decrypting the messages: {{err}}", err) - } - - ptBuf := bytes.NewBuffer(nil) - ptBuf.ReadFrom(md.UnverifiedBody) - - return ptBuf, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go deleted file mode 100644 index bb0f367d..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go +++ /dev/null @@ -1,140 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" -) - -// PubKeyFileFlag implements flag.Value and command.Example to receive exactly -// one PGP or keybase key via a flag. -type PubKeyFileFlag string - -func (p *PubKeyFileFlag) String() string { return string(*p) } - -func (p *PubKeyFileFlag) Set(val string) error { - if p != nil && *p != "" { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - if len(keys) > 1 { - return errors.New("can only specify one pgp key") - } - - *p = PubKeyFileFlag(keys[0]) - return nil -} - -func (p *PubKeyFileFlag) Example() string { return "keybase:user" } - -// PGPPubKeyFiles implements the flag.Value interface and allows parsing and -// reading a list of PGP public key files. -type PubKeyFilesFlag []string - -func (p *PubKeyFilesFlag) String() string { - return fmt.Sprint(*p) -} - -func (p *PubKeyFilesFlag) Set(val string) error { - if len(*p) > 0 { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - *p = PubKeyFilesFlag(keys) - return nil -} - -func (p *PubKeyFilesFlag) Example() string { return "keybase:user1, keybase:user2, ..." } - -// ParsePGPKeys takes a list of PGP keys and parses them either using keybase -// or reading them from disk and returns the "expanded" list of pgp keys in -// the same order. -func ParsePGPKeys(keyfiles []string) ([]string, error) { - keys := make([]string, len(keyfiles)) - - keybaseMap, err := FetchKeybasePubkeys(keyfiles) - if err != nil { - return nil, err - } - - for i, keyfile := range keyfiles { - keyfile = strings.TrimSpace(keyfile) - - if strings.HasPrefix(keyfile, kbPrefix) { - key, ok := keybaseMap[keyfile] - if !ok || key == "" { - return nil, fmt.Errorf("keybase user %q not found", strings.TrimPrefix(keyfile, kbPrefix)) - } - keys[i] = key - continue - } - - pgpStr, err := ReadPGPFile(keyfile) - if err != nil { - return nil, err - } - keys[i] = pgpStr - } - - return keys, nil -} - -// ReadPGPFile reads the given PGP file from disk. -func ReadPGPFile(path string) (string, error) { - if path[0] == '@' { - path = path[1:] - } - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - buf := bytes.NewBuffer(nil) - _, err = buf.ReadFrom(f) - if err != nil { - return "", err - } - - // First parse as an armored keyring file, if that doesn't work, treat it as a straight binary/b64 string - keyReader := bytes.NewReader(buf.Bytes()) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err == nil { - if len(entityList) != 1 { - return "", fmt.Errorf("more than one key found in file %q", path) - } - if entityList[0] == nil { - return "", fmt.Errorf("primary key was nil for file %q", path) - } - - serializedEntity := bytes.NewBuffer(nil) - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error serializing entity for file %q: {{err}}", path), err) - } - - return base64.StdEncoding.EncodeToString(serializedEntity.Bytes()), nil - } - - _, err = base64.StdEncoding.DecodeString(buf.String()) - if err == nil { - return buf.String(), nil - } - return base64.StdEncoding.EncodeToString(buf.Bytes()), nil - -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go deleted file mode 100644 index eba06776..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go +++ /dev/null @@ -1,117 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/keybase/go-crypto/openpgp" -) - -const ( - kbPrefix = "keybase:" -) - -// FetchKeybasePubkeys fetches public keys from Keybase given a set of -// usernames, which are derived from correctly formatted input entries. It -// doesn't use their client code due to both the API and the fact that it is -// considered alpha and probably best not to rely on it. The keys are returned -// as base64-encoded strings. -func FetchKeybasePubkeys(input []string) (map[string]string, error) { - client := cleanhttp.DefaultClient() - if client == nil { - return nil, fmt.Errorf("unable to create an http client") - } - - if len(input) == 0 { - return nil, nil - } - - usernames := make([]string, 0, len(input)) - for _, v := range input { - if strings.HasPrefix(v, kbPrefix) { - usernames = append(usernames, strings.TrimPrefix(v, kbPrefix)) - } - } - - if len(usernames) == 0 { - return nil, nil - } - - ret := make(map[string]string, len(usernames)) - url := fmt.Sprintf("https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s&fields=public_keys", strings.Join(usernames, ",")) - resp, err := client.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - type PublicKeys struct { - Primary struct { - Bundle string - } - } - - type LThem struct { - PublicKeys `json:"public_keys"` - } - - type KbResp struct { - Status struct { - Name string - } - Them []LThem - } - - out := &KbResp{ - Them: []LThem{}, - } - - if err := jsonutil.DecodeJSONFromReader(resp.Body, out); err != nil { - return nil, err - } - - if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) - } - - missingNames := make([]string, 0, len(usernames)) - var keyReader *bytes.Reader - serializedEntity := bytes.NewBuffer(nil) - for i, themVal := range out.Them { - if themVal.Primary.Bundle == "" { - missingNames = append(missingNames, usernames[i]) - continue - } - keyReader = bytes.NewReader([]byte(themVal.Primary.Bundle)) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err != nil { - return nil, err - } - if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) - } - if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) - } - - serializedEntity.Reset() - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error serializing entity for user %q: {{err}}", usernames[i]), err) - } - - // The API returns values in the same ordering requested, so this should properly match - ret[kbPrefix+usernames[i]] = base64.StdEncoding.EncodeToString(serializedEntity.Bytes()) - } - - if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go deleted file mode 100644 index c10a9055..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go +++ /dev/null @@ -1,271 +0,0 @@ -package pgpkeys - -const ( - TestPrivKey1 = `lQOYBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAEAB/wL+KX0mdeISEpX -oDgt766Key1Kthe8nbEs5dOXIsP7OR7ZPcnE2hy6gftgVFnBGEZnWVN70vmJd6Z5y9d1mI+GecXj -UL0EpI0EmohyYDJsHUnght/5ecRNFA+VeNmGPYNQGCeHJyZOiFunGGENpHU7BbubAht8delz37Mx -JQgvMyR6AKvg8HKBoQeqV1uMWNJE/vKwV/z1dh1sjK/GFxu05Qaq0GTfAjVLuFOyJTS95yq6gblD -jUdbHLp7tBeqIKo9voWCJF5mGOlq3973vVoWETy9b0YYPCE/M7fXmK9dJITHqkROLMW6TgcFeIw4 -yL5KOBCHk+QGPSvyQN7R7Fd5BADwuT1HZmvg7Y9GjarKXDjxdNemUiHtba2rUzfH6uNmKNQvwQek -nma5palNUJ4/dz1aPB21FUBXJF5yWwXEdApl+lIDU0J5m4UD26rqEVRq9Kx3GsX+yfcwObkrSzW6 -kmnQSB5KI0fIuegMTM+Jxo3pB/mIRwDTMmk+vfzIGyW+7QQA8aFwFLMdKdfLgSGbl5Z6etmOAVQ2 -Oe2ebegU9z/ewi/Rdt2s9yQiAdGVM8+q15Saz8a+kyS/l1CjNPzr3VpYx1OdZ3gb7i2xoy9GdMYR -ZpTq3TuST95kx/9DqA97JrP23G47U0vwF/cg8ixCYF8Fz5dG4DEsxgMwKqhGdW58wMMD/iytkfMk -Vk6Z958Rpy7lhlC6L3zpO38767bSeZ8gRRi/NMFVOSGYepKFarnfxcTiNa+EoSVA6hUo1N64nALE -sJBpyOoTfKIpz7WwTF1+WogkiYrfM6lHon1+3qlziAcRW0IohM3g2C1i3GWdON4Cl8/PDO3R0E52 -N6iG/ctNNeMiPe60EFZhdWx0IFRlc3QgS2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d -4hIHsG7kmJRTJfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF3 -9jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poe -o+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeUR -BRWdA5gEVduM9QEIAL53hJ5bZJ7oEDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkf -Rqnv981fFwGnh2+I1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a -9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu -9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/z -bfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOleYwxk+FoTqXEAEQEAAQAH+wVyQXaNwnjQ -xfW+M8SJNo0C7e+0d7HsuBTA/d/eP4bj6+X8RaRFVwiMvSAoxsqBNCLJP00qzzKfRQWJseD1H35z -UjM7rNVUEL2k1yppyp61S0qj0TdhVUfJDYZqRYonVgRMvzfDTB1ryKrefKenQYL/jGd9VYMnKmWZ -6GVk4WWXXx61iOt2HNcmSXKetMM1Mg67woPZkA3fJaXZ+zW0zMu4lTSB7yl3+vLGIFYILkCFnREr -drQ+pmIMwozUAt+pBq8dylnkHh6g/FtRfWmLIMDqM1NlyuHRp3dyLDFdTA93osLG0QJblfX54W34 -byX7a4HASelGi3nPjjOAsTFDkuEEANV2viaWk1CV4ryDrXGmy4Xo32Md+laGPRcVfbJ0mjZjhQsO -gWC1tjMs1qZMPhcrKIBCjjdAcAIrGV9h3CXc0uGuez4XxLO+TPBKaS0B8rKhnKph1YZuf+HrOhzS -astDnOjNIT+qucCL/qSbdYpj9of3yY61S59WphPOBjoVM3BFBADka6ZCk81gx8jA2E1e9UqQDmdM -FZaVA1E7++kqVSFRDJGnq+5GrBTwCJ+sevi+Rvf8Nx4AXvpCdtMBPX9RogsUFcR0pMrKBrgRo/Vg -EpuodY2Ef1VtqXR24OxtRf1UwvHKydIsU05rzMAy5uGgQvTzRTXxZFLGUY31wjWqmo9VPQP+PnwA -K83EV2kk2bsXwZ9MXg05iXqGQYR4bEc/12v04BtaNaDS53hBDO4JIa3Bnz+5oUoYhb8FgezUKA9I -n6RdKTTP1BLAu8titeozpNF07V++dPiSE2wrIVsaNHL1pUwW0ql50titVwe+EglWiCKPtJBcCPUA -3oepSPchiDjPqrNCYIkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZAQIABgUCVduM -9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYulEimOPzLUX/Z -XZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr -9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEc -ZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4 -EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY+XsKVYRf -NIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcIPXFv3m3WfUln -G/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O9uK3lQozbw2g -H9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKf -PRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h -7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPrivKey2 = `lQOYBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAEAB/oCBqTIsxlUgLtz -HRpWW5MJ+93xvmVV0JHhRK/ygKghq+zpC6S+cn7dwrEj1JTPh+17lyemYQK+RMeiBEduoWNKuHUd -WX353w2411rrc/VuGTglzhd8Ir2BdJlPesCzw4JQnrWqcBqN52W+iwhnE7PWVhnvItWnx6APK5Se -q7dzFWy8Z8tNIHm0pBQbeyo6x2rHHSWkr2fs7V02qFQhii1ayFRMcgdOWSNX6CaZJuYhk/DyjApN -9pVhi3P1pNMpFeV0Pt8Gl1f/9o6/HpAYYEt/6vtVRhFUGgtNi95oc0oyzIJxliRvd6+Z236osigQ -QEBwj1ImRK8TKyWPlykiJWc5BADfldgOCA55o3Qz/z/oVE1mm+a3FmPPTQlHBXotNEsrWV2wmJHe -lNQPI6ZwMtLrBSg8PUpG2Rvao6XJ4ZBl/VcDwfcLgCnALPCcL0L0Z3vH3Sc9Ta/bQWJODG7uSaI1 -iVJ7ArKNtVzTqRQWK967mol9CCqh4A0jRrH0aVEFbrqQ/QQA58iEJaFhzFZjufjC9N8Isn3Ky7xu -h+dk001RNCb1GnNZcx4Ld2IB+uXyYjtg7dNaUhGgGuCBo9nax89bMsBzzUukx3SHq1pxopMg6Dm8 -ImBoIAicuQWgEkaP2T0rlwCozUalJZaG1gyrzkPhkeY7CglpJycHLHfY2MIb46c8+58D/iJ83Q5j -Y4x+sqW2QeUYFwqCcOW8Urg64UxEkgXZXiNMwTAJCaxp/Pz7cgeUDwgv+6CXEdnT1910+byzK9ha -V1Q/65+/JYuCeyHxcoAb4Wtpdl7GALGd/1G0UAmq47yrefEr/b00uS35i1qUUhOzo1NmEZch/bvF -kmJ+WtAHunZcOCu0EFZhdWx0IFRlc3QgS2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOuDLGfrXolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHip -ZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABq -hb5ojexdnAYRswaHV201ZCclj9rnJN1PAg0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmG -kdrg8K8ARmRILjmwuBAgJM0eXBZHNGWXelk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0 -vDttB+ZXqF88W9jAYlvdgbTtajNF5IDYDjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlx -k4edA5gEVduQkQEIAOjZV5tbpfIh5QefpIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe -4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/t -GF5xE3e5CoZRsHV/c92h3t1LdJNOnC5mUKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBH -yt0tdHtIWuQv6joTJzujqViRhlCwQYzQSKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1r -ENO8JOuPu6tMS+znFu67skq2gFFZwCQWIjdHm+2ukE+PE580WAWudyMAEQEAAQAH/i7ndRPI+t0T -AdEu0dTIdyrrg3g7gd471kQtIVZZwTYSy2yhNY/Ciu72s3ab8QNCxY8dNL5bRk8FKjHslAoNSFdO -8iZSLiDgIHOZOcjYe6pqdgQaeTHodm1Otrn2SbB+K/3oX6W/y1xe18aSojGba/nHMj5PeJbIN9Pi -jmh0WMLD/0rmkTTxR7qQ5+kMV4O29xY4qjdYRD5O0adeZX0mNncmlmQ+rX9yxrtSgFROu1jwVtfP -hcNetifTTshJnTwND8hux5ECEadlIVBHypW28Hth9TRBXmddTmv7L7mdtUO6DybgkpWpw4k4LPsk -uZ6aY4wcGRp7EVfWGr9NHbq/n+0EAOlhDXIGdylkQsndjBMyhPsXZa5fFBmOyHjXj733195Jgr1v -ZjaIomrA9cvYrmN75oKrG1jJsMEl6HfC/ZPzEj6E51/p1PRdHP7CdUUA+DG8x4M3jn+e43psVuAR -a1XbN+8/bOa0ubt7ljVPjAEvWRSvU9dRaQz93w3fduAuM07dBAD/ayK3e0d6JMJMrU50lNOXQBgL -rFbg4rWzPO9BJQdhjOhmOZQiUa1Q+EV+s95yIUg1OAfaMP9KRIljr5RCdGNS6WoMNBAQOSrZpelf -jW4NpzphNfWDGVkUoPoskVtJz/nu9d860dGd3Al0kSmtUpMu5QKlo+sSxXUPbWLUn8V9/wP/ScCW -H+0gtL4R7SFazPeTIP+Cu5oR7A/DlFVLJKa3vo+atkhSvwxHGbg04vb/W4mKhGGVtMBtlhRmaWOe -PhUulU5FdaYsdlpN/Yd+hhgU6NHlyImPGVEHWD8c6CG8qoZfpR33j2sqshs4i/MtJZeBvl62vxPn -9bDN7KAjFNll9axAjIkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZAQIABgUCVduQ -kQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDDhnV3bXQsCvn/ -6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQe3l4CqJvkn6j -ybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4KBIrp/bhG6Pdn -igKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eYENtyOmEMWOFC -LLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H/1trYUtJjXQK -HmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7PkUZTfpaP/L6 -DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0UPEnjvtZTp5yO -hTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQdw/2epIewH0L/ -FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4MFOMVRn1dc3q -dXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPrivKey3 = `lQOXBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAEAB/dQbElFIa0VklZa -39ZLhtbBxACSWH3ql3EtRZaB2Mh4zSALbFyJDQfScOy8AZHmv66Ozxit9X9WsYr9OzcHujgl/2da -A3lybF6iLw1YDNaL11G6kuyn5sFP6lYGMRGOIWSik9oSVF6slo8m8ujRLdBsdMXVcElHKzCJiWmt -JZHEnUkl9X96fIPajMBfWjHHwcaeMOc77nvjwqy5wC4EY8TSVYzxeZHL7DADQ0EHBcThlmfizpCq -26LMVb6ju8STH7uDDFyKmhr/hC2vOkt+PKsvBCmW8/ESanO1zKPD9cvSsOWr2rZWNnkDRftqzOU5 -OCrI+3o9E74+toNb07bPntEEAMEStOzSvqZ6NKdh7EZYPA4mkkFC+EiHYIoinP1sd9V8O2Hq+dzx -yFHtWu0LmP6uWXk45vsP9y1UMJcEa33ew5JJa7zgucI772/BNvd/Oys/PqwIAl6uNIY8uYLgmn4L -1IPatp7vDiXzZSivPZd4yN4S4zCypZp9cnpO3qv8q7CtBADW87IA0TabdoxiN+m4XL7sYDRIfglr -MRPAlfrkAUaGDBx/t1xb6IaKk7giFdwHpTI6+g9XNkqKqogMe4Fp+nsd1xtfsNUBn6iKZavm5kXe -Lp9QgE+K6mvIreOTe2PKQqXqgPRG6+SRGatoKeY76fIpd8AxOJyWERxcq2lUHLn45QP/UXDTcYB7 -gzJtZrfpXN0GqQ0lYXMzbQfLnkUsu3mYzArfNy0otzEmKTkwmKclNY1/EJSzSdHfgmeA260a0nLK -64C0wPgSmOqw90qwi5odAYSjSFBapDbyGF86JpHrLxyEEpGoXanRPwWfbiWp19Nwg6nknA87AtaM -3+AHjbWzwCpHL7QQVmF1bHQgVGVzdCBLZXkgM4kBOAQTAQIAIgUCVduSIwIbLwYLCQgHAwIGFQgC -CQoLBBYCAwECHgECF4AACgkQ9HlLVvwtxt1aMQf/aaGoL1rRWTUjM6DEShXFhWpV29rEjSdNk5N+ -ZwVifgdCVD5IsSjI1Z7mO2SHHiTm4eKnHAofM6/TZgzXg1YLpu8rDYJARMsM8bgK/xgxSamGjm2c -wN220jOnwePIlG0drNTW5N6zb/K6qHoscJ6NUkjS5JPdGJuq7B0bdCM8/xSbG75gL34U5bYqK38B -DwmW4UMl2rf/BJfxV9hmsZ2Cat4TspgyiWEKTMZI+PugXKDDwuoqgm+320K4EqFkwG4y/WwHkKgk -hZ0+io5lzhTsvVd2p8q8VlH9GG5eA3WWQj0yqucsOmKQvcuT5y0vFY6NQJbyuioqgdlgEXtc+p0B -+Z0DmARV25IjAQgA49yN3hCBsuWoiTezoE9FHJXOCVOBR1/4jStQPJtoMl8mhtl3xTp7iGQ+9GhD -y0l5+fP+qcP/rfBq0BslhxVOZ7jQjdUoM6ZUZzJoPGIo/V2KwqpwQl3tdCIjvagCJeYQfTL7lTCc -4ySz+XBoAYMwZVGMcRcjp+JE8Wx9Ovzuq8wnelbU6I5dVJ7O4E1OWbIkLuytDX+fDEvfft6/oPXN -Bl3cm6FzEuQetQQss3DOG9xnvS+DrjmMCbPwR2a++ioQ8+geoqA/kB4cAI6xOb3ncoeGDHc1i4Y9 -T9Ggi+6Aq3girmfDtNYVOM8cZUXcZNCvLkJn8DNeIvnuFUSEO+a5PwARAQABAAf/TPd98CmRNdV/ -VUI8aYT9Kkervdi4DVzsfvrHcoFn88PSJrCkVTmI6qw526Kwa6VZD0YMmll7LszLt5nD1lorDrwN -rir3FmMzlVwge20IvXRwX4rkunYxtA2oFvL+LsEEhtXGx0ERbWRDapk+eGxQ15hxIO4Y/Cdg9E+a -CWfQUrTSnC6qMVfVYMGfnM1yNX3OWattEFfmxQas5XqQk/0FgjCZALixdanjN/r1tjp5/2MiSD8N -Wkemzsr6yPicnc3+BOZc5YOOnH8FqBvVHcDlSJI6pCOCEiO3Pq2QEk/1evONulbF116mLnQoGrpp -W77l+5O42VUpZfjROCPd5DYyMQQA492CFXZpDIJ2emB9/nK8X6IzdVRK3oof8btbSNnme5afIzhs -wR1ruX30O7ThfB+5ezpbgK1C988CWkr9SNSTy43omarafGig6/Y1RzdiITILuIGfbChoSpc70jXx -U0nzJ/1i9yZ/vDgP3EC2miRhlDcp5w0Bu0oMBlgG/1uhj0cEAP/+7aFGP0fo2MZPhyl5feHKWj4k -85XoAIpMBnzF6HTGU3ljAE56a+4sVw3bWB755DPhvpZvDkX60I9iIJxio8TK5ITdfjlLhxuskXyt -ycwWI/4J+soeq4meoxK9jxZJuDl/qvoGfyzNg1oy2OBehX8+6erW46kr6Z/MQutS3zJJBACmJHrK -VR40qD7a8KbvfuM3ruwlm5JqT/Ykq1gfKKxHjWDIUIeyBX/axGQvAGNYeuuQCzZ0+QsEWur3C4kN -U+Pb5K1WGyOKkhJzivSI56AG3d8TA/Q0JhqST6maY0fvUoahWSCcpd7MULa3n1zx5Wsvi8mkVtup -Js/IDi/kqneqM0XviQI+BBgBAgAJBQJV25IjAhsuASkJEPR5S1b8LcbdwF0gBBkBAgAGBQJV25Ij -AAoJEAUj/03Hcrkg84UIAKxn9nizYtwSgDnVNb5PnD5h6+Ui6r7ffYm2o0im4YhakbFTHIPI9PRh -BavRI5sE5Fg2vtE/x38jattoUrJoNoq9Gh9iv5PBfL3amEGjul0RRqYGl+ub+yv7YGAAHbHcdZen -4gx15VWGpB7y3hycWbdzV8h3EAPKIm5XmB7YyXmArnI3CoJA+HtTZGoL6WZWUwka9YichGfaZ/oD -umENg1l87Pp2RqvjLKHmv2tGCtnDzyv/IiWur9zopFQiCc8ysVgRq6CA5x5nzbv6MqRspYUS4e2I -LFbuREA3blR+caw9oX41IYzarW8IbgeIXJ3HqUyhczRKF/z5nDKtX/kHMCqlbAgAnfu0TALnwVuj -KeXLo4Y7OA9LTEqfORcw62q5OjSoQf/VsRSwGSefv3kGZk5N/igELluU3qpG/twZI/TSL6zGqXU2 -FOMlyMm1849TOB9b4B//4dHrjzPhztzowKMMUqeTxmSgYtFTshKN6eQ0XO+7ZuOXEmSKXS4kOUs9 -ttfzSiPNXUZL2D5nFU9H7rw3VAuXYVTrOx+Dfi6mYsscbxUbi8THODI2Q7B9Ni92DJE1OOe4+57o -fXZ9ln24I14bna/uVHd6hBwLEE6eLCCKkHxQnnZFZduXDHMK0a0OL8RYHfMtNSem4pyC5wDQui1u -KFIzGEPKVoBF9U7VBXpyxpsz+A==` - - TestPubKey1 = `mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOfLr44B -HbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRTJfjECi+AuTGeDwBy84TD -cRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3CEe8cMwIPqPT2kajJVdOyrvkyuFOdPFOE -A7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlB -C0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXa -QKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7oEDCn -aY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I1Ktm698UAZS9Jt8y -jak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb -6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5N -ZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu -9p315E87DOleYwxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYu -lEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHN -C1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0 -YwKoz3h9+QEcZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJi -oPn2jVMnXCm4EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH -/AtY+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcI -PXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O -9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx -8iDV+dNtDVKfPRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKd -OIu60YPNE4+h7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPubKey2 = `mQENBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOuDLGfr -XolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHipZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO -2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABqhb5ojexdnAYRswaHV201ZCclj9rnJN1P -Ag0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmGkdrg8K8ARmRILjmwuBAgJM0eXBZHNGWX -elk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0vDttB+ZXqF88W9jAYlvdgbTtajNF5IDY -DjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlxk4e5AQ0EVduQkQEIAOjZV5tbpfIh5Qef -pIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg -+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/tGF5xE3e5CoZRsHV/c92h3t1LdJNOnC5m -UKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBHyt0tdHtIWuQv6joTJzujqViRhlCwQYzQ -SKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1rENO8JOuPu6tMS+znFu67skq2gFFZwCQW -IjdHm+2ukE+PE580WAWudyMAEQEAAYkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZ -AQIABgUCVduQkQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDD -hnV3bXQsCvn/6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQ -e3l4CqJvkn6jybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4K -BIrp/bhG6PdnigKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eY -ENtyOmEMWOFCLLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H -/1trYUtJjXQKHmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7 -PkUZTfpaP/L6DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0U -PEnjvtZTp5yOhTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQd -w/2epIewH0L/FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4 -MFOMVRn1dc3qdXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPubKey3 = `mQENBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDOJATgEEwECACIFAlXbkiMCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEPR5S1b8 -LcbdWjEH/2mhqC9a0Vk1IzOgxEoVxYVqVdvaxI0nTZOTfmcFYn4HQlQ+SLEoyNWe5jtkhx4k5uHi -pxwKHzOv02YM14NWC6bvKw2CQETLDPG4Cv8YMUmpho5tnMDdttIzp8HjyJRtHazU1uTes2/yuqh6 -LHCejVJI0uST3RibquwdG3QjPP8Umxu+YC9+FOW2Kit/AQ8JluFDJdq3/wSX8VfYZrGdgmreE7KY -MolhCkzGSPj7oFygw8LqKoJvt9tCuBKhZMBuMv1sB5CoJIWdPoqOZc4U7L1XdqfKvFZR/RhuXgN1 -lkI9MqrnLDpikL3Lk+ctLxWOjUCW8roqKoHZYBF7XPqdAfm5AQ0EVduSIwEIAOPcjd4QgbLlqIk3 -s6BPRRyVzglTgUdf+I0rUDybaDJfJobZd8U6e4hkPvRoQ8tJefnz/qnD/63watAbJYcVTme40I3V -KDOmVGcyaDxiKP1disKqcEJd7XQiI72oAiXmEH0y+5UwnOMks/lwaAGDMGVRjHEXI6fiRPFsfTr8 -7qvMJ3pW1OiOXVSezuBNTlmyJC7srQ1/nwxL337ev6D1zQZd3JuhcxLkHrUELLNwzhvcZ70vg645 -jAmz8EdmvvoqEPPoHqKgP5AeHACOsTm953KHhgx3NYuGPU/RoIvugKt4Iq5nw7TWFTjPHGVF3GTQ -ry5CZ/AzXiL57hVEhDvmuT8AEQEAAYkCPgQYAQIACQUCVduSIwIbLgEpCRD0eUtW/C3G3cBdIAQZ -AQIABgUCVduSIwAKCRAFI/9Nx3K5IPOFCACsZ/Z4s2LcEoA51TW+T5w+YevlIuq+332JtqNIpuGI -WpGxUxyDyPT0YQWr0SObBORYNr7RP8d/I2rbaFKyaDaKvRofYr+TwXy92phBo7pdEUamBpfrm/sr -+2BgAB2x3HWXp+IMdeVVhqQe8t4cnFm3c1fIdxADyiJuV5ge2Ml5gK5yNwqCQPh7U2RqC+lmVlMJ -GvWInIRn2mf6A7phDYNZfOz6dkar4yyh5r9rRgrZw88r/yIlrq/c6KRUIgnPMrFYEauggOceZ827 -+jKkbKWFEuHtiCxW7kRAN25UfnGsPaF+NSGM2q1vCG4HiFydx6lMoXM0Shf8+ZwyrV/5BzAqpWwI -AJ37tEwC58Fboynly6OGOzgPS0xKnzkXMOtquTo0qEH/1bEUsBknn795BmZOTf4oBC5blN6qRv7c -GSP00i+sxql1NhTjJcjJtfOPUzgfW+Af/+HR648z4c7c6MCjDFKnk8ZkoGLRU7ISjenkNFzvu2bj -lxJkil0uJDlLPbbX80ojzV1GS9g+ZxVPR+68N1QLl2FU6zsfg34upmLLHG8VG4vExzgyNkOwfTYv -dgyRNTjnuPue6H12fZZ9uCNeG52v7lR3eoQcCxBOniwgipB8UJ52RWXblwxzCtGtDi/EWB3zLTUn -puKcgucA0LotbihSMxhDylaARfVO1QV6csabM/g=` - - TestAAPubKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzz -wiMwBS5cD0darGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7 -H+/mhfFvKmgr0Y5kDCF1j0T/063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX -1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0fsF5St9jhO7mbZU9EFkv9O3t3EaUR -fHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg8hQssKeVGpuskTdz -5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3QgS2V5 -IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ -EOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRT -JfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1Z -mumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4z -J2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+ -7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7o -EDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I -1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okj -h5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTj -OleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2o -P/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOle -Ywxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVh -EGipBmpDGRYulEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHk -GRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRd -tPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEcZHvsjSZjgydKvfLY -cm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4EKc7 -fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY -+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7 -moViAAcIPXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWko -jHqyob3cyLgy6z9Q557O9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJ -iEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKfPRENiLOOc19MmS+phmUy -rbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h7u2CfYyF -Pu3AlUaGNMBlvy6PEpU= -=NUTS ------END PGP PUBLIC KEY BLOCK-----` -) diff --git a/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go deleted file mode 100644 index ed40c7fb..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go +++ /dev/null @@ -1,61 +0,0 @@ -package pluginutil - -import ( - "os" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/vault/helper/mlock" -) - -var ( - // 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" -) - -// 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/helper/pluginutil/runner.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go deleted file mode 100644 index 2323684d..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go +++ /dev/null @@ -1,193 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/sha256" - "crypto/tls" - "flag" - "fmt" - "os/exec" - "time" - - log "github.com/hashicorp/go-hclog" - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/version" -) - -// Looker defines the plugin Lookup function that looks into the plugin catalog -// for available plugins and returns a PluginRunner -type Looker interface { - LookupPlugin(context.Context, string, consts.PluginType) (*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 { - ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) - MlockEnabled() bool -} - -// LookRunnerUtil defines the functions for both Looker and Wrapper -type LookRunnerUtil interface { - Looker - RunnerUtil -} - -// 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"` - 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.runCommon(ctx, wrapper, pluginSets, hs, env, logger, 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 pluginutil.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.runCommon(ctx, wrapper, pluginSets, hs, env, logger, true) - -} - -func (r *PluginRunner) runCommon(ctx context.Context, wrapper RunnerUtil, pluginSets map[int]plugin.PluginSet, hs plugin.HandshakeConfig, env []string, logger log.Logger, isMetadataMode bool) (*plugin.Client, error) { - cmd := exec.Command(r.Command, r.Args...) - - // `env` should always go last to avoid overwriting internal values that might - // have been provided externally. - cmd.Env = append(cmd.Env, r.Env...) - cmd.Env = append(cmd.Env, env...) - - // Add the mlock setting to the ENV of the plugin - if wrapper != nil && wrapper.MlockEnabled() { - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMlockEnabled, "true")) - } - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginVaultVersionEnv, version.GetVersion().Version)) - - var clientTLSConfig *tls.Config - if !isMetadataMode { - // Add the metadata mode ENV and set it to false - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMetadataModeEnv, "false")) - - // 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, 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)) - } else { - logger = logger.With("metadata", "true") - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMetadataModeEnv, "true")) - } - - secureConfig := &plugin.SecureConfig{ - Checksum: r.Sha256, - Hash: sha256.New(), - } - - clientConfig := &plugin.ClientConfig{ - HandshakeConfig: hs, - VersionedPlugins: pluginSets, - Cmd: cmd, - SecureConfig: secureConfig, - TLSConfig: clientTLSConfig, - Logger: logger, - AllowedProtocols: []plugin.Protocol{ - plugin.ProtocolNetRPC, - plugin.ProtocolGRPC, - }, - } - - client := plugin.NewClient(clientConfig) - - return client, nil -} - -// APIClientMeta is a helper that plugins can use to configure TLS connections -// back to Vault. -type APIClientMeta struct { - // These are set by the command line flags. - flagCACert string - flagCAPath string - flagClientCert string - flagClientKey string - flagInsecure bool -} - -// FlagSet returns the flag set for configuring the TLS connection -func (f *APIClientMeta) FlagSet() *flag.FlagSet { - fs := flag.NewFlagSet("vault plugin settings", flag.ContinueOnError) - - fs.StringVar(&f.flagCACert, "ca-cert", "", "") - fs.StringVar(&f.flagCAPath, "ca-path", "", "") - fs.StringVar(&f.flagClientCert, "client-cert", "", "") - fs.StringVar(&f.flagClientKey, "client-key", "", "") - fs.BoolVar(&f.flagInsecure, "tls-skip-verify", false, "") - - return fs -} - -// GetTLSConfig will return a TLSConfig based off the values from the flags -func (f *APIClientMeta) GetTLSConfig() *api.TLSConfig { - // If we need custom TLS configuration, then set it - if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure { - t := &api.TLSConfig{ - CACert: f.flagCACert, - CAPath: f.flagCAPath, - ClientCert: f.flagClientCert, - ClientKey: f.flagClientKey, - TLSServerName: "", - Insecure: f.flagInsecure, - } - - return t - } - - return nil -} - -// 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/helper/pluginutil/tls.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go deleted file mode 100644 index d43f7780..00000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go +++ /dev/null @@ -1,241 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "errors" - "net/url" - "os" - "time" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/certutil" -) - -var ( - // 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" -) - -// 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, - } - - tlsConfig.BuildNameToCertificate() - - 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 -} - -// VaultPluginTLSProvider is run inside a plugin and retrieves the response -// wrapped TLS certificate from vault. It returns a configured TLS Config. -func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, error) { - if os.Getenv(PluginMetadataModeEnv) == "true" { - return nil - } - - return func() (*tls.Config, error) { - unwrapToken := os.Getenv(PluginUnwrapTokenEnv) - - // Parse the JWT and retrieve the vault address - wt, err := jws.ParseJWT([]byte(unwrapToken)) - if err != nil { - return nil, errwrap.Wrapf("error decoding token: {{err}}", err) - } - if wt == nil { - return nil, errors.New("nil decoded token") - } - - addrRaw := wt.Claims().Get("addr") - if addrRaw == nil { - return nil, errors.New("decoded token does not contain the active node's api_addr") - } - vaultAddr, ok := addrRaw.(string) - if !ok { - return nil, errors.New("decoded token's api_addr not valid") - } - if vaultAddr == "" { - return nil, errors.New(`no vault api_addr found`) - } - - // Sanity check the value - if _, err := url.Parse(vaultAddr); err != nil { - return nil, errwrap.Wrapf("error parsing the vault api_addr: {{err}}", err) - } - - // Unwrap the token - clientConf := api.DefaultConfig() - clientConf.Address = vaultAddr - if apiTLSConfig != nil { - err := clientConf.ConfigureTLS(apiTLSConfig) - if err != nil { - return nil, errwrap.Wrapf("error configuring api client {{err}}", err) - } - } - client, err := api.NewClient(clientConf) - if err != nil { - return nil, errwrap.Wrapf("error during api client creation: {{err}}", err) - } - - secret, err := client.Logical().Unwrap(unwrapToken) - if err != nil { - return nil, errwrap.Wrapf("error during token unwrap request: {{err}}", err) - } - if secret == nil { - return nil, errors.New("error during token unwrap request: secret is nil") - } - - // Retrieve and parse the server's certificate - serverCertBytesRaw, ok := secret.Data["ServerCert"].(string) - if !ok { - return nil, errors.New("error unmarshalling certificate") - } - - serverCertBytes, err := base64.StdEncoding.DecodeString(serverCertBytesRaw) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - serverCert, err := x509.ParseCertificate(serverCertBytes) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - // Retrieve and parse the server's private key - serverKeyB64, ok := secret.Data["ServerKey"].(string) - if !ok { - return nil, errors.New("error unmarshalling certificate") - } - - serverKeyRaw, err := base64.StdEncoding.DecodeString(serverKeyB64) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - serverKey, err := x509.ParseECPrivateKey(serverKeyRaw) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - // Add CA cert to the cert pool - caCertPool := x509.NewCertPool() - caCertPool.AddCert(serverCert) - - // Build a certificate object out of the server's cert and private key. - cert := tls.Certificate{ - Certificate: [][]byte{serverCertBytes}, - PrivateKey: serverKey, - Leaf: serverCert, - } - - // Setup TLS config - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - RootCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - // TLS 1.2 minimum - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{cert}, - ServerName: serverCert.Subject.CommonName, - } - tlsConfig.BuildNameToCertificate() - - return tlsConfig, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go b/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go deleted file mode 100644 index 3d4340ee..00000000 --- a/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go +++ /dev/null @@ -1,131 +0,0 @@ -package policyutil - -import ( - "sort" - "strings" - - "github.com/hashicorp/vault/helper/strutil" -) - -const ( - AddDefaultPolicy = true - DoNotAddDefaultPolicy = false -) - -// ParsePolicies parses a comma-delimited list of policies. -// The resulting collection will have no duplicate elements. -// If 'root' policy was present in the list of policies, then -// all other policies will be ignored, the result will contain -// just the 'root'. In cases where 'root' is not present, if -// 'default' policy is not already present, it will be added. -func ParsePolicies(policiesRaw interface{}) []string { - if policiesRaw == nil { - return []string{"default"} - } - - var policies []string - switch policiesRaw.(type) { - case string: - if policiesRaw.(string) == "" { - return []string{} - } - policies = strings.Split(policiesRaw.(string), ",") - case []string: - policies = policiesRaw.([]string) - } - - return SanitizePolicies(policies, false) -} - -// SanitizePolicies performs the common input validation tasks -// which are performed on the list of policies across Vault. -// The resulting collection will have no duplicate elements. -// If 'root' policy was present in the list of policies, then -// all other policies will be ignored, the result will contain -// just the 'root'. In cases where 'root' is not present, if -// 'default' policy is not already present, it will be added -// if addDefault is set to true. -func SanitizePolicies(policies []string, addDefault bool) []string { - defaultFound := false - for i, p := range policies { - policies[i] = strings.ToLower(strings.TrimSpace(p)) - // Eliminate unnamed policies. - if policies[i] == "" { - continue - } - - // If 'root' policy is present, ignore all other policies. - if policies[i] == "root" { - policies = []string{"root"} - defaultFound = true - break - } - if policies[i] == "default" { - defaultFound = true - } - } - - // Always add 'default' except only if the policies contain 'root'. - if addDefault && (len(policies) == 0 || !defaultFound) { - policies = append(policies, "default") - } - - return strutil.RemoveDuplicates(policies, true) -} - -// EquivalentPolicies checks whether the given policy sets are equivalent, as in, -// they contain the same values. The benefit of this method is that it leaves -// the "default" policy out of its comparisons as it may be added later by core -// after a set of policies has been saved by a backend. -func EquivalentPolicies(a, b []string) bool { - switch { - case a == nil && b == nil: - return true - case a == nil && len(b) == 1 && b[0] == "default": - return true - case b == nil && len(a) == 1 && a[0] == "default": - return true - case a == nil || b == nil: - return false - } - - // First we'll build maps to ensure unique values and filter default - mapA := map[string]bool{} - mapB := map[string]bool{} - for _, keyA := range a { - if keyA == "default" { - continue - } - mapA[keyA] = true - } - for _, keyB := range b { - if keyB == "default" { - continue - } - mapB[keyB] = true - } - - // Now we'll build our checking slices - var sortedA, sortedB []string - for keyA, _ := range mapA { - sortedA = append(sortedA, keyA) - } - for keyB, _ := range mapB { - sortedB = append(sortedB, keyB) - } - sort.Strings(sortedA) - sort.Strings(sortedB) - - // Finally, compare - if len(sortedA) != len(sortedB) { - return false - } - - for i := range sortedA { - if sortedA[i] != sortedB[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/hashicorp/vault/helper/reload/reload.go b/vendor/github.com/hashicorp/vault/helper/reload/reload.go deleted file mode 100644 index 44526c08..00000000 --- a/vendor/github.com/hashicorp/vault/helper/reload/reload.go +++ /dev/null @@ -1,85 +0,0 @@ -package reload - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "sync" - - "github.com/hashicorp/errwrap" -) - -// ReloadFunc are functions that are called when a reload is requested -type ReloadFunc func(map[string]interface{}) error - -// CertificateGetter satisfies ReloadFunc and its GetCertificate method -// satisfies the tls.GetCertificate function signature. Currently it does not -// allow changing paths after the fact. -type CertificateGetter struct { - sync.RWMutex - - cert *tls.Certificate - - certFile string - keyFile string - passphrase string -} - -func NewCertificateGetter(certFile, keyFile, passphrase string) *CertificateGetter { - return &CertificateGetter{ - certFile: certFile, - keyFile: keyFile, - passphrase: passphrase, - } -} - -func (cg *CertificateGetter) Reload(_ map[string]interface{}) error { - certPEMBlock, err := ioutil.ReadFile(cg.certFile) - if err != nil { - return err - } - keyPEMBlock, err := ioutil.ReadFile(cg.keyFile) - if err != nil { - return err - } - - // Check for encrypted pem block - keyBlock, _ := pem.Decode(keyPEMBlock) - if keyBlock == nil { - return errors.New("decoded PEM is blank") - } - - if x509.IsEncryptedPEMBlock(keyBlock) { - keyBlock.Bytes, err = x509.DecryptPEMBlock(keyBlock, []byte(cg.passphrase)) - if err != nil { - return errwrap.Wrapf("Decrypting PEM block failed {{err}}", err) - } - keyPEMBlock = pem.EncodeToMemory(keyBlock) - } - - cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) - if err != nil { - return err - } - - cg.Lock() - defer cg.Unlock() - - cg.cert = &cert - - return nil -} - -func (cg *CertificateGetter) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { - cg.RLock() - defer cg.RUnlock() - - if cg.cert == nil { - return nil, fmt.Errorf("nil certificate") - } - - return cg.cert, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/salt/salt.go b/vendor/github.com/hashicorp/vault/helper/salt/salt.go deleted file mode 100644 index 4fd56205..00000000 --- a/vendor/github.com/hashicorp/vault/helper/salt/salt.go +++ /dev/null @@ -1,178 +0,0 @@ -package salt - -import ( - "context" - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "encoding/hex" - "fmt" - "hash" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" -) - -const ( - // DefaultLocation is the path in the view we store our key salt - // if no other path is provided. - DefaultLocation = "salt" -) - -// Salt is used to manage a persistent salt key which is used to -// hash values. This allows keys to be generated and recovered -// using the global salt. Primarily, this allows paths in the storage -// backend to be obfuscated if they may contain sensitive information. -type Salt struct { - config *Config - salt string - generated bool -} - -type HashFunc func([]byte) []byte - -// Config is used to parameterize the Salt -type Config struct { - // Location is the path in the storage backend for the - // salt. Uses DefaultLocation if not specified. - Location string - - // HashFunc is the hashing function to use for salting. - // Defaults to SHA1 if not provided. - HashFunc HashFunc - - // HMAC allows specification of a hash function to use for - // the HMAC helpers - HMAC func() hash.Hash - - // String prepended to HMAC strings for identification. - // Required if using HMAC - HMACType string -} - -// NewSalt creates a new salt based on the configuration -func NewSalt(ctx context.Context, view logical.Storage, config *Config) (*Salt, error) { - // Setup the configuration - if config == nil { - config = &Config{} - } - if config.Location == "" { - config.Location = DefaultLocation - } - if config.HashFunc == nil { - config.HashFunc = SHA256Hash - } - if config.HMAC == nil { - config.HMAC = sha256.New - config.HMACType = "hmac-sha256" - } - - // Create the salt - s := &Salt{ - config: config, - } - - // Look for the salt - var raw *logical.StorageEntry - var err error - if view != nil { - raw, err = view.Get(ctx, config.Location) - if err != nil { - return nil, errwrap.Wrapf("failed to read salt: {{err}}", err) - } - } - - // Restore the salt if it exists - if raw != nil { - s.salt = string(raw.Value) - } - - // Generate a new salt if necessary - if s.salt == "" { - s.salt, err = uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to generate uuid: {{err}}", err) - } - s.generated = true - if view != nil { - raw := &logical.StorageEntry{ - Key: config.Location, - Value: []byte(s.salt), - } - if err := view.Put(ctx, raw); err != nil { - return nil, errwrap.Wrapf("failed to persist salt: {{err}}", err) - } - } - } - - if config.HMAC != nil { - if len(config.HMACType) == 0 { - return nil, fmt.Errorf("HMACType must be defined") - } - } - - return s, nil -} - -// SaltID is used to apply a salt and hash function to an ID to make sure -// it is not reversible -func (s *Salt) SaltID(id string) string { - return SaltID(s.salt, id, s.config.HashFunc) -} - -// GetHMAC is used to apply a salt and hash function to data to make sure it is -// not reversible, with an additional HMAC -func (s *Salt) GetHMAC(data string) string { - hm := hmac.New(s.config.HMAC, []byte(s.salt)) - hm.Write([]byte(data)) - return hex.EncodeToString(hm.Sum(nil)) -} - -// GetIdentifiedHMAC is used to apply a salt and hash function to data to make -// sure it is not reversible, with an additional HMAC, and ID prepended -func (s *Salt) GetIdentifiedHMAC(data string) string { - return s.config.HMACType + ":" + s.GetHMAC(data) -} - -// DidGenerate returns if the underlying salt value was generated -// on initialization or if an existing salt value was loaded -func (s *Salt) DidGenerate() bool { - return s.generated -} - -// SaltIDHashFunc uses the supplied hash function instead of the configured -// hash func in the salt. -func (s *Salt) SaltIDHashFunc(id string, hashFunc HashFunc) string { - return SaltID(s.salt, id, hashFunc) -} - -// SaltID is used to apply a salt and hash function to an ID to make sure -// it is not reversible -func SaltID(salt, id string, hash HashFunc) string { - comb := salt + id - hashVal := hash([]byte(comb)) - return hex.EncodeToString(hashVal) -} - -func HMACValue(salt, val string, hashFunc func() hash.Hash) string { - hm := hmac.New(hashFunc, []byte(salt)) - hm.Write([]byte(val)) - return hex.EncodeToString(hm.Sum(nil)) -} - -func HMACIdentifiedValue(salt, val, hmacType string, hashFunc func() hash.Hash) string { - return hmacType + ":" + HMACValue(salt, val, hashFunc) -} - -// SHA1Hash returns the SHA1 of the input -func SHA1Hash(inp []byte) []byte { - hashed := sha1.Sum(inp) - return hashed[:] -} - -// SHA256Hash returns the SHA256 of the input -func SHA256Hash(inp []byte) []byte { - hashed := sha256.Sum256(inp) - return hashed[:] -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go b/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go deleted file mode 100644 index 3518ed8f..00000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go +++ /dev/null @@ -1,355 +0,0 @@ -package storagepacker - -import ( - "context" - "crypto/md5" - "encoding/hex" - "fmt" - "strconv" - "strings" - - "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" -) - -const ( - bucketCount = 256 - StoragePackerBucketsPrefix = "packer/buckets/" -) - -// StoragePacker packs the objects into a specific number of buckets by hashing -// its ID and indexing it. Currently this supports only 256 bucket entries and -// hence relies on the first byte of the hash value for indexing. The items -// that gets inserted into the packer should implement StorageBucketItem -// interface. -type StoragePacker struct { - view logical.Storage - logger log.Logger - storageLocks []*locksutil.LockEntry - viewPrefix string -} - -// BucketPath returns the storage entry key for a given bucket key -func (s *StoragePacker) BucketPath(bucketKey string) string { - return s.viewPrefix + bucketKey -} - -// BucketKeyHash returns the MD5 hash of the bucket storage key in which -// the item will be stored. The choice of MD5 is only for hash performance -// reasons since its value is not used for any security sensitive operation. -func (s *StoragePacker) BucketKeyHashByItemID(itemID string) string { - return s.BucketKeyHashByKey(s.BucketPath(s.BucketKey(itemID))) -} - -// BucketKeyHashByKey returns the MD5 hash of the bucket storage key -func (s *StoragePacker) BucketKeyHashByKey(bucketKey string) string { - hf := md5.New() - hf.Write([]byte(bucketKey)) - return hex.EncodeToString(hf.Sum(nil)) -} - -// View returns the storage view configured to be used by the packer -func (s *StoragePacker) View() logical.Storage { - return s.view -} - -// Get returns a bucket for a given key -func (s *StoragePacker) GetBucket(key string) (*Bucket, error) { - if key == "" { - return nil, fmt.Errorf("missing bucket key") - } - - lock := locksutil.LockForKey(s.storageLocks, key) - lock.RLock() - defer lock.RUnlock() - - // Read from the underlying view - storageEntry, err := s.view.Get(context.Background(), key) - if err != nil { - return nil, errwrap.Wrapf("failed to read packed storage entry: {{err}}", err) - } - if storageEntry == nil { - return nil, nil - } - - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return nil, errwrap.Wrapf("failed to decompress packed storage entry: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - var bucket Bucket - err = proto.Unmarshal(uncompressedData, &bucket) - if err != nil { - return nil, errwrap.Wrapf("failed to decode packed storage entry: {{err}}", err) - } - - return &bucket, nil -} - -// upsert either inserts a new item into the bucket or updates an existing one -// if an item with a matching key is already present. -func (s *Bucket) upsert(item *Item) error { - if s == nil { - return fmt.Errorf("nil storage bucket") - } - - if item == nil { - return fmt.Errorf("nil item") - } - - if item.ID == "" { - return fmt.Errorf("missing item ID") - } - - // Look for an item with matching key and don't modify the collection - // while iterating - foundIdx := -1 - for itemIdx, bucketItems := range s.Items { - if bucketItems.ID == item.ID { - foundIdx = itemIdx - break - } - } - - // If there is no match, append the item, otherwise update it - if foundIdx == -1 { - s.Items = append(s.Items, item) - } else { - s.Items[foundIdx] = item - } - - return nil -} - -// BucketIndex returns the bucket key index for a given storage key -func (s *StoragePacker) BucketIndex(key string) uint8 { - hf := md5.New() - hf.Write([]byte(key)) - return uint8(hf.Sum(nil)[0]) -} - -// BucketKey returns the bucket key for a given item ID -func (s *StoragePacker) BucketKey(itemID string) string { - return strconv.Itoa(int(s.BucketIndex(itemID))) -} - -// DeleteItem removes the storage entry which the given key refers to from its -// corresponding bucket. -func (s *StoragePacker) DeleteItem(itemID string) error { - - if itemID == "" { - return fmt.Errorf("empty item ID") - } - - // Get the bucket key - bucketKey := s.BucketKey(itemID) - - // Prepend the view prefix - bucketPath := s.BucketPath(bucketKey) - - // Read from underlying view - storageEntry, err := s.view.Get(context.Background(), bucketPath) - if err != nil { - return errwrap.Wrapf("failed to read packed storage value: {{err}}", err) - } - if storageEntry == nil { - return nil - } - - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return errwrap.Wrapf("failed to decompress packed storage value: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - var bucket Bucket - err = proto.Unmarshal(uncompressedData, &bucket) - if err != nil { - return errwrap.Wrapf("failed decoding packed storage entry: {{err}}", err) - } - - // Look for a matching storage entry - foundIdx := -1 - for itemIdx, item := range bucket.Items { - if item.ID == itemID { - foundIdx = itemIdx - break - } - } - - // If there is a match, remove it from the collection and persist the - // resulting collection - if foundIdx != -1 { - bucket.Items = append(bucket.Items[:foundIdx], bucket.Items[foundIdx+1:]...) - - // Persist bucket entry only if there is an update - err = s.PutBucket(&bucket) - if err != nil { - return err - } - } - - return nil -} - -// Put stores a packed bucket entry -func (s *StoragePacker) PutBucket(bucket *Bucket) error { - if bucket == nil { - return fmt.Errorf("nil bucket entry") - } - - if bucket.Key == "" { - return fmt.Errorf("missing key") - } - - if !strings.HasPrefix(bucket.Key, s.viewPrefix) { - return fmt.Errorf("incorrect prefix; bucket entry key should have %q prefix", s.viewPrefix) - } - - marshaledBucket, err := proto.Marshal(bucket) - if err != nil { - return errwrap.Wrapf("failed to marshal bucket: {{err}}", err) - } - - compressedBucket, err := compressutil.Compress(marshaledBucket, &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeSnappy, - }) - if err != nil { - return errwrap.Wrapf("failed to compress packed bucket: {{err}}", err) - } - - // Store the compressed value - err = s.view.Put(context.Background(), &logical.StorageEntry{ - Key: bucket.Key, - Value: compressedBucket, - }) - if err != nil { - return errwrap.Wrapf("failed to persist packed storage entry: {{err}}", err) - } - - return nil -} - -// GetItem fetches the storage entry for a given key from its corresponding -// bucket. -func (s *StoragePacker) GetItem(itemID string) (*Item, error) { - if itemID == "" { - return nil, fmt.Errorf("empty item ID") - } - - bucketKey := s.BucketKey(itemID) - bucketPath := s.BucketPath(bucketKey) - - // Fetch the bucket entry - bucket, err := s.GetBucket(bucketPath) - if err != nil { - return nil, errwrap.Wrapf("failed to read packed storage item: {{err}}", err) - } - if bucket == nil { - return nil, nil - } - - // Look for a matching storage entry in the bucket items - for _, item := range bucket.Items { - if item.ID == itemID { - return item, nil - } - } - - return nil, nil -} - -// PutItem stores a storage entry in its corresponding bucket -func (s *StoragePacker) PutItem(item *Item) error { - if item == nil { - return fmt.Errorf("nil item") - } - - if item.ID == "" { - return fmt.Errorf("missing ID in item") - } - - var err error - bucketKey := s.BucketKey(item.ID) - bucketPath := s.BucketPath(bucketKey) - - bucket := &Bucket{ - Key: bucketPath, - } - - // In this case, we persist the storage entry regardless of the read - // storageEntry below is nil or not. Hence, directly acquire write lock - // even to read the entry. - lock := locksutil.LockForKey(s.storageLocks, bucketPath) - lock.Lock() - defer lock.Unlock() - - // Check if there is an existing bucket for a given key - storageEntry, err := s.view.Get(context.Background(), bucketPath) - if err != nil { - return errwrap.Wrapf("failed to read packed storage bucket entry: {{err}}", err) - } - - if storageEntry == nil { - // If the bucket entry does not exist, this will be the only item the - // bucket that is going to be persisted. - bucket.Items = []*Item{ - item, - } - } else { - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return errwrap.Wrapf("failed to decompress packed storage entry: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - err = proto.Unmarshal(uncompressedData, bucket) - if err != nil { - return errwrap.Wrapf("failed to decode packed storage entry: {{err}}", err) - } - - err = bucket.upsert(item) - if err != nil { - return errwrap.Wrapf("failed to update entry in packed storage entry: {{err}}", err) - } - } - - // Persist the result - return s.PutBucket(bucket) -} - -// NewStoragePacker creates a new storage packer for a given view -func NewStoragePacker(view logical.Storage, logger log.Logger, viewPrefix string) (*StoragePacker, error) { - if view == nil { - return nil, fmt.Errorf("nil view") - } - - if viewPrefix == "" { - viewPrefix = StoragePackerBucketsPrefix - } - - if !strings.HasSuffix(viewPrefix, "/") { - viewPrefix = viewPrefix + "/" - } - - // Create a new packer object for the given view - packer := &StoragePacker{ - view: view, - viewPrefix: viewPrefix, - logger: logger, - storageLocks: locksutil.CreateLocks(), - } - - return packer, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go b/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go deleted file mode 100644 index 6319feef..00000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/storagepacker/types.proto - -package storagepacker - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - any "github.com/golang/protobuf/ptypes/any" - math "math" -) - -// 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 Item struct { - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Message *any.Any `sentinel:"" protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Item) Reset() { *m = Item{} } -func (m *Item) String() string { return proto.CompactTextString(m) } -func (*Item) ProtoMessage() {} -func (*Item) Descriptor() ([]byte, []int) { - return fileDescriptor_c0e98c66c4f51b7f, []int{0} -} - -func (m *Item) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Item.Unmarshal(m, b) -} -func (m *Item) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Item.Marshal(b, m, deterministic) -} -func (m *Item) XXX_Merge(src proto.Message) { - xxx_messageInfo_Item.Merge(m, src) -} -func (m *Item) XXX_Size() int { - return xxx_messageInfo_Item.Size(m) -} -func (m *Item) XXX_DiscardUnknown() { - xxx_messageInfo_Item.DiscardUnknown(m) -} - -var xxx_messageInfo_Item proto.InternalMessageInfo - -func (m *Item) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Item) GetMessage() *any.Any { - if m != nil { - return m.Message - } - return nil -} - -type Bucket struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Items []*Item `sentinel:"" protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Bucket) Reset() { *m = Bucket{} } -func (m *Bucket) String() string { return proto.CompactTextString(m) } -func (*Bucket) ProtoMessage() {} -func (*Bucket) Descriptor() ([]byte, []int) { - return fileDescriptor_c0e98c66c4f51b7f, []int{1} -} - -func (m *Bucket) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Bucket.Unmarshal(m, b) -} -func (m *Bucket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Bucket.Marshal(b, m, deterministic) -} -func (m *Bucket) XXX_Merge(src proto.Message) { - xxx_messageInfo_Bucket.Merge(m, src) -} -func (m *Bucket) XXX_Size() int { - return xxx_messageInfo_Bucket.Size(m) -} -func (m *Bucket) XXX_DiscardUnknown() { - xxx_messageInfo_Bucket.DiscardUnknown(m) -} - -var xxx_messageInfo_Bucket proto.InternalMessageInfo - -func (m *Bucket) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *Bucket) GetItems() []*Item { - if m != nil { - return m.Items - } - return nil -} - -func init() { - proto.RegisterType((*Item)(nil), "storagepacker.Item") - proto.RegisterType((*Bucket)(nil), "storagepacker.Bucket") -} - -func init() { proto.RegisterFile("helper/storagepacker/types.proto", fileDescriptor_c0e98c66c4f51b7f) } - -var fileDescriptor_c0e98c66c4f51b7f = []byte{ - // 219 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x8f, 0x41, 0x4b, 0xc3, 0x40, - 0x10, 0x85, 0x49, 0xaa, 0x15, 0xb7, 0x28, 0xb2, 0x7a, 0x88, 0x9e, 0x42, 0x4f, 0xf1, 0x32, 0x83, - 0xf5, 0x17, 0x58, 0x50, 0xf0, 0x9a, 0xa3, 0xb7, 0x4d, 0x3a, 0x6e, 0x96, 0x64, 0xbb, 0xcb, 0xee, - 0xac, 0xb0, 0xff, 0x5e, 0xda, 0xd8, 0x43, 0xc1, 0xdb, 0xc0, 0xfb, 0xf8, 0xe6, 0x3d, 0x51, 0x0f, - 0x34, 0x79, 0x0a, 0x18, 0xd9, 0x05, 0xa5, 0xc9, 0xab, 0x7e, 0xa4, 0x80, 0x9c, 0x3d, 0x45, 0xf0, - 0xc1, 0xb1, 0x93, 0x37, 0x67, 0xd1, 0xd3, 0xa3, 0x76, 0x4e, 0x4f, 0x84, 0xc7, 0xb0, 0x4b, 0xdf, - 0xa8, 0xf6, 0x79, 0x26, 0xd7, 0x1f, 0xe2, 0xe2, 0x93, 0xc9, 0xca, 0x5b, 0x51, 0x9a, 0x5d, 0x55, - 0xd4, 0x45, 0x73, 0xdd, 0x96, 0x66, 0x27, 0x41, 0x5c, 0x59, 0x8a, 0x51, 0x69, 0xaa, 0xca, 0xba, - 0x68, 0x56, 0x9b, 0x07, 0x98, 0x25, 0x70, 0x92, 0xc0, 0xdb, 0x3e, 0xb7, 0x27, 0x68, 0xfd, 0x2e, - 0x96, 0xdb, 0xd4, 0x8f, 0xc4, 0xf2, 0x4e, 0x2c, 0x46, 0xca, 0x7f, 0xaa, 0xc3, 0x29, 0x9f, 0xc5, - 0xa5, 0x61, 0xb2, 0xb1, 0x2a, 0xeb, 0x45, 0xb3, 0xda, 0xdc, 0xc3, 0x59, 0x3b, 0x38, 0xfc, 0x6f, - 0x67, 0x62, 0xfb, 0xf2, 0x85, 0xda, 0xf0, 0x90, 0x3a, 0xe8, 0x9d, 0xc5, 0x41, 0xc5, 0xc1, 0xf4, - 0x2e, 0x78, 0xfc, 0x51, 0x69, 0x62, 0xfc, 0x6f, 0x77, 0xb7, 0x3c, 0x16, 0x7a, 0xfd, 0x0d, 0x00, - 0x00, 0xff, 0xff, 0x1c, 0x8e, 0xb4, 0xa9, 0x16, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto b/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto deleted file mode 100644 index 8d8a998c..00000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/storagepacker"; - -package storagepacker; - -import "google/protobuf/any.proto"; - -message Item { - string id = 1; - google.protobuf.Any message = 2; -} - -message Bucket { - string key = 1; - repeated Item items = 2; -} diff --git a/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go b/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go deleted file mode 100644 index 5b23a408..00000000 --- a/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go +++ /dev/null @@ -1,381 +0,0 @@ -package strutil - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/errwrap" - glob "github.com/ryanuber/go-glob" -) - -// StrListContainsGlob looks for a string in a list of strings and allows -// globs. -func StrListContainsGlob(haystack []string, needle string) bool { - for _, item := range haystack { - if glob.Glob(item, needle) { - return true - } - } - return false -} - -// StrListContains looks for a string in a list of strings. -func StrListContains(haystack []string, needle string) bool { - for _, item := range haystack { - if item == needle { - return true - } - } - return false -} - -// StrListSubset checks if a given list is a subset -// of another set -func StrListSubset(super, sub []string) bool { - for _, item := range sub { - if !StrListContains(super, item) { - return false - } - } - return true -} - -// ParseDedupAndSortStrings parses a comma separated list of strings -// into a slice of strings. The return slice will be sorted and will -// not contain duplicate or empty items. -func ParseDedupAndSortStrings(input string, sep string) []string { - input = strings.TrimSpace(input) - parsed := []string{} - if input == "" { - // Don't return nil - return parsed - } - return RemoveDuplicates(strings.Split(input, sep), false) -} - -// ParseDedupLowercaseAndSortStrings parses a comma separated list of -// strings into a slice of strings. The return slice will be sorted and -// will not contain duplicate or empty items. The values will be converted -// to lower case. -func ParseDedupLowercaseAndSortStrings(input string, sep string) []string { - input = strings.TrimSpace(input) - parsed := []string{} - if input == "" { - // Don't return nil - return parsed - } - return RemoveDuplicates(strings.Split(input, sep), true) -} - -// ParseKeyValues parses a comma separated list of `=` tuples -// into a map[string]string. -func ParseKeyValues(input string, out map[string]string, sep string) error { - if out == nil { - return fmt.Errorf("'out is nil") - } - - keyValues := ParseDedupLowercaseAndSortStrings(input, sep) - if len(keyValues) == 0 { - return nil - } - - for _, keyValue := range keyValues { - shards := strings.Split(keyValue, "=") - if len(shards) != 2 { - return fmt.Errorf("invalid format") - } - - key := strings.TrimSpace(shards[0]) - value := strings.TrimSpace(shards[1]) - if key == "" || value == "" { - return fmt.Errorf("invalid pair: key: %q value: %q", key, value) - } - out[key] = value - } - return nil -} - -// ParseArbitraryKeyValues parses arbitrary tuples. The input -// can be one of the following: -// * JSON string -// * Base64 encoded JSON string -// * Comma separated list of `=` pairs -// * Base64 encoded string containing comma separated list of -// `=` pairs -// -// Input will be parsed into the output parameter, which should -// be a non-nil map[string]string. -func ParseArbitraryKeyValues(input string, out map[string]string, sep string) error { - input = strings.TrimSpace(input) - if input == "" { - return nil - } - if out == nil { - return fmt.Errorf("'out' is nil") - } - - // Try to base64 decode the input. If successful, consider the decoded - // value as input. - inputBytes, err := base64.StdEncoding.DecodeString(input) - if err == nil { - input = string(inputBytes) - } - - // Try to JSON unmarshal the input. If successful, consider that the - // metadata was supplied as JSON input. - err = json.Unmarshal([]byte(input), &out) - if err != nil { - // If JSON unmarshalling fails, consider that the input was - // supplied as a comma separated string of 'key=value' pairs. - if err = ParseKeyValues(input, out, sep); err != nil { - return errwrap.Wrapf("failed to parse the input: {{err}}", err) - } - } - - // Validate the parsed input - for key, value := range out { - if key != "" && value == "" { - return fmt.Errorf("invalid value for key %q", key) - } - } - - return nil -} - -// ParseStringSlice parses a `sep`-separated list of strings into a -// []string with surrounding whitespace removed. -// -// The output will always be a valid slice but may be of length zero. -func ParseStringSlice(input string, sep string) []string { - input = strings.TrimSpace(input) - if input == "" { - return []string{} - } - - splitStr := strings.Split(input, sep) - ret := make([]string, len(splitStr)) - for i, val := range splitStr { - ret[i] = strings.TrimSpace(val) - } - - return ret -} - -// ParseArbitraryStringSlice parses arbitrary string slice. The input -// can be one of the following: -// * JSON string -// * Base64 encoded JSON string -// * `sep` separated list of values -// * Base64-encoded string containing a `sep` separated list of values -// -// Note that the separator is ignored if the input is found to already be in a -// structured format (e.g., JSON) -// -// The output will always be a valid slice but may be of length zero. -func ParseArbitraryStringSlice(input string, sep string) []string { - input = strings.TrimSpace(input) - if input == "" { - return []string{} - } - - // Try to base64 decode the input. If successful, consider the decoded - // value as input. - inputBytes, err := base64.StdEncoding.DecodeString(input) - if err == nil { - input = string(inputBytes) - } - - ret := []string{} - - // Try to JSON unmarshal the input. If successful, consider that the - // metadata was supplied as JSON input. - err = json.Unmarshal([]byte(input), &ret) - if err != nil { - // If JSON unmarshalling fails, consider that the input was - // supplied as a separated string of values. - return ParseStringSlice(input, sep) - } - - if ret == nil { - return []string{} - } - - return ret -} - -// TrimStrings takes a slice of strings and returns a slice of strings -// with trimmed spaces -func TrimStrings(items []string) []string { - ret := make([]string, len(items)) - for i, item := range items { - ret[i] = strings.TrimSpace(item) - } - return ret -} - -// RemoveDuplicates removes duplicate and empty elements from a slice of -// strings. This also may convert the items in the slice to lower case and -// returns a sorted slice. -func RemoveDuplicates(items []string, lowercase bool) []string { - itemsMap := map[string]bool{} - for _, item := range items { - item = strings.TrimSpace(item) - if lowercase { - item = strings.ToLower(item) - } - if item == "" { - continue - } - itemsMap[item] = true - } - items = make([]string, 0, len(itemsMap)) - for item := range itemsMap { - items = append(items, item) - } - sort.Strings(items) - return items -} - -// EquivalentSlices checks whether the given string sets are equivalent, as in, -// they contain the same values. -func EquivalentSlices(a, b []string) bool { - if a == nil && b == nil { - return true - } - - if a == nil || b == nil { - return false - } - - // First we'll build maps to ensure unique values - mapA := map[string]bool{} - mapB := map[string]bool{} - for _, keyA := range a { - mapA[keyA] = true - } - for _, keyB := range b { - mapB[keyB] = true - } - - // Now we'll build our checking slices - var sortedA, sortedB []string - for keyA := range mapA { - sortedA = append(sortedA, keyA) - } - for keyB := range mapB { - sortedB = append(sortedB, keyB) - } - sort.Strings(sortedA) - sort.Strings(sortedB) - - // Finally, compare - if len(sortedA) != len(sortedB) { - return false - } - - for i := range sortedA { - if sortedA[i] != sortedB[i] { - return false - } - } - - return true -} - -// StrListDelete removes the first occurrence of the given item from the slice -// of strings if the item exists. -func StrListDelete(s []string, d string) []string { - if s == nil { - return s - } - - for index, element := range s { - if element == d { - return append(s[:index], s[index+1:]...) - } - } - - return s -} - -// GlobbedStringsMatch compares item to val with support for a leading and/or -// trailing wildcard '*' in item. -func GlobbedStringsMatch(item, val string) bool { - if len(item) < 2 { - return val == item - } - - hasPrefix := strings.HasPrefix(item, "*") - hasSuffix := strings.HasSuffix(item, "*") - - if hasPrefix && hasSuffix { - return strings.Contains(val, item[1:len(item)-1]) - } else if hasPrefix { - return strings.HasSuffix(val, item[1:]) - } else if hasSuffix { - return strings.HasPrefix(val, item[:len(item)-1]) - } - - return val == item -} - -// AppendIfMissing adds a string to a slice if the given string is not present -func AppendIfMissing(slice []string, i string) []string { - if StrListContains(slice, i) { - return slice - } - return append(slice, i) -} - -// MergeSlices adds an arbitrary number of slices together, uniquely -func MergeSlices(args ...[]string) []string { - all := map[string]struct{}{} - for _, slice := range args { - for _, v := range slice { - all[v] = struct{}{} - } - } - - result := make([]string, 0, len(all)) - for k := range all { - result = append(result, k) - } - sort.Strings(result) - return result -} - -// Difference returns the set difference (A - B) of the two given slices. The -// result will also remove any duplicated values in set A regardless of whether -// that matches any values in set B. -func Difference(a, b []string, lowercase bool) []string { - if len(a) == 0 || len(b) == 0 { - return a - } - - a = RemoveDuplicates(a, lowercase) - b = RemoveDuplicates(b, lowercase) - - itemsMap := map[string]bool{} - for _, aVal := range a { - itemsMap[aVal] = true - } - - // Perform difference calculation - for _, bVal := range b { - if _, ok := itemsMap[bVal]; ok { - itemsMap[bVal] = false - } - } - - items := []string{} - for item, exists := range itemsMap { - if exists { - items = append(items, item) - } - } - sort.Strings(items) - return items -} diff --git a/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go b/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go deleted file mode 100644 index 08b3ebd0..00000000 --- a/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go +++ /dev/null @@ -1,54 +0,0 @@ -package tlsutil - -import ( - "crypto/tls" - "fmt" - - "github.com/hashicorp/vault/helper/strutil" -) - -// TLSLookup maps the tls_min_version configuration to the internal value -var TLSLookup = map[string]uint16{ - "tls10": tls.VersionTLS10, - "tls11": tls.VersionTLS11, - "tls12": tls.VersionTLS12, -} - -// ParseCiphers parse ciphersuites from the comma-separated string into recognized slice -func ParseCiphers(cipherStr string) ([]uint16, error) { - suites := []uint16{} - ciphers := strutil.ParseStringSlice(cipherStr, ",") - cipherMap := map[string]uint16{ - "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, - "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, - "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, - "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, - "TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256, - "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, - "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, - "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, - "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, - } - for _, cipher := range ciphers { - if v, ok := cipherMap[cipher]; ok { - suites = append(suites, v) - } else { - return suites, fmt.Errorf("unsupported cipher %q", cipher) - } - } - - return suites, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go b/vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go deleted file mode 100644 index 9c84a1d4..00000000 --- a/vendor/github.com/hashicorp/vault/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 creation call, the - // created token'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/helper/xor/xor.go b/vendor/github.com/hashicorp/vault/helper/xor/xor.go deleted file mode 100644 index 0d9567eb..00000000 --- a/vendor/github.com/hashicorp/vault/helper/xor/xor.go +++ /dev/null @@ -1,48 +0,0 @@ -package xor - -import ( - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" -) - -// XORBytes takes two byte slices and XORs them together, returning the final -// byte slice. It is an error to pass in two byte slices that do not have the -// same length. -func XORBytes(a, b []byte) ([]byte, error) { - if len(a) != len(b) { - return nil, fmt.Errorf("length of byte slices is not equivalent: %d != %d", len(a), len(b)) - } - - buf := make([]byte, len(a)) - - for i, _ := range a { - buf[i] = a[i] ^ b[i] - } - - return buf, nil -} - -// XORBase64 takes two base64-encoded strings and XORs the decoded byte slices -// together, returning the final byte slice. It is an error to pass in two -// strings that do not have the same length to their base64-decoded byte slice. -func XORBase64(a, b string) ([]byte, error) { - aBytes, err := base64.StdEncoding.DecodeString(a) - if err != nil { - return nil, errwrap.Wrapf("error decoding first base64 value: {{err}}", err) - } - if aBytes == nil || len(aBytes) == 0 { - return nil, fmt.Errorf("decoded first base64 value is nil or empty") - } - - bBytes, err := base64.StdEncoding.DecodeString(b) - if err != nil { - return nil, errwrap.Wrapf("error decoding second base64 value: {{err}}", err) - } - if bBytes == nil || len(bBytes) == 0 { - return nil, fmt.Errorf("decoded second base64 value is nil or empty") - } - - return XORBytes(aBytes, bBytes) -} diff --git a/vendor/github.com/hashicorp/vault/http/cors.go b/vendor/github.com/hashicorp/vault/http/cors.go deleted file mode 100644 index 9e8b6fa1..00000000 --- a/vendor/github.com/hashicorp/vault/http/cors.go +++ /dev/null @@ -1,67 +0,0 @@ -package http - -import ( - "fmt" - "net/http" - "strings" - - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/vault" -) - -var allowedMethods = []string{ - http.MethodDelete, - http.MethodGet, - http.MethodOptions, - http.MethodPost, - http.MethodPut, - "LIST", // LIST is not an official HTTP method, but Vault supports it. -} - -func wrapCORSHandler(h http.Handler, core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - corsConf := core.CORSConfig() - - // If CORS is not enabled or if no Origin header is present (i.e. the request - // is from the Vault CLI. A browser will always send an Origin header), then - // just return a 204. - if !corsConf.IsEnabled() { - h.ServeHTTP(w, req) - return - } - - origin := req.Header.Get("Origin") - requestMethod := req.Header.Get("Access-Control-Request-Method") - - if origin == "" { - h.ServeHTTP(w, req) - return - } - - // Return a 403 if the origin is not allowed to make cross-origin requests. - if !corsConf.IsValidOrigin(origin) { - respondError(w, http.StatusForbidden, fmt.Errorf("origin not allowed")) - return - } - - if req.Method == http.MethodOptions && !strutil.StrListContains(allowedMethods, requestMethod) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - w.Header().Set("Access-Control-Allow-Origin", origin) - w.Header().Set("Vary", "Origin") - - // apply headers for preflight requests - if req.Method == http.MethodOptions { - w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ",")) - w.Header().Set("Access-Control-Allow-Headers", strings.Join(corsConf.AllowedHeaders, ",")) - w.Header().Set("Access-Control-Max-Age", "300") - - return - } - - h.ServeHTTP(w, req) - return - }) -} diff --git a/vendor/github.com/hashicorp/vault/http/handler.go b/vendor/github.com/hashicorp/vault/http/handler.go deleted file mode 100644 index d236457a..00000000 --- a/vendor/github.com/hashicorp/vault/http/handler.go +++ /dev/null @@ -1,808 +0,0 @@ -package http - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/textproto" - "net/url" - "os" - "strings" - "time" - - "github.com/NYTimes/gziphandler" - "github.com/elazarl/go-bindata-assetfs" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/pathmanager" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -const ( - // WrapTTLHeaderName is the name of the header containing a directive to - // wrap the response - WrapTTLHeaderName = "X-Vault-Wrap-TTL" - - // WrapFormatHeaderName is the name of the header containing the format to - // wrap in; has no effect if the wrap TTL is not set - WrapFormatHeaderName = "X-Vault-Wrap-Format" - - // NoRequestForwardingHeaderName is the name of the header telling Vault - // not to use request forwarding - NoRequestForwardingHeaderName = "X-Vault-No-Request-Forwarding" - - // MFAHeaderName represents the HTTP header which carries the credentials - // required to perform MFA on any path. - MFAHeaderName = "X-Vault-MFA" - - // canonicalMFAHeaderName is the MFA header value's format in the request - // headers. Do not alter the casing of this string. - canonicalMFAHeaderName = "X-Vault-Mfa" - - // PolicyOverrideHeaderName is the header set to request overriding - // soft-mandatory Sentinel policies. - PolicyOverrideHeaderName = "X-Vault-Policy-Override" - - // DefaultMaxRequestSize is the default maximum accepted request size. This - // is to prevent a denial of service attack where no Content-Length is - // provided and the server is fed ever more data until it exhausts memory. - // Can be overridden per listener. - DefaultMaxRequestSize = 32 * 1024 * 1024 -) - -var ( - // Set to false by stub_asset if the ui build tag isn't enabled - uiBuiltIn = true - - // perfStandbyAlwaysForwardPaths is used to check a requested path against - // the always forward list - perfStandbyAlwaysForwardPaths = pathmanager.New() - - injectDataIntoTopRoutes = []string{ - "/v1/sys/audit", - "/v1/sys/audit/", - "/v1/sys/audit-hash/", - "/v1/sys/auth", - "/v1/sys/auth/", - "/v1/sys/config/cors", - "/v1/sys/config/auditing/request-headers/", - "/v1/sys/config/auditing/request-headers", - "/v1/sys/capabilities", - "/v1/sys/capabilities-accessor", - "/v1/sys/capabilities-self", - "/v1/sys/key-status", - "/v1/sys/mounts", - "/v1/sys/mounts/", - "/v1/sys/policy", - "/v1/sys/policy/", - "/v1/sys/rekey/backup", - "/v1/sys/rekey/recovery-key-backup", - "/v1/sys/remount", - "/v1/sys/rotate", - "/v1/sys/wrapping/wrap", - } -) - -// Handler returns an http.Handler for the API. This can be used on -// its own to mount the Vault API within another web server. -func Handler(props *vault.HandlerProperties) http.Handler { - core := props.Core - - // Create the muxer to handle the actual endpoints - mux := http.NewServeMux() - mux.Handle("/v1/sys/init", handleSysInit(core)) - mux.Handle("/v1/sys/seal-status", handleSysSealStatus(core)) - mux.Handle("/v1/sys/seal", handleSysSeal(core)) - mux.Handle("/v1/sys/step-down", handleRequestForwarding(core, handleSysStepDown(core))) - mux.Handle("/v1/sys/unseal", handleSysUnseal(core)) - mux.Handle("/v1/sys/leader", handleSysLeader(core)) - mux.Handle("/v1/sys/health", handleSysHealth(core)) - mux.Handle("/v1/sys/generate-root/attempt", handleRequestForwarding(core, handleSysGenerateRootAttempt(core, vault.GenerateStandardRootTokenStrategy))) - mux.Handle("/v1/sys/generate-root/update", handleRequestForwarding(core, handleSysGenerateRootUpdate(core, vault.GenerateStandardRootTokenStrategy))) - mux.Handle("/v1/sys/rekey/init", handleRequestForwarding(core, handleSysRekeyInit(core, false))) - mux.Handle("/v1/sys/rekey/update", handleRequestForwarding(core, handleSysRekeyUpdate(core, false))) - mux.Handle("/v1/sys/rekey/verify", handleRequestForwarding(core, handleSysRekeyVerify(core, false))) - mux.Handle("/v1/sys/rekey-recovery-key/init", handleRequestForwarding(core, handleSysRekeyInit(core, true))) - mux.Handle("/v1/sys/rekey-recovery-key/update", handleRequestForwarding(core, handleSysRekeyUpdate(core, true))) - mux.Handle("/v1/sys/rekey-recovery-key/verify", handleRequestForwarding(core, handleSysRekeyVerify(core, true))) - for _, path := range injectDataIntoTopRoutes { - mux.Handle(path, handleRequestForwarding(core, handleLogicalWithInjector(core))) - } - mux.Handle("/v1/sys/", handleRequestForwarding(core, handleLogical(core))) - mux.Handle("/v1/", handleRequestForwarding(core, handleLogical(core))) - if core.UIEnabled() == true { - if uiBuiltIn { - mux.Handle("/ui/", http.StripPrefix("/ui/", gziphandler.GzipHandler(handleUIHeaders(core, handleUI(http.FileServer(&UIAssetWrapper{FileSystem: assetFS()})))))) - mux.Handle("/robots.txt", gziphandler.GzipHandler(handleUIHeaders(core, handleUI(http.FileServer(&UIAssetWrapper{FileSystem: assetFS()}))))) - } else { - mux.Handle("/ui/", handleUIHeaders(core, handleUIStub())) - } - mux.Handle("/ui", handleUIRedirect()) - mux.Handle("/", handleUIRedirect()) - } - - additionalRoutes(mux, core) - - // Wrap the handler in another handler to trigger all help paths. - helpWrappedHandler := wrapHelpHandler(mux, core) - corsWrappedHandler := wrapCORSHandler(helpWrappedHandler, core) - - genericWrappedHandler := genericWrapping(core, corsWrappedHandler, props) - - // Wrap the handler with PrintablePathCheckHandler to check for non-printable - // characters in the request path. - printablePathCheckHandler := genericWrappedHandler - if !props.DisablePrintableCheck { - printablePathCheckHandler = cleanhttp.PrintablePathCheckHandler(genericWrappedHandler, nil) - } - - return printablePathCheckHandler -} - -// wrapGenericHandler wraps the handler with an extra layer of handler where -// tasks that should be commonly handled for all the requests and/or responses -// are performed. -func wrapGenericHandler(core *vault.Core, h http.Handler, maxRequestSize int64, maxRequestDuration time.Duration) http.Handler { - if maxRequestDuration == 0 { - maxRequestDuration = vault.DefaultMaxRequestDuration - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Set the Cache-Control header for all the responses returned - // by Vault - w.Header().Set("Cache-Control", "no-store") - - // Start with the request context - ctx := r.Context() - var cancelFunc context.CancelFunc - // Add our timeout - ctx, cancelFunc = context.WithTimeout(ctx, maxRequestDuration) - // Add a size limiter if desired - if maxRequestSize > 0 { - ctx = context.WithValue(ctx, "max_request_size", maxRequestSize) - } - ctx = context.WithValue(ctx, "original_request_path", r.URL.Path) - r = r.WithContext(ctx) - - switch { - case strings.HasPrefix(r.URL.Path, "/v1/"): - newR, status := adjustRequest(core, r) - if status != 0 { - respondError(w, status, nil) - cancelFunc() - return - } - r = newR - - case strings.HasPrefix(r.URL.Path, "/ui"), r.URL.Path == "/robots.txt", r.URL.Path == "/": - default: - respondError(w, http.StatusNotFound, nil) - cancelFunc() - return - } - - h.ServeHTTP(w, r) - cancelFunc() - return - }) -} - -func WrapForwardedForHandler(h http.Handler, authorizedAddrs []*sockaddr.SockAddrMarshaler, rejectNotPresent, rejectNonAuthz bool, hopSkips int) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - headers, headersOK := r.Header[textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")] - if !headersOK || len(headers) == 0 { - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, fmt.Errorf("missing x-forwarded-for header and configured to reject when not present")) - return - } - - host, port, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - // If not rejecting treat it like we just don't have a valid - // header because we can't do a comparison against an address we - // can't understand - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client hostport: {{err}}", err)) - return - } - - addr, err := sockaddr.NewIPAddr(host) - if err != nil { - // We treat this the same as the case above - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client address: {{err}}", err)) - return - } - - var found bool - for _, authz := range authorizedAddrs { - if authz.Contains(addr) { - found = true - break - } - } - if !found { - // If we didn't find it and aren't configured to reject, simply - // don't trust it - if !rejectNonAuthz { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, fmt.Errorf("client address not authorized for x-forwarded-for and configured to reject connection")) - return - } - - // At this point we have at least one value and it's authorized - - // Split comma separated ones, which are common. This brings it in line - // to the multiple-header case. - var acc []string - for _, header := range headers { - vals := strings.Split(header, ",") - for _, v := range vals { - acc = append(acc, strings.TrimSpace(v)) - } - } - - indexToUse := len(acc) - 1 - hopSkips - if indexToUse < 0 { - // This is likely an error in either configuration or other - // infrastructure. We could either deny the request, or we - // could simply not trust the value. Denying the request is - // "safer" since if this logic is configured at all there may - // be an assumption it can always be trusted. Given that we can - // deny accepting the request at all if it's not from an - // authorized address, if we're at this point the address is - // authorized (or we've turned off explicit rejection) and we - // should assume that what comes in should be properly - // formatted. - respondError(w, http.StatusBadRequest, fmt.Errorf("malformed x-forwarded-for configuration or request, hops to skip (%d) would skip before earliest chain link (chain length %d)", hopSkips, len(headers))) - return - } - - r.RemoteAddr = net.JoinHostPort(acc[indexToUse], port) - h.ServeHTTP(w, r) - return - }) -} - -// A lookup on a token that is about to expire returns nil, which means by the -// time we can validate a wrapping token lookup will return nil since it will -// be revoked after the call. So we have to do the validation here. -func wrappingVerificationFunc(ctx context.Context, core *vault.Core, req *logical.Request) error { - if req == nil { - return fmt.Errorf("invalid request") - } - - valid, err := core.ValidateWrappingToken(ctx, req) - if err != nil { - return errwrap.Wrapf("error validating wrapping token: {{err}}", err) - } - if !valid { - return fmt.Errorf("wrapping token is not valid or does not exist") - } - - return nil -} - -// stripPrefix is a helper to strip a prefix from the path. It will -// return false from the second return value if it the prefix doesn't exist. -func stripPrefix(prefix, path string) (string, bool) { - if !strings.HasPrefix(path, prefix) { - return "", false - } - - path = path[len(prefix):] - if path == "" { - return "", false - } - - return path, true -} - -func handleUIHeaders(core *vault.Core, h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - header := w.Header() - - userHeaders, err := core.UIHeaders() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if userHeaders != nil { - for k := range userHeaders { - v := userHeaders.Get(k) - header.Set(k, v) - } - } - h.ServeHTTP(w, req) - }) -} - -func handleUI(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - - // The fileserver handler strips trailing slashes and does a redirect. - // We don't want the redirect to happen so we preemptively trim the slash - // here. - req.URL.Path = strings.TrimSuffix(req.URL.Path, "/") - h.ServeHTTP(w, req) - return - }) -} - -func handleUIStub() http.Handler { - stubHTML := ` - - - -
-
-
- - - -

Vault UI is not available in this binary.

-
-

To get Vault UI do one of the following:

-
    -
  • Download an official release
  • -
  • Run make release to create your own release binaries. -
  • Run make dev-ui to create a development binary with the UI. -
-
-
- - ` - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte(stubHTML)) - }) -} - -func handleUIRedirect() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - http.Redirect(w, req, "/ui/", 307) - return - }) -} - -type UIAssetWrapper struct { - FileSystem *assetfs.AssetFS -} - -func (fs *UIAssetWrapper) Open(name string) (http.File, error) { - file, err := fs.FileSystem.Open(name) - if err == nil { - return file, nil - } - // serve index.html instead of 404ing - if err == os.ErrNotExist { - return fs.FileSystem.Open("index.html") - } - return nil, err -} - -func parseRequest(r *http.Request, w http.ResponseWriter, out interface{}) error { - // Limit the maximum number of bytes to MaxRequestSize to protect - // against an indefinite amount of data being read. - reader := r.Body - ctx := r.Context() - maxRequestSize := ctx.Value("max_request_size") - if maxRequestSize != nil { - max, ok := maxRequestSize.(int64) - if !ok { - return errors.New("could not parse max_request_size from request context") - } - if max > 0 { - reader = http.MaxBytesReader(w, r.Body, max) - } - } - err := jsonutil.DecodeJSONFromReader(reader, out) - if err != nil && err != io.EOF { - return errwrap.Wrapf("failed to parse JSON input: {{err}}", err) - } - return err -} - -// handleRequestForwarding determines whether to forward a request or not, -// falling back on the older behavior of redirecting the client -func handleRequestForwarding(core *vault.Core, handler http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // If we are a performance standby we can handle the request. - if core.PerfStandby() { - ns, err := namespace.FromContext(r.Context()) - if err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - path := ns.TrimmedPath(r.URL.Path[len("/v1/"):]) - switch { - case !perfStandbyAlwaysForwardPaths.HasPath(path): - handler.ServeHTTP(w, r) - return - case strings.HasPrefix(path, "auth/token/create/"): - isBatch, err := core.IsBatchTokenCreationRequest(r.Context(), path) - if err == nil && isBatch { - handler.ServeHTTP(w, r) - return - } - } - } - - // Note: in an HA setup, this call will also ensure that connections to - // the leader are set up, as that happens once the advertised cluster - // values are read during this function - isLeader, leaderAddr, _, err := core.Leader() - if err != nil { - if err == vault.ErrHANotEnabled { - // Standalone node, serve request normally - handler.ServeHTTP(w, r) - return - } - // Some internal error occurred - respondError(w, http.StatusInternalServerError, err) - return - } - if isLeader { - // No forwarding needed, we're leader - handler.ServeHTTP(w, r) - return - } - if leaderAddr == "" { - respondError(w, http.StatusInternalServerError, fmt.Errorf("local node not active but active cluster node not found")) - return - } - - forwardRequest(core, w, r) - return - }) -} - -func forwardRequest(core *vault.Core, w http.ResponseWriter, r *http.Request) { - if r.Header.Get(vault.IntNoForwardingHeaderName) != "" { - respondStandby(core, w, r.URL) - return - } - - if r.Header.Get(NoRequestForwardingHeaderName) != "" { - // Forwarding explicitly disabled, fall back to previous behavior - core.Logger().Debug("handleRequestForwarding: forwarding disabled by client request") - respondStandby(core, w, r.URL) - return - } - - // Attempt forwarding the request. If we cannot forward -- perhaps it's - // been disabled on the active node -- this will return with an - // ErrCannotForward and we simply fall back - statusCode, header, retBytes, err := core.ForwardRequest(r) - if err != nil { - if err == vault.ErrCannotForward { - core.Logger().Debug("cannot forward request (possibly disabled on active node), falling back") - } else { - core.Logger().Error("forward request error", "error", err) - } - - // Fall back to redirection - respondStandby(core, w, r.URL) - return - } - - if header != nil { - for k, v := range header { - w.Header()[k] = v - } - } - - w.WriteHeader(statusCode) - w.Write(retBytes) -} - -// request is a helper to perform a request and properly exit in the -// case of an error. -func request(core *vault.Core, w http.ResponseWriter, rawReq *http.Request, r *logical.Request) (*logical.Response, bool) { - resp, err := core.HandleRequest(rawReq.Context(), r) - if r.LastRemoteWAL() > 0 && !vault.WaitUntilWALShipped(rawReq.Context(), core, r.LastRemoteWAL()) { - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning("Timeout hit while waiting for local replicated cluster to apply primary's write; this client may encounter stale reads of values written during this operation.") - } - if errwrap.Contains(err, consts.ErrStandby.Error()) { - respondStandby(core, w, rawReq.URL) - return resp, false - } - - if respondErrorCommon(w, r, resp, err) { - return resp, false - } - - return resp, true -} - -// respondStandby is used to trigger a redirect in the case that this Vault is currently a hot standby -func respondStandby(core *vault.Core, w http.ResponseWriter, reqURL *url.URL) { - // Request the leader address - _, redirectAddr, _, err := core.Leader() - if err != nil { - if err == vault.ErrHANotEnabled { - // Standalone node, serve 503 - err = errors.New("node is not active") - respondError(w, http.StatusServiceUnavailable, err) - return - } - - respondError(w, http.StatusInternalServerError, err) - return - } - - // If there is no leader, generate a 503 error - if redirectAddr == "" { - err = errors.New("no active Vault instance found") - respondError(w, http.StatusServiceUnavailable, err) - return - } - - // Parse the redirect location - redirectURL, err := url.Parse(redirectAddr) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Generate a redirect URL - finalURL := url.URL{ - Scheme: redirectURL.Scheme, - Host: redirectURL.Host, - Path: reqURL.Path, - RawQuery: reqURL.RawQuery, - } - - // Ensure there is a scheme, default to https - if finalURL.Scheme == "" { - finalURL.Scheme = "https" - } - - // If we have an address, redirect! We use a 307 code - // because we don't actually know if its permanent and - // the request method should be preserved. - w.Header().Set("Location", finalURL.String()) - w.WriteHeader(307) -} - -// getTokenFromReq parse headers of the incoming request to extract token if present -// it accepts Authorization Bearer (RFC6750) and X-Vault-Token header -func getTokenFromReq(r *http.Request) (string, error) { - if token := r.Header.Get(consts.AuthHeaderName); token != "" { - return token, nil - } - if v := r.Header.Get("Authorization"); v != "" { - // Reference for Authorization header format: https://tools.ietf.org/html/rfc7236#section-3 - - // If string does not start by Bearer, or contains any space after it. It is a formatting error - if !strings.HasPrefix(v, "Bearer ") || strings.LastIndexByte(v, ' ') > 7 { - return "", fmt.Errorf("the Authorization header provided is wrongly formatted. Please use \"Bearer \"") - } - return v[7:], nil - } - return "", nil -} - -// requestAuth adds the token to the logical.Request if it exists. -func requestAuth(core *vault.Core, r *http.Request, req *logical.Request) (*logical.Request, error) { - // Attach the header value if we have it - if token, err := getTokenFromReq(r); err != nil { - return req, err - } else if token != "" { - req.ClientToken = token - - // Also attach the accessor if we have it. This doesn't fail if it - // doesn't exist because the request may be to an unauthenticated - // endpoint/login endpoint where a bad current token doesn't matter, or - // a token from a Vault version pre-accessors. - te, err := core.LookupToken(r.Context(), token) - if err != nil && strings.Count(token, ".") != 2 { - return req, err - } - if err == nil && te != nil { - req.ClientTokenAccessor = te.Accessor - req.ClientTokenRemainingUses = te.NumUses - req.SetTokenEntry(te) - } - } - - return req, nil -} - -func requestPolicyOverride(r *http.Request, req *logical.Request) error { - raw := r.Header.Get(PolicyOverrideHeaderName) - if raw == "" { - return nil - } - - override, err := parseutil.ParseBool(raw) - if err != nil { - return err - } - - req.PolicyOverride = override - return nil -} - -// requestWrapInfo adds the WrapInfo value to the logical.Request if wrap info exists -func requestWrapInfo(r *http.Request, req *logical.Request) (*logical.Request, error) { - // First try for the header value - wrapTTL := r.Header.Get(WrapTTLHeaderName) - if wrapTTL == "" { - return req, nil - } - - // If it has an allowed suffix parse as a duration string - dur, err := parseutil.ParseDurationSecond(wrapTTL) - if err != nil { - return req, err - } - if int64(dur) < 0 { - return req, fmt.Errorf("requested wrap ttl cannot be negative") - } - - req.WrapInfo = &logical.RequestWrapInfo{ - TTL: dur, - } - - wrapFormat := r.Header.Get(WrapFormatHeaderName) - switch wrapFormat { - case "jwt": - req.WrapInfo.Format = "jwt" - } - - return req, nil -} - -// parseMFAHeader parses the MFAHeaderName in the request headers and organizes -// them with MFA method name as the index. -func parseMFAHeader(req *logical.Request) error { - if req == nil { - return fmt.Errorf("request is nil") - } - - if req.Headers == nil { - return nil - } - - // Reset and initialize the credentials in the request - req.MFACreds = make(map[string][]string) - - for _, mfaHeaderValue := range req.Headers[canonicalMFAHeaderName] { - // Skip the header with no value in it - if mfaHeaderValue == "" { - continue - } - - // Handle the case where only method name is mentioned and no value - // is supplied - if !strings.Contains(mfaHeaderValue, ":") { - // Mark the presense of method name, but set an empty set to it - // indicating that there were no values supplied for the method - if req.MFACreds[mfaHeaderValue] == nil { - req.MFACreds[mfaHeaderValue] = []string{} - } - continue - } - - shardSplits := strings.SplitN(mfaHeaderValue, ":", 2) - if shardSplits[0] == "" { - return fmt.Errorf("invalid data in header %q; missing method name", MFAHeaderName) - } - - if shardSplits[1] == "" { - return fmt.Errorf("invalid data in header %q; missing method value", MFAHeaderName) - } - - req.MFACreds[shardSplits[0]] = append(req.MFACreds[shardSplits[0]], shardSplits[1]) - } - - return nil -} - -func respondError(w http.ResponseWriter, status int, err error) { - logical.AdjustErrorStatusCode(&status, err) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - - 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 respondErrorCommon(w http.ResponseWriter, req *logical.Request, resp *logical.Response, err error) bool { - statusCode, newErr := logical.RespondErrorCommon(req, resp, err) - if newErr == nil && statusCode == 0 { - return false - } - - respondError(w, statusCode, newErr) - return true -} - -func respondOk(w http.ResponseWriter, body interface{}) { - w.Header().Set("Content-Type", "application/json") - - if body == nil { - w.WriteHeader(http.StatusNoContent) - } else { - w.WriteHeader(http.StatusOK) - enc := json.NewEncoder(w) - enc.Encode(body) - } -} - -type ErrorResponse struct { - Errors []string `json:"errors"` -} diff --git a/vendor/github.com/hashicorp/vault/http/help.go b/vendor/github.com/hashicorp/vault/http/help.go deleted file mode 100644 index b7243931..00000000 --- a/vendor/github.com/hashicorp/vault/http/help.go +++ /dev/null @@ -1,58 +0,0 @@ -package http - -import ( - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -func wrapHelpHandler(h http.Handler, core *vault.Core) http.Handler { - return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) { - // If the help parameter is not blank, then show the help. We request - // forward because standby nodes do not have mounts and other state. - if v := req.URL.Query().Get("help"); v != "" || req.Method == "HELP" { - handleRequestForwarding(core, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handleHelp(core, w, r) - })).ServeHTTP(writer, req) - return - } - - h.ServeHTTP(writer, req) - return - }) -} - -func handleHelp(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ns, err := namespace.FromContext(r.Context()) - if err != nil { - respondError(w, http.StatusBadRequest, nil) - return - } - path := ns.TrimmedPath(r.URL.Path[len("/v1/"):]) - - req, err := requestAuth(core, r, &logical.Request{ - Operation: logical.HelpOperation, - Path: path, - Connection: getConnection(r), - }) - if err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - respondError(w, http.StatusForbidden, nil) - return - } - respondError(w, http.StatusBadRequest, errwrap.Wrapf("error performing token check: {{err}}", err)) - return - } - - resp, err := core.HandleRequest(r.Context(), req) - if err != nil { - respondErrorCommon(w, req, resp, err) - return - } - - respondOk(w, resp.Data) -} diff --git a/vendor/github.com/hashicorp/vault/http/logical.go b/vendor/github.com/hashicorp/vault/http/logical.go deleted file mode 100644 index a211d648..00000000 --- a/vendor/github.com/hashicorp/vault/http/logical.go +++ /dev/null @@ -1,380 +0,0 @@ -package http - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -func buildLogicalRequest(core *vault.Core, w http.ResponseWriter, r *http.Request) (*logical.Request, int, error) { - ns, err := namespace.FromContext(r.Context()) - if err != nil { - return nil, http.StatusBadRequest, nil - } - path := ns.TrimmedPath(r.URL.Path[len("/v1/"):]) - - var data map[string]interface{} - - // Determine the operation - var op logical.Operation - switch r.Method { - case "DELETE": - op = logical.DeleteOperation - - case "GET": - op = logical.ReadOperation - queryVals := r.URL.Query() - var list bool - var err error - listStr := queryVals.Get("list") - if listStr != "" { - list, err = strconv.ParseBool(listStr) - if err != nil { - return nil, http.StatusBadRequest, nil - } - if list { - op = logical.ListOperation - if !strings.HasSuffix(path, "/") { - path += "/" - } - } - } - - if !list { - getData := map[string]interface{}{} - - for k, v := range r.URL.Query() { - // Skip the help key as this is a reserved parameter - if k == "help" { - continue - } - - switch { - case len(v) == 0: - case len(v) == 1: - getData[k] = v[0] - default: - getData[k] = v - } - } - - if len(getData) > 0 { - data = getData - } - } - - case "POST", "PUT": - op = logical.UpdateOperation - // Parse the request if we can - if op == logical.UpdateOperation { - err := parseRequest(r, w, &data) - if err == io.EOF { - data = nil - err = nil - } - if err != nil { - return nil, http.StatusBadRequest, err - } - } - - case "LIST": - op = logical.ListOperation - if !strings.HasSuffix(path, "/") { - path += "/" - } - - case "OPTIONS": - default: - return nil, http.StatusMethodNotAllowed, nil - } - - request_id, err := uuid.GenerateUUID() - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf("failed to generate identifier for the request: {{err}}", err) - } - - req, err := requestAuth(core, r, &logical.Request{ - ID: request_id, - Operation: op, - Path: path, - Data: data, - Connection: getConnection(r), - Headers: r.Header, - }) - if err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - return nil, http.StatusForbidden, nil - } - return nil, http.StatusBadRequest, errwrap.Wrapf("error performing token check: {{err}}", err) - } - - req, err = requestWrapInfo(r, req) - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf("error parsing X-Vault-Wrap-TTL header: {{err}}", err) - } - - err = parseMFAHeader(req) - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf("failed to parse X-Vault-MFA header: {{err}}", err) - } - - err = requestPolicyOverride(r, req) - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf(fmt.Sprintf(`failed to parse %s header: {{err}}`, PolicyOverrideHeaderName), err) - } - - return req, 0, nil -} - -func handleLogical(core *vault.Core) http.Handler { - return handleLogicalInternal(core, false) -} - -func handleLogicalWithInjector(core *vault.Core) http.Handler { - return handleLogicalInternal(core, true) -} - -func handleLogicalInternal(core *vault.Core, injectDataIntoTopLevel bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - // Always forward requests that are using a limited use count token - if core.PerfStandby() && req.ClientTokenRemainingUses > 0 { - forwardRequest(core, w, r) - return - } - - // req.Path will be relative by this point. The prefix check is first - // to fail faster if we're not in this situation since it's a hot path - switch { - case strings.HasPrefix(req.Path, "sys/wrapping/"), strings.HasPrefix(req.Path, "auth/token/"): - // Get the token ns info; if we match the paths below we want to - // swap in the token context (but keep the relative path) - if err != nil { - core.Logger().Warn("error looking up just-set context", "error", err) - respondError(w, http.StatusInternalServerError, err) - return - } - te := req.TokenEntry() - newCtx := r.Context() - if te != nil { - ns, err := vault.NamespaceByID(newCtx, te.NamespaceID, core) - if err != nil { - core.Logger().Warn("error looking up namespace from the token's namespace ID", "error", err) - respondError(w, http.StatusInternalServerError, err) - return - } - if ns != nil { - newCtx = namespace.ContextWithNamespace(newCtx, ns) - } - } - switch req.Path { - case "sys/wrapping/lookup", "sys/wrapping/rewrap", "sys/wrapping/unwrap": - r = r.WithContext(newCtx) - if err := wrappingVerificationFunc(r.Context(), core, req); err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - respondError(w, http.StatusForbidden, err) - } else { - respondError(w, http.StatusBadRequest, err) - } - return - } - - // The -self paths have no meaning outside of the token NS, so - // requests for these paths always go to the token NS - case "auth/token/lookup-self", "auth/token/renew-self", "auth/token/revoke-self": - r = r.WithContext(newCtx) - } - } - - // Make the internal request. We attach the connection info - // as well in case this is an authentication request that requires - // it. Vault core handles stripping this if we need to. This also - // handles all error cases; if we hit respondLogical, the request is a - // success. - resp, ok := request(core, w, r, req) - if !ok { - return - } - - // Build the proper response - respondLogical(w, r, req, resp, injectDataIntoTopLevel) - }) -} - -func respondLogical(w http.ResponseWriter, r *http.Request, req *logical.Request, resp *logical.Response, injectDataIntoTopLevel bool) { - var httpResp *logical.HTTPResponse - var ret interface{} - - if resp != nil { - if resp.Redirect != "" { - // If we have a redirect, redirect! We use a 307 code - // because we don't actually know if its permanent. - http.Redirect(w, r, resp.Redirect, 307) - return - } - - // Check if this is a raw response - if _, ok := resp.Data[logical.HTTPStatusCode]; ok { - respondRaw(w, r, resp) - return - } - - if resp.WrapInfo != nil && resp.WrapInfo.Token != "" { - httpResp = &logical.HTTPResponse{ - WrapInfo: &logical.HTTPWrapInfo{ - Token: resp.WrapInfo.Token, - Accessor: resp.WrapInfo.Accessor, - TTL: int(resp.WrapInfo.TTL.Seconds()), - CreationTime: resp.WrapInfo.CreationTime.Format(time.RFC3339Nano), - CreationPath: resp.WrapInfo.CreationPath, - WrappedAccessor: resp.WrapInfo.WrappedAccessor, - }, - } - } else { - httpResp = logical.LogicalResponseToHTTPResponse(resp) - httpResp.RequestID = req.ID - } - - ret = httpResp - - if injectDataIntoTopLevel { - injector := logical.HTTPSysInjector{ - Response: httpResp, - } - ret = injector - } - } - - // Respond - respondOk(w, ret) - return -} - -// respondRaw is used when the response is using HTTPContentType and HTTPRawBody -// to change the default response handling. This is only used for specific things like -// returning the CRL information on the PKI backends. -func respondRaw(w http.ResponseWriter, r *http.Request, resp *logical.Response) { - retErr := func(w http.ResponseWriter, err string) { - w.Header().Set("X-Vault-Raw-Error", err) - w.WriteHeader(http.StatusInternalServerError) - w.Write(nil) - } - - // Ensure this is never a secret or auth response - if resp.Secret != nil || resp.Auth != nil { - retErr(w, "raw responses cannot contain secrets or auth") - return - } - - // Get the status code - statusRaw, ok := resp.Data[logical.HTTPStatusCode] - if !ok { - retErr(w, "no status code given") - return - } - - var status int - switch statusRaw.(type) { - case int: - status = statusRaw.(int) - case float64: - status = int(statusRaw.(float64)) - case json.Number: - s64, err := statusRaw.(json.Number).Float64() - if err != nil { - retErr(w, "cannot decode status code") - return - } - status = int(s64) - default: - retErr(w, "cannot decode status code") - return - } - - nonEmpty := status != http.StatusNoContent - - var contentType string - var body []byte - - // Get the content type header; don't require it if the body is empty - contentTypeRaw, ok := resp.Data[logical.HTTPContentType] - if !ok && nonEmpty { - retErr(w, "no content type given") - return - } - if ok { - contentType, ok = contentTypeRaw.(string) - if !ok { - retErr(w, "cannot decode content type") - return - } - } - - if nonEmpty { - // Get the body - bodyRaw, ok := resp.Data[logical.HTTPRawBody] - if !ok { - goto WRITE_RESPONSE - } - - switch bodyRaw.(type) { - case string: - // This is best effort. The value may already be base64-decoded so - // if it doesn't work we just use as-is - bodyDec, err := base64.StdEncoding.DecodeString(bodyRaw.(string)) - if err == nil { - body = bodyDec - } else { - body = []byte(bodyRaw.(string)) - } - case []byte: - body = bodyRaw.([]byte) - default: - retErr(w, "cannot decode body") - return - } - } - -WRITE_RESPONSE: - // Write the response - if contentType != "" { - w.Header().Set("Content-Type", contentType) - } - - w.WriteHeader(status) - w.Write(body) -} - -// getConnection is used to format the connection information for -// attaching to a logical request -func getConnection(r *http.Request) (connection *logical.Connection) { - var remoteAddr string - - remoteAddr, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - remoteAddr = "" - } - - connection = &logical.Connection{ - RemoteAddr: remoteAddr, - ConnState: r.TLS, - } - return -} diff --git a/vendor/github.com/hashicorp/vault/http/stub_assets.go b/vendor/github.com/hashicorp/vault/http/stub_assets.go deleted file mode 100644 index c64ac582..00000000 --- a/vendor/github.com/hashicorp/vault/http/stub_assets.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !ui - -package http - -import ( - assetfs "github.com/elazarl/go-bindata-assetfs" -) - -func init() { - uiBuiltIn = false -} - -// assetFS is a stub for building Vault without a UI. -func assetFS() *assetfs.AssetFS { - return nil -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_generate_root.go b/vendor/github.com/hashicorp/vault/http/sys_generate_root.go deleted file mode 100644 index f60d1e3f..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_generate_root.go +++ /dev/null @@ -1,211 +0,0 @@ -package http - -import ( - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "io" - "net/http" - - "github.com/hashicorp/vault/helper/base62" - "github.com/hashicorp/vault/vault" -) - -func handleSysGenerateRootAttempt(core *vault.Core, generateStrategy vault.GenerateRootStrategy) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysGenerateRootAttemptGet(core, w, r, "") - case "POST", "PUT": - handleSysGenerateRootAttemptPut(core, w, r, generateStrategy) - case "DELETE": - handleSysGenerateRootAttemptDelete(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysGenerateRootAttemptGet(core *vault.Core, w http.ResponseWriter, r *http.Request, otp string) { - ctx, cancel := core.GetContext() - defer cancel() - - // Get the current seal configuration - barrierConfig, err := core.SealAccess().BarrierConfig(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - sealConfig := barrierConfig - if core.SealAccess().RecoveryKeySupported() { - sealConfig, err = core.SealAccess().RecoveryConfig(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - } - - // Get the generation configuration - generationConfig, err := core.GenerateRootConfiguration() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Get the progress - progress, err := core.GenerateRootProgress() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Format the status - status := &GenerateRootStatusResponse{ - Started: false, - Progress: progress, - Required: sealConfig.SecretThreshold, - Complete: false, - OTPLength: vault.TokenLength + 2, - OTP: otp, - } - if generationConfig != nil { - status.Nonce = generationConfig.Nonce - status.Started = true - status.PGPFingerprint = generationConfig.PGPFingerprint - } - - respondOk(w, status) -} - -func handleSysGenerateRootAttemptPut(core *vault.Core, w http.ResponseWriter, r *http.Request, generateStrategy vault.GenerateRootStrategy) { - // Parse the request - var req GenerateRootInitRequest - if err := parseRequest(r, w, &req); err != nil && err != io.EOF { - respondError(w, http.StatusBadRequest, err) - return - } - - var err error - var genned bool - - switch { - case len(req.PGPKey) > 0, len(req.OTP) > 0: - default: - genned = true - req.OTP, err = base62.Random(vault.TokenLength+2, true) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - } - - // Attemptialize the generation - if err := core.GenerateRootInit(req.OTP, req.PGPKey, generateStrategy); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - if genned { - handleSysGenerateRootAttemptGet(core, w, r, req.OTP) - return - } - - handleSysGenerateRootAttemptGet(core, w, r, "") -} - -func handleSysGenerateRootAttemptDelete(core *vault.Core, w http.ResponseWriter, r *http.Request) { - err := core.GenerateRootCancel() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - respondOk(w, nil) -} - -func handleSysGenerateRootUpdate(core *vault.Core, generateStrategy vault.GenerateRootStrategy) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Parse the request - var req GenerateRootUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on root generation - result, err := core.GenerateRootUpdate(ctx, key, req.Nonce, generateStrategy) - if err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - resp := &GenerateRootStatusResponse{ - Complete: result.Progress == result.Required, - Nonce: req.Nonce, - Progress: result.Progress, - Required: result.Required, - Started: true, - EncodedToken: result.EncodedToken, - PGPFingerprint: result.PGPFingerprint, - } - - if generateStrategy == vault.GenerateStandardRootTokenStrategy { - resp.EncodedRootToken = result.EncodedToken - } - - respondOk(w, resp) - }) -} - -type GenerateRootInitRequest struct { - OTP string `json:"otp"` - PGPKey string `json:"pgp_key"` -} - -type GenerateRootStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - Progress int `json:"progress"` - Required int `json:"required"` - Complete bool `json:"complete"` - EncodedToken string `json:"encoded_token"` - EncodedRootToken string `json:"encoded_root_token"` - PGPFingerprint string `json:"pgp_fingerprint"` - OTP string `json:"otp"` - OTPLength int `json:"otp_length"` -} - -type GenerateRootUpdateRequest struct { - Nonce string - Key string -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_health.go b/vendor/github.com/hashicorp/vault/http/sys_health.go deleted file mode 100644 index 02136cec..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_health.go +++ /dev/null @@ -1,202 +0,0 @@ -package http - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/vault" - "github.com/hashicorp/vault/version" -) - -func handleSysHealth(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysHealthGet(core, w, r) - case "HEAD": - handleSysHealthHead(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func fetchStatusCode(r *http.Request, field string) (int, bool, bool) { - var err error - statusCode := http.StatusOK - if statusCodeStr, statusCodeOk := r.URL.Query()[field]; statusCodeOk { - statusCode, err = strconv.Atoi(statusCodeStr[0]) - if err != nil || len(statusCodeStr) < 1 { - return http.StatusBadRequest, false, false - } - return statusCode, true, true - } - return statusCode, false, true -} - -func handleSysHealthGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - code, body, err := getSysHealth(core, r) - if err != nil { - core.Logger().Error("error checking health", "error", err) - respondError(w, http.StatusInternalServerError, nil) - return - } - - if body == nil { - respondError(w, code, nil) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - - // Generate the response - enc := json.NewEncoder(w) - enc.Encode(body) -} - -func handleSysHealthHead(core *vault.Core, w http.ResponseWriter, r *http.Request) { - code, body, err := getSysHealth(core, r) - if err != nil { - code = http.StatusInternalServerError - } - - if body != nil { - w.Header().Set("Content-Type", "application/json") - } - w.WriteHeader(code) -} - -func getSysHealth(core *vault.Core, r *http.Request) (int, *HealthResponse, error) { - // Check if being a standby is allowed for the purpose of a 200 OK - _, standbyOK := r.URL.Query()["standbyok"] - _, perfStandbyOK := r.URL.Query()["perfstandbyok"] - - uninitCode := http.StatusNotImplemented - if code, found, ok := fetchStatusCode(r, "uninitcode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - uninitCode = code - } - - sealedCode := http.StatusServiceUnavailable - if code, found, ok := fetchStatusCode(r, "sealedcode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - sealedCode = code - } - - standbyCode := http.StatusTooManyRequests // Consul warning code - if code, found, ok := fetchStatusCode(r, "standbycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - standbyCode = code - } - - activeCode := http.StatusOK - if code, found, ok := fetchStatusCode(r, "activecode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - activeCode = code - } - - drSecondaryCode := 472 // unofficial 4xx status code - if code, found, ok := fetchStatusCode(r, "drsecondarycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - drSecondaryCode = code - } - - perfStandbyCode := 473 // unofficial 4xx status code - if code, found, ok := fetchStatusCode(r, "performancestandbycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - perfStandbyCode = code - } - - ctx := context.Background() - - // Check system status - sealed := core.Sealed() - standby, _ := core.Standby() - perfStandby := core.PerfStandby() - var replicationState consts.ReplicationState - if standby { - replicationState = core.ActiveNodeReplicationState() - } else { - replicationState = core.ReplicationState() - } - - init, err := core.Initialized(ctx) - if err != nil { - return http.StatusInternalServerError, nil, err - } - - // Determine the status code - code := activeCode - switch { - case !init: - code = uninitCode - case sealed: - code = sealedCode - case replicationState.HasState(consts.ReplicationDRSecondary): - code = drSecondaryCode - case !perfStandbyOK && perfStandby: - code = perfStandbyCode - case !standbyOK && standby: - code = standbyCode - } - - // Fetch the local cluster name and identifier - var clusterName, clusterID string - if !sealed { - cluster, err := core.Cluster(ctx) - if err != nil { - return http.StatusInternalServerError, nil, err - } - if cluster == nil { - return http.StatusInternalServerError, nil, fmt.Errorf("failed to fetch cluster details") - } - clusterName = cluster.Name - clusterID = cluster.ID - } - - // Format the body - body := &HealthResponse{ - Initialized: init, - Sealed: sealed, - Standby: standby, - PerformanceStandby: perfStandby, - ReplicationPerformanceMode: replicationState.GetPerformanceString(), - ReplicationDRMode: replicationState.GetDRString(), - ServerTimeUTC: time.Now().UTC().Unix(), - Version: version.GetVersion().VersionNumber(), - ClusterName: clusterName, - ClusterID: clusterID, - } - - if init && !sealed && !standby { - body.LastWAL = vault.LastWAL(core) - } - - return code, body, nil -} - -type HealthResponse struct { - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - Standby bool `json:"standby"` - PerformanceStandby bool `json:"performance_standby"` - ReplicationPerformanceMode string `json:"replication_performance_mode"` - ReplicationDRMode string `json:"replication_dr_mode"` - ServerTimeUTC int64 `json:"server_time_utc"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` - LastWAL uint64 `json:"last_wal,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_init.go b/vendor/github.com/hashicorp/vault/http/sys_init.go deleted file mode 100644 index 39e2c555..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_init.go +++ /dev/null @@ -1,165 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/vault" -) - -func handleSysInit(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysInitGet(core, w, r) - case "PUT", "POST": - handleSysInitPut(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysInitGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - init, err := core.Initialized(context.Background()) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - respondOk(w, &InitStatusResponse{ - Initialized: init, - }) -} - -func handleSysInitPut(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - // Parse the request - var req InitRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - // Initialize - barrierConfig := &vault.SealConfig{ - SecretShares: req.SecretShares, - SecretThreshold: req.SecretThreshold, - StoredShares: req.StoredShares, - PGPKeys: req.PGPKeys, - } - - recoveryConfig := &vault.SealConfig{ - SecretShares: req.RecoveryShares, - SecretThreshold: req.RecoveryThreshold, - PGPKeys: req.RecoveryPGPKeys, - } - - // N.B. Although the core is capable of handling situations where some keys - // are stored and some aren't, in practice, replication + HSMs makes this - // extremely hard to reason about, to the point that it will probably never - // be supported. The reason is that each HSM needs to encode the master key - // separately, which means the shares must be generated independently, - // which means both that the shares will be different *AND* there would - // need to be a way to actually allow fetching of the generated keys by - // operators. - if core.SealAccess().StoredKeysSupported() { - if len(barrierConfig.PGPKeys) > 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("PGP keys not supported when storing shares")) - return - } - barrierConfig.SecretShares = 1 - barrierConfig.SecretThreshold = 1 - barrierConfig.StoredShares = 1 - core.Logger().Warn("stored keys supported on init, forcing shares/threshold to 1") - } else { - if barrierConfig.StoredShares > 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("stored keys are not supported by the current seal type")) - return - } - } - - if len(barrierConfig.PGPKeys) > 0 && len(barrierConfig.PGPKeys) != barrierConfig.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys")) - return - } - - if core.SealAccess().RecoveryKeySupported() { - if len(recoveryConfig.PGPKeys) > 0 && len(recoveryConfig.PGPKeys) != recoveryConfig.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys for recovery")) - return - } - } - - initParams := &vault.InitParams{ - BarrierConfig: barrierConfig, - RecoveryConfig: recoveryConfig, - RootTokenPGPKey: req.RootTokenPGPKey, - } - - result, initErr := core.Initialize(ctx, initParams) - if initErr != nil { - if !errwrap.ContainsType(initErr, new(vault.NonFatalError)) { - respondError(w, http.StatusBadRequest, initErr) - return - } else { - // Add a warnings field? The error will be logged in the vault log - // already. - } - } - - // Encode the keys - keys := make([]string, 0, len(result.SecretShares)) - keysB64 := make([]string, 0, len(result.SecretShares)) - for _, k := range result.SecretShares { - keys = append(keys, hex.EncodeToString(k)) - keysB64 = append(keysB64, base64.StdEncoding.EncodeToString(k)) - } - - resp := &InitResponse{ - Keys: keys, - KeysB64: keysB64, - RootToken: result.RootToken, - } - - if len(result.RecoveryShares) > 0 { - resp.RecoveryKeys = make([]string, 0, len(result.RecoveryShares)) - resp.RecoveryKeysB64 = make([]string, 0, len(result.RecoveryShares)) - for _, k := range result.RecoveryShares { - resp.RecoveryKeys = append(resp.RecoveryKeys, hex.EncodeToString(k)) - resp.RecoveryKeysB64 = append(resp.RecoveryKeysB64, base64.StdEncoding.EncodeToString(k)) - } - } - - core.UnsealWithStoredKeys(ctx) - - respondOk(w, resp) -} - -type InitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - RecoveryShares int `json:"recovery_shares"` - RecoveryThreshold int `json:"recovery_threshold"` - RecoveryPGPKeys []string `json:"recovery_pgp_keys"` - RootTokenPGPKey string `json:"root_token_pgp_key"` -} - -type InitResponse struct { - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - RecoveryKeys []string `json:"recovery_keys,omitempty"` - RecoveryKeysB64 []string `json:"recovery_keys_base64,omitempty"` - RootToken string `json:"root_token"` -} - -type InitStatusResponse struct { - Initialized bool `json:"initialized"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_leader.go b/vendor/github.com/hashicorp/vault/http/sys_leader.go deleted file mode 100644 index 76ba92b2..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_leader.go +++ /dev/null @@ -1,56 +0,0 @@ -package http - -import ( - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/vault" -) - -func handleSysLeader(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysLeaderGet(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysLeaderGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - haEnabled := true - isLeader, address, clusterAddr, err := core.Leader() - if errwrap.Contains(err, vault.ErrHANotEnabled.Error()) { - haEnabled = false - err = nil - } - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - resp := &LeaderResponse{ - HAEnabled: haEnabled, - IsSelf: isLeader, - LeaderAddress: address, - LeaderClusterAddress: clusterAddr, - PerfStandby: core.PerfStandby(), - } - if resp.PerfStandby { - resp.PerfStandbyLastRemoteWAL = vault.LastRemoteWAL(core) - } else if isLeader || !haEnabled { - resp.LastWAL = vault.LastWAL(core) - } - - respondOk(w, resp) -} - -type LeaderResponse struct { - HAEnabled bool `json:"ha_enabled"` - IsSelf bool `json:"is_self"` - LeaderAddress string `json:"leader_address"` - LeaderClusterAddress string `json:"leader_cluster_address"` - PerfStandby bool `json:"performance_standby"` - PerfStandbyLastRemoteWAL uint64 `json:"performance_standby_last_remote_wal"` - LastWAL uint64 `json:"last_wal,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_rekey.go b/vendor/github.com/hashicorp/vault/http/sys_rekey.go deleted file mode 100644 index 54149c44..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_rekey.go +++ /dev/null @@ -1,411 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/vault" -) - -func handleSysRekeyInit(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - repState := core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - respondError(w, http.StatusBadRequest, - fmt.Errorf("rekeying can only be performed on the primary cluster when replication is activated")) - return - } - - ctx, cancel := core.GetContext() - defer cancel() - - switch { - case recovery && !core.SealAccess().RecoveryKeySupported(): - respondError(w, http.StatusBadRequest, fmt.Errorf("recovery rekeying not supported")) - case r.Method == "GET": - handleSysRekeyInitGet(ctx, core, recovery, w, r) - case r.Method == "POST" || r.Method == "PUT": - handleSysRekeyInitPut(ctx, core, recovery, w, r) - case r.Method == "DELETE": - handleSysRekeyInitDelete(ctx, core, recovery, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysRekeyInitGet(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - barrierConfig, barrierConfErr := core.SealAccess().BarrierConfig(ctx) - if barrierConfErr != nil { - respondError(w, http.StatusInternalServerError, barrierConfErr) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - // Get the rekey configuration - rekeyConf, err := core.RekeyConfig(recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - sealThreshold, err := core.RekeyThreshold(ctx, recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - // Format the status - status := &RekeyStatusResponse{ - Started: false, - T: 0, - N: 0, - Required: sealThreshold, - } - if rekeyConf != nil { - // Get the progress - started, progress, err := core.RekeyProgress(recovery, false) - if err != nil { - respondError(w, err.Code(), err) - return - } - - status.Nonce = rekeyConf.Nonce - status.Started = started - status.T = rekeyConf.SecretThreshold - status.N = rekeyConf.SecretShares - status.Progress = progress - status.VerificationRequired = rekeyConf.VerificationRequired - status.VerificationNonce = rekeyConf.VerificationNonce - if rekeyConf.PGPKeys != nil && len(rekeyConf.PGPKeys) != 0 { - pgpFingerprints, err := pgpkeys.GetFingerprints(rekeyConf.PGPKeys, nil) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - status.PGPFingerprints = pgpFingerprints - status.Backup = rekeyConf.Backup - } - } - respondOk(w, status) -} - -func handleSysRekeyInitPut(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - // Parse the request - var req RekeyRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - if req.Backup && len(req.PGPKeys) == 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("cannot request a backup of the new keys without providing PGP keys for encryption")) - return - } - - if len(req.PGPKeys) > 0 && len(req.PGPKeys) != req.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys for rekey")) - return - } - - // Initialize the rekey - err := core.RekeyInit(&vault.SealConfig{ - SecretShares: req.SecretShares, - SecretThreshold: req.SecretThreshold, - StoredShares: req.StoredShares, - PGPKeys: req.PGPKeys, - Backup: req.Backup, - VerificationRequired: req.RequireVerification, - }, recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - handleSysRekeyInitGet(ctx, core, recovery, w, r) -} - -func handleSysRekeyInitDelete(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - if err := core.RekeyCancel(recovery); err != nil { - respondError(w, err.Code(), err) - return - } - respondOk(w, nil) -} - -func handleSysRekeyUpdate(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - // Parse the request - var req RekeyUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on rekey - result, rekeyErr := core.RekeyUpdate(ctx, key, req.Nonce, recovery) - if rekeyErr != nil { - respondError(w, rekeyErr.Code(), rekeyErr) - return - } - - // Format the response - resp := &RekeyUpdateResponse{} - if result != nil { - resp.Complete = true - resp.Nonce = req.Nonce - resp.Backup = result.Backup - resp.PGPFingerprints = result.PGPFingerprints - resp.VerificationRequired = result.VerificationRequired - resp.VerificationNonce = result.VerificationNonce - - // Encode the keys - keys := make([]string, 0, len(result.SecretShares)) - keysB64 := make([]string, 0, len(result.SecretShares)) - for _, k := range result.SecretShares { - keys = append(keys, hex.EncodeToString(k)) - keysB64 = append(keysB64, base64.StdEncoding.EncodeToString(k)) - } - resp.Keys = keys - resp.KeysB64 = keysB64 - respondOk(w, resp) - } else { - handleSysRekeyInitGet(ctx, core, recovery, w, r) - } - }) -} - -func handleSysRekeyVerify(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - repState := core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - respondError(w, http.StatusBadRequest, - fmt.Errorf("rekeying can only be performed on the primary cluster when replication is activated")) - return - } - - ctx, cancel := core.GetContext() - defer cancel() - - switch { - case recovery && !core.SealAccess().RecoveryKeySupported(): - respondError(w, http.StatusBadRequest, fmt.Errorf("recovery rekeying not supported")) - case r.Method == "GET": - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) - case r.Method == "POST" || r.Method == "PUT": - handleSysRekeyVerifyPut(ctx, core, recovery, w, r) - case r.Method == "DELETE": - handleSysRekeyVerifyDelete(ctx, core, recovery, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysRekeyVerifyGet(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - barrierConfig, barrierConfErr := core.SealAccess().BarrierConfig(ctx) - if barrierConfErr != nil { - respondError(w, http.StatusInternalServerError, barrierConfErr) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - // Get the rekey configuration - rekeyConf, err := core.RekeyConfig(recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - if rekeyConf == nil { - respondError(w, http.StatusBadRequest, errors.New("no rekey configuration found")) - return - } - - // Get the progress - started, progress, err := core.RekeyProgress(recovery, true) - if err != nil { - respondError(w, err.Code(), err) - return - } - - // Format the status - status := &RekeyVerificationStatusResponse{ - Started: started, - Nonce: rekeyConf.VerificationNonce, - T: rekeyConf.SecretThreshold, - N: rekeyConf.SecretShares, - Progress: progress, - } - respondOk(w, status) -} - -func handleSysRekeyVerifyDelete(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - if err := core.RekeyVerifyRestart(recovery); err != nil { - respondError(w, err.Code(), err) - return - } - - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) -} - -func handleSysRekeyVerifyPut(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - // Parse the request - var req RekeyVerificationUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on rekey - result, rekeyErr := core.RekeyVerify(ctx, key, req.Nonce, recovery) - if rekeyErr != nil { - respondError(w, rekeyErr.Code(), rekeyErr) - return - } - - // Format the response - resp := &RekeyVerificationUpdateResponse{} - if result != nil { - resp.Complete = true - resp.Nonce = result.Nonce - respondOk(w, resp) - } else { - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) - } -} - -type RekeyRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - Backup bool `json:"backup"` - RequireVerification bool `json:"require_verification"` -} - -type RekeyStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Required int `json:"required"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyUpdateRequest struct { - Nonce string - Key string -} - -type RekeyUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyVerificationUpdateRequest struct { - Nonce string `json:"nonce"` - Key string `json:"key"` -} - -type RekeyVerificationStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` -} - -type RekeyVerificationUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_seal.go b/vendor/github.com/hashicorp/vault/http/sys_seal.go deleted file mode 100644 index fd4e2f9e..00000000 --- a/vendor/github.com/hashicorp/vault/http/sys_seal.go +++ /dev/null @@ -1,261 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" - "github.com/hashicorp/vault/version" -) - -func handleSysSeal(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - switch req.Operation { - case logical.UpdateOperation: - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Seal with the token above - // We use context.Background since there won't be a request context if the node isn't active - if err := core.SealWithRequest(r.Context(), req); err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - respondError(w, http.StatusForbidden, err) - return - } - respondError(w, http.StatusInternalServerError, err) - return - } - - respondOk(w, nil) - }) -} - -func handleSysStepDown(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - switch req.Operation { - case logical.UpdateOperation: - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Seal with the token above - if err := core.StepDown(r.Context(), req); err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - respondError(w, http.StatusForbidden, err) - return - } - respondError(w, http.StatusInternalServerError, err) - return - } - - respondOk(w, nil) - }) -} - -func handleSysUnseal(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "PUT": - case "POST": - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Parse the request - var req UnsealRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - if req.Reset { - if !core.Sealed() { - respondError(w, http.StatusBadRequest, errors.New("vault is unsealed")) - return - } - core.ResetUnsealProcess() - handleSysSealStatusRaw(core, w, r) - return - } - - isInSealMigration := core.IsInSealMigration() - if !req.Migrate && isInSealMigration { - respondError( - w, http.StatusBadRequest, - errors.New("'migrate' parameter must be set true in JSON body when in seal migration mode")) - return - } - if req.Migrate && !isInSealMigration { - respondError( - w, http.StatusBadRequest, - errors.New("'migrate' parameter set true in JSON body when not in seal migration mode")) - return - } - - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON, or 'reset' set to true")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - // Attempt the unseal - if core.SealAccess().RecoveryKeySupported() { - _, err = core.UnsealWithRecoveryKeys(key) - } else { - _, err = core.Unseal(key) - } - if err != nil { - switch { - case errwrap.ContainsType(err, new(vault.ErrInvalidKey)): - case errwrap.Contains(err, vault.ErrBarrierInvalidKey.Error()): - case errwrap.Contains(err, vault.ErrBarrierNotInit.Error()): - case errwrap.Contains(err, vault.ErrBarrierSealed.Error()): - case errwrap.Contains(err, consts.ErrStandby.Error()): - default: - respondError(w, http.StatusInternalServerError, err) - return - } - respondError(w, http.StatusBadRequest, err) - return - } - - // Return the seal status - handleSysSealStatusRaw(core, w, r) - }) -} - -func handleSysSealStatus(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - handleSysSealStatusRaw(core, w, r) - }) -} - -func handleSysSealStatusRaw(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - sealed := core.Sealed() - - var sealConfig *vault.SealConfig - var err error - if core.SealAccess().RecoveryKeySupported() { - sealConfig, err = core.SealAccess().RecoveryConfig(ctx) - } else { - sealConfig, err = core.SealAccess().BarrierConfig(ctx) - } - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - if sealConfig == nil { - respondOk(w, &SealStatusResponse{ - Type: core.SealAccess().BarrierType(), - Initialized: false, - Sealed: true, - RecoverySeal: core.SealAccess().RecoveryKeySupported(), - }) - return - } - - // Fetch the local cluster name and identifier - var clusterName, clusterID string - if !sealed { - cluster, err := core.Cluster(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if cluster == nil { - respondError(w, http.StatusInternalServerError, fmt.Errorf("failed to fetch cluster details")) - return - } - clusterName = cluster.Name - clusterID = cluster.ID - } - - progress, nonce := core.SecretProgress() - - respondOk(w, &SealStatusResponse{ - Type: sealConfig.Type, - Initialized: true, - Sealed: sealed, - T: sealConfig.SecretThreshold, - N: sealConfig.SecretShares, - Progress: progress, - Nonce: nonce, - Version: version.GetVersion().VersionNumber(), - Migration: core.IsInSealMigration(), - ClusterName: clusterName, - ClusterID: clusterID, - RecoverySeal: core.SealAccess().RecoveryKeySupported(), - }) -} - -type SealStatusResponse struct { - Type string `json:"type"` - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Nonce string `json:"nonce"` - Version string `json:"version"` - Migration bool `json:"migration"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` - RecoverySeal bool `json:"recovery_seal"` -} - -// Note: because we didn't provide explicit tagging in the past we can't do it -// now because if it then no longer accepts capitalized versions it could break -// clients -type UnsealRequest struct { - Key string - Reset bool - Migrate bool -} diff --git a/vendor/github.com/hashicorp/vault/http/testing.go b/vendor/github.com/hashicorp/vault/http/testing.go deleted file mode 100644 index ebc2edd1..00000000 --- a/vendor/github.com/hashicorp/vault/http/testing.go +++ /dev/null @@ -1,67 +0,0 @@ -package http - -import ( - "fmt" - "net" - "net/http" - "testing" - - "github.com/hashicorp/vault/vault" -) - -func TestListener(tb testing.TB) (net.Listener, string) { - fail := func(format string, args ...interface{}) { - panic(fmt.Sprintf(format, args...)) - } - if tb != nil { - fail = tb.Fatalf - } - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - fail("err: %s", err) - } - addr := "http://" + ln.Addr().String() - return ln, addr -} - -func TestServerWithListenerAndProperties(tb testing.TB, ln net.Listener, addr string, core *vault.Core, props *vault.HandlerProperties) { - // Create a muxer to handle our requests so that we can authenticate - // for tests. - mux := http.NewServeMux() - mux.Handle("/_test/auth", http.HandlerFunc(testHandleAuth)) - mux.Handle("/", Handler(props)) - - server := &http.Server{ - Addr: ln.Addr().String(), - Handler: mux, - ErrorLog: core.Logger().StandardLogger(nil), - } - go server.Serve(ln) -} - -func TestServerWithListener(tb testing.TB, ln net.Listener, addr string, core *vault.Core) { - // Create a muxer to handle our requests so that we can authenticate - // for tests. - props := &vault.HandlerProperties{ - Core: core, - MaxRequestSize: DefaultMaxRequestSize, - } - TestServerWithListenerAndProperties(tb, ln, addr, core, props) -} - -func TestServer(tb testing.TB, core *vault.Core) (net.Listener, string) { - ln, addr := TestListener(tb) - TestServerWithListener(tb, ln, addr, core) - return ln, addr -} - -func TestServerAuth(tb testing.TB, addr string, token string) { - if _, err := http.Get(addr + "/_test/auth?token=" + token); err != nil { - tb.Fatalf("error authenticating: %s", err) - } -} - -func testHandleAuth(w http.ResponseWriter, req *http.Request) { - respondOk(w, nil) -} diff --git a/vendor/github.com/hashicorp/vault/http/util.go b/vendor/github.com/hashicorp/vault/http/util.go deleted file mode 100644 index ee7c546c..00000000 --- a/vendor/github.com/hashicorp/vault/http/util.go +++ /dev/null @@ -1,22 +0,0 @@ -package http - -import ( - "net/http" - - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/vault" -) - -var ( - adjustRequest = func(c *vault.Core, r *http.Request) (*http.Request, int) { - return r.WithContext(namespace.ContextWithNamespace(r.Context(), namespace.RootNamespace)), 0 - } - - genericWrapping = func(core *vault.Core, in http.Handler, props *vault.HandlerProperties) http.Handler { - // Wrap the help wrapped handler with another layer with a generic - // handler - return wrapGenericHandler(core, in, props.MaxRequestSize, props.MaxRequestDuration) - } - - additionalRoutes = func(mux *http.ServeMux, core *vault.Core) {} -) diff --git a/vendor/github.com/hashicorp/vault/logical/auth.go b/vendor/github.com/hashicorp/vault/logical/auth.go deleted file mode 100644 index 7b12e399..00000000 --- a/vendor/github.com/hashicorp/vault/logical/auth.go +++ /dev/null @@ -1,99 +0,0 @@ -package logical - -import ( - "fmt" - "time" - - "github.com/hashicorp/go-sockaddr" -) - -// Auth is the resulting authentication information that is part of -// Response for credential backends. -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"` - - // 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"` -} - -func (a *Auth) GoString() string { - return fmt.Sprintf("*%#v", *a) -} diff --git a/vendor/github.com/hashicorp/vault/logical/connection.go b/vendor/github.com/hashicorp/vault/logical/connection.go deleted file mode 100644 index a504b10c..00000000 --- a/vendor/github.com/hashicorp/vault/logical/connection.go +++ /dev/null @@ -1,15 +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"` - - // ConnState is the TLS connection state if applicable. - ConnState *tls.ConnectionState `sentinel:""` -} diff --git a/vendor/github.com/hashicorp/vault/logical/error.go b/vendor/github.com/hashicorp/vault/logical/error.go deleted file mode 100644 index a264f979..00000000 --- a/vendor/github.com/hashicorp/vault/logical/error.go +++ /dev/null @@ -1,90 +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") - - // 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") -) - -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 -// unforseen 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/logical/framework/backend.go b/vendor/github.com/hashicorp/vault/logical/framework/backend.go deleted file mode 100644 index 52b490b5..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/backend.go +++ /dev/null @@ -1,608 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "sort" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" -) - -// Backend is an implementation of logical.Backend that allows -// the implementer to code a backend using a much more programmer-friendly -// framework that handles a lot of the routing and validation for you. -// -// This is recommended over implementing logical.Backend directly. -type Backend struct { - // Help is the help text that is shown when a help request is made - // on the root of this resource. The root help is special since we - // show all the paths that can be requested. - Help string - - // Paths are the various routes that the backend responds to. - // This cannot be modified after construction (i.e. dynamically changing - // paths, including adding or removing, is not allowed once the - // backend is in use). - // - // PathsSpecial is the list of path patterns that denote the - // paths above that require special privileges. These can't be - // regular expressions, it is either exact match or prefix match. - // For prefix match, append '*' as a suffix. - Paths []*Path - PathsSpecial *logical.Paths - - // Secrets is the list of secret types that this backend can - // return. It is used to automatically generate proper responses, - // and ease specifying callbacks for revocation, renewal, etc. - Secrets []*Secret - - // PeriodicFunc is the callback, which if set, will be invoked when the - // periodic timer of RollbackManager ticks. This can be used by - // backends to do anything it wishes to do periodically. - // - // PeriodicFunc can be invoked to, say to periodically delete stale - // entries in backend's storage, while the backend is still being used. - // (Note the different of this action from what `Clean` does, which is - // invoked just before the backend is unmounted). - PeriodicFunc periodicFunc - - // WALRollback is called when a WAL entry (see wal.go) has to be rolled - // back. It is called with the data from the entry. - // - // WALRollbackMinAge is the minimum age of a WAL entry before it is attempted - // to be rolled back. This should be longer than the maximum time it takes - // to successfully create a secret. - WALRollback WALRollbackFunc - WALRollbackMinAge time.Duration - - // Clean is called on unload to clean up e.g any existing connections - // to the backend, if required. - Clean CleanupFunc - - // Invalidate is called when a keys is modified if required - Invalidate InvalidateFunc - - // AuthRenew is the callback to call when a RenewRequest for an - // authentication comes in. By default, renewal won't be allowed. - // See the built-in AuthRenew helpers in lease.go for common callbacks. - AuthRenew OperationFunc - - // Type is the logical.BackendType for the backend implementation - BackendType logical.BackendType - - logger log.Logger - system logical.SystemView - once sync.Once - pathsRe []*regexp.Regexp -} - -// periodicFunc is the callback called when the RollbackManager's timer ticks. -// This can be utilized by the backends to do anything it wants. -type periodicFunc func(context.Context, *logical.Request) error - -// OperationFunc is the callback called for an operation on a path. -type OperationFunc func(context.Context, *logical.Request, *FieldData) (*logical.Response, error) - -// ExistenceFunc is the callback called for an existence check on a path. -type ExistenceFunc func(context.Context, *logical.Request, *FieldData) (bool, error) - -// WALRollbackFunc is the callback for rollbacks. -type WALRollbackFunc func(context.Context, *logical.Request, string, interface{}) error - -// CleanupFunc is the callback for backend unload. -type CleanupFunc func(context.Context) - -// InvalidateFunc is the callback for backend key invalidation. -type InvalidateFunc func(context.Context, string) - -// HandleExistenceCheck is the logical.Backend implementation. -func (b *Backend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (checkFound bool, exists bool, err error) { - b.once.Do(b.init) - - // Ensure we are only doing this when one of the correct operations is in play - switch req.Operation { - case logical.CreateOperation: - case logical.UpdateOperation: - default: - return false, false, fmt.Errorf("incorrect operation type %v for an existence check", req.Operation) - } - - // Find the matching route - path, captures := b.route(req.Path) - if path == nil { - return false, false, logical.ErrUnsupportedPath - } - - if path.ExistenceCheck == nil { - return false, false, nil - } - - checkFound = true - - // Build up the data for the route, with the URL taking priority - // for the fields over the PUT data. - raw := make(map[string]interface{}, len(path.Fields)) - for k, v := range req.Data { - raw[k] = v - } - for k, v := range captures { - raw[k] = v - } - - fd := FieldData{ - Raw: raw, - Schema: path.Fields} - - err = fd.Validate() - if err != nil { - return false, false, errutil.UserError{Err: err.Error()} - } - - // Call the callback with the request and the data - exists, err = path.ExistenceCheck(ctx, req, &fd) - return -} - -// HandleRequest is the logical.Backend implementation. -func (b *Backend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - b.once.Do(b.init) - - // Check for special cased global operations. These don't route - // to a specific Path. - switch req.Operation { - case logical.RenewOperation: - fallthrough - case logical.RevokeOperation: - return b.handleRevokeRenew(ctx, req) - case logical.RollbackOperation: - return b.handleRollback(ctx, req) - } - - // If the path is empty and it is a help operation, handle that. - if req.Path == "" && req.Operation == logical.HelpOperation { - return b.handleRootHelp() - } - - // Find the matching route - path, captures := b.route(req.Path) - if path == nil { - return nil, logical.ErrUnsupportedPath - } - - // Check if a feature is required and if the license has that feature - if path.FeatureRequired != license.FeatureNone { - hasFeature := b.system.HasFeature(path.FeatureRequired) - if !hasFeature { - return nil, logical.CodedError(401, "Feature Not Enabled") - } - } - - // Build up the data for the route, with the URL taking priority - // for the fields over the PUT data. - raw := make(map[string]interface{}, len(path.Fields)) - for k, v := range req.Data { - raw[k] = v - } - for k, v := range captures { - raw[k] = v - } - - // Look up the callback for this operation, preferring the - // path.Operations definition if present. - var callback OperationFunc - - if path.Operations != nil { - if op, ok := path.Operations[req.Operation]; ok { - callback = op.Handler() - } - } else { - callback = path.Callbacks[req.Operation] - } - ok := callback != nil - - if !ok { - if req.Operation == logical.HelpOperation { - callback = path.helpCallback(b) - ok = true - } - } - if !ok { - return nil, logical.ErrUnsupportedOperation - } - - fd := FieldData{ - Raw: raw, - Schema: path.Fields} - - if req.Operation != logical.HelpOperation { - err := fd.Validate() - if err != nil { - return nil, err - } - } - - return callback(ctx, req, &fd) -} - -// SpecialPaths is the logical.Backend implementation. -func (b *Backend) SpecialPaths() *logical.Paths { - return b.PathsSpecial -} - -// Cleanup is used to release resources and prepare to stop the backend -func (b *Backend) Cleanup(ctx context.Context) { - if b.Clean != nil { - b.Clean(ctx) - } -} - -// InvalidateKey is used to clear caches and reset internal state on key changes -func (b *Backend) InvalidateKey(ctx context.Context, key string) { - if b.Invalidate != nil { - b.Invalidate(ctx, key) - } -} - -// Setup is used to initialize the backend with the initial backend configuration -func (b *Backend) Setup(ctx context.Context, config *logical.BackendConfig) error { - b.logger = config.Logger - b.system = config.System - return nil -} - -// Logger can be used to get the logger. If no logger has been set, -// the logs will be discarded. -func (b *Backend) Logger() log.Logger { - if b.logger != nil { - return b.logger - } - - return logging.NewVaultLoggerWithWriter(ioutil.Discard, log.NoLevel) -} - -// System returns the backend's system view. -func (b *Backend) System() logical.SystemView { - return b.system -} - -// Type returns the backend type -func (b *Backend) Type() logical.BackendType { - return b.BackendType -} - -// Route looks up the path that would be used for a given path string. -func (b *Backend) Route(path string) *Path { - result, _ := b.route(path) - return result -} - -// Secret is used to look up the secret with the given type. -func (b *Backend) Secret(k string) *Secret { - for _, s := range b.Secrets { - if s.Type == k { - return s - } - } - - return nil -} - -func (b *Backend) init() { - b.pathsRe = make([]*regexp.Regexp, len(b.Paths)) - for i, p := range b.Paths { - if len(p.Pattern) == 0 { - panic(fmt.Sprintf("Routing pattern cannot be blank")) - } - // Automatically anchor the pattern - if p.Pattern[0] != '^' { - p.Pattern = "^" + p.Pattern - } - if p.Pattern[len(p.Pattern)-1] != '$' { - p.Pattern = p.Pattern + "$" - } - b.pathsRe[i] = regexp.MustCompile(p.Pattern) - } -} - -func (b *Backend) route(path string) (*Path, map[string]string) { - b.once.Do(b.init) - - for i, re := range b.pathsRe { - matches := re.FindStringSubmatch(path) - if matches == nil { - continue - } - - // We have a match, determine the mapping of the captures and - // store that for returning. - var captures map[string]string - path := b.Paths[i] - if captureNames := re.SubexpNames(); len(captureNames) > 1 { - captures = make(map[string]string, len(captureNames)) - for i, name := range captureNames { - if name != "" { - captures[name] = matches[i] - } - } - } - - return path, captures - } - - return nil, nil -} - -func (b *Backend) handleRootHelp() (*logical.Response, error) { - // Build a mapping of the paths and get the paths alphabetized to - // make the output prettier. - pathsMap := make(map[string]*Path) - paths := make([]string, 0, len(b.Paths)) - for i, p := range b.pathsRe { - paths = append(paths, p.String()) - pathsMap[p.String()] = b.Paths[i] - } - sort.Strings(paths) - - // Build the path data - pathData := make([]rootHelpTemplatePath, 0, len(paths)) - for _, route := range paths { - p := pathsMap[route] - pathData = append(pathData, rootHelpTemplatePath{ - Path: route, - Help: strings.TrimSpace(p.HelpSynopsis), - }) - } - - help, err := executeTemplate(rootHelpTemplate, &rootHelpTemplateData{ - Help: strings.TrimSpace(b.Help), - Paths: pathData, - }) - if err != nil { - return nil, err - } - - // Build OpenAPI response for the entire backend - doc := NewOASDocument() - if err := documentPaths(b, doc); err != nil { - b.Logger().Warn("error generating OpenAPI", "error", err) - } - - return logical.HelpResponse(help, nil, doc), nil -} - -func (b *Backend) handleRevokeRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - // Special case renewal of authentication for credential backends - if req.Operation == logical.RenewOperation && req.Auth != nil { - return b.handleAuthRenew(ctx, req) - } - - if req.Secret == nil { - return nil, fmt.Errorf("request has no secret") - } - - rawSecretType, ok := req.Secret.InternalData["secret_type"] - if !ok { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - secretType, ok := rawSecretType.(string) - if !ok { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - - secret := b.Secret(secretType) - if secret == nil { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - - switch req.Operation { - case logical.RenewOperation: - return secret.HandleRenew(ctx, req) - case logical.RevokeOperation: - return secret.HandleRevoke(ctx, req) - default: - return nil, fmt.Errorf("invalid operation for revoke/renew: %q", req.Operation) - } -} - -// handleRollback invokes the PeriodicFunc set on the backend. It also does a WAL rollback operation. -func (b *Backend) handleRollback(ctx context.Context, req *logical.Request) (*logical.Response, error) { - // Response is not expected from the periodic operation. - if b.PeriodicFunc != nil { - if err := b.PeriodicFunc(ctx, req); err != nil { - return nil, err - } - } - - return b.handleWALRollback(ctx, req) -} - -func (b *Backend) handleAuthRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.AuthRenew == nil { - return logical.ErrorResponse("this auth type doesn't support renew"), nil - } - - return b.AuthRenew(ctx, req, nil) -} - -func (b *Backend) handleWALRollback(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.WALRollback == nil { - return nil, logical.ErrUnsupportedOperation - } - - var merr error - keys, err := ListWAL(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - if len(keys) == 0 { - return nil, nil - } - - // Calculate the minimum time that the WAL entries could be - // created in order to be rolled back. - age := b.WALRollbackMinAge - if age == 0 { - age = 10 * time.Minute - } - minAge := time.Now().Add(-1 * age) - if _, ok := req.Data["immediate"]; ok { - minAge = time.Now().Add(1000 * time.Hour) - } - - for _, k := range keys { - entry, err := GetWAL(ctx, req.Storage, k) - if err != nil { - merr = multierror.Append(merr, err) - continue - } - if entry == nil { - continue - } - - // If the entry isn't old enough, then don't roll it back - if !time.Unix(entry.CreatedAt, 0).Before(minAge) { - continue - } - - // Attempt a WAL rollback - err = b.WALRollback(ctx, req, entry.Kind, entry.Data) - if err != nil { - err = errwrap.Wrapf(fmt.Sprintf("error rolling back %q entry: {{err}}", entry.Kind), err) - } - if err == nil { - err = DeleteWAL(ctx, req.Storage, k) - } - if err != nil { - merr = multierror.Append(merr, err) - } - } - - if merr == nil { - return nil, nil - } - - return logical.ErrorResponse(merr.Error()), nil -} - -// FieldSchema is a basic schema to describe the format of a path field. -type FieldSchema struct { - Type FieldType - Default interface{} - Description string - Required bool - Deprecated bool -} - -// DefaultOrZero returns the default value if it is set, or otherwise -// the zero value of the type. -func (s *FieldSchema) DefaultOrZero() interface{} { - if s.Default != nil { - switch s.Type { - case TypeDurationSecond: - var result int - switch inp := s.Default.(type) { - case nil: - return s.Type.Zero() - case int: - result = inp - case int64: - result = int(inp) - case float32: - result = int(inp) - case float64: - result = int(inp) - case string: - dur, err := parseutil.ParseDurationSecond(inp) - if err != nil { - return s.Type.Zero() - } - result = int(dur.Seconds()) - case json.Number: - valInt64, err := inp.Int64() - if err != nil { - return s.Type.Zero() - } - result = int(valInt64) - default: - return s.Type.Zero() - } - return result - - default: - return s.Default - } - } - - return s.Type.Zero() -} - -// Zero returns the correct zero-value for a specific FieldType -func (t FieldType) Zero() interface{} { - switch t { - case TypeString, TypeNameString, TypeLowerCaseString: - return "" - case TypeInt: - return 0 - case TypeBool: - return false - case TypeMap: - return map[string]interface{}{} - case TypeKVPairs: - return map[string]string{} - case TypeDurationSecond: - return 0 - case TypeSlice: - return []interface{}{} - case TypeStringSlice, TypeCommaStringSlice: - return []string{} - case TypeCommaIntSlice: - return []int{} - case TypeHeader: - return http.Header{} - default: - panic("unknown type: " + t.String()) - } -} - -type rootHelpTemplateData struct { - Help string - Paths []rootHelpTemplatePath -} - -type rootHelpTemplatePath struct { - Path string - Help string -} - -const rootHelpTemplate = ` -## DESCRIPTION - -{{.Help}} - -## PATHS - -The following paths are supported by this backend. To view help for -any of the paths below, use the help command with any route matching -the path pattern. Note that depending on the policy of your auth token, -you may or may not be able to access certain paths. - -{{range .Paths}}{{indent 4 .Path}} -{{indent 8 .Help}} - -{{end}} - -` diff --git a/vendor/github.com/hashicorp/vault/logical/framework/field_data.go b/vendor/github.com/hashicorp/vault/logical/framework/field_data.go deleted file mode 100644 index ae4eefa7..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/field_data.go +++ /dev/null @@ -1,410 +0,0 @@ -package framework - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/mitchellh/mapstructure" -) - -// FieldData is the structure passed to the callback to handle a path -// containing the populated parameters for fields. This should be used -// instead of the raw (*vault.Request).Data to access data in a type-safe -// way. -type FieldData struct { - Raw map[string]interface{} - Schema map[string]*FieldSchema -} - -// Validate cycles through raw data and validate conversions in -// the schema, so we don't get an error/panic later when -// trying to get data out. Data not in the schema is not -// an error at this point, so we don't worry about it. -func (d *FieldData) Validate() error { - for field, value := range d.Raw { - - schema, ok := d.Schema[field] - if !ok { - continue - } - - switch schema.Type { - case TypeBool, TypeInt, TypeMap, TypeDurationSecond, TypeString, TypeLowerCaseString, - TypeNameString, TypeSlice, TypeStringSlice, TypeCommaStringSlice, - TypeKVPairs, TypeCommaIntSlice, TypeHeader: - _, _, err := d.getPrimitive(field, schema) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error converting input %v for field %q: {{err}}", value, field), err) - } - default: - return fmt.Errorf("unknown field type %q for field %q", schema.Type, field) - } - } - - return nil -} - -// Get gets the value for the given field. If the key is an invalid field, -// FieldData will panic. If you want a safer version of this method, use -// GetOk. If the field k is not set, the default value (if set) will be -// returned, otherwise the zero value will be returned. -func (d *FieldData) Get(k string) interface{} { - schema, ok := d.Schema[k] - if !ok { - panic(fmt.Sprintf("field %s not in the schema", k)) - } - - // If the value can't be decoded, use the zero or default value for the field - // type - value, ok := d.GetOk(k) - if !ok || value == nil { - value = schema.DefaultOrZero() - } - - return value -} - -// GetDefaultOrZero gets the default value set on the schema for the given -// field. If there is no default value set, the zero value of the type -// will be returned. -func (d *FieldData) GetDefaultOrZero(k string) interface{} { - schema, ok := d.Schema[k] - if !ok { - panic(fmt.Sprintf("field %s not in the schema", k)) - } - - return schema.DefaultOrZero() -} - -// GetFirst gets the value for the given field names, in order from first -// to last. This can be useful for fields with a current name, and one or -// more deprecated names. The second return value will be false if the keys -// are invalid or the keys are not set at all. -func (d *FieldData) GetFirst(k ...string) (interface{}, bool) { - for _, v := range k { - if result, ok := d.GetOk(v); ok { - return result, ok - } - } - return nil, false -} - -// GetOk gets the value for the given field. The second return value will be -// false if the key is invalid or the key is not set at all. If the field k is -// set and the decoded value is nil, the default or zero value -// will be returned instead. -func (d *FieldData) GetOk(k string) (interface{}, bool) { - schema, ok := d.Schema[k] - if !ok { - return nil, false - } - - result, ok, err := d.GetOkErr(k) - if err != nil { - panic(fmt.Sprintf("error reading %s: %s", k, err)) - } - - if ok && result == nil { - result = schema.DefaultOrZero() - } - - return result, ok -} - -// GetOkErr is the most conservative of all the Get methods. It returns -// whether key is set or not, but also an error value. The error value is -// non-nil if the field doesn't exist or there was an error parsing the -// field value. -func (d *FieldData) GetOkErr(k string) (interface{}, bool, error) { - schema, ok := d.Schema[k] - if !ok { - return nil, false, fmt.Errorf("unknown field: %q", k) - } - - switch schema.Type { - case TypeBool, TypeInt, TypeMap, TypeDurationSecond, TypeString, TypeLowerCaseString, - TypeNameString, TypeSlice, TypeStringSlice, TypeCommaStringSlice, - TypeKVPairs, TypeCommaIntSlice, TypeHeader: - return d.getPrimitive(k, schema) - default: - return nil, false, - fmt.Errorf("unknown field type %q for field %q", schema.Type, k) - } -} - -func (d *FieldData) getPrimitive(k string, schema *FieldSchema) (interface{}, bool, error) { - raw, ok := d.Raw[k] - if !ok { - return nil, false, nil - } - - switch schema.Type { - case TypeBool: - var result bool - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - return result, true, nil - - case TypeInt: - var result int - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - return result, true, nil - - case TypeString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - return result, true, nil - - case TypeLowerCaseString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - return strings.ToLower(result), true, nil - - case TypeNameString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - matched, err := regexp.MatchString("^\\w(([\\w-.]+)?\\w)?$", result) - if err != nil { - return nil, false, err - } - if !matched { - return nil, false, errors.New("field does not match the formatting rules") - } - return result, true, nil - - case TypeMap: - var result map[string]interface{} - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - return result, true, nil - - case TypeDurationSecond: - var result int - switch inp := raw.(type) { - case nil: - return nil, false, nil - case int: - result = inp - case int32: - result = int(inp) - case int64: - result = int(inp) - case uint: - result = int(inp) - case uint32: - result = int(inp) - case uint64: - result = int(inp) - case float32: - result = int(inp) - case float64: - result = int(inp) - case string: - dur, err := parseutil.ParseDurationSecond(inp) - if err != nil { - return nil, false, err - } - result = int(dur.Seconds()) - case json.Number: - valInt64, err := inp.Int64() - if err != nil { - return nil, false, err - } - result = int(valInt64) - default: - return nil, false, fmt.Errorf("invalid input '%v'", raw) - } - if result < 0 { - return nil, false, fmt.Errorf("cannot provide negative value '%d'", result) - } - return result, true, nil - - case TypeCommaIntSlice: - var result []int - config := &mapstructure.DecoderConfig{ - Result: &result, - WeaklyTypedInput: true, - DecodeHook: mapstructure.StringToSliceHookFunc(","), - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, false, err - } - if err := decoder.Decode(raw); err != nil { - return nil, false, err - } - if len(result) == 0 { - return make([]int, 0), true, nil - } - return result, true, nil - - case TypeSlice: - var result []interface{} - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - if len(result) == 0 { - return make([]interface{}, 0), true, nil - } - return result, true, nil - - case TypeStringSlice: - var result []string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, false, err - } - if len(result) == 0 { - return make([]string, 0), true, nil - } - return strutil.TrimStrings(result), true, nil - - case TypeCommaStringSlice: - res, err := parseutil.ParseCommaStringSlice(raw) - if err != nil { - return nil, false, err - } - return res, true, nil - - case TypeKVPairs: - // First try to parse this as a map - var mapResult map[string]string - if err := mapstructure.WeakDecode(raw, &mapResult); err == nil { - return mapResult, true, nil - } - - // If map parse fails, parse as a string list of = delimited pairs - var listResult []string - if err := mapstructure.WeakDecode(raw, &listResult); err != nil { - return nil, false, err - } - - result := make(map[string]string, len(listResult)) - for _, keyPair := range listResult { - keyPairSlice := strings.SplitN(keyPair, "=", 2) - if len(keyPairSlice) != 2 || keyPairSlice[0] == "" { - return nil, false, fmt.Errorf("invalid key pair %q", keyPair) - } - result[keyPairSlice[0]] = keyPairSlice[1] - } - return result, true, nil - - case TypeHeader: - /* - - There are multiple ways a header could be provided: - - 1. As a map[string]interface{} that resolves to a map[string]string or map[string][]string, or a mix of both - because that's permitted for headers. - This mainly comes from the API. - - 2. As a string... - a. That contains JSON that originally was JSON, but then was base64 encoded. - b. That contains JSON, ex. `{"content-type":"text/json","accept":["encoding/json"]}`. - This mainly comes from the API and is used to save space while sending in the header. - - 3. As an array of strings that contains comma-delimited key-value pairs associated via a colon, - ex: `content-type:text/json`,`accept:encoding/json`. - This mainly comes from the CLI. - - We go through these sequentially below. - - */ - result := http.Header{} - - toHeader := func(resultMap map[string]interface{}) (http.Header, error) { - header := http.Header{} - for headerKey, headerValGroup := range resultMap { - switch typedHeader := headerValGroup.(type) { - case string: - header.Add(headerKey, typedHeader) - case []string: - for _, headerVal := range typedHeader { - header.Add(headerKey, headerVal) - } - case []interface{}: - for _, headerVal := range typedHeader { - strHeaderVal, ok := headerVal.(string) - if !ok { - // All header values should already be strings when they're being sent in. - // Even numbers and booleans will be treated as strings. - return nil, fmt.Errorf("received non-string value for header key:%s, val:%s", headerKey, headerValGroup) - } - header.Add(headerKey, strHeaderVal) - } - default: - return nil, fmt.Errorf("unrecognized type for %s", headerValGroup) - } - } - return header, nil - } - - resultMap := make(map[string]interface{}) - - // 1. Are we getting a map from the API? - if err := mapstructure.WeakDecode(raw, &resultMap); err == nil { - result, err = toHeader(resultMap) - if err != nil { - return nil, false, err - } - return result, true, nil - } - - // 2. Are we getting a JSON string? - if headerStr, ok := raw.(string); ok { - // a. Is it base64 encoded? - headerBytes, err := base64.StdEncoding.DecodeString(headerStr) - if err != nil { - // b. It's not base64 encoded, it's a straight-out JSON string. - headerBytes = []byte(headerStr) - } - if err := json.NewDecoder(bytes.NewReader(headerBytes)).Decode(&resultMap); err != nil { - return nil, false, err - } - result, err = toHeader(resultMap) - if err != nil { - return nil, false, err - } - return result, true, nil - } - - // 3. Are we getting an array of fields like "content-type:encoding/json" from the CLI? - var keyPairs []interface{} - if err := mapstructure.WeakDecode(raw, &keyPairs); err == nil { - for _, keyPairIfc := range keyPairs { - keyPair, ok := keyPairIfc.(string) - if !ok { - return nil, false, fmt.Errorf("invalid key pair %q", keyPair) - } - keyPairSlice := strings.SplitN(keyPair, ":", 2) - if len(keyPairSlice) != 2 || keyPairSlice[0] == "" { - return nil, false, fmt.Errorf("invalid key pair %q", keyPair) - } - result.Add(keyPairSlice[0], keyPairSlice[1]) - } - return result, true, nil - } - return nil, false, fmt.Errorf("%s not provided an expected format", raw) - - default: - panic(fmt.Sprintf("Unknown type: %s", schema.Type)) - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/field_type.go b/vendor/github.com/hashicorp/vault/logical/framework/field_type.go deleted file mode 100644 index 64a6a56d..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/field_type.go +++ /dev/null @@ -1,78 +0,0 @@ -package framework - -// FieldType is the enum of types that a field can be. -type FieldType uint - -const ( - TypeInvalid FieldType = 0 - TypeString FieldType = iota - TypeInt - TypeBool - TypeMap - - // TypeDurationSecond represent as seconds, this can be either an - // integer or go duration format string (e.g. 24h) - TypeDurationSecond - - // TypeSlice represents a slice of any type - TypeSlice - - // TypeStringSlice is a helper for TypeSlice that returns a sanitized - // slice of strings - TypeStringSlice - - // TypeCommaStringSlice is a helper for TypeSlice that returns a sanitized - // slice of strings and also supports parsing a comma-separated list in - // a string field - TypeCommaStringSlice - - // TypeLowerCaseString is a helper for TypeString that returns a lowercase - // version of the provided string - TypeLowerCaseString - - // TypeNameString represents a name that is URI safe and follows specific - // rules. These rules include start and end with an alphanumeric - // character and characters in the middle can be alphanumeric or . or -. - TypeNameString - - // TypeKVPairs allows you to represent the data as a map or a list of - // equal sign delimited key pairs - TypeKVPairs - - // TypeCommaIntSlice is a helper for TypeSlice that returns a sanitized - // slice of Ints - TypeCommaIntSlice - - // TypeHeader is a helper for sending request headers through to Vault. - // For instance, the AWS and AliCloud credential plugins both act as a - // benevolent MITM for a request, and the headers are sent through and - // parsed. - TypeHeader -) - -func (t FieldType) String() string { - switch t { - case TypeString: - return "string" - case TypeLowerCaseString: - return "lowercase string" - case TypeNameString: - return "name string" - case TypeInt: - return "int" - case TypeBool: - return "bool" - case TypeMap: - return "map" - case TypeKVPairs: - return "keypair" - case TypeDurationSecond: - return "duration (sec)" - case TypeSlice, TypeStringSlice, TypeCommaStringSlice, TypeCommaIntSlice: - return "slice" - case TypeHeader: - return "header" - default: - return "unknown type" - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/lease.go b/vendor/github.com/hashicorp/vault/logical/framework/lease.go deleted file mode 100644 index 4f55ae0d..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/lease.go +++ /dev/null @@ -1,106 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" -) - -// LeaseExtend is left for backwards compatibility for plugins. This function -// now just passes back the data that was passed into it to be processed in core. -// DEPRECATED -func LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical.SystemView) OperationFunc { - return func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) { - switch { - case req.Auth != nil: - req.Auth.TTL = backendIncrement - req.Auth.MaxTTL = backendMax - return &logical.Response{Auth: req.Auth}, nil - case req.Secret != nil: - req.Secret.TTL = backendIncrement - req.Secret.MaxTTL = backendMax - return &logical.Response{Secret: req.Secret}, nil - } - return nil, fmt.Errorf("no lease options for request") - } -} - -// CalculateTTL takes all the user-specified, backend, and system inputs and calculates -// a TTL for a lease -func CalculateTTL(sysView logical.SystemView, increment, backendTTL, period, backendMaxTTL, explicitMaxTTL time.Duration, startTime time.Time) (ttl time.Duration, warnings []string, errors error) { - // Truncate all times to the second since that is the lowest precision for - // TTLs - now := time.Now().Truncate(time.Second) - if startTime.IsZero() { - startTime = now - } else { - startTime = startTime.Truncate(time.Second) - } - - // Use the mount's configured max unless the backend specifies - // something more restrictive (perhaps from a role configuration - // parameter) - maxTTL := sysView.MaxLeaseTTL() - if backendMaxTTL > 0 && backendMaxTTL < maxTTL { - maxTTL = backendMaxTTL - } - if explicitMaxTTL > 0 && explicitMaxTTL < maxTTL { - maxTTL = explicitMaxTTL - } - - // Should never happen, but guard anyways - if maxTTL <= 0 { - return 0, nil, fmt.Errorf("max TTL must be greater than zero") - } - - var maxValidTime time.Time - switch { - case period > 0: - // Cap the period value to the sys max_ttl value - if period > maxTTL { - warnings = append(warnings, - fmt.Sprintf("period of %q exceeded the effective max_ttl of %q; period value is capped accordingly", period, maxTTL)) - period = maxTTL - } - ttl = period - - if explicitMaxTTL > 0 { - maxValidTime = startTime.Add(explicitMaxTTL) - } - default: - switch { - case increment > 0: - ttl = increment - case backendTTL > 0: - ttl = backendTTL - default: - ttl = sysView.DefaultLeaseTTL() - } - - // We cannot go past this time - maxValidTime = startTime.Add(maxTTL) - } - - if !maxValidTime.IsZero() { - // Determine the max valid TTL - maxValidTTL := maxValidTime.Sub(now) - - // If we are past the max TTL, we shouldn't be in this function...but - // fast path out if we are - if maxValidTTL < 0 { - return 0, nil, fmt.Errorf("past the max TTL, cannot renew") - } - - // If the proposed expiration is after the maximum TTL of the lease, - // cap the increment to whatever is left - if maxValidTTL-ttl < 0 { - warnings = append(warnings, - fmt.Sprintf("TTL of %q exceeded the effective max_ttl of %q; TTL value is capped accordingly", ttl, maxValidTTL)) - ttl = maxValidTTL - } - } - - return ttl, warnings, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/openapi.go b/vendor/github.com/hashicorp/vault/logical/framework/openapi.go deleted file mode 100644 index 237311f2..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/openapi.go +++ /dev/null @@ -1,613 +0,0 @@ -package framework - -import ( - "fmt" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/version" - "github.com/mitchellh/mapstructure" -) - -// OpenAPI specification (OAS): https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md -const OASVersion = "3.0.2" - -// NewOASDocument returns an empty OpenAPI document. -func NewOASDocument() *OASDocument { - return &OASDocument{ - Version: OASVersion, - Info: OASInfo{ - Title: "HashiCorp Vault API", - Description: "HTTP API that gives you full access to Vault. All API routes are prefixed with `/v1/`.", - Version: version.GetVersion().Version, - License: OASLicense{ - Name: "Mozilla Public License 2.0", - URL: "https://www.mozilla.org/en-US/MPL/2.0", - }, - }, - Paths: make(map[string]*OASPathItem), - } -} - -// NewOASDocumentFromMap builds an OASDocument from an existing map version of a document. -// If a document has been decoded from JSON or received from a plugin, it will be as a map[string]interface{} -// and needs special handling beyond the default mapstructure decoding. -func NewOASDocumentFromMap(input map[string]interface{}) (*OASDocument, error) { - - // The Responses map uses integer keys (the response code), but once translated into JSON - // (e.g. during the plugin transport) these become strings. mapstructure will not coerce these back - // to integers without a custom decode hook. - decodeHook := func(src reflect.Type, tgt reflect.Type, inputRaw interface{}) (interface{}, error) { - - // Only alter data if: - // 1. going from string to int - // 2. string represent an int in status code range (100-599) - if src.Kind() == reflect.String && tgt.Kind() == reflect.Int { - if input, ok := inputRaw.(string); ok { - if intval, err := strconv.Atoi(input); err == nil { - if intval >= 100 && intval < 600 { - return intval, nil - } - } - } - } - return inputRaw, nil - } - - doc := new(OASDocument) - - config := &mapstructure.DecoderConfig{ - DecodeHook: decodeHook, - Result: doc, - } - - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - - if err := decoder.Decode(input); err != nil { - return nil, err - } - - return doc, nil -} - -type OASDocument struct { - Version string `json:"openapi" mapstructure:"openapi"` - Info OASInfo `json:"info"` - Paths map[string]*OASPathItem `json:"paths"` -} - -type OASInfo struct { - Title string `json:"title"` - Description string `json:"description"` - Version string `json:"version"` - License OASLicense `json:"license"` -} - -type OASLicense struct { - Name string `json:"name"` - URL string `json:"url"` -} - -type OASPathItem struct { - Description string `json:"description,omitempty"` - Parameters []OASParameter `json:"parameters,omitempty"` - Sudo bool `json:"x-vault-sudo,omitempty" mapstructure:"x-vault-sudo"` - Unauthenticated bool `json:"x-vault-unauthenticated,omitempty" mapstructure:"x-vault-unauthenticated"` - CreateSupported bool `json:"x-vault-create-supported,omitempty" mapstructure:"x-vault-create-supported"` - - Get *OASOperation `json:"get,omitempty"` - Post *OASOperation `json:"post,omitempty"` - Delete *OASOperation `json:"delete,omitempty"` -} - -// NewOASOperation creates an empty OpenAPI Operations object. -func NewOASOperation() *OASOperation { - return &OASOperation{ - Responses: make(map[int]*OASResponse), - } -} - -type OASOperation struct { - Summary string `json:"summary,omitempty"` - Description string `json:"description,omitempty"` - Tags []string `json:"tags,omitempty"` - Parameters []OASParameter `json:"parameters,omitempty"` - RequestBody *OASRequestBody `json:"requestBody,omitempty"` - Responses map[int]*OASResponse `json:"responses"` - Deprecated bool `json:"deprecated,omitempty"` -} - -type OASParameter struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - In string `json:"in"` - Schema *OASSchema `json:"schema,omitempty"` - Required bool `json:"required,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` -} - -type OASRequestBody struct { - Description string `json:"description,omitempty"` - Content OASContent `json:"content,omitempty"` -} - -type OASContent map[string]*OASMediaTypeObject - -type OASMediaTypeObject struct { - Schema *OASSchema `json:"schema,omitempty"` -} - -type OASSchema struct { - Type string `json:"type,omitempty"` - Description string `json:"description,omitempty"` - Properties map[string]*OASSchema `json:"properties,omitempty"` - Items *OASSchema `json:"items,omitempty"` - Format string `json:"format,omitempty"` - Pattern string `json:"pattern,omitempty"` - Example interface{} `json:"example,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` -} - -type OASResponse struct { - Description string `json:"description"` - Content OASContent `json:"content,omitempty"` -} - -var OASStdRespOK = &OASResponse{ - Description: "OK", -} - -var OASStdRespNoContent = &OASResponse{ - Description: "empty body", -} - -// Regex for handling optional and named parameters in paths, and string cleanup. -// Predefined here to avoid substantial recompilation. - -// Capture optional path elements in ungreedy (?U) fashion -// Both "(leases/)?renew" and "(/(?P.+))?" formats are detected -var optRe = regexp.MustCompile(`(?U)\([^(]*\)\?|\(/\(\?P<[^(]*\)\)\?`) - -var reqdRe = regexp.MustCompile(`\(?\?P<(\w+)>[^)]*\)?`) // Capture required parameters, e.g. "(?Pregex)" -var altRe = regexp.MustCompile(`\((.*)\|(.*)\)`) // Capture alternation elements, e.g. "(raw/?$|raw/(?P.+))" -var pathFieldsRe = regexp.MustCompile(`{(\w+)}`) // Capture OpenAPI-style named parameters, e.g. "lookup/{urltoken}", -var cleanCharsRe = regexp.MustCompile("[()^$?]") // Set of regex characters that will be stripped during cleaning -var cleanSuffixRe = regexp.MustCompile(`/\?\$?$`) // Path suffix patterns that will be stripped during cleaning -var wsRe = regexp.MustCompile(`\s+`) // Match whitespace, to be compressed during cleaning -var altFieldsGroupRe = regexp.MustCompile(`\(\?P<\w+>\w+(\|\w+)+\)`) // Match named groups that limit options, e.g. "(?a|b|c)" -var altFieldsRe = regexp.MustCompile(`\w+(\|\w+)+`) // Match an options set, e.g. "a|b|c" - -// documentPaths parses all paths in a framework.Backend into OpenAPI paths. -func documentPaths(backend *Backend, doc *OASDocument) error { - for _, p := range backend.Paths { - if err := documentPath(p, backend.SpecialPaths(), backend.BackendType, doc); err != nil { - return err - } - } - - return nil -} - -// documentPath parses a framework.Path into one or more OpenAPI paths. -func documentPath(p *Path, specialPaths *logical.Paths, backendType logical.BackendType, doc *OASDocument) error { - var sudoPaths []string - var unauthPaths []string - - if specialPaths != nil { - sudoPaths = specialPaths.Root - unauthPaths = specialPaths.Unauthenticated - } - - // Convert optional parameters into distinct patterns to be process independently. - paths := expandPattern(p.Pattern) - - for _, path := range paths { - // Construct a top level PathItem which will be populated as the path is processed. - pi := OASPathItem{ - Description: cleanString(p.HelpSynopsis), - } - - pi.Sudo = specialPathMatch(path, sudoPaths) - pi.Unauthenticated = specialPathMatch(path, unauthPaths) - - // If the newer style Operations map isn't defined, create one from the legacy fields. - operations := p.Operations - if operations == nil { - operations = make(map[logical.Operation]OperationHandler) - - for opType, cb := range p.Callbacks { - operations[opType] = &PathOperation{ - Callback: cb, - Summary: p.HelpSynopsis, - } - } - } - - // Process path and header parameters, which are common to all operations. - // Body fields will be added to individual operations. - pathFields, bodyFields := splitFields(p.Fields, path) - - for name, field := range pathFields { - location := "path" - required := true - - // Header parameters are part of the Parameters group but with - // a dedicated "header" location, a header parameter is not required. - if field.Type == TypeHeader { - location = "header" - required = false - } - - t := convertType(field.Type) - p := OASParameter{ - Name: name, - Description: cleanString(field.Description), - In: location, - Schema: &OASSchema{ - Type: t.baseType, - Pattern: t.pattern, - }, - Required: required, - Deprecated: field.Deprecated, - } - pi.Parameters = append(pi.Parameters, p) - } - - // Sort parameters for a stable output - sort.Slice(pi.Parameters, func(i, j int) bool { - return strings.ToLower(pi.Parameters[i].Name) < strings.ToLower(pi.Parameters[j].Name) - }) - - // Process each supported operation by building up an Operation object - // with descriptions, properties and examples from the framework.Path data. - for opType, opHandler := range operations { - props := opHandler.Properties() - if props.Unpublished { - continue - } - - if opType == logical.CreateOperation { - pi.CreateSupported = true - - // If both Create and Update are defined, only process Update. - if operations[logical.UpdateOperation] != nil { - continue - } - } - - // If both List and Read are defined, only process Read. - if opType == logical.ListOperation && operations[logical.ReadOperation] != nil { - continue - } - - op := NewOASOperation() - - op.Summary = props.Summary - op.Description = props.Description - op.Deprecated = props.Deprecated - - // Add any fields not present in the path as body parameters for POST. - if opType == logical.CreateOperation || opType == logical.UpdateOperation { - s := &OASSchema{ - Type: "object", - Properties: make(map[string]*OASSchema), - } - - for name, field := range bodyFields { - openapiField := convertType(field.Type) - p := OASSchema{ - Type: openapiField.baseType, - Description: cleanString(field.Description), - Format: openapiField.format, - Pattern: openapiField.pattern, - Deprecated: field.Deprecated, - } - if openapiField.baseType == "array" { - p.Items = &OASSchema{ - Type: openapiField.items, - } - } - s.Properties[name] = &p - } - - // If examples were given, use the first one as the sample - // of this schema. - if len(props.Examples) > 0 { - s.Example = props.Examples[0].Data - } - - // Set the final request body. Only JSON request data is supported. - if len(s.Properties) > 0 || s.Example != nil { - op.RequestBody = &OASRequestBody{ - Content: OASContent{ - "application/json": &OASMediaTypeObject{ - Schema: s, - }, - }, - } - } - } - - // LIST is represented as GET with a `list` query parameter - if opType == logical.ListOperation || (opType == logical.ReadOperation && operations[logical.ListOperation] != nil) { - op.Parameters = append(op.Parameters, OASParameter{ - Name: "list", - Description: "Return a list if `true`", - In: "query", - Schema: &OASSchema{Type: "string"}, - }) - } - - // Add tags based on backend type - var tags []string - switch backendType { - case logical.TypeLogical: - tags = []string{"secrets"} - case logical.TypeCredential: - tags = []string{"auth"} - } - - op.Tags = append(op.Tags, tags...) - - // Set default responses. - if len(props.Responses) == 0 { - if opType == logical.DeleteOperation { - op.Responses[204] = OASStdRespNoContent - } else { - op.Responses[200] = OASStdRespOK - } - } - - // Add any defined response details. - for code, responses := range props.Responses { - var description string - content := make(OASContent) - - for i, resp := range responses { - if i == 0 { - description = resp.Description - } - if resp.Example != nil { - mediaType := resp.MediaType - if mediaType == "" { - mediaType = "application/json" - } - - // create a version of the response that will not emit null items - cr, err := cleanResponse(resp.Example) - if err != nil { - return err - } - - // Only one example per media type is allowed, so first one wins - if _, ok := content[mediaType]; !ok { - content[mediaType] = &OASMediaTypeObject{ - Schema: &OASSchema{ - Example: cr, - }, - } - } - } - } - - op.Responses[code] = &OASResponse{ - Description: description, - Content: content, - } - } - - switch opType { - case logical.CreateOperation, logical.UpdateOperation: - pi.Post = op - case logical.ReadOperation, logical.ListOperation: - pi.Get = op - case logical.DeleteOperation: - pi.Delete = op - } - } - - doc.Paths["/"+path] = &pi - } - - return nil -} - -func specialPathMatch(path string, specialPaths []string) bool { - // Test for exact or prefix match of special paths. - for _, sp := range specialPaths { - if sp == path || - (strings.HasSuffix(sp, "*") && strings.HasPrefix(path, sp[0:len(sp)-1])) { - return true - } - } - return false -} - -// expandPattern expands a regex pattern by generating permutations of any optional parameters -// and changing named parameters into their {openapi} equivalents. -func expandPattern(pattern string) []string { - var paths []string - - // GenericNameRegex adds a regex that complicates our parsing. It is much easier to - // detect and remove it now than to compensate for in the other regexes. - // - // example: (?P\\w(([\\w-.]+)?\\w)?) -> (?P) - base := GenericNameRegex("") - start := strings.Index(base, ">") - end := strings.LastIndex(base, ")") - regexToRemove := "" - if start != -1 && end != -1 && end > start { - regexToRemove = base[start+1 : end] - } - pattern = strings.Replace(pattern, regexToRemove, "", -1) - - // Simplify named fields that have limited options, e.g. (?Pa|b|c) -> (.+) - pattern = altFieldsGroupRe.ReplaceAllStringFunc(pattern, func(s string) string { - return altFieldsRe.ReplaceAllString(s, ".+") - }) - - // Initialize paths with the original pattern or the halves of an - // alternation, which is also present in some patterns. - matches := altRe.FindAllStringSubmatch(pattern, -1) - if len(matches) > 0 { - paths = []string{matches[0][1], matches[0][2]} - } else { - paths = []string{pattern} - } - - // Expand all optional regex elements into two paths. This approach is really only useful up to 2 optional - // groups, but we probably don't want to deal with the exponential increase beyond that anyway. - for i := 0; i < len(paths); i++ { - p := paths[i] - - // match is a 2-element slice that will have a start and end index - // for the left-most match of a regex of form: (lease/)? - match := optRe.FindStringIndex(p) - - if match != nil { - // create a path that includes the optional element but without - // parenthesis or the '?' character. - paths[i] = p[:match[0]] + p[match[0]+1:match[1]-2] + p[match[1]:] - - // create a path that excludes the optional element. - paths = append(paths, p[:match[0]]+p[match[1]:]) - i-- - } - } - - // Replace named parameters (?P) with {foo} - var replacedPaths []string - - for _, path := range paths { - result := reqdRe.FindAllStringSubmatch(path, -1) - if result != nil { - for _, p := range result { - par := p[1] - path = strings.Replace(path, p[0], fmt.Sprintf("{%s}", par), 1) - } - } - // Final cleanup - path = cleanSuffixRe.ReplaceAllString(path, "") - path = cleanCharsRe.ReplaceAllString(path, "") - replacedPaths = append(replacedPaths, path) - } - - return replacedPaths -} - -// schemaType is a subset of the JSON Schema elements used as a target -// for conversions from Vault's standard FieldTypes. -type schemaType struct { - baseType string - items string - format string - pattern string -} - -// convertType translates a FieldType into an OpenAPI type. -// In the case of arrays, a subtype is returned as well. -func convertType(t FieldType) schemaType { - ret := schemaType{} - - switch t { - case TypeString, TypeHeader: - ret.baseType = "string" - case TypeNameString: - ret.baseType = "string" - ret.pattern = `\w([\w-.]*\w)?` - case TypeLowerCaseString: - ret.baseType = "string" - ret.format = "lowercase" - case TypeInt: - ret.baseType = "number" - case TypeDurationSecond: - ret.baseType = "number" - ret.format = "seconds" - case TypeBool: - ret.baseType = "boolean" - case TypeMap: - ret.baseType = "object" - ret.format = "map" - case TypeKVPairs: - ret.baseType = "object" - ret.format = "kvpairs" - case TypeSlice: - ret.baseType = "array" - ret.items = "object" - case TypeStringSlice, TypeCommaStringSlice: - ret.baseType = "array" - ret.items = "string" - case TypeCommaIntSlice: - ret.baseType = "array" - ret.items = "number" - default: - log.L().Warn("error parsing field type", "type", t) - ret.format = "unknown" - } - - return ret -} - -// cleanString prepares s for inclusion in the output -func cleanString(s string) string { - // clean leading/trailing whitespace, and replace whitespace runs into a single space - s = strings.TrimSpace(s) - s = wsRe.ReplaceAllString(s, " ") - return s -} - -// splitFields partitions fields into path and body groups -// The input pattern is expected to have been run through expandPattern, -// with paths parameters denotes in {braces}. -func splitFields(allFields map[string]*FieldSchema, pattern string) (pathFields, bodyFields map[string]*FieldSchema) { - pathFields = make(map[string]*FieldSchema) - bodyFields = make(map[string]*FieldSchema) - - for _, match := range pathFieldsRe.FindAllStringSubmatch(pattern, -1) { - name := match[1] - pathFields[name] = allFields[name] - } - - for name, field := range allFields { - if _, ok := pathFields[name]; !ok { - // Header fields are in "parameters" with other path fields - if field.Type == TypeHeader { - pathFields[name] = field - } else { - bodyFields[name] = field - } - } - } - - return pathFields, bodyFields -} - -// cleanedResponse is identical to logical.Response but with nulls -// removed from from JSON encoding -type cleanedResponse struct { - Secret *logical.Secret `json:"secret,omitempty"` - Auth *logical.Auth `json:"auth,omitempty"` - Data map[string]interface{} `json:"data,omitempty"` - Redirect string `json:"redirect,omitempty"` - Warnings []string `json:"warnings,omitempty"` - WrapInfo *wrapping.ResponseWrapInfo `json:"wrap_info,omitempty"` -} - -func cleanResponse(resp *logical.Response) (*cleanedResponse, error) { - var r cleanedResponse - - if err := mapstructure.Decode(resp, &r); err != nil { - return nil, err - } - - return &r, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path.go b/vendor/github.com/hashicorp/vault/logical/framework/path.go deleted file mode 100644 index 4093caa0..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path.go +++ /dev/null @@ -1,278 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/logical" -) - -// Helper which returns a generic regex string for creating endpoint patterns -// that are identified by the given name in the backends -func GenericNameRegex(name string) string { - return fmt.Sprintf("(?P<%s>\\w(([\\w-.]+)?\\w)?)", name) -} - -// GenericNameWithAtRegex returns a generic regex that allows alphanumeric -// characters along with -, . and @. -func GenericNameWithAtRegex(name string) string { - return fmt.Sprintf("(?P<%s>\\w(([\\w-.@]+)?\\w)?)", name) -} - -// Helper which returns a regex string for optionally accepting the a field -// from the API URL -func OptionalParamRegex(name string) string { - return fmt.Sprintf("(/(?P<%s>.+))?", name) -} - -// Helper which returns a regex string for capturing an entire endpoint path -// as the given name. -func MatchAllRegex(name string) string { - return fmt.Sprintf(`(?P<%s>.*)`, name) -} - -// PathAppend is a helper for appending lists of paths into a single -// list. -func PathAppend(paths ...[]*Path) []*Path { - result := make([]*Path, 0, 10) - for _, ps := range paths { - result = append(result, ps...) - } - - return result -} - -// Path is a single path that the backend responds to. -type Path struct { - // Pattern is the pattern of the URL that matches this path. - // - // This should be a valid regular expression. Named captures will be - // exposed as fields that should map to a schema in Fields. If a named - // capture is not a field in the Fields map, then it will be ignored. - Pattern string - - // Fields is the mapping of data fields to a schema describing that - // field. Named captures in the Pattern also map to fields. If a named - // capture name matches a PUT body name, the named capture takes - // priority. - // - // Note that only named capture fields are available in every operation, - // whereas all fields are available in the Write operation. - Fields map[string]*FieldSchema - - // Operations is the set of operations supported and the associated OperationsHandler. - // - // If both Create and Update operations are present, documentation and examples from - // the Update definition will be used. Similarly if both Read and List are present, - // Read will be used for documentation. - Operations map[logical.Operation]OperationHandler - - // Callbacks are the set of callbacks that are called for a given - // operation. If a callback for a specific operation is not present, - // then logical.ErrUnsupportedOperation is automatically generated. - // - // The help operation is the only operation that the Path will - // automatically handle if the Help field is set. If both the Help - // field is set and there is a callback registered here, then the - // callback will be called. - // - // Deprecated: Operations should be used instead and will take priority if present. - Callbacks map[logical.Operation]OperationFunc - - // ExistenceCheck, if implemented, is used to query whether a given - // resource exists or not. This is used for ACL purposes: if an Update - // action is specified, and the existence check returns false, the action - // is not allowed since the resource must first be created. The reverse is - // also true. If not specified, the Update action is forced and the user - // must have UpdateCapability on the path. - ExistenceCheck ExistenceFunc - - // FeatureRequired, if implemented, will validate if the given feature is - // enabled for the set of paths - FeatureRequired license.Features - - // Deprecated denotes that this path is considered deprecated. This may - // be reflected in help and documentation. - Deprecated bool - - // Help is text describing how to use this path. This will be used - // to auto-generate the help operation. The Path will automatically - // generate a parameter listing and URL structure based on the - // regular expression, so the help text should just contain a description - // of what happens. - // - // HelpSynopsis is a one-sentence description of the path. This will - // be automatically line-wrapped at 80 characters. - // - // HelpDescription is a long-form description of the path. This will - // be automatically line-wrapped at 80 characters. - HelpSynopsis string - HelpDescription string -} - -// OperationHandler defines and describes a specific operation handler. -type OperationHandler interface { - Handler() OperationFunc - Properties() OperationProperties -} - -// OperationProperties describes an operation for documentation, help text, -// and other clients. A Summary should always be provided, whereas other -// fields can be populated as needed. -type OperationProperties struct { - // Summary is a brief (usually one line) description of the operation. - Summary string - - // Description is extended documentation of the operation and may contain - // Markdown-formatted text markup. - Description string - - // Examples provides samples of the expected request data. The most - // relevant example should be first in the list, as it will be shown in - // documentation that supports only a single example. - Examples []RequestExample - - // Responses provides a list of response description for a given response - // code. The most relevant response should be first in the list, as it will - // be shown in documentation that only allows a single example. - Responses map[int][]Response - - // Unpublished indicates that this operation should not appear in public - // documentation or help text. The operation may still have documentation - // attached that can be used internally. - Unpublished bool - - // Deprecated indicates that this operation should be avoided. - Deprecated bool -} - -// RequestExample is example of request data. -type RequestExample struct { - Description string // optional description of the request - Data map[string]interface{} // map version of sample JSON request data - - // Optional example response to the sample request. This approach is considered - // provisional for now, and this field may be changed or removed. - Response *Response -} - -// Response describes and optional demonstrations an operation response. -type Response struct { - Description string // summary of the the response and should always be provided - MediaType string // media type of the response, defaulting to "application/json" if empty - Example *logical.Response // example response data -} - -// PathOperation is a concrete implementation of OperationHandler. -type PathOperation struct { - Callback OperationFunc - Summary string - Description string - Examples []RequestExample - Responses map[int][]Response - Unpublished bool - Deprecated bool -} - -func (p *PathOperation) Handler() OperationFunc { - return p.Callback -} - -func (p *PathOperation) Properties() OperationProperties { - return OperationProperties{ - Summary: strings.TrimSpace(p.Summary), - Description: strings.TrimSpace(p.Description), - Responses: p.Responses, - Examples: p.Examples, - Unpublished: p.Unpublished, - Deprecated: p.Deprecated, - } -} - -func (p *Path) helpCallback(b *Backend) OperationFunc { - return func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) { - var tplData pathTemplateData - tplData.Request = req.Path - tplData.RoutePattern = p.Pattern - tplData.Synopsis = strings.TrimSpace(p.HelpSynopsis) - if tplData.Synopsis == "" { - tplData.Synopsis = "" - } - tplData.Description = strings.TrimSpace(p.HelpDescription) - if tplData.Description == "" { - tplData.Description = "" - } - - // Alphabetize the fields - fieldKeys := make([]string, 0, len(p.Fields)) - for k, _ := range p.Fields { - fieldKeys = append(fieldKeys, k) - } - sort.Strings(fieldKeys) - - // Build the field help - tplData.Fields = make([]pathTemplateFieldData, len(fieldKeys)) - for i, k := range fieldKeys { - schema := p.Fields[k] - description := strings.TrimSpace(schema.Description) - if description == "" { - description = "" - } - - tplData.Fields[i] = pathTemplateFieldData{ - Key: k, - Type: schema.Type.String(), - Description: description, - } - } - - help, err := executeTemplate(pathHelpTemplate, &tplData) - if err != nil { - return nil, errwrap.Wrapf("error executing template: {{err}}", err) - } - - // Build OpenAPI response for this path - doc := NewOASDocument() - if err := documentPath(p, b.SpecialPaths(), b.BackendType, doc); err != nil { - b.Logger().Warn("error generating OpenAPI", "error", err) - } - - return logical.HelpResponse(help, nil, doc), nil - } -} - -type pathTemplateData struct { - Request string - RoutePattern string - Synopsis string - Description string - Fields []pathTemplateFieldData -} - -type pathTemplateFieldData struct { - Key string - Type string - Description string - URL bool -} - -const pathHelpTemplate = ` -Request: {{.Request}} -Matching Route: {{.RoutePattern}} - -{{.Synopsis}} - -{{ if .Fields -}} -## PARAMETERS -{{range .Fields}} -{{indent 4 .Key}} ({{.Type}}) -{{indent 8 .Description}} -{{end}}{{end}} -## DESCRIPTION - -{{.Description}} -` diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path_map.go b/vendor/github.com/hashicorp/vault/logical/framework/path_map.go deleted file mode 100644 index 83aa0baf..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path_map.go +++ /dev/null @@ -1,283 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "strings" - "sync" - - saltpkg "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -// PathMap can be used to generate a path that stores mappings in the -// storage. It is a structure that also exports functions for querying the -// mappings. -// -// The primary use case for this is for credential providers to do their -// mapping to policies. -type PathMap struct { - Prefix string - Name string - Schema map[string]*FieldSchema - CaseSensitive bool - Salt *saltpkg.Salt - SaltFunc func(context.Context) (*saltpkg.Salt, error) - - once sync.Once -} - -func (p *PathMap) init() { - if p.Prefix == "" { - p.Prefix = "map" - } - - if p.Schema == nil { - p.Schema = map[string]*FieldSchema{ - "value": &FieldSchema{ - Type: TypeString, - Description: fmt.Sprintf("Value for %s mapping", p.Name), - }, - } - } -} - -// pathStruct returns the pathStruct for this mapping -func (p *PathMap) pathStruct(ctx context.Context, s logical.Storage, k string) (*PathStruct, error) { - p.once.Do(p.init) - - // If we don't care about casing, store everything lowercase - if !p.CaseSensitive { - k = strings.ToLower(k) - } - - // The original key before any salting - origKey := k - - // If we have a salt, apply it before lookup - salt := p.Salt - var err error - if p.SaltFunc != nil { - salt, err = p.SaltFunc(ctx) - if err != nil { - return nil, err - } - } - if salt != nil { - k = "s" + salt.SaltIDHashFunc(k, saltpkg.SHA256Hash) - } - - finalName := fmt.Sprintf("map/%s/%s", p.Name, k) - ps := &PathStruct{ - Name: finalName, - Schema: p.Schema, - } - - if !strings.HasPrefix(origKey, "s") && k != origKey { - // Ensure that no matter what happens what is returned is the final - // path - defer func() { - ps.Name = finalName - }() - - // - // Check for unsalted version and upgrade if so - // - - // Generate the unsalted name - unsaltedName := fmt.Sprintf("map/%s/%s", p.Name, origKey) - // Set the path struct to use the unsalted name - ps.Name = unsaltedName - - val, err := ps.Get(ctx, s) - if err != nil { - return nil, err - } - // If not nil, we have an unsalted entry -- upgrade it - if val != nil { - // Set the path struct to use the desired final name - ps.Name = finalName - err = ps.Put(ctx, s, val) - if err != nil { - return nil, err - } - // Set it back to the old path and delete - ps.Name = unsaltedName - err = ps.Delete(ctx, s) - if err != nil { - return nil, err - } - // We'll set this in the deferred function but doesn't hurt here - ps.Name = finalName - } - - // - // Check for SHA1 hashed version and upgrade if so - // - - // Generate the SHA1 hash suffixed path name - sha1SuffixedName := fmt.Sprintf("map/%s/%s", p.Name, salt.SaltID(origKey)) - - // Set the path struct to use the SHA1 hash suffixed path name - ps.Name = sha1SuffixedName - - val, err = ps.Get(ctx, s) - if err != nil { - return nil, err - } - // If not nil, we have an SHA1 hash suffixed entry -- upgrade it - if val != nil { - // Set the path struct to use the desired final name - ps.Name = finalName - err = ps.Put(ctx, s, val) - if err != nil { - return nil, err - } - // Set it back to the old path and delete - ps.Name = sha1SuffixedName - err = ps.Delete(ctx, s) - if err != nil { - return nil, err - } - // We'll set this in the deferred function but doesn't hurt here - ps.Name = finalName - } - } - - return ps, nil -} - -// Get reads a value out of the mapping -func (p *PathMap) Get(ctx context.Context, s logical.Storage, k string) (map[string]interface{}, error) { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return nil, err - } - return ps.Get(ctx, s) -} - -// Put writes a value into the mapping -func (p *PathMap) Put(ctx context.Context, s logical.Storage, k string, v map[string]interface{}) error { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return err - } - return ps.Put(ctx, s, v) -} - -// Delete removes a value from the mapping -func (p *PathMap) Delete(ctx context.Context, s logical.Storage, k string) error { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return err - } - return ps.Delete(ctx, s) -} - -// List reads the keys under a given path -func (p *PathMap) List(ctx context.Context, s logical.Storage, prefix string) ([]string, error) { - stripPrefix := fmt.Sprintf("struct/map/%s/", p.Name) - fullPrefix := fmt.Sprintf("%s%s", stripPrefix, prefix) - out, err := s.List(ctx, fullPrefix) - if err != nil { - return nil, err - } - stripped := make([]string, len(out)) - for idx, k := range out { - stripped[idx] = strings.TrimPrefix(k, stripPrefix) - } - return stripped, nil -} - -// Paths are the paths to append to the Backend paths. -func (p *PathMap) Paths() []*Path { - p.once.Do(p.init) - - // Build the schema by simply adding the "key" - schema := make(map[string]*FieldSchema) - for k, v := range p.Schema { - schema[k] = v - } - schema["key"] = &FieldSchema{ - Type: TypeString, - Description: fmt.Sprintf("Key for the %s mapping", p.Name), - } - - return []*Path{ - &Path{ - Pattern: fmt.Sprintf("%s/%s/?$", p.Prefix, p.Name), - - Callbacks: map[logical.Operation]OperationFunc{ - logical.ListOperation: p.pathList(), - logical.ReadOperation: p.pathList(), - }, - - HelpSynopsis: fmt.Sprintf("Read mappings for %s", p.Name), - }, - - &Path{ - Pattern: fmt.Sprintf(`%s/%s/(?P[-\w]+)`, p.Prefix, p.Name), - - Fields: schema, - - Callbacks: map[logical.Operation]OperationFunc{ - logical.CreateOperation: p.pathSingleWrite(), - logical.ReadOperation: p.pathSingleRead(), - logical.UpdateOperation: p.pathSingleWrite(), - logical.DeleteOperation: p.pathSingleDelete(), - }, - - HelpSynopsis: fmt.Sprintf("Read/write/delete a single %s mapping", p.Name), - - ExistenceCheck: p.pathSingleExistenceCheck(), - }, - } -} - -func (p *PathMap) pathList() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - keys, err := p.List(ctx, req.Storage, "") - if err != nil { - return nil, err - } - - return logical.ListResponse(keys), nil - } -} - -func (p *PathMap) pathSingleRead() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - v, err := p.Get(ctx, req.Storage, d.Get("key").(string)) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: v, - }, nil - } -} - -func (p *PathMap) pathSingleWrite() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Put(ctx, req.Storage, d.Get("key").(string), d.Raw) - return nil, err - } -} - -func (p *PathMap) pathSingleDelete() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Delete(ctx, req.Storage, d.Get("key").(string)) - return nil, err - } -} - -func (p *PathMap) pathSingleExistenceCheck() ExistenceFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (bool, error) { - v, err := p.Get(ctx, req.Storage, d.Get("key").(string)) - if err != nil { - return false, err - } - return v != nil, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go b/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go deleted file mode 100644 index beaed52d..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go +++ /dev/null @@ -1,124 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" -) - -// PathStruct can be used to generate a path that stores a struct -// in the storage. This structure is a map[string]interface{} but the -// types are set according to the schema in this structure. -type PathStruct struct { - Name string - Path string - Schema map[string]*FieldSchema - HelpSynopsis string - HelpDescription string - - Read bool -} - -// Get reads the structure. -func (p *PathStruct) Get(ctx context.Context, s logical.Storage) (map[string]interface{}, error) { - entry, err := s.Get(ctx, fmt.Sprintf("struct/%s", p.Name)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result map[string]interface{} - if err := jsonutil.DecodeJSON(entry.Value, &result); err != nil { - return nil, err - } - - return result, nil -} - -// Put writes the structure. -func (p *PathStruct) Put(ctx context.Context, s logical.Storage, v map[string]interface{}) error { - bytes, err := json.Marshal(v) - if err != nil { - return err - } - - return s.Put(ctx, &logical.StorageEntry{ - Key: fmt.Sprintf("struct/%s", p.Name), - Value: bytes, - }) -} - -// Delete removes the structure. -func (p *PathStruct) Delete(ctx context.Context, s logical.Storage) error { - return s.Delete(ctx, fmt.Sprintf("struct/%s", p.Name)) -} - -// Paths are the paths to append to the Backend paths. -func (p *PathStruct) Paths() []*Path { - // The single path we support to read/write this config - path := &Path{ - Pattern: p.Path, - Fields: p.Schema, - - Callbacks: map[logical.Operation]OperationFunc{ - logical.CreateOperation: p.pathWrite(), - logical.UpdateOperation: p.pathWrite(), - logical.DeleteOperation: p.pathDelete(), - }, - - ExistenceCheck: p.pathExistenceCheck(), - - HelpSynopsis: p.HelpSynopsis, - HelpDescription: p.HelpDescription, - } - - // If we support reads, add that - if p.Read { - path.Callbacks[logical.ReadOperation] = p.pathRead() - } - - return []*Path{path} -} - -func (p *PathStruct) pathRead() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - v, err := p.Get(ctx, req.Storage) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: v, - }, nil - } -} - -func (p *PathStruct) pathWrite() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Put(ctx, req.Storage, d.Raw) - return nil, err - } -} - -func (p *PathStruct) pathDelete() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Delete(ctx, req.Storage) - return nil, err - } -} - -func (p *PathStruct) pathExistenceCheck() ExistenceFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (bool, error) { - v, err := p.Get(ctx, req.Storage) - if err != nil { - return false, err - } - - return v != nil, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go b/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go deleted file mode 100644 index 089cf7f2..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go +++ /dev/null @@ -1,65 +0,0 @@ -package framework - -import ( - "context" - "sort" - "strings" - - "github.com/hashicorp/vault/logical" -) - -// PolicyMap is a specialization of PathMap that expects the values to -// be lists of policies. This assists in querying and loading policies -// from the PathMap. -type PolicyMap struct { - PathMap - - DefaultKey string - PolicyKey string -} - -func (p *PolicyMap) Policies(ctx context.Context, s logical.Storage, names ...string) ([]string, error) { - policyKey := "value" - if p.PolicyKey != "" { - policyKey = p.PolicyKey - } - - if p.DefaultKey != "" { - newNames := make([]string, len(names)+1) - newNames[0] = p.DefaultKey - copy(newNames[1:], names) - names = newNames - } - - set := make(map[string]struct{}) - for _, name := range names { - v, err := p.Get(ctx, s, name) - if err != nil { - return nil, err - } - - valuesRaw, ok := v[policyKey] - if !ok { - continue - } - - values, ok := valuesRaw.(string) - if !ok { - continue - } - - for _, p := range strings.Split(values, ",") { - if p = strings.TrimSpace(p); p != "" { - set[p] = struct{}{} - } - } - } - - list := make([]string, 0, len(set)) - for k, _ := range set { - list = append(list, k) - } - sort.Strings(list) - - return list, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/secret.go b/vendor/github.com/hashicorp/vault/logical/framework/secret.go deleted file mode 100644 index 616a055c..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/secret.go +++ /dev/null @@ -1,91 +0,0 @@ -package framework - -import ( - "context" - "time" - - "github.com/hashicorp/vault/logical" -) - -// Secret is a type of secret that can be returned from a backend. -type Secret struct { - // Type is the name of this secret type. This is used to setup the - // vault ID and to look up the proper secret structure when revocation/ - // renewal happens. Once this is set this should not be changed. - // - // The format of this must match (case insensitive): ^a-Z0-9_$ - Type string - - // Fields is the mapping of data fields and schema that comprise - // the structure of this secret. - Fields map[string]*FieldSchema - - // DefaultDuration is the default value for the duration of the lease for - // this secret. This can be manually overwritten with the result of - // Response(). - // - // If these aren't set, Vault core will set a default lease period which - // may come from a mount tuning. - DefaultDuration time.Duration - - // Renew is the callback called to renew this secret. If Renew is - // not specified then renewable is set to false in the secret. - // See lease.go for helpers for this value. - Renew OperationFunc - - // Revoke is the callback called to revoke this secret. This is required. - Revoke OperationFunc -} - -func (s *Secret) Renewable() bool { - return s.Renew != nil -} - -func (s *Secret) Response( - data, internal map[string]interface{}) *logical.Response { - internalData := make(map[string]interface{}) - for k, v := range internal { - internalData[k] = v - } - internalData["secret_type"] = s.Type - - return &logical.Response{ - Secret: &logical.Secret{ - LeaseOptions: logical.LeaseOptions{ - TTL: s.DefaultDuration, - Renewable: s.Renewable(), - }, - InternalData: internalData, - }, - - Data: data, - } -} - -// HandleRenew is the request handler for renewing this secret. -func (s *Secret) HandleRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if !s.Renewable() { - return nil, logical.ErrUnsupportedOperation - } - - data := &FieldData{ - Raw: req.Data, - Schema: s.Fields, - } - - return s.Renew(ctx, req, data) -} - -// HandleRevoke is the request handler for renewing this secret. -func (s *Secret) HandleRevoke(ctx context.Context, req *logical.Request) (*logical.Response, error) { - data := &FieldData{ - Raw: req.Data, - Schema: s.Fields, - } - - if s.Revoke != nil { - return s.Revoke(ctx, req, data) - } - - return nil, logical.ErrUnsupportedOperation -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/template.go b/vendor/github.com/hashicorp/vault/logical/framework/template.go deleted file mode 100644 index 3abdd624..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/template.go +++ /dev/null @@ -1,42 +0,0 @@ -package framework - -import ( - "bufio" - "bytes" - "strings" - "text/template" - - "github.com/hashicorp/errwrap" -) - -func executeTemplate(tpl string, data interface{}) (string, error) { - // Define the functions - funcs := map[string]interface{}{ - "indent": funcIndent, - } - - // Parse the help template - t, err := template.New("root").Funcs(funcs).Parse(tpl) - if err != nil { - return "", errwrap.Wrapf("error parsing template: {{err}}", err) - } - - // Execute the template and store the output - var buf bytes.Buffer - if err := t.Execute(&buf, data); err != nil { - return "", errwrap.Wrapf("error executing template: {{err}}", err) - } - - return strings.TrimSpace(buf.String()), nil -} - -func funcIndent(count int, text string) string { - var buf bytes.Buffer - prefix := strings.Repeat(" ", count) - scan := bufio.NewScanner(strings.NewReader(text)) - for scan.Scan() { - buf.WriteString(prefix + scan.Text() + "\n") - } - - return strings.TrimRight(buf.String(), "\n") -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/testing.go b/vendor/github.com/hashicorp/vault/logical/framework/testing.go deleted file mode 100644 index a00a3241..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/testing.go +++ /dev/null @@ -1,15 +0,0 @@ -package framework - -import ( - "testing" -) - -// TestBackendRoutes is a helper to test that all the given routes will -// route properly in the backend. -func TestBackendRoutes(t *testing.T, b *Backend, rs []string) { - for _, r := range rs { - if b.Route(r) == nil { - t.Fatalf("bad route: %s", r) - } - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/wal.go b/vendor/github.com/hashicorp/vault/logical/framework/wal.go deleted file mode 100644 index c8fa3b87..00000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/wal.go +++ /dev/null @@ -1,101 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "strings" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" -) - -// WALPrefix is the prefix within Storage where WAL entries will be written. -const WALPrefix = "wal/" - -type WALEntry struct { - ID string `json:"-"` - Kind string `json:"type"` - Data interface{} `json:"data"` - CreatedAt int64 `json:"created_at"` -} - -// PutWAL writes some data to the WAL. -// -// The kind parameter is used by the framework to allow users to store -// multiple kinds of WAL data and to easily disambiguate what data they're -// expecting. -// -// Data within the WAL that is uncommitted (CommitWAL hasn't be called) -// will be given to the rollback callback when an rollback operation is -// received, allowing the backend to clean up some partial states. -// -// The data must be JSON encodable. -// -// This returns a unique ID that can be used to reference this WAL data. -// WAL data cannot be modified. You can only add to the WAL and commit existing -// WAL entries. -func PutWAL(ctx context.Context, s logical.Storage, kind string, data interface{}) (string, error) { - value, err := json.Marshal(&WALEntry{ - Kind: kind, - Data: data, - CreatedAt: time.Now().UTC().Unix(), - }) - if err != nil { - return "", err - } - - id, err := uuid.GenerateUUID() - if err != nil { - return "", err - } - - return id, s.Put(ctx, &logical.StorageEntry{ - Key: WALPrefix + id, - Value: value, - }) -} - -// GetWAL reads a specific entry from the WAL. If the entry doesn't exist, -// then nil value is returned. -// -// The kind, value, and error are returned. -func GetWAL(ctx context.Context, s logical.Storage, id string) (*WALEntry, error) { - entry, err := s.Get(ctx, WALPrefix+id) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var raw WALEntry - if err := jsonutil.DecodeJSON(entry.Value, &raw); err != nil { - return nil, err - } - raw.ID = id - - return &raw, nil -} - -// DeleteWAL commits the WAL entry with the given ID. Once committed, -// it is assumed that the operation was a success and doesn't need to -// be rolled back. -func DeleteWAL(ctx context.Context, s logical.Storage, id string) error { - return s.Delete(ctx, WALPrefix+id) -} - -// ListWAL lists all the entries in the WAL. -func ListWAL(ctx context.Context, s logical.Storage) ([]string, error) { - keys, err := s.List(ctx, WALPrefix) - if err != nil { - return nil, err - } - - for i, k := range keys { - keys[i] = strings.TrimPrefix(k, WALPrefix) - } - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/identity.pb.go b/vendor/github.com/hashicorp/vault/logical/identity.pb.go deleted file mode 100644 index cd196522..00000000 --- a/vendor/github.com/hashicorp/vault/logical/identity.pb.go +++ /dev/null @@ -1,187 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: logical/identity.proto - -package logical - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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 Entity struct { - // ID is the unique identifier for the entity - ID string `sentinel:"" protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - // Name is the human-friendly unique identifier for the entity - Name string `sentinel:"" protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Aliases contains thhe alias mappings for the given entity - Aliases []*Alias `sentinel:"" protobuf:"bytes,3,rep,name=aliases,proto3" json:"aliases,omitempty"` - // Metadata represents the custom data tied to this entity - Metadata map[string]string `sentinel:"" 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"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Entity) Reset() { *m = Entity{} } -func (m *Entity) String() string { return proto.CompactTextString(m) } -func (*Entity) ProtoMessage() {} -func (*Entity) Descriptor() ([]byte, []int) { - return fileDescriptor_04442ca37d5e30be, []int{0} -} - -func (m *Entity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Entity.Unmarshal(m, b) -} -func (m *Entity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Entity.Marshal(b, m, deterministic) -} -func (m *Entity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Entity.Merge(m, src) -} -func (m *Entity) XXX_Size() int { - return xxx_messageInfo_Entity.Size(m) -} -func (m *Entity) XXX_DiscardUnknown() { - xxx_messageInfo_Entity.DiscardUnknown(m) -} - -var xxx_messageInfo_Entity proto.InternalMessageInfo - -func (m *Entity) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Entity) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Entity) GetAliases() []*Alias { - if m != nil { - return m.Aliases - } - return nil -} - -func (m *Entity) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -type Alias struct { - // MountType is the backend mount's type to which this identity belongs - MountType string `sentinel:"" 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 `sentinel:"" 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 `sentinel:"" protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the custom data tied to this alias - Metadata map[string]string `sentinel:"" 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"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Alias) Reset() { *m = Alias{} } -func (m *Alias) String() string { return proto.CompactTextString(m) } -func (*Alias) ProtoMessage() {} -func (*Alias) Descriptor() ([]byte, []int) { - return fileDescriptor_04442ca37d5e30be, []int{1} -} - -func (m *Alias) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Alias.Unmarshal(m, b) -} -func (m *Alias) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Alias.Marshal(b, m, deterministic) -} -func (m *Alias) XXX_Merge(src proto.Message) { - xxx_messageInfo_Alias.Merge(m, src) -} -func (m *Alias) XXX_Size() int { - return xxx_messageInfo_Alias.Size(m) -} -func (m *Alias) XXX_DiscardUnknown() { - xxx_messageInfo_Alias.DiscardUnknown(m) -} - -var xxx_messageInfo_Alias proto.InternalMessageInfo - -func (m *Alias) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *Alias) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *Alias) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Alias) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func init() { - proto.RegisterType((*Entity)(nil), "logical.Entity") - proto.RegisterMapType((map[string]string)(nil), "logical.Entity.MetadataEntry") - proto.RegisterType((*Alias)(nil), "logical.Alias") - proto.RegisterMapType((map[string]string)(nil), "logical.Alias.MetadataEntry") -} - -func init() { proto.RegisterFile("logical/identity.proto", fileDescriptor_04442ca37d5e30be) } - -var fileDescriptor_04442ca37d5e30be = []byte{ - // 287 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x91, 0x4f, 0x4b, 0xc3, 0x40, - 0x10, 0xc5, 0x49, 0xd2, 0x3f, 0x76, 0xa4, 0x45, 0x06, 0x91, 0x20, 0x16, 0x4a, 0x50, 0xc8, 0x29, - 0x01, 0xbd, 0x54, 0x3d, 0x55, 0xda, 0x43, 0x0f, 0x5e, 0x82, 0x27, 0x2f, 0x32, 0x4d, 0x97, 0x66, - 0x31, 0xc9, 0x86, 0x64, 0x52, 0xc8, 0x97, 0xf4, 0xec, 0xc7, 0x91, 0x6e, 0xb6, 0xc1, 0xe2, 0xd9, - 0xdb, 0xec, 0xef, 0xcd, 0xce, 0xbe, 0x79, 0x0b, 0x57, 0xa9, 0xda, 0xc9, 0x98, 0xd2, 0x50, 0x6e, - 0x45, 0xce, 0x92, 0x9b, 0xa0, 0x28, 0x15, 0x2b, 0x1c, 0x1a, 0xee, 0x7d, 0x59, 0x30, 0x58, 0x69, - 0x05, 0x27, 0x60, 0xaf, 0x97, 0xae, 0x35, 0xb3, 0xfc, 0x51, 0x64, 0xaf, 0x97, 0x88, 0xd0, 0xcb, - 0x29, 0x13, 0xae, 0xad, 0x89, 0xae, 0xd1, 0x87, 0x21, 0xa5, 0x92, 0x2a, 0x51, 0xb9, 0xce, 0xcc, - 0xf1, 0xcf, 0xef, 0x27, 0x81, 0x99, 0x14, 0x2c, 0x0e, 0x3c, 0x3a, 0xca, 0xf8, 0x08, 0x67, 0x99, - 0x60, 0xda, 0x12, 0x93, 0xdb, 0xd3, 0xad, 0xd3, 0xae, 0xb5, 0x7d, 0x30, 0x78, 0x35, 0xfa, 0x2a, - 0xe7, 0xb2, 0x89, 0xba, 0xf6, 0xeb, 0x67, 0x18, 0x9f, 0x48, 0x78, 0x01, 0xce, 0xa7, 0x68, 0x8c, - 0xb5, 0x43, 0x89, 0x97, 0xd0, 0xdf, 0x53, 0x5a, 0x1f, 0xcd, 0xb5, 0x87, 0x27, 0x7b, 0x6e, 0x79, - 0xdf, 0x16, 0xf4, 0xb5, 0x15, 0x9c, 0x02, 0x64, 0xaa, 0xce, 0xf9, 0x83, 0x9b, 0x42, 0x98, 0xcb, - 0x23, 0x4d, 0xde, 0x9a, 0x42, 0xe0, 0x1d, 0x4c, 0x5a, 0x99, 0xe2, 0x58, 0x54, 0x95, 0x2a, 0xcd, - 0xac, 0xb1, 0xa6, 0x0b, 0x03, 0xbb, 0x14, 0x9c, 0x5f, 0x29, 0xcc, 0xff, 0xec, 0x76, 0x73, 0x1a, - 0xc3, 0xbf, 0xac, 0xf6, 0x72, 0xfb, 0xee, 0xed, 0x24, 0x27, 0xf5, 0x26, 0x88, 0x55, 0x16, 0x26, - 0x54, 0x25, 0x32, 0x56, 0x65, 0x11, 0xee, 0xa9, 0x4e, 0x39, 0x34, 0x06, 0x36, 0x03, 0xfd, 0xc3, - 0x0f, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbf, 0xfb, 0x6f, 0x8c, 0xfb, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/logical/identity.proto b/vendor/github.com/hashicorp/vault/logical/identity.proto deleted file mode 100644 index b9c56713..00000000 --- a/vendor/github.com/hashicorp/vault/logical/identity.proto +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/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; -} - -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 - map metadata = 4; -} diff --git a/vendor/github.com/hashicorp/vault/logical/lease.go b/vendor/github.com/hashicorp/vault/logical/lease.go deleted file mode 100644 index 97bbe4f6..00000000 --- a/vendor/github.com/hashicorp/vault/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/logical/logical.go b/vendor/github.com/hashicorp/vault/logical/logical.go deleted file mode 100644 index a3456e96..00000000 --- a/vendor/github.com/hashicorp/vault/logical/logical.go +++ /dev/null @@ -1,126 +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 { - // 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 paths that require a root token to access - Root []string - - // Unauthenticated are the paths that can be accessed without any auth. - Unauthenticated []string - - // LocalStorage are paths (prefixes) that are local to this instance; this - // indicates that these paths should not be replicated - 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 -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin.pb.go b/vendor/github.com/hashicorp/vault/logical/plugin.pb.go deleted file mode 100644 index b66bea54..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin.pb.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: logical/plugin.proto - -package logical - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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 PluginEnvironment struct { - // VaultVersion is the version of the Vault server - VaultVersion string `protobuf:"bytes,1,opt,name=vault_version,json=vaultVersion,proto3" json:"vault_version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PluginEnvironment) Reset() { *m = PluginEnvironment{} } -func (m *PluginEnvironment) String() string { return proto.CompactTextString(m) } -func (*PluginEnvironment) ProtoMessage() {} -func (*PluginEnvironment) Descriptor() ([]byte, []int) { - return fileDescriptor_0f04cd6a1a3a5255, []int{0} -} - -func (m *PluginEnvironment) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PluginEnvironment.Unmarshal(m, b) -} -func (m *PluginEnvironment) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PluginEnvironment.Marshal(b, m, deterministic) -} -func (m *PluginEnvironment) XXX_Merge(src proto.Message) { - xxx_messageInfo_PluginEnvironment.Merge(m, src) -} -func (m *PluginEnvironment) XXX_Size() int { - return xxx_messageInfo_PluginEnvironment.Size(m) -} -func (m *PluginEnvironment) XXX_DiscardUnknown() { - xxx_messageInfo_PluginEnvironment.DiscardUnknown(m) -} - -var xxx_messageInfo_PluginEnvironment proto.InternalMessageInfo - -func (m *PluginEnvironment) GetVaultVersion() string { - if m != nil { - return m.VaultVersion - } - return "" -} - -func init() { - proto.RegisterType((*PluginEnvironment)(nil), "logical.PluginEnvironment") -} - -func init() { proto.RegisterFile("logical/plugin.proto", fileDescriptor_0f04cd6a1a3a5255) } - -var fileDescriptor_0f04cd6a1a3a5255 = []byte{ - // 133 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc9, 0xc9, 0x4f, 0xcf, - 0x4c, 0x4e, 0xcc, 0xd1, 0x2f, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x62, 0x87, 0x8a, 0x2a, 0x59, 0x70, 0x09, 0x06, 0x80, 0x25, 0x5c, 0xf3, 0xca, 0x32, 0x8b, - 0xf2, 0xf3, 0x72, 0x53, 0xf3, 0x4a, 0x84, 0x94, 0xb9, 0x78, 0xcb, 0x12, 0x4b, 0x73, 0x4a, 0xe2, - 0xcb, 0x52, 0x8b, 0x8a, 0x33, 0xf3, 0xf3, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x78, 0xc0, - 0x82, 0x61, 0x10, 0x31, 0x27, 0x95, 0x28, 0xa5, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, - 0xfc, 0x5c, 0xfd, 0x8c, 0xc4, 0xe2, 0x8c, 0xcc, 0xe4, 0xfc, 0xa2, 0x02, 0x7d, 0xb0, 0x22, 0x7d, - 0xa8, 0xf9, 0x49, 0x6c, 0x60, 0xfb, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa3, 0xff, 0x48, - 0xa9, 0x87, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin.proto b/vendor/github.com/hashicorp/vault/logical/plugin.proto deleted file mode 100644 index ec849347..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/logical"; - -package logical; - -message PluginEnvironment { - // VaultVersion is the version of the Vault server - string vault_version = 1; -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend.go deleted file mode 100644 index ac367c16..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend.go +++ /dev/null @@ -1,83 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - "sync/atomic" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -var _ plugin.Plugin = (*BackendPlugin)(nil) -var _ plugin.GRPCPlugin = (*BackendPlugin)(nil) -var _ plugin.Plugin = (*GRPCBackendPlugin)(nil) -var _ plugin.GRPCPlugin = (*GRPCBackendPlugin)(nil) - -// BackendPlugin is the plugin.Plugin implementation -type BackendPlugin struct { - *GRPCBackendPlugin -} - -// GRPCBackendPlugin is the plugin.Plugin implementation that only supports GRPC -// transport -type GRPCBackendPlugin struct { - Factory logical.Factory - MetadataMode bool - Logger log.Logger - - // Embeding this will disable the netRPC protocol - plugin.NetRPCUnsupportedPlugin -} - -// Server gets called when on plugin.Serve() -func (b *BackendPlugin) Server(broker *plugin.MuxBroker) (interface{}, error) { - return &backendPluginServer{ - factory: b.Factory, - broker: broker, - // We pass the logger down into the backend so go-plugin will forward - // logs for us. - logger: b.Logger, - }, nil -} - -// Client gets called on plugin.NewClient() -func (b BackendPlugin) Client(broker *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { - return &backendPluginClient{ - client: c, - broker: broker, - metadataMode: b.MetadataMode, - }, nil -} - -func (b GRPCBackendPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - pb.RegisterBackendServer(s, &backendGRPCPluginServer{ - broker: broker, - factory: b.Factory, - // We pass the logger down into the backend so go-plugin will forward - // logs for us. - logger: b.Logger, - }) - return nil -} - -func (b *GRPCBackendPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - ret := &backendGRPCPluginClient{ - client: pb.NewBackendClient(c), - clientConn: c, - broker: broker, - cleanupCh: make(chan struct{}), - doneCtx: ctx, - metadataMode: b.MetadataMode, - } - - // Create the value and set the type - ret.server = new(atomic.Value) - ret.server.Store((*grpc.Server)(nil)) - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go deleted file mode 100644 index 43a442f4..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go +++ /dev/null @@ -1,248 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "net/rpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/logical" -) - -var ( - ErrClientInMetadataMode = errors.New("plugin client can not perform action while in metadata mode") -) - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendPluginClient struct { - broker *plugin.MuxBroker - client *rpc.Client - metadataMode bool - - system logical.SystemView - logger log.Logger -} - -// HandleRequestArgs is the args for HandleRequest method. -type HandleRequestArgs struct { - StorageID uint32 - Request *logical.Request -} - -// HandleRequestReply is the reply for HandleRequest method. -type HandleRequestReply struct { - Response *logical.Response - Error error -} - -// SpecialPathsReply is the reply for SpecialPaths method. -type SpecialPathsReply struct { - Paths *logical.Paths -} - -// SystemReply is the reply for System method. -type SystemReply struct { - SystemView logical.SystemView - Error error -} - -// HandleExistenceCheckArgs is the args for HandleExistenceCheck method. -type HandleExistenceCheckArgs struct { - StorageID uint32 - Request *logical.Request -} - -// HandleExistenceCheckReply is the reply for HandleExistenceCheck method. -type HandleExistenceCheckReply struct { - CheckFound bool - Exists bool - Error error -} - -// SetupArgs is the args for Setup method. -type SetupArgs struct { - StorageID uint32 - LoggerID uint32 - SysViewID uint32 - Config map[string]string - BackendUUID string -} - -// SetupReply is the reply for Setup method. -type SetupReply struct { - Error error -} - -// TypeReply is the reply for the Type method. -type TypeReply struct { - Type logical.BackendType -} - -func (b *backendPluginClient) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.metadataMode { - return nil, ErrClientInMetadataMode - } - - // Do not send the storage, since go-plugin cannot serialize - // interfaces. The server will pick up the storage from the shim. - req.Storage = nil - args := &HandleRequestArgs{ - Request: req, - } - var reply HandleRequestReply - - if req.Connection != nil { - oldConnState := req.Connection.ConnState - req.Connection.ConnState = nil - defer func() { - req.Connection.ConnState = oldConnState - }() - } - - err := b.client.Call("Plugin.HandleRequest", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - if reply.Error.Error() == logical.ErrUnsupportedOperation.Error() { - return nil, logical.ErrUnsupportedOperation - } - - return reply.Response, reply.Error - } - - return reply.Response, nil -} - -func (b *backendPluginClient) SpecialPaths() *logical.Paths { - var reply SpecialPathsReply - err := b.client.Call("Plugin.SpecialPaths", new(interface{}), &reply) - if err != nil { - return nil - } - - return reply.Paths -} - -// System returns vault's system view. The backend client stores the view during -// Setup, so there is no need to shim the system just to get it back. -func (b *backendPluginClient) System() logical.SystemView { - return b.system -} - -// Logger returns vault's logger. The backend client stores the logger during -// Setup, so there is no need to shim the logger just to get it back. -func (b *backendPluginClient) Logger() log.Logger { - return b.logger -} - -func (b *backendPluginClient) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - if b.metadataMode { - return false, false, ErrClientInMetadataMode - } - - // Do not send the storage, since go-plugin cannot serialize - // interfaces. The server will pick up the storage from the shim. - req.Storage = nil - args := &HandleExistenceCheckArgs{ - Request: req, - } - var reply HandleExistenceCheckReply - - if req.Connection != nil { - oldConnState := req.Connection.ConnState - req.Connection.ConnState = nil - defer func() { - req.Connection.ConnState = oldConnState - }() - } - - err := b.client.Call("Plugin.HandleExistenceCheck", args, &reply) - if err != nil { - return false, false, err - } - if reply.Error != nil { - // THINKING: Should be be a switch on all error types? - if reply.Error.Error() == logical.ErrUnsupportedPath.Error() { - return false, false, logical.ErrUnsupportedPath - } - return false, false, reply.Error - } - - return reply.CheckFound, reply.Exists, nil -} - -func (b *backendPluginClient) Cleanup(ctx context.Context) { - b.client.Call("Plugin.Cleanup", new(interface{}), &struct{}{}) -} - -func (b *backendPluginClient) Initialize(ctx context.Context) error { - if b.metadataMode { - return ErrClientInMetadataMode - } - err := b.client.Call("Plugin.Initialize", new(interface{}), &struct{}{}) - return err -} - -func (b *backendPluginClient) InvalidateKey(ctx context.Context, key string) { - if b.metadataMode { - return - } - b.client.Call("Plugin.InvalidateKey", key, &struct{}{}) -} - -func (b *backendPluginClient) Setup(ctx context.Context, config *logical.BackendConfig) error { - // Shim logical.Storage - storageImpl := config.StorageView - if b.metadataMode { - storageImpl = &NOOPStorage{} - } - storageID := b.broker.NextId() - go b.broker.AcceptAndServe(storageID, &StorageServer{ - impl: storageImpl, - }) - - // Shim logical.SystemView - sysViewImpl := config.System - if b.metadataMode { - sysViewImpl = &logical.StaticSystemView{} - } - sysViewID := b.broker.NextId() - go b.broker.AcceptAndServe(sysViewID, &SystemViewServer{ - impl: sysViewImpl, - }) - - args := &SetupArgs{ - StorageID: storageID, - SysViewID: sysViewID, - Config: config.Config, - BackendUUID: config.BackendUUID, - } - var reply SetupReply - - err := b.client.Call("Plugin.Setup", args, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - - // Set system and logger for getter methods - b.system = config.System - b.logger = config.Logger - - return nil -} - -func (b *backendPluginClient) Type() logical.BackendType { - var reply TypeReply - err := b.client.Call("Plugin.Type", new(interface{}), &reply) - if err != nil { - return logical.TypeUnknown - } - - return logical.BackendType(reply.Type) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go deleted file mode 100644 index a03e089f..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go +++ /dev/null @@ -1,148 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "net/rpc" - - "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -var ( - ErrServerInMetadataMode = errors.New("plugin server can not perform action while in metadata mode") -) - -// backendPluginServer is the RPC server that backendPluginClient talks to, -// it methods conforming to requirements by net/rpc -type backendPluginServer struct { - broker *plugin.MuxBroker - backend logical.Backend - factory logical.Factory - - logger hclog.Logger - sysViewClient *rpc.Client - storageClient *rpc.Client -} - -func (b *backendPluginServer) HandleRequest(args *HandleRequestArgs, reply *HandleRequestReply) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - storage := &StorageClient{client: b.storageClient} - args.Request.Storage = storage - - resp, err := b.backend.HandleRequest(context.Background(), args.Request) - *reply = HandleRequestReply{ - Response: resp, - Error: wrapError(err), - } - - return nil -} - -func (b *backendPluginServer) SpecialPaths(_ interface{}, reply *SpecialPathsReply) error { - *reply = SpecialPathsReply{ - Paths: b.backend.SpecialPaths(), - } - return nil -} - -func (b *backendPluginServer) HandleExistenceCheck(args *HandleExistenceCheckArgs, reply *HandleExistenceCheckReply) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - storage := &StorageClient{client: b.storageClient} - args.Request.Storage = storage - - checkFound, exists, err := b.backend.HandleExistenceCheck(context.TODO(), args.Request) - *reply = HandleExistenceCheckReply{ - CheckFound: checkFound, - Exists: exists, - Error: wrapError(err), - } - - return nil -} - -func (b *backendPluginServer) Cleanup(_ interface{}, _ *struct{}) error { - b.backend.Cleanup(context.Background()) - - // Close rpc clients - b.sysViewClient.Close() - b.storageClient.Close() - return nil -} - -func (b *backendPluginServer) InvalidateKey(args string, _ *struct{}) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - b.backend.InvalidateKey(context.Background(), args) - return nil -} - -// Setup dials into the plugin's broker to get a shimmed storage, logger, and -// system view of the backend. This method also instantiates the underlying -// backend through its factory func for the server side of the plugin. -func (b *backendPluginServer) Setup(args *SetupArgs, reply *SetupReply) error { - // Dial for storage - storageConn, err := b.broker.Dial(args.StorageID) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - return nil - } - rawStorageClient := rpc.NewClient(storageConn) - b.storageClient = rawStorageClient - - storage := &StorageClient{client: rawStorageClient} - - // Dial for sys view - sysViewConn, err := b.broker.Dial(args.SysViewID) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - return nil - } - rawSysViewClient := rpc.NewClient(sysViewConn) - b.sysViewClient = rawSysViewClient - - sysView := &SystemViewClient{client: rawSysViewClient} - - config := &logical.BackendConfig{ - StorageView: storage, - Logger: b.logger, - System: sysView, - Config: args.Config, - BackendUUID: args.BackendUUID, - } - - // Call the underlying backend factory after shims have been created - // to set b.backend - backend, err := b.factory(context.Background(), config) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - } - b.backend = backend - - return nil -} - -func (b *backendPluginServer) Type(_ interface{}, reply *TypeReply) error { - *reply = TypeReply{ - Type: b.backend.Type(), - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go deleted file mode 100644 index a65eeebe..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go +++ /dev/null @@ -1,12 +0,0 @@ -package plugin - -import ( - "math" - - "google.golang.org/grpc" -) - -var largeMsgGRPCCallOpts []grpc.CallOption = []grpc.CallOption{ - grpc.MaxCallSendMsgSize(math.MaxInt32), - grpc.MaxCallRecvMsgSize(math.MaxInt32), -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go deleted file mode 100644 index 60ef1828..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go +++ /dev/null @@ -1,245 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "math" - "sync/atomic" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -var ErrPluginShutdown = errors.New("plugin is shut down") - -// Validate backendGRPCPluginClient satisfies the logical.Backend interface -var _ logical.Backend = &backendGRPCPluginClient{} - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendGRPCPluginClient struct { - broker *plugin.GRPCBroker - client pb.BackendClient - metadataMode bool - - system logical.SystemView - logger log.Logger - - // This is used to signal to the Cleanup function that it can proceed - // because we have a defined server - cleanupCh chan struct{} - - // server is the grpc server used for serving storage and sysview requests. - server *atomic.Value - - // clientConn is the underlying grpc connection to the server, we store it - // so it can be cleaned up. - clientConn *grpc.ClientConn - doneCtx context.Context -} - -func (b *backendGRPCPluginClient) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.metadataMode { - return nil, ErrClientInMetadataMode - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - protoReq, err := pb.LogicalRequestToProtoRequest(req) - if err != nil { - return nil, err - } - - reply, err := b.client.HandleRequest(ctx, &pb.HandleRequestArgs{ - Request: protoReq, - }, largeMsgGRPCCallOpts...) - if err != nil { - if b.doneCtx.Err() != nil { - return nil, ErrPluginShutdown - } - - return nil, err - } - resp, err := pb.ProtoResponseToLogicalResponse(reply.Response) - if err != nil { - return nil, err - } - if reply.Err != nil { - return resp, pb.ProtoErrToErr(reply.Err) - } - - return resp, nil -} - -func (b *backendGRPCPluginClient) SpecialPaths() *logical.Paths { - reply, err := b.client.SpecialPaths(b.doneCtx, &pb.Empty{}) - if err != nil { - return nil - } - - if reply.Paths == nil { - return nil - } - - return &logical.Paths{ - Root: reply.Paths.Root, - Unauthenticated: reply.Paths.Unauthenticated, - LocalStorage: reply.Paths.LocalStorage, - SealWrapStorage: reply.Paths.SealWrapStorage, - } -} - -// System returns vault's system view. The backend client stores the view during -// Setup, so there is no need to shim the system just to get it back. -func (b *backendGRPCPluginClient) System() logical.SystemView { - return b.system -} - -// Logger returns vault's logger. The backend client stores the logger during -// Setup, so there is no need to shim the logger just to get it back. -func (b *backendGRPCPluginClient) Logger() log.Logger { - return b.logger -} - -func (b *backendGRPCPluginClient) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - if b.metadataMode { - return false, false, ErrClientInMetadataMode - } - - protoReq, err := pb.LogicalRequestToProtoRequest(req) - if err != nil { - return false, false, err - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - reply, err := b.client.HandleExistenceCheck(ctx, &pb.HandleExistenceCheckArgs{ - Request: protoReq, - }, largeMsgGRPCCallOpts...) - if err != nil { - if b.doneCtx.Err() != nil { - return false, false, ErrPluginShutdown - } - return false, false, err - } - if reply.Err != nil { - return false, false, pb.ProtoErrToErr(reply.Err) - } - - return reply.CheckFound, reply.Exists, nil -} - -func (b *backendGRPCPluginClient) Cleanup(ctx context.Context) { - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - b.client.Cleanup(ctx, &pb.Empty{}) - - // This will block until Setup has run the function to create a new server - // in b.server. If we stop here before it has a chance to actually start - // listening, when it starts listening it will immediatley error out and - // exit, which is fine. Overall this ensures that we do not miss stopping - // the server if it ends up being created after Cleanup is called. - <-b.cleanupCh - server := b.server.Load() - if server != nil { - server.(*grpc.Server).GracefulStop() - } - b.clientConn.Close() -} - -func (b *backendGRPCPluginClient) InvalidateKey(ctx context.Context, key string) { - if b.metadataMode { - return - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - b.client.InvalidateKey(ctx, &pb.InvalidateKeyArgs{ - Key: key, - }) -} - -func (b *backendGRPCPluginClient) Setup(ctx context.Context, config *logical.BackendConfig) error { - // Shim logical.Storage - storageImpl := config.StorageView - if b.metadataMode { - storageImpl = &NOOPStorage{} - } - storage := &GRPCStorageServer{ - impl: storageImpl, - } - - // Shim logical.SystemView - sysViewImpl := config.System - if b.metadataMode { - sysViewImpl = &logical.StaticSystemView{} - } - sysView := &gRPCSystemViewServer{ - impl: sysViewImpl, - } - - // Register the server in this closure. - serverFunc := func(opts []grpc.ServerOption) *grpc.Server { - opts = append(opts, grpc.MaxRecvMsgSize(math.MaxInt32)) - opts = append(opts, grpc.MaxSendMsgSize(math.MaxInt32)) - - s := grpc.NewServer(opts...) - pb.RegisterSystemViewServer(s, sysView) - pb.RegisterStorageServer(s, storage) - b.server.Store(s) - close(b.cleanupCh) - return s - } - brokerID := b.broker.NextId() - go b.broker.AcceptAndServe(brokerID, serverFunc) - - args := &pb.SetupArgs{ - BrokerID: brokerID, - Config: config.Config, - BackendUUID: config.BackendUUID, - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - reply, err := b.client.Setup(ctx, args) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - - // Set system and logger for getter methods - b.system = config.System - b.logger = config.Logger - - return nil -} - -func (b *backendGRPCPluginClient) Type() logical.BackendType { - reply, err := b.client.Type(b.doneCtx, &pb.Empty{}) - if err != nil { - return logical.TypeUnknown - } - - return logical.BackendType(reply.Type) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go deleted file mode 100644 index 7869a70b..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go +++ /dev/null @@ -1,142 +0,0 @@ -package plugin - -import ( - "context" - - log "github.com/hashicorp/go-hclog" - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" - "google.golang.org/grpc" -) - -type backendGRPCPluginServer struct { - broker *plugin.GRPCBroker - backend logical.Backend - - factory logical.Factory - - brokeredClient *grpc.ClientConn - - logger log.Logger -} - -// Setup dials into the plugin's broker to get a shimmed storage, logger, and -// system view of the backend. This method also instantiates the underlying -// backend through its factory func for the server side of the plugin. -func (b *backendGRPCPluginServer) Setup(ctx context.Context, args *pb.SetupArgs) (*pb.SetupReply, error) { - // Dial for storage - brokeredClient, err := b.broker.Dial(args.BrokerID) - if err != nil { - return &pb.SetupReply{}, err - } - b.brokeredClient = brokeredClient - storage := newGRPCStorageClient(brokeredClient) - sysView := newGRPCSystemView(brokeredClient) - - config := &logical.BackendConfig{ - StorageView: storage, - Logger: b.logger, - System: sysView, - Config: args.Config, - BackendUUID: args.BackendUUID, - } - - // Call the underlying backend factory after shims have been created - // to set b.backend - backend, err := b.factory(ctx, config) - if err != nil { - return &pb.SetupReply{ - Err: pb.ErrToString(err), - }, nil - } - b.backend = backend - - return &pb.SetupReply{}, nil -} - -func (b *backendGRPCPluginServer) HandleRequest(ctx context.Context, args *pb.HandleRequestArgs) (*pb.HandleRequestReply, error) { - if pluginutil.InMetadataMode() { - return &pb.HandleRequestReply{}, ErrServerInMetadataMode - } - - logicalReq, err := pb.ProtoRequestToLogicalRequest(args.Request) - if err != nil { - return &pb.HandleRequestReply{}, err - } - - logicalReq.Storage = newGRPCStorageClient(b.brokeredClient) - - resp, respErr := b.backend.HandleRequest(ctx, logicalReq) - - pbResp, err := pb.LogicalResponseToProtoResponse(resp) - if err != nil { - return &pb.HandleRequestReply{}, err - } - - return &pb.HandleRequestReply{ - Response: pbResp, - Err: pb.ErrToProtoErr(respErr), - }, nil -} - -func (b *backendGRPCPluginServer) SpecialPaths(ctx context.Context, args *pb.Empty) (*pb.SpecialPathsReply, error) { - paths := b.backend.SpecialPaths() - if paths == nil { - return &pb.SpecialPathsReply{ - Paths: nil, - }, nil - } - - return &pb.SpecialPathsReply{ - Paths: &pb.Paths{ - Root: paths.Root, - Unauthenticated: paths.Unauthenticated, - LocalStorage: paths.LocalStorage, - SealWrapStorage: paths.SealWrapStorage, - }, - }, nil -} - -func (b *backendGRPCPluginServer) HandleExistenceCheck(ctx context.Context, args *pb.HandleExistenceCheckArgs) (*pb.HandleExistenceCheckReply, error) { - if pluginutil.InMetadataMode() { - return &pb.HandleExistenceCheckReply{}, ErrServerInMetadataMode - } - - logicalReq, err := pb.ProtoRequestToLogicalRequest(args.Request) - if err != nil { - return &pb.HandleExistenceCheckReply{}, err - } - logicalReq.Storage = newGRPCStorageClient(b.brokeredClient) - - checkFound, exists, err := b.backend.HandleExistenceCheck(ctx, logicalReq) - return &pb.HandleExistenceCheckReply{ - CheckFound: checkFound, - Exists: exists, - Err: pb.ErrToProtoErr(err), - }, nil -} - -func (b *backendGRPCPluginServer) Cleanup(ctx context.Context, _ *pb.Empty) (*pb.Empty, error) { - b.backend.Cleanup(ctx) - - // Close rpc clients - b.brokeredClient.Close() - return &pb.Empty{}, nil -} - -func (b *backendGRPCPluginServer) InvalidateKey(ctx context.Context, args *pb.InvalidateKeyArgs) (*pb.Empty, error) { - if pluginutil.InMetadataMode() { - return &pb.Empty{}, ErrServerInMetadataMode - } - - b.backend.InvalidateKey(ctx, args.Key) - return &pb.Empty{}, nil -} - -func (b *backendGRPCPluginServer) Type(ctx context.Context, _ *pb.Empty) (*pb.TypeReply, error) { - return &pb.TypeReply{ - Type: uint32(b.backend.Type()), - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go deleted file mode 100644 index ffe13390..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go +++ /dev/null @@ -1,110 +0,0 @@ -package plugin - -import ( - "context" - "errors" - - "google.golang.org/grpc" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -func newGRPCStorageClient(conn *grpc.ClientConn) *GRPCStorageClient { - return &GRPCStorageClient{ - client: pb.NewStorageClient(conn), - } -} - -// GRPCStorageClient is an implementation of logical.Storage that communicates -// over RPC. -type GRPCStorageClient struct { - client pb.StorageClient -} - -func (s *GRPCStorageClient) List(ctx context.Context, prefix string) ([]string, error) { - reply, err := s.client.List(ctx, &pb.StorageListArgs{ - Prefix: prefix, - }, largeMsgGRPCCallOpts...) - if err != nil { - return []string{}, err - } - if reply.Err != "" { - return reply.Keys, errors.New(reply.Err) - } - return reply.Keys, nil -} - -func (s *GRPCStorageClient) Get(ctx context.Context, key string) (*logical.StorageEntry, error) { - reply, err := s.client.Get(ctx, &pb.StorageGetArgs{ - Key: key, - }, largeMsgGRPCCallOpts...) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - return pb.ProtoStorageEntryToLogicalStorageEntry(reply.Entry), nil -} - -func (s *GRPCStorageClient) Put(ctx context.Context, entry *logical.StorageEntry) error { - reply, err := s.client.Put(ctx, &pb.StoragePutArgs{ - Entry: pb.LogicalStorageEntryToProtoStorageEntry(entry), - }, largeMsgGRPCCallOpts...) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - return nil -} - -func (s *GRPCStorageClient) Delete(ctx context.Context, key string) error { - reply, err := s.client.Delete(ctx, &pb.StorageDeleteArgs{ - Key: key, - }) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - return nil -} - -// StorageServer is a net/rpc compatible structure for serving -type GRPCStorageServer struct { - impl logical.Storage -} - -func (s *GRPCStorageServer) List(ctx context.Context, args *pb.StorageListArgs) (*pb.StorageListReply, error) { - keys, err := s.impl.List(ctx, args.Prefix) - return &pb.StorageListReply{ - Keys: keys, - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Get(ctx context.Context, args *pb.StorageGetArgs) (*pb.StorageGetReply, error) { - storageEntry, err := s.impl.Get(ctx, args.Key) - return &pb.StorageGetReply{ - Entry: pb.LogicalStorageEntryToProtoStorageEntry(storageEntry), - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Put(ctx context.Context, args *pb.StoragePutArgs) (*pb.StoragePutReply, error) { - err := s.impl.Put(ctx, pb.ProtoStorageEntryToLogicalStorageEntry(args.Entry)) - return &pb.StoragePutReply{ - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Delete(ctx context.Context, args *pb.StorageDeleteArgs) (*pb.StorageDeleteReply, error) { - err := s.impl.Delete(ctx, args.Key) - return &pb.StorageDeleteReply{ - Err: pb.ErrToString(err), - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go deleted file mode 100644 index 5b7a5824..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go +++ /dev/null @@ -1,269 +0,0 @@ -package plugin - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" - "google.golang.org/grpc" -) - -func newGRPCSystemView(conn *grpc.ClientConn) *gRPCSystemViewClient { - return &gRPCSystemViewClient{ - client: pb.NewSystemViewClient(conn), - } -} - -type gRPCSystemViewClient struct { - client pb.SystemViewClient -} - -func (s *gRPCSystemViewClient) DefaultLeaseTTL() time.Duration { - reply, err := s.client.DefaultLeaseTTL(context.Background(), &pb.Empty{}) - if err != nil { - return 0 - } - - return time.Duration(reply.TTL) -} - -func (s *gRPCSystemViewClient) MaxLeaseTTL() time.Duration { - reply, err := s.client.MaxLeaseTTL(context.Background(), &pb.Empty{}) - if err != nil { - return 0 - } - - return time.Duration(reply.TTL) -} - -func (s *gRPCSystemViewClient) SudoPrivilege(ctx context.Context, path string, token string) bool { - reply, err := s.client.SudoPrivilege(ctx, &pb.SudoPrivilegeArgs{ - Path: path, - Token: token, - }) - if err != nil { - return false - } - - return reply.Sudo -} - -func (s *gRPCSystemViewClient) Tainted() bool { - reply, err := s.client.Tainted(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Tainted -} - -func (s *gRPCSystemViewClient) CachingDisabled() bool { - reply, err := s.client.CachingDisabled(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Disabled -} - -func (s *gRPCSystemViewClient) ReplicationState() consts.ReplicationState { - reply, err := s.client.ReplicationState(context.Background(), &pb.Empty{}) - if err != nil { - return consts.ReplicationUnknown - } - - return consts.ReplicationState(reply.State) -} - -func (s *gRPCSystemViewClient) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - buf, err := json.Marshal(data) - if err != nil { - return nil, err - } - - reply, err := s.client.ResponseWrapData(ctx, &pb.ResponseWrapDataArgs{ - Data: string(buf[:]), - TTL: int64(ttl), - JWT: false, - }) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - - info, err := pb.ProtoResponseWrapInfoToLogicalResponseWrapInfo(reply.WrapInfo) - if err != nil { - return nil, err - } - - return info, nil -} - -func (s *gRPCSystemViewClient) LookupPlugin(_ context.Context, _ string, _ consts.PluginType) (*pluginutil.PluginRunner, error) { - return nil, fmt.Errorf("cannot call LookupPlugin from a plugin backend") -} - -func (s *gRPCSystemViewClient) MlockEnabled() bool { - reply, err := s.client.MlockEnabled(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Enabled -} - -func (s *gRPCSystemViewClient) HasFeature(feature license.Features) bool { - // Not implemented - return false -} - -func (s *gRPCSystemViewClient) LocalMount() bool { - reply, err := s.client.LocalMount(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Local -} - -func (s *gRPCSystemViewClient) EntityInfo(entityID string) (*logical.Entity, error) { - reply, err := s.client.EntityInfo(context.Background(), &pb.EntityInfoArgs{ - EntityID: entityID, - }) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - - return reply.Entity, nil -} - -func (s *gRPCSystemViewClient) PluginEnv(ctx context.Context) (*logical.PluginEnvironment, error) { - reply, err := s.client.PluginEnv(ctx, &pb.Empty{}) - if err != nil { - return nil, err - } - - return reply.PluginEnvironment, nil -} - -type gRPCSystemViewServer struct { - impl logical.SystemView -} - -func (s *gRPCSystemViewServer) DefaultLeaseTTL(ctx context.Context, _ *pb.Empty) (*pb.TTLReply, error) { - ttl := s.impl.DefaultLeaseTTL() - return &pb.TTLReply{ - TTL: int64(ttl), - }, nil -} - -func (s *gRPCSystemViewServer) MaxLeaseTTL(ctx context.Context, _ *pb.Empty) (*pb.TTLReply, error) { - ttl := s.impl.MaxLeaseTTL() - return &pb.TTLReply{ - TTL: int64(ttl), - }, nil -} - -func (s *gRPCSystemViewServer) SudoPrivilege(ctx context.Context, args *pb.SudoPrivilegeArgs) (*pb.SudoPrivilegeReply, error) { - sudo := s.impl.SudoPrivilege(ctx, args.Path, args.Token) - return &pb.SudoPrivilegeReply{ - Sudo: sudo, - }, nil -} - -func (s *gRPCSystemViewServer) Tainted(ctx context.Context, _ *pb.Empty) (*pb.TaintedReply, error) { - tainted := s.impl.Tainted() - return &pb.TaintedReply{ - Tainted: tainted, - }, nil -} - -func (s *gRPCSystemViewServer) CachingDisabled(ctx context.Context, _ *pb.Empty) (*pb.CachingDisabledReply, error) { - cachingDisabled := s.impl.CachingDisabled() - return &pb.CachingDisabledReply{ - Disabled: cachingDisabled, - }, nil -} - -func (s *gRPCSystemViewServer) ReplicationState(ctx context.Context, _ *pb.Empty) (*pb.ReplicationStateReply, error) { - replicationState := s.impl.ReplicationState() - return &pb.ReplicationStateReply{ - State: int32(replicationState), - }, nil -} - -func (s *gRPCSystemViewServer) ResponseWrapData(ctx context.Context, args *pb.ResponseWrapDataArgs) (*pb.ResponseWrapDataReply, error) { - data := map[string]interface{}{} - err := json.Unmarshal([]byte(args.Data), &data) - if err != nil { - return &pb.ResponseWrapDataReply{}, err - } - - // Do not allow JWTs to be returned - info, err := s.impl.ResponseWrapData(ctx, data, time.Duration(args.TTL), false) - if err != nil { - return &pb.ResponseWrapDataReply{ - Err: pb.ErrToString(err), - }, nil - } - - pbInfo, err := pb.LogicalResponseWrapInfoToProtoResponseWrapInfo(info) - if err != nil { - return &pb.ResponseWrapDataReply{}, err - } - - return &pb.ResponseWrapDataReply{ - WrapInfo: pbInfo, - }, nil -} - -func (s *gRPCSystemViewServer) MlockEnabled(ctx context.Context, _ *pb.Empty) (*pb.MlockEnabledReply, error) { - enabled := s.impl.MlockEnabled() - return &pb.MlockEnabledReply{ - Enabled: enabled, - }, nil -} - -func (s *gRPCSystemViewServer) LocalMount(ctx context.Context, _ *pb.Empty) (*pb.LocalMountReply, error) { - local := s.impl.LocalMount() - return &pb.LocalMountReply{ - Local: local, - }, nil -} - -func (s *gRPCSystemViewServer) EntityInfo(ctx context.Context, args *pb.EntityInfoArgs) (*pb.EntityInfoReply, error) { - entity, err := s.impl.EntityInfo(args.EntityID) - if err != nil { - return &pb.EntityInfoReply{ - Err: pb.ErrToString(err), - }, nil - } - return &pb.EntityInfoReply{ - Entity: entity, - }, nil -} - -func (s *gRPCSystemViewServer) PluginEnv(ctx context.Context, _ *pb.Empty) (*pb.PluginEnvReply, error) { - pluginEnv, err := s.impl.PluginEnv(ctx) - if err != nil { - return &pb.PluginEnvReply{ - Err: pb.ErrToString(err), - }, nil - } - return &pb.PluginEnvReply{ - PluginEnvironment: pluginEnv, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/logger.go b/vendor/github.com/hashicorp/vault/logical/plugin/logger.go deleted file mode 100644 index a59a8a3d..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/logger.go +++ /dev/null @@ -1,134 +0,0 @@ -package plugin - -import hclog "github.com/hashicorp/go-hclog" - -type LoggerServer struct { - logger hclog.Logger -} - -func (l *LoggerServer) Trace(args *LoggerArgs, _ *struct{}) error { - l.logger.Trace(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Debug(args *LoggerArgs, _ *struct{}) error { - l.logger.Debug(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Info(args *LoggerArgs, _ *struct{}) error { - l.logger.Info(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Warn(args *LoggerArgs, reply *LoggerReply) error { - l.logger.Warn(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Error(args *LoggerArgs, reply *LoggerReply) error { - l.logger.Error(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Log(args *LoggerArgs, _ *struct{}) error { - - switch translateLevel(args.Level) { - - case hclog.Trace: - l.logger.Trace(args.Msg, args.Args...) - - case hclog.Debug: - l.logger.Debug(args.Msg, args.Args...) - - case hclog.Info: - l.logger.Info(args.Msg, args.Args...) - - case hclog.Warn: - l.logger.Warn(args.Msg, args.Args...) - - case hclog.Error: - l.logger.Error(args.Msg, args.Args...) - - case hclog.NoLevel: - } - return nil -} - -func (l *LoggerServer) SetLevel(args int, _ *struct{}) error { - level := translateLevel(args) - l.logger = hclog.New(&hclog.LoggerOptions{Level: level}) - return nil -} - -func (l *LoggerServer) IsTrace(args interface{}, reply *LoggerReply) error { - result := l.logger.IsTrace() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsDebug(args interface{}, reply *LoggerReply) error { - result := l.logger.IsDebug() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsInfo(args interface{}, reply *LoggerReply) error { - result := l.logger.IsInfo() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsWarn(args interface{}, reply *LoggerReply) error { - result := l.logger.IsWarn() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -type LoggerArgs struct { - Level int - Msg string - Args []interface{} -} - -// LoggerReply contains the RPC reply. Not all fields may be used -// for a particular RPC call. -type LoggerReply struct { - IsTrue bool - Error error -} - -func translateLevel(logxiLevel int) hclog.Level { - - switch logxiLevel { - - case 1000, 10: - // logxi.LevelAll, logxi.LevelTrace: - return hclog.Trace - - case 7: - // logxi.LevelDebug: - return hclog.Debug - - case 6, 5: - // logxi.LevelInfo, logxi.LevelNotice: - return hclog.Info - - case 4: - // logxi.LevelWarn: - return hclog.Warn - - case 3, 2, 1, -1: - // logxi.LevelError, logxi.LevelFatal, logxi.LevelAlert, logxi.LevelEmergency: - return hclog.Error - } - return hclog.NoLevel -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go b/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go deleted file mode 100644 index d9aeed0f..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go +++ /dev/null @@ -1,91 +0,0 @@ -package plugin - -import ( - "context" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/logical" -) - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendTracingMiddleware struct { - logger log.Logger - - next logical.Backend -} - -// Validate the backendTracingMiddle object satisfies the backend interface -var _ logical.Backend = &backendTracingMiddleware{} - -func (b *backendTracingMiddleware) HandleRequest(ctx context.Context, req *logical.Request) (resp *logical.Response, err error) { - defer func(then time.Time) { - b.logger.Trace("handle request", "path", req.Path, "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("handle request", "path", req.Path, "status", "started") - return b.next.HandleRequest(ctx, req) -} - -func (b *backendTracingMiddleware) SpecialPaths() *logical.Paths { - defer func(then time.Time) { - b.logger.Trace("special paths", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("special paths", "status", "started") - return b.next.SpecialPaths() -} - -func (b *backendTracingMiddleware) System() logical.SystemView { - return b.next.System() -} - -func (b *backendTracingMiddleware) Logger() log.Logger { - return b.next.Logger() -} - -func (b *backendTracingMiddleware) HandleExistenceCheck(ctx context.Context, req *logical.Request) (found bool, exists bool, err error) { - defer func(then time.Time) { - b.logger.Trace("handle existence check", "path", req.Path, "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("handle existence check", "path", req.Path, "status", "started") - return b.next.HandleExistenceCheck(ctx, req) -} - -func (b *backendTracingMiddleware) Cleanup(ctx context.Context) { - defer func(then time.Time) { - b.logger.Trace("cleanup", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("cleanup", "status", "started") - b.next.Cleanup(ctx) -} - -func (b *backendTracingMiddleware) InvalidateKey(ctx context.Context, key string) { - defer func(then time.Time) { - b.logger.Trace("invalidate key", "key", key, "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("invalidate key", "key", key, "status", "started") - b.next.InvalidateKey(ctx, key) -} - -func (b *backendTracingMiddleware) Setup(ctx context.Context, config *logical.BackendConfig) (err error) { - defer func(then time.Time) { - b.logger.Trace("setup", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("setup", "status", "started") - return b.next.Setup(ctx, config) -} - -func (b *backendTracingMiddleware) Type() logical.BackendType { - defer func(then time.Time) { - b.logger.Trace("type", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("type", "status", "started") - return b.next.Type() -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.pb.go b/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.pb.go deleted file mode 100644 index 911bb497..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.pb.go +++ /dev/null @@ -1,3791 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: logical/plugin/pb/backend.proto - -package pb - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - timestamp "github.com/golang/protobuf/ptypes/timestamp" - logical "github.com/hashicorp/vault/logical" - 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_25821d34acc7c5ef, []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 (m *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(m, 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 - -type Header struct { - Header []string `sentinel:"" protobuf:"bytes,1,rep,name=header,proto3" json:"header,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Header) Reset() { *m = Header{} } -func (m *Header) String() string { return proto.CompactTextString(m) } -func (*Header) ProtoMessage() {} -func (*Header) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{1} -} - -func (m *Header) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Header.Unmarshal(m, b) -} -func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Header.Marshal(b, m, deterministic) -} -func (m *Header) XXX_Merge(src proto.Message) { - xxx_messageInfo_Header.Merge(m, src) -} -func (m *Header) XXX_Size() int { - return xxx_messageInfo_Header.Size(m) -} -func (m *Header) XXX_DiscardUnknown() { - xxx_messageInfo_Header.DiscardUnknown(m) -} - -var xxx_messageInfo_Header proto.InternalMessageInfo - -func (m *Header) GetHeader() []string { - if m != nil { - return m.Header - } - return nil -} - -type ProtoError struct { - // Error type can be one of: - // ErrTypeUnknown uint32 = iota - // ErrTypeUserError - // ErrTypeInternalError - // ErrTypeCodedError - // ErrTypeStatusBadRequest - // ErrTypeUnsupportedOperation - // ErrTypeUnsupportedPath - // ErrTypeInvalidRequest - // ErrTypePermissionDenied - // ErrTypeMultiAuthzPending - ErrType uint32 `sentinel:"" protobuf:"varint,1,opt,name=err_type,json=errType,proto3" json:"err_type,omitempty"` - ErrMsg string `sentinel:"" protobuf:"bytes,2,opt,name=err_msg,json=errMsg,proto3" json:"err_msg,omitempty"` - ErrCode int64 `sentinel:"" protobuf:"varint,3,opt,name=err_code,json=errCode,proto3" json:"err_code,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProtoError) Reset() { *m = ProtoError{} } -func (m *ProtoError) String() string { return proto.CompactTextString(m) } -func (*ProtoError) ProtoMessage() {} -func (*ProtoError) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{2} -} - -func (m *ProtoError) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProtoError.Unmarshal(m, b) -} -func (m *ProtoError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProtoError.Marshal(b, m, deterministic) -} -func (m *ProtoError) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProtoError.Merge(m, src) -} -func (m *ProtoError) XXX_Size() int { - return xxx_messageInfo_ProtoError.Size(m) -} -func (m *ProtoError) XXX_DiscardUnknown() { - xxx_messageInfo_ProtoError.DiscardUnknown(m) -} - -var xxx_messageInfo_ProtoError proto.InternalMessageInfo - -func (m *ProtoError) GetErrType() uint32 { - if m != nil { - return m.ErrType - } - return 0 -} - -func (m *ProtoError) GetErrMsg() string { - if m != nil { - return m.ErrMsg - } - return "" -} - -func (m *ProtoError) GetErrCode() int64 { - if m != nil { - return m.ErrCode - } - return 0 -} - -// Paths is the structure of special paths that is used for SpecialPaths. -type Paths struct { - // Root are the paths that require a root token to access - Root []string `sentinel:"" protobuf:"bytes,1,rep,name=root,proto3" json:"root,omitempty"` - // Unauthenticated are the paths that can be accessed without any auth. - Unauthenticated []string `sentinel:"" protobuf:"bytes,2,rep,name=unauthenticated,proto3" json:"unauthenticated,omitempty"` - // LocalStorage are paths (prefixes) that are local to this instance; this - // indicates that these paths should not be replicated - LocalStorage []string `sentinel:"" protobuf:"bytes,3,rep,name=local_storage,json=localStorage,proto3" json:"local_storage,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,4,rep,name=seal_wrap_storage,json=sealWrapStorage,proto3" json:"seal_wrap_storage,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Paths) Reset() { *m = Paths{} } -func (m *Paths) String() string { return proto.CompactTextString(m) } -func (*Paths) ProtoMessage() {} -func (*Paths) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{3} -} - -func (m *Paths) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Paths.Unmarshal(m, b) -} -func (m *Paths) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Paths.Marshal(b, m, deterministic) -} -func (m *Paths) XXX_Merge(src proto.Message) { - xxx_messageInfo_Paths.Merge(m, src) -} -func (m *Paths) XXX_Size() int { - return xxx_messageInfo_Paths.Size(m) -} -func (m *Paths) XXX_DiscardUnknown() { - xxx_messageInfo_Paths.DiscardUnknown(m) -} - -var xxx_messageInfo_Paths proto.InternalMessageInfo - -func (m *Paths) GetRoot() []string { - if m != nil { - return m.Root - } - return nil -} - -func (m *Paths) GetUnauthenticated() []string { - if m != nil { - return m.Unauthenticated - } - return nil -} - -func (m *Paths) GetLocalStorage() []string { - if m != nil { - return m.LocalStorage - } - return nil -} - -func (m *Paths) GetSealWrapStorage() []string { - if m != nil { - return m.SealWrapStorage - } - return nil -} - -type Request struct { - // ID is the uuid associated with each request - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // If set, the name given to the replication secondary where this request - // originated - ReplicationCluster string `sentinel:"" protobuf:"bytes,2,opt,name=ReplicationCluster,proto3" json:"ReplicationCluster,omitempty"` - // Operation is the requested operation type - Operation string `sentinel:"" protobuf:"bytes,3,opt,name=operation,proto3" json:"operation,omitempty"` - // Path is the part of the request path not consumed by the - // routing. As an example, if the original request path is "prod/aws/foo" - // and the AWS logical backend is mounted at "prod/aws/", then the - // final path is "foo" since the mount prefix is trimmed. - Path string `sentinel:"" protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"` - // Request data is a JSON object that must have keys with string type. - Data string `sentinel:"" protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"` - // Secret will be non-nil only for Revoke and Renew operations - // to represent the secret that was returned prior. - Secret *Secret `sentinel:"" protobuf:"bytes,6,opt,name=secret,proto3" json:"secret,omitempty"` - // Auth will be non-nil only for Renew operations - // to represent the auth that was returned prior. - Auth *Auth `sentinel:"" protobuf:"bytes,7,opt,name=auth,proto3" json:"auth,omitempty"` - // 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]*Header `sentinel:"" protobuf:"bytes,8,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // 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 `sentinel:"" protobuf:"bytes,9,opt,name=client_token,json=clientToken,proto3" json:"client_token,omitempty"` - // ClientTokenAccessor is provided to the core so that the it can get - // logged as part of request audit logging. - ClientTokenAccessor string `sentinel:"" protobuf:"bytes,10,opt,name=client_token_accessor,json=clientTokenAccessor,proto3" json:"client_token_accessor,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,11,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,12,opt,name=mount_point,json=mountPoint,proto3" json:"mount_point,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,13,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - // MountAccessor is provided so that identities returned by the authentication - // backends can be tied to the mount it belongs to. - MountAccessor string `sentinel:"" protobuf:"bytes,14,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - // WrapInfo contains requested response wrapping parameters - WrapInfo *RequestWrapInfo `sentinel:"" protobuf:"bytes,15,opt,name=wrap_info,json=wrapInfo,proto3" json:"wrap_info,omitempty"` - // ClientTokenRemainingUses represents the allowed number of uses left on the - // token supplied - ClientTokenRemainingUses int64 `sentinel:"" protobuf:"varint,16,opt,name=client_token_remaining_uses,json=clientTokenRemainingUses,proto3" json:"client_token_remaining_uses,omitempty"` - // EntityID is the identity of the caller extracted out of the token used - // to make this request - EntityID string `sentinel:"" protobuf:"bytes,17,opt,name=entity_id,json=entityId,proto3" json:"entity_id,omitempty"` - // PolicyOverride indicates that the requestor wishes to override - // soft-mandatory Sentinel policies - PolicyOverride bool `sentinel:"" protobuf:"varint,18,opt,name=policy_override,json=policyOverride,proto3" json:"policy_override,omitempty"` - // 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 `sentinel:"" protobuf:"varint,19,opt,name=unauthenticated,proto3" json:"unauthenticated,omitempty"` - // Connection will be non-nil only for credential providers to - // inspect the connection information and potentially use it for - // authentication/protection. - Connection *Connection `sentinel:"" protobuf:"bytes,20,opt,name=connection,proto3" json:"connection,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{4} -} - -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (m *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(m, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -func (m *Request) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Request) GetReplicationCluster() string { - if m != nil { - return m.ReplicationCluster - } - return "" -} - -func (m *Request) GetOperation() string { - if m != nil { - return m.Operation - } - return "" -} - -func (m *Request) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *Request) GetData() string { - if m != nil { - return m.Data - } - return "" -} - -func (m *Request) GetSecret() *Secret { - if m != nil { - return m.Secret - } - return nil -} - -func (m *Request) GetAuth() *Auth { - if m != nil { - return m.Auth - } - return nil -} - -func (m *Request) GetHeaders() map[string]*Header { - if m != nil { - return m.Headers - } - return nil -} - -func (m *Request) GetClientToken() string { - if m != nil { - return m.ClientToken - } - return "" -} - -func (m *Request) GetClientTokenAccessor() string { - if m != nil { - return m.ClientTokenAccessor - } - return "" -} - -func (m *Request) GetDisplayName() string { - if m != nil { - return m.DisplayName - } - return "" -} - -func (m *Request) GetMountPoint() string { - if m != nil { - return m.MountPoint - } - return "" -} - -func (m *Request) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *Request) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *Request) GetWrapInfo() *RequestWrapInfo { - if m != nil { - return m.WrapInfo - } - return nil -} - -func (m *Request) GetClientTokenRemainingUses() int64 { - if m != nil { - return m.ClientTokenRemainingUses - } - return 0 -} - -func (m *Request) GetEntityID() string { - if m != nil { - return m.EntityID - } - return "" -} - -func (m *Request) GetPolicyOverride() bool { - if m != nil { - return m.PolicyOverride - } - return false -} - -func (m *Request) GetUnauthenticated() bool { - if m != nil { - return m.Unauthenticated - } - return false -} - -func (m *Request) GetConnection() *Connection { - if m != nil { - return m.Connection - } - return nil -} - -type Auth struct { - LeaseOptions *LeaseOptions `sentinel:"" protobuf:"bytes,1,opt,name=lease_options,json=leaseOptions,proto3" json:"lease_options,omitempty"` - // InternalData is a JSON object 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 string `sentinel:"" protobuf:"bytes,2,opt,name=internal_data,json=internalData,proto3" json:"internal_data,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,3,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` - // Policies is the list of policies that the authenticated user - // is associated with. - Policies []string `sentinel:"" protobuf:"bytes,4,rep,name=policies,proto3" json:"policies,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,5,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // 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 `sentinel:"" protobuf:"bytes,6,opt,name=client_token,json=clientToken,proto3" json:"client_token,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,7,opt,name=accessor,proto3" json:"accessor,omitempty"` - // 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 int64 `sentinel:"" protobuf:"varint,8,opt,name=period,proto3" json:"period,omitempty"` - // Number of allowed uses of the issued token - NumUses int64 `sentinel:"" protobuf:"varint,9,opt,name=num_uses,json=numUses,proto3" json:"num_uses,omitempty"` - // EntityID is the identifier of the entity in identity store to which the - // identity of the authenticating client belongs to. - EntityID string `sentinel:"" protobuf:"bytes,10,opt,name=entity_id,json=entityId,proto3" json:"entity_id,omitempty"` - // Alias is the information about the authenticated client returned by - // the auth backend - Alias *logical.Alias `sentinel:"" protobuf:"bytes,11,opt,name=alias,proto3" json:"alias,omitempty"` - // 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 []*logical.Alias `sentinel:"" protobuf:"bytes,12,rep,name=group_aliases,json=groupAliases,proto3" json:"group_aliases,omitempty"` - // If set, restricts usage of the certificates to client IPs falling within - // the range of the specified CIDR(s). - BoundCIDRs []string `sentinel:"" protobuf:"bytes,13,rep,name=bound_cidrs,json=boundCidrs,proto3" json:"bound_cidrs,omitempty"` - // TokenPolicies and IdentityPolicies break down the list in Policies to - // help determine where a policy was sourced - TokenPolicies []string `sentinel:"" protobuf:"bytes,14,rep,name=token_policies,json=tokenPolicies,proto3" json:"token_policies,omitempty"` - IdentityPolicies []string `sentinel:"" protobuf:"bytes,15,rep,name=identity_policies,json=identityPolicies,proto3" json:"identity_policies,omitempty"` - // Explicit maximum lifetime for the token. Unlike normal TTLs, the maximum - // TTL is a hard limit and cannot be exceeded, also counts for periodic tokens. - ExplicitMaxTTL int64 `sentinel:"" protobuf:"varint,16,opt,name=explicit_max_ttl,json=explicitMaxTtl,proto3" json:"explicit_max_ttl,omitempty"` - // TokenType is the type of token being requested - TokenType uint32 `sentinel:"" protobuf:"varint,17,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Auth) Reset() { *m = Auth{} } -func (m *Auth) String() string { return proto.CompactTextString(m) } -func (*Auth) ProtoMessage() {} -func (*Auth) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{5} -} - -func (m *Auth) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Auth.Unmarshal(m, b) -} -func (m *Auth) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Auth.Marshal(b, m, deterministic) -} -func (m *Auth) XXX_Merge(src proto.Message) { - xxx_messageInfo_Auth.Merge(m, src) -} -func (m *Auth) XXX_Size() int { - return xxx_messageInfo_Auth.Size(m) -} -func (m *Auth) XXX_DiscardUnknown() { - xxx_messageInfo_Auth.DiscardUnknown(m) -} - -var xxx_messageInfo_Auth proto.InternalMessageInfo - -func (m *Auth) GetLeaseOptions() *LeaseOptions { - if m != nil { - return m.LeaseOptions - } - return nil -} - -func (m *Auth) GetInternalData() string { - if m != nil { - return m.InternalData - } - return "" -} - -func (m *Auth) GetDisplayName() string { - if m != nil { - return m.DisplayName - } - return "" -} - -func (m *Auth) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *Auth) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Auth) GetClientToken() string { - if m != nil { - return m.ClientToken - } - return "" -} - -func (m *Auth) GetAccessor() string { - if m != nil { - return m.Accessor - } - return "" -} - -func (m *Auth) GetPeriod() int64 { - if m != nil { - return m.Period - } - return 0 -} - -func (m *Auth) GetNumUses() int64 { - if m != nil { - return m.NumUses - } - return 0 -} - -func (m *Auth) GetEntityID() string { - if m != nil { - return m.EntityID - } - return "" -} - -func (m *Auth) GetAlias() *logical.Alias { - if m != nil { - return m.Alias - } - return nil -} - -func (m *Auth) GetGroupAliases() []*logical.Alias { - if m != nil { - return m.GroupAliases - } - return nil -} - -func (m *Auth) GetBoundCIDRs() []string { - if m != nil { - return m.BoundCIDRs - } - return nil -} - -func (m *Auth) GetTokenPolicies() []string { - if m != nil { - return m.TokenPolicies - } - return nil -} - -func (m *Auth) GetIdentityPolicies() []string { - if m != nil { - return m.IdentityPolicies - } - return nil -} - -func (m *Auth) GetExplicitMaxTTL() int64 { - if m != nil { - return m.ExplicitMaxTTL - } - return 0 -} - -func (m *Auth) GetTokenType() uint32 { - if m != nil { - return m.TokenType - } - return 0 -} - -type TokenEntry struct { - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Accessor string `sentinel:"" protobuf:"bytes,2,opt,name=accessor,proto3" json:"accessor,omitempty"` - Parent string `sentinel:"" protobuf:"bytes,3,opt,name=parent,proto3" json:"parent,omitempty"` - Policies []string `sentinel:"" protobuf:"bytes,4,rep,name=policies,proto3" json:"policies,omitempty"` - Path string `sentinel:"" protobuf:"bytes,5,opt,name=path,proto3" json:"path,omitempty"` - Meta map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=meta,proto3" json:"meta,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - DisplayName string `sentinel:"" protobuf:"bytes,7,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` - NumUses int64 `sentinel:"" protobuf:"varint,8,opt,name=num_uses,json=numUses,proto3" json:"num_uses,omitempty"` - CreationTime int64 `sentinel:"" protobuf:"varint,9,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - TTL int64 `sentinel:"" protobuf:"varint,10,opt,name=ttl,proto3" json:"ttl,omitempty"` - ExplicitMaxTTL int64 `sentinel:"" protobuf:"varint,11,opt,name=explicit_max_ttl,json=explicitMaxTtl,proto3" json:"explicit_max_ttl,omitempty"` - Role string `sentinel:"" protobuf:"bytes,12,opt,name=role,proto3" json:"role,omitempty"` - Period int64 `sentinel:"" protobuf:"varint,13,opt,name=period,proto3" json:"period,omitempty"` - EntityID string `sentinel:"" protobuf:"bytes,14,opt,name=entity_id,json=entityId,proto3" json:"entity_id,omitempty"` - BoundCIDRs []string `sentinel:"" protobuf:"bytes,15,rep,name=bound_cidrs,json=boundCidrs,proto3" json:"bound_cidrs,omitempty"` - NamespaceID string `sentinel:"" protobuf:"bytes,16,opt,name=namespace_id,json=namespaceID,proto3" json:"namespace_id,omitempty"` - CubbyholeID string `sentinel:"" protobuf:"bytes,17,opt,name=cubbyhole_id,json=cubbyholeId,proto3" json:"cubbyhole_id,omitempty"` - Type uint32 `sentinel:"" protobuf:"varint,18,opt,name=type,proto3" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TokenEntry) Reset() { *m = TokenEntry{} } -func (m *TokenEntry) String() string { return proto.CompactTextString(m) } -func (*TokenEntry) ProtoMessage() {} -func (*TokenEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{6} -} - -func (m *TokenEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TokenEntry.Unmarshal(m, b) -} -func (m *TokenEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TokenEntry.Marshal(b, m, deterministic) -} -func (m *TokenEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_TokenEntry.Merge(m, src) -} -func (m *TokenEntry) XXX_Size() int { - return xxx_messageInfo_TokenEntry.Size(m) -} -func (m *TokenEntry) XXX_DiscardUnknown() { - xxx_messageInfo_TokenEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_TokenEntry proto.InternalMessageInfo - -func (m *TokenEntry) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *TokenEntry) GetAccessor() string { - if m != nil { - return m.Accessor - } - return "" -} - -func (m *TokenEntry) GetParent() string { - if m != nil { - return m.Parent - } - return "" -} - -func (m *TokenEntry) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *TokenEntry) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *TokenEntry) GetMeta() map[string]string { - if m != nil { - return m.Meta - } - return nil -} - -func (m *TokenEntry) GetDisplayName() string { - if m != nil { - return m.DisplayName - } - return "" -} - -func (m *TokenEntry) GetNumUses() int64 { - if m != nil { - return m.NumUses - } - return 0 -} - -func (m *TokenEntry) GetCreationTime() int64 { - if m != nil { - return m.CreationTime - } - return 0 -} - -func (m *TokenEntry) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -func (m *TokenEntry) GetExplicitMaxTTL() int64 { - if m != nil { - return m.ExplicitMaxTTL - } - return 0 -} - -func (m *TokenEntry) GetRole() string { - if m != nil { - return m.Role - } - return "" -} - -func (m *TokenEntry) GetPeriod() int64 { - if m != nil { - return m.Period - } - return 0 -} - -func (m *TokenEntry) GetEntityID() string { - if m != nil { - return m.EntityID - } - return "" -} - -func (m *TokenEntry) GetBoundCIDRs() []string { - if m != nil { - return m.BoundCIDRs - } - return nil -} - -func (m *TokenEntry) GetNamespaceID() string { - if m != nil { - return m.NamespaceID - } - return "" -} - -func (m *TokenEntry) GetCubbyholeID() string { - if m != nil { - return m.CubbyholeID - } - return "" -} - -func (m *TokenEntry) GetType() uint32 { - if m != nil { - return m.Type - } - return 0 -} - -type LeaseOptions struct { - TTL int64 `sentinel:"" protobuf:"varint,1,opt,name=TTL,proto3" json:"TTL,omitempty"` - Renewable bool `sentinel:"" protobuf:"varint,2,opt,name=renewable,proto3" json:"renewable,omitempty"` - Increment int64 `sentinel:"" protobuf:"varint,3,opt,name=increment,proto3" json:"increment,omitempty"` - IssueTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,4,opt,name=issue_time,json=issueTime,proto3" json:"issue_time,omitempty"` - MaxTTL int64 `sentinel:"" protobuf:"varint,5,opt,name=MaxTTL,proto3" json:"MaxTTL,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LeaseOptions) Reset() { *m = LeaseOptions{} } -func (m *LeaseOptions) String() string { return proto.CompactTextString(m) } -func (*LeaseOptions) ProtoMessage() {} -func (*LeaseOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{7} -} - -func (m *LeaseOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LeaseOptions.Unmarshal(m, b) -} -func (m *LeaseOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LeaseOptions.Marshal(b, m, deterministic) -} -func (m *LeaseOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_LeaseOptions.Merge(m, src) -} -func (m *LeaseOptions) XXX_Size() int { - return xxx_messageInfo_LeaseOptions.Size(m) -} -func (m *LeaseOptions) XXX_DiscardUnknown() { - xxx_messageInfo_LeaseOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_LeaseOptions proto.InternalMessageInfo - -func (m *LeaseOptions) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -func (m *LeaseOptions) GetRenewable() bool { - if m != nil { - return m.Renewable - } - return false -} - -func (m *LeaseOptions) GetIncrement() int64 { - if m != nil { - return m.Increment - } - return 0 -} - -func (m *LeaseOptions) GetIssueTime() *timestamp.Timestamp { - if m != nil { - return m.IssueTime - } - return nil -} - -func (m *LeaseOptions) GetMaxTTL() int64 { - if m != nil { - return m.MaxTTL - } - return 0 -} - -type Secret struct { - LeaseOptions *LeaseOptions `sentinel:"" protobuf:"bytes,1,opt,name=lease_options,json=leaseOptions,proto3" json:"lease_options,omitempty"` - // InternalData is a JSON object that is stored with the secret. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - InternalData string `sentinel:"" protobuf:"bytes,2,opt,name=internal_data,json=internalData,proto3" json:"internal_data,omitempty"` - // 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:"" protobuf:"bytes,3,opt,name=lease_id,json=leaseId,proto3" json:"lease_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Secret) Reset() { *m = Secret{} } -func (m *Secret) String() string { return proto.CompactTextString(m) } -func (*Secret) ProtoMessage() {} -func (*Secret) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{8} -} - -func (m *Secret) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Secret.Unmarshal(m, b) -} -func (m *Secret) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Secret.Marshal(b, m, deterministic) -} -func (m *Secret) XXX_Merge(src proto.Message) { - xxx_messageInfo_Secret.Merge(m, src) -} -func (m *Secret) XXX_Size() int { - return xxx_messageInfo_Secret.Size(m) -} -func (m *Secret) XXX_DiscardUnknown() { - xxx_messageInfo_Secret.DiscardUnknown(m) -} - -var xxx_messageInfo_Secret proto.InternalMessageInfo - -func (m *Secret) GetLeaseOptions() *LeaseOptions { - if m != nil { - return m.LeaseOptions - } - return nil -} - -func (m *Secret) GetInternalData() string { - if m != nil { - return m.InternalData - } - return "" -} - -func (m *Secret) GetLeaseID() string { - if m != nil { - return m.LeaseID - } - return "" -} - -type Response struct { - // Secret, if not nil, denotes that this response represents a secret. - Secret *Secret `sentinel:"" protobuf:"bytes,1,opt,name=secret,proto3" json:"secret,omitempty"` - // Auth, if not nil, contains the authentication information for - // this response. This is only checked and means something for - // credential backends. - Auth *Auth `sentinel:"" protobuf:"bytes,2,opt,name=auth,proto3" json:"auth,omitempty"` - // Response data is a JSON object 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 string `sentinel:"" protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - // 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 `sentinel:"" protobuf:"bytes,4,opt,name=redirect,proto3" json:"redirect,omitempty"` - // Warnings allow operations or backends to return warnings in response - // to user actions without failing the action outright. - Warnings []string `sentinel:"" protobuf:"bytes,5,rep,name=warnings,proto3" json:"warnings,omitempty"` - // Information for wrapping the response in a cubbyhole - WrapInfo *ResponseWrapInfo `sentinel:"" protobuf:"bytes,6,opt,name=wrap_info,json=wrapInfo,proto3" json:"wrap_info,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{9} -} - -func (m *Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Response.Unmarshal(m, b) -} -func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Response.Marshal(b, m, deterministic) -} -func (m *Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Response.Merge(m, src) -} -func (m *Response) XXX_Size() int { - return xxx_messageInfo_Response.Size(m) -} -func (m *Response) XXX_DiscardUnknown() { - xxx_messageInfo_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Response proto.InternalMessageInfo - -func (m *Response) GetSecret() *Secret { - if m != nil { - return m.Secret - } - return nil -} - -func (m *Response) GetAuth() *Auth { - if m != nil { - return m.Auth - } - return nil -} - -func (m *Response) GetData() string { - if m != nil { - return m.Data - } - return "" -} - -func (m *Response) GetRedirect() string { - if m != nil { - return m.Redirect - } - return "" -} - -func (m *Response) GetWarnings() []string { - if m != nil { - return m.Warnings - } - return nil -} - -func (m *Response) GetWrapInfo() *ResponseWrapInfo { - if m != nil { - return m.WrapInfo - } - return nil -} - -type ResponseWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL int64 `sentinel:"" protobuf:"varint,1,opt,name=TTL,proto3" json:"TTL,omitempty"` - // The token containing the wrapped response - Token string `sentinel:"" protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"` - // The token accessor for the wrapped response token - Accessor string `sentinel:"" protobuf:"bytes,3,opt,name=accessor,proto3" json:"accessor,omitempty"` - // The creation time. This can be used with the TTL to figure out an - // expected expiration. - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,4,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // If the contained response is the output of a token creation call, the - // created token's accessor will be accessible here - WrappedAccessor string `sentinel:"" protobuf:"bytes,5,opt,name=wrapped_accessor,json=wrappedAccessor,proto3" json:"wrapped_accessor,omitempty"` - // WrappedEntityID is the entity identifier of the caller who initiated the - // wrapping request - WrappedEntityID string `sentinel:"" protobuf:"bytes,6,opt,name=wrapped_entity_id,json=wrappedEntityID,proto3" json:"wrapped_entity_id,omitempty"` - // The format to use. This doesn't get returned, it's only internal. - Format string `sentinel:"" protobuf:"bytes,7,opt,name=format,proto3" json:"format,omitempty"` - // CreationPath is the original request path that was used to create - // the wrapped response. - CreationPath string `sentinel:"" protobuf:"bytes,8,opt,name=creation_path,json=creationPath,proto3" json:"creation_path,omitempty"` - // Controls seal wrapping behavior downstream for specific use cases - SealWrap bool `sentinel:"" protobuf:"varint,9,opt,name=seal_wrap,json=sealWrap,proto3" json:"seal_wrap,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseWrapInfo) Reset() { *m = ResponseWrapInfo{} } -func (m *ResponseWrapInfo) String() string { return proto.CompactTextString(m) } -func (*ResponseWrapInfo) ProtoMessage() {} -func (*ResponseWrapInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{10} -} - -func (m *ResponseWrapInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseWrapInfo.Unmarshal(m, b) -} -func (m *ResponseWrapInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseWrapInfo.Marshal(b, m, deterministic) -} -func (m *ResponseWrapInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseWrapInfo.Merge(m, src) -} -func (m *ResponseWrapInfo) XXX_Size() int { - return xxx_messageInfo_ResponseWrapInfo.Size(m) -} -func (m *ResponseWrapInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseWrapInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseWrapInfo proto.InternalMessageInfo - -func (m *ResponseWrapInfo) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -func (m *ResponseWrapInfo) GetToken() string { - if m != nil { - return m.Token - } - return "" -} - -func (m *ResponseWrapInfo) GetAccessor() string { - if m != nil { - return m.Accessor - } - return "" -} - -func (m *ResponseWrapInfo) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *ResponseWrapInfo) GetWrappedAccessor() string { - if m != nil { - return m.WrappedAccessor - } - return "" -} - -func (m *ResponseWrapInfo) GetWrappedEntityID() string { - if m != nil { - return m.WrappedEntityID - } - return "" -} - -func (m *ResponseWrapInfo) GetFormat() string { - if m != nil { - return m.Format - } - return "" -} - -func (m *ResponseWrapInfo) GetCreationPath() string { - if m != nil { - return m.CreationPath - } - return "" -} - -func (m *ResponseWrapInfo) GetSealWrap() bool { - if m != nil { - return m.SealWrap - } - return false -} - -type RequestWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL int64 `sentinel:"" protobuf:"varint,1,opt,name=TTL,proto3" json:"TTL,omitempty"` - // The format to use for the wrapped response; if not specified it's a bare - // token - Format string `sentinel:"" protobuf:"bytes,2,opt,name=format,proto3" json:"format,omitempty"` - // A flag to conforming backends that data for a given request should be - // seal wrapped - SealWrap bool `sentinel:"" protobuf:"varint,3,opt,name=seal_wrap,json=sealWrap,proto3" json:"seal_wrap,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RequestWrapInfo) Reset() { *m = RequestWrapInfo{} } -func (m *RequestWrapInfo) String() string { return proto.CompactTextString(m) } -func (*RequestWrapInfo) ProtoMessage() {} -func (*RequestWrapInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{11} -} - -func (m *RequestWrapInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RequestWrapInfo.Unmarshal(m, b) -} -func (m *RequestWrapInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RequestWrapInfo.Marshal(b, m, deterministic) -} -func (m *RequestWrapInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_RequestWrapInfo.Merge(m, src) -} -func (m *RequestWrapInfo) XXX_Size() int { - return xxx_messageInfo_RequestWrapInfo.Size(m) -} -func (m *RequestWrapInfo) XXX_DiscardUnknown() { - xxx_messageInfo_RequestWrapInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_RequestWrapInfo proto.InternalMessageInfo - -func (m *RequestWrapInfo) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -func (m *RequestWrapInfo) GetFormat() string { - if m != nil { - return m.Format - } - return "" -} - -func (m *RequestWrapInfo) GetSealWrap() bool { - if m != nil { - return m.SealWrap - } - return false -} - -// HandleRequestArgs is the args for HandleRequest method. -type HandleRequestArgs struct { - StorageID uint32 `sentinel:"" protobuf:"varint,1,opt,name=storage_id,json=storageId,proto3" json:"storage_id,omitempty"` - Request *Request `sentinel:"" protobuf:"bytes,2,opt,name=request,proto3" json:"request,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandleRequestArgs) Reset() { *m = HandleRequestArgs{} } -func (m *HandleRequestArgs) String() string { return proto.CompactTextString(m) } -func (*HandleRequestArgs) ProtoMessage() {} -func (*HandleRequestArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{12} -} - -func (m *HandleRequestArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandleRequestArgs.Unmarshal(m, b) -} -func (m *HandleRequestArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandleRequestArgs.Marshal(b, m, deterministic) -} -func (m *HandleRequestArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandleRequestArgs.Merge(m, src) -} -func (m *HandleRequestArgs) XXX_Size() int { - return xxx_messageInfo_HandleRequestArgs.Size(m) -} -func (m *HandleRequestArgs) XXX_DiscardUnknown() { - xxx_messageInfo_HandleRequestArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_HandleRequestArgs proto.InternalMessageInfo - -func (m *HandleRequestArgs) GetStorageID() uint32 { - if m != nil { - return m.StorageID - } - return 0 -} - -func (m *HandleRequestArgs) GetRequest() *Request { - if m != nil { - return m.Request - } - return nil -} - -// HandleRequestReply is the reply for HandleRequest method. -type HandleRequestReply struct { - Response *Response `sentinel:"" protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"` - Err *ProtoError `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandleRequestReply) Reset() { *m = HandleRequestReply{} } -func (m *HandleRequestReply) String() string { return proto.CompactTextString(m) } -func (*HandleRequestReply) ProtoMessage() {} -func (*HandleRequestReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{13} -} - -func (m *HandleRequestReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandleRequestReply.Unmarshal(m, b) -} -func (m *HandleRequestReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandleRequestReply.Marshal(b, m, deterministic) -} -func (m *HandleRequestReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandleRequestReply.Merge(m, src) -} -func (m *HandleRequestReply) XXX_Size() int { - return xxx_messageInfo_HandleRequestReply.Size(m) -} -func (m *HandleRequestReply) XXX_DiscardUnknown() { - xxx_messageInfo_HandleRequestReply.DiscardUnknown(m) -} - -var xxx_messageInfo_HandleRequestReply proto.InternalMessageInfo - -func (m *HandleRequestReply) GetResponse() *Response { - if m != nil { - return m.Response - } - return nil -} - -func (m *HandleRequestReply) GetErr() *ProtoError { - if m != nil { - return m.Err - } - return nil -} - -// SpecialPathsReply is the reply for SpecialPaths method. -type SpecialPathsReply struct { - Paths *Paths `sentinel:"" protobuf:"bytes,1,opt,name=paths,proto3" json:"paths,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SpecialPathsReply) Reset() { *m = SpecialPathsReply{} } -func (m *SpecialPathsReply) String() string { return proto.CompactTextString(m) } -func (*SpecialPathsReply) ProtoMessage() {} -func (*SpecialPathsReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{14} -} - -func (m *SpecialPathsReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SpecialPathsReply.Unmarshal(m, b) -} -func (m *SpecialPathsReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SpecialPathsReply.Marshal(b, m, deterministic) -} -func (m *SpecialPathsReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_SpecialPathsReply.Merge(m, src) -} -func (m *SpecialPathsReply) XXX_Size() int { - return xxx_messageInfo_SpecialPathsReply.Size(m) -} -func (m *SpecialPathsReply) XXX_DiscardUnknown() { - xxx_messageInfo_SpecialPathsReply.DiscardUnknown(m) -} - -var xxx_messageInfo_SpecialPathsReply proto.InternalMessageInfo - -func (m *SpecialPathsReply) GetPaths() *Paths { - if m != nil { - return m.Paths - } - return nil -} - -// HandleExistenceCheckArgs is the args for HandleExistenceCheck method. -type HandleExistenceCheckArgs struct { - StorageID uint32 `sentinel:"" protobuf:"varint,1,opt,name=storage_id,json=storageId,proto3" json:"storage_id,omitempty"` - Request *Request `sentinel:"" protobuf:"bytes,2,opt,name=request,proto3" json:"request,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandleExistenceCheckArgs) Reset() { *m = HandleExistenceCheckArgs{} } -func (m *HandleExistenceCheckArgs) String() string { return proto.CompactTextString(m) } -func (*HandleExistenceCheckArgs) ProtoMessage() {} -func (*HandleExistenceCheckArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{15} -} - -func (m *HandleExistenceCheckArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandleExistenceCheckArgs.Unmarshal(m, b) -} -func (m *HandleExistenceCheckArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandleExistenceCheckArgs.Marshal(b, m, deterministic) -} -func (m *HandleExistenceCheckArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandleExistenceCheckArgs.Merge(m, src) -} -func (m *HandleExistenceCheckArgs) XXX_Size() int { - return xxx_messageInfo_HandleExistenceCheckArgs.Size(m) -} -func (m *HandleExistenceCheckArgs) XXX_DiscardUnknown() { - xxx_messageInfo_HandleExistenceCheckArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_HandleExistenceCheckArgs proto.InternalMessageInfo - -func (m *HandleExistenceCheckArgs) GetStorageID() uint32 { - if m != nil { - return m.StorageID - } - return 0 -} - -func (m *HandleExistenceCheckArgs) GetRequest() *Request { - if m != nil { - return m.Request - } - return nil -} - -// HandleExistenceCheckReply is the reply for HandleExistenceCheck method. -type HandleExistenceCheckReply struct { - CheckFound bool `sentinel:"" protobuf:"varint,1,opt,name=check_found,json=checkFound,proto3" json:"check_found,omitempty"` - Exists bool `sentinel:"" protobuf:"varint,2,opt,name=exists,proto3" json:"exists,omitempty"` - Err *ProtoError `sentinel:"" protobuf:"bytes,3,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandleExistenceCheckReply) Reset() { *m = HandleExistenceCheckReply{} } -func (m *HandleExistenceCheckReply) String() string { return proto.CompactTextString(m) } -func (*HandleExistenceCheckReply) ProtoMessage() {} -func (*HandleExistenceCheckReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{16} -} - -func (m *HandleExistenceCheckReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandleExistenceCheckReply.Unmarshal(m, b) -} -func (m *HandleExistenceCheckReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandleExistenceCheckReply.Marshal(b, m, deterministic) -} -func (m *HandleExistenceCheckReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandleExistenceCheckReply.Merge(m, src) -} -func (m *HandleExistenceCheckReply) XXX_Size() int { - return xxx_messageInfo_HandleExistenceCheckReply.Size(m) -} -func (m *HandleExistenceCheckReply) XXX_DiscardUnknown() { - xxx_messageInfo_HandleExistenceCheckReply.DiscardUnknown(m) -} - -var xxx_messageInfo_HandleExistenceCheckReply proto.InternalMessageInfo - -func (m *HandleExistenceCheckReply) GetCheckFound() bool { - if m != nil { - return m.CheckFound - } - return false -} - -func (m *HandleExistenceCheckReply) GetExists() bool { - if m != nil { - return m.Exists - } - return false -} - -func (m *HandleExistenceCheckReply) GetErr() *ProtoError { - if m != nil { - return m.Err - } - return nil -} - -// SetupArgs is the args for Setup method. -type SetupArgs struct { - BrokerID uint32 `sentinel:"" protobuf:"varint,1,opt,name=broker_id,json=brokerId,proto3" json:"broker_id,omitempty"` - Config map[string]string `sentinel:"" protobuf:"bytes,2,rep,name=Config,proto3" json:"Config,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - BackendUUID string `sentinel:"" protobuf:"bytes,3,opt,name=backendUUID,proto3" json:"backendUUID,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SetupArgs) Reset() { *m = SetupArgs{} } -func (m *SetupArgs) String() string { return proto.CompactTextString(m) } -func (*SetupArgs) ProtoMessage() {} -func (*SetupArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{17} -} - -func (m *SetupArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SetupArgs.Unmarshal(m, b) -} -func (m *SetupArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SetupArgs.Marshal(b, m, deterministic) -} -func (m *SetupArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_SetupArgs.Merge(m, src) -} -func (m *SetupArgs) XXX_Size() int { - return xxx_messageInfo_SetupArgs.Size(m) -} -func (m *SetupArgs) XXX_DiscardUnknown() { - xxx_messageInfo_SetupArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_SetupArgs proto.InternalMessageInfo - -func (m *SetupArgs) GetBrokerID() uint32 { - if m != nil { - return m.BrokerID - } - return 0 -} - -func (m *SetupArgs) GetConfig() map[string]string { - if m != nil { - return m.Config - } - return nil -} - -func (m *SetupArgs) GetBackendUUID() string { - if m != nil { - return m.BackendUUID - } - return "" -} - -// SetupReply is the reply for Setup method. -type SetupReply struct { - Err string `sentinel:"" protobuf:"bytes,1,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SetupReply) Reset() { *m = SetupReply{} } -func (m *SetupReply) String() string { return proto.CompactTextString(m) } -func (*SetupReply) ProtoMessage() {} -func (*SetupReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{18} -} - -func (m *SetupReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SetupReply.Unmarshal(m, b) -} -func (m *SetupReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SetupReply.Marshal(b, m, deterministic) -} -func (m *SetupReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_SetupReply.Merge(m, src) -} -func (m *SetupReply) XXX_Size() int { - return xxx_messageInfo_SetupReply.Size(m) -} -func (m *SetupReply) XXX_DiscardUnknown() { - xxx_messageInfo_SetupReply.DiscardUnknown(m) -} - -var xxx_messageInfo_SetupReply proto.InternalMessageInfo - -func (m *SetupReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -// TypeReply is the reply for the Type method. -type TypeReply struct { - Type uint32 `sentinel:"" protobuf:"varint,1,opt,name=type,proto3" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TypeReply) Reset() { *m = TypeReply{} } -func (m *TypeReply) String() string { return proto.CompactTextString(m) } -func (*TypeReply) ProtoMessage() {} -func (*TypeReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{19} -} - -func (m *TypeReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TypeReply.Unmarshal(m, b) -} -func (m *TypeReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TypeReply.Marshal(b, m, deterministic) -} -func (m *TypeReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_TypeReply.Merge(m, src) -} -func (m *TypeReply) XXX_Size() int { - return xxx_messageInfo_TypeReply.Size(m) -} -func (m *TypeReply) XXX_DiscardUnknown() { - xxx_messageInfo_TypeReply.DiscardUnknown(m) -} - -var xxx_messageInfo_TypeReply proto.InternalMessageInfo - -func (m *TypeReply) GetType() uint32 { - if m != nil { - return m.Type - } - return 0 -} - -type InvalidateKeyArgs struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InvalidateKeyArgs) Reset() { *m = InvalidateKeyArgs{} } -func (m *InvalidateKeyArgs) String() string { return proto.CompactTextString(m) } -func (*InvalidateKeyArgs) ProtoMessage() {} -func (*InvalidateKeyArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{20} -} - -func (m *InvalidateKeyArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InvalidateKeyArgs.Unmarshal(m, b) -} -func (m *InvalidateKeyArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InvalidateKeyArgs.Marshal(b, m, deterministic) -} -func (m *InvalidateKeyArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_InvalidateKeyArgs.Merge(m, src) -} -func (m *InvalidateKeyArgs) XXX_Size() int { - return xxx_messageInfo_InvalidateKeyArgs.Size(m) -} -func (m *InvalidateKeyArgs) XXX_DiscardUnknown() { - xxx_messageInfo_InvalidateKeyArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_InvalidateKeyArgs proto.InternalMessageInfo - -func (m *InvalidateKeyArgs) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -type StorageEntry struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Value []byte `sentinel:"" protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - SealWrap bool `sentinel:"" protobuf:"varint,3,opt,name=seal_wrap,json=sealWrap,proto3" json:"seal_wrap,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageEntry) Reset() { *m = StorageEntry{} } -func (m *StorageEntry) String() string { return proto.CompactTextString(m) } -func (*StorageEntry) ProtoMessage() {} -func (*StorageEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{21} -} - -func (m *StorageEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageEntry.Unmarshal(m, b) -} -func (m *StorageEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageEntry.Marshal(b, m, deterministic) -} -func (m *StorageEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageEntry.Merge(m, src) -} -func (m *StorageEntry) XXX_Size() int { - return xxx_messageInfo_StorageEntry.Size(m) -} -func (m *StorageEntry) XXX_DiscardUnknown() { - xxx_messageInfo_StorageEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageEntry proto.InternalMessageInfo - -func (m *StorageEntry) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *StorageEntry) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *StorageEntry) GetSealWrap() bool { - if m != nil { - return m.SealWrap - } - return false -} - -type StorageListArgs struct { - Prefix string `sentinel:"" protobuf:"bytes,1,opt,name=prefix,proto3" json:"prefix,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageListArgs) Reset() { *m = StorageListArgs{} } -func (m *StorageListArgs) String() string { return proto.CompactTextString(m) } -func (*StorageListArgs) ProtoMessage() {} -func (*StorageListArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{22} -} - -func (m *StorageListArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageListArgs.Unmarshal(m, b) -} -func (m *StorageListArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageListArgs.Marshal(b, m, deterministic) -} -func (m *StorageListArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageListArgs.Merge(m, src) -} -func (m *StorageListArgs) XXX_Size() int { - return xxx_messageInfo_StorageListArgs.Size(m) -} -func (m *StorageListArgs) XXX_DiscardUnknown() { - xxx_messageInfo_StorageListArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageListArgs proto.InternalMessageInfo - -func (m *StorageListArgs) GetPrefix() string { - if m != nil { - return m.Prefix - } - return "" -} - -type StorageListReply struct { - Keys []string `sentinel:"" protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` - Err string `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageListReply) Reset() { *m = StorageListReply{} } -func (m *StorageListReply) String() string { return proto.CompactTextString(m) } -func (*StorageListReply) ProtoMessage() {} -func (*StorageListReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{23} -} - -func (m *StorageListReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageListReply.Unmarshal(m, b) -} -func (m *StorageListReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageListReply.Marshal(b, m, deterministic) -} -func (m *StorageListReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageListReply.Merge(m, src) -} -func (m *StorageListReply) XXX_Size() int { - return xxx_messageInfo_StorageListReply.Size(m) -} -func (m *StorageListReply) XXX_DiscardUnknown() { - xxx_messageInfo_StorageListReply.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageListReply proto.InternalMessageInfo - -func (m *StorageListReply) GetKeys() []string { - if m != nil { - return m.Keys - } - return nil -} - -func (m *StorageListReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type StorageGetArgs struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageGetArgs) Reset() { *m = StorageGetArgs{} } -func (m *StorageGetArgs) String() string { return proto.CompactTextString(m) } -func (*StorageGetArgs) ProtoMessage() {} -func (*StorageGetArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{24} -} - -func (m *StorageGetArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageGetArgs.Unmarshal(m, b) -} -func (m *StorageGetArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageGetArgs.Marshal(b, m, deterministic) -} -func (m *StorageGetArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageGetArgs.Merge(m, src) -} -func (m *StorageGetArgs) XXX_Size() int { - return xxx_messageInfo_StorageGetArgs.Size(m) -} -func (m *StorageGetArgs) XXX_DiscardUnknown() { - xxx_messageInfo_StorageGetArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageGetArgs proto.InternalMessageInfo - -func (m *StorageGetArgs) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -type StorageGetReply struct { - Entry *StorageEntry `sentinel:"" protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"` - Err string `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageGetReply) Reset() { *m = StorageGetReply{} } -func (m *StorageGetReply) String() string { return proto.CompactTextString(m) } -func (*StorageGetReply) ProtoMessage() {} -func (*StorageGetReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{25} -} - -func (m *StorageGetReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageGetReply.Unmarshal(m, b) -} -func (m *StorageGetReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageGetReply.Marshal(b, m, deterministic) -} -func (m *StorageGetReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageGetReply.Merge(m, src) -} -func (m *StorageGetReply) XXX_Size() int { - return xxx_messageInfo_StorageGetReply.Size(m) -} -func (m *StorageGetReply) XXX_DiscardUnknown() { - xxx_messageInfo_StorageGetReply.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageGetReply proto.InternalMessageInfo - -func (m *StorageGetReply) GetEntry() *StorageEntry { - if m != nil { - return m.Entry - } - return nil -} - -func (m *StorageGetReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type StoragePutArgs struct { - Entry *StorageEntry `sentinel:"" protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StoragePutArgs) Reset() { *m = StoragePutArgs{} } -func (m *StoragePutArgs) String() string { return proto.CompactTextString(m) } -func (*StoragePutArgs) ProtoMessage() {} -func (*StoragePutArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{26} -} - -func (m *StoragePutArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StoragePutArgs.Unmarshal(m, b) -} -func (m *StoragePutArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StoragePutArgs.Marshal(b, m, deterministic) -} -func (m *StoragePutArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoragePutArgs.Merge(m, src) -} -func (m *StoragePutArgs) XXX_Size() int { - return xxx_messageInfo_StoragePutArgs.Size(m) -} -func (m *StoragePutArgs) XXX_DiscardUnknown() { - xxx_messageInfo_StoragePutArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_StoragePutArgs proto.InternalMessageInfo - -func (m *StoragePutArgs) GetEntry() *StorageEntry { - if m != nil { - return m.Entry - } - return nil -} - -type StoragePutReply struct { - Err string `sentinel:"" protobuf:"bytes,1,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StoragePutReply) Reset() { *m = StoragePutReply{} } -func (m *StoragePutReply) String() string { return proto.CompactTextString(m) } -func (*StoragePutReply) ProtoMessage() {} -func (*StoragePutReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{27} -} - -func (m *StoragePutReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StoragePutReply.Unmarshal(m, b) -} -func (m *StoragePutReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StoragePutReply.Marshal(b, m, deterministic) -} -func (m *StoragePutReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoragePutReply.Merge(m, src) -} -func (m *StoragePutReply) XXX_Size() int { - return xxx_messageInfo_StoragePutReply.Size(m) -} -func (m *StoragePutReply) XXX_DiscardUnknown() { - xxx_messageInfo_StoragePutReply.DiscardUnknown(m) -} - -var xxx_messageInfo_StoragePutReply proto.InternalMessageInfo - -func (m *StoragePutReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type StorageDeleteArgs struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageDeleteArgs) Reset() { *m = StorageDeleteArgs{} } -func (m *StorageDeleteArgs) String() string { return proto.CompactTextString(m) } -func (*StorageDeleteArgs) ProtoMessage() {} -func (*StorageDeleteArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{28} -} - -func (m *StorageDeleteArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageDeleteArgs.Unmarshal(m, b) -} -func (m *StorageDeleteArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageDeleteArgs.Marshal(b, m, deterministic) -} -func (m *StorageDeleteArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageDeleteArgs.Merge(m, src) -} -func (m *StorageDeleteArgs) XXX_Size() int { - return xxx_messageInfo_StorageDeleteArgs.Size(m) -} -func (m *StorageDeleteArgs) XXX_DiscardUnknown() { - xxx_messageInfo_StorageDeleteArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageDeleteArgs proto.InternalMessageInfo - -func (m *StorageDeleteArgs) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -type StorageDeleteReply struct { - Err string `sentinel:"" protobuf:"bytes,1,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StorageDeleteReply) Reset() { *m = StorageDeleteReply{} } -func (m *StorageDeleteReply) String() string { return proto.CompactTextString(m) } -func (*StorageDeleteReply) ProtoMessage() {} -func (*StorageDeleteReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{29} -} - -func (m *StorageDeleteReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StorageDeleteReply.Unmarshal(m, b) -} -func (m *StorageDeleteReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StorageDeleteReply.Marshal(b, m, deterministic) -} -func (m *StorageDeleteReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_StorageDeleteReply.Merge(m, src) -} -func (m *StorageDeleteReply) XXX_Size() int { - return xxx_messageInfo_StorageDeleteReply.Size(m) -} -func (m *StorageDeleteReply) XXX_DiscardUnknown() { - xxx_messageInfo_StorageDeleteReply.DiscardUnknown(m) -} - -var xxx_messageInfo_StorageDeleteReply proto.InternalMessageInfo - -func (m *StorageDeleteReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type TTLReply struct { - TTL int64 `sentinel:"" protobuf:"varint,1,opt,name=TTL,proto3" json:"TTL,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TTLReply) Reset() { *m = TTLReply{} } -func (m *TTLReply) String() string { return proto.CompactTextString(m) } -func (*TTLReply) ProtoMessage() {} -func (*TTLReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{30} -} - -func (m *TTLReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TTLReply.Unmarshal(m, b) -} -func (m *TTLReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TTLReply.Marshal(b, m, deterministic) -} -func (m *TTLReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_TTLReply.Merge(m, src) -} -func (m *TTLReply) XXX_Size() int { - return xxx_messageInfo_TTLReply.Size(m) -} -func (m *TTLReply) XXX_DiscardUnknown() { - xxx_messageInfo_TTLReply.DiscardUnknown(m) -} - -var xxx_messageInfo_TTLReply proto.InternalMessageInfo - -func (m *TTLReply) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -type SudoPrivilegeArgs struct { - Path string `sentinel:"" protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` - Token string `sentinel:"" protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SudoPrivilegeArgs) Reset() { *m = SudoPrivilegeArgs{} } -func (m *SudoPrivilegeArgs) String() string { return proto.CompactTextString(m) } -func (*SudoPrivilegeArgs) ProtoMessage() {} -func (*SudoPrivilegeArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{31} -} - -func (m *SudoPrivilegeArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SudoPrivilegeArgs.Unmarshal(m, b) -} -func (m *SudoPrivilegeArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SudoPrivilegeArgs.Marshal(b, m, deterministic) -} -func (m *SudoPrivilegeArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_SudoPrivilegeArgs.Merge(m, src) -} -func (m *SudoPrivilegeArgs) XXX_Size() int { - return xxx_messageInfo_SudoPrivilegeArgs.Size(m) -} -func (m *SudoPrivilegeArgs) XXX_DiscardUnknown() { - xxx_messageInfo_SudoPrivilegeArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_SudoPrivilegeArgs proto.InternalMessageInfo - -func (m *SudoPrivilegeArgs) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *SudoPrivilegeArgs) GetToken() string { - if m != nil { - return m.Token - } - return "" -} - -type SudoPrivilegeReply struct { - Sudo bool `sentinel:"" protobuf:"varint,1,opt,name=sudo,proto3" json:"sudo,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SudoPrivilegeReply) Reset() { *m = SudoPrivilegeReply{} } -func (m *SudoPrivilegeReply) String() string { return proto.CompactTextString(m) } -func (*SudoPrivilegeReply) ProtoMessage() {} -func (*SudoPrivilegeReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{32} -} - -func (m *SudoPrivilegeReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SudoPrivilegeReply.Unmarshal(m, b) -} -func (m *SudoPrivilegeReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SudoPrivilegeReply.Marshal(b, m, deterministic) -} -func (m *SudoPrivilegeReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_SudoPrivilegeReply.Merge(m, src) -} -func (m *SudoPrivilegeReply) XXX_Size() int { - return xxx_messageInfo_SudoPrivilegeReply.Size(m) -} -func (m *SudoPrivilegeReply) XXX_DiscardUnknown() { - xxx_messageInfo_SudoPrivilegeReply.DiscardUnknown(m) -} - -var xxx_messageInfo_SudoPrivilegeReply proto.InternalMessageInfo - -func (m *SudoPrivilegeReply) GetSudo() bool { - if m != nil { - return m.Sudo - } - return false -} - -type TaintedReply struct { - Tainted bool `sentinel:"" protobuf:"varint,1,opt,name=tainted,proto3" json:"tainted,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TaintedReply) Reset() { *m = TaintedReply{} } -func (m *TaintedReply) String() string { return proto.CompactTextString(m) } -func (*TaintedReply) ProtoMessage() {} -func (*TaintedReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{33} -} - -func (m *TaintedReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TaintedReply.Unmarshal(m, b) -} -func (m *TaintedReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TaintedReply.Marshal(b, m, deterministic) -} -func (m *TaintedReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_TaintedReply.Merge(m, src) -} -func (m *TaintedReply) XXX_Size() int { - return xxx_messageInfo_TaintedReply.Size(m) -} -func (m *TaintedReply) XXX_DiscardUnknown() { - xxx_messageInfo_TaintedReply.DiscardUnknown(m) -} - -var xxx_messageInfo_TaintedReply proto.InternalMessageInfo - -func (m *TaintedReply) GetTainted() bool { - if m != nil { - return m.Tainted - } - return false -} - -type CachingDisabledReply struct { - Disabled bool `sentinel:"" protobuf:"varint,1,opt,name=disabled,proto3" json:"disabled,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CachingDisabledReply) Reset() { *m = CachingDisabledReply{} } -func (m *CachingDisabledReply) String() string { return proto.CompactTextString(m) } -func (*CachingDisabledReply) ProtoMessage() {} -func (*CachingDisabledReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{34} -} - -func (m *CachingDisabledReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CachingDisabledReply.Unmarshal(m, b) -} -func (m *CachingDisabledReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CachingDisabledReply.Marshal(b, m, deterministic) -} -func (m *CachingDisabledReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_CachingDisabledReply.Merge(m, src) -} -func (m *CachingDisabledReply) XXX_Size() int { - return xxx_messageInfo_CachingDisabledReply.Size(m) -} -func (m *CachingDisabledReply) XXX_DiscardUnknown() { - xxx_messageInfo_CachingDisabledReply.DiscardUnknown(m) -} - -var xxx_messageInfo_CachingDisabledReply proto.InternalMessageInfo - -func (m *CachingDisabledReply) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -type ReplicationStateReply struct { - State int32 `sentinel:"" protobuf:"varint,1,opt,name=state,proto3" json:"state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReplicationStateReply) Reset() { *m = ReplicationStateReply{} } -func (m *ReplicationStateReply) String() string { return proto.CompactTextString(m) } -func (*ReplicationStateReply) ProtoMessage() {} -func (*ReplicationStateReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{35} -} - -func (m *ReplicationStateReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReplicationStateReply.Unmarshal(m, b) -} -func (m *ReplicationStateReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReplicationStateReply.Marshal(b, m, deterministic) -} -func (m *ReplicationStateReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReplicationStateReply.Merge(m, src) -} -func (m *ReplicationStateReply) XXX_Size() int { - return xxx_messageInfo_ReplicationStateReply.Size(m) -} -func (m *ReplicationStateReply) XXX_DiscardUnknown() { - xxx_messageInfo_ReplicationStateReply.DiscardUnknown(m) -} - -var xxx_messageInfo_ReplicationStateReply proto.InternalMessageInfo - -func (m *ReplicationStateReply) GetState() int32 { - if m != nil { - return m.State - } - return 0 -} - -type ResponseWrapDataArgs struct { - Data string `sentinel:"" protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` - TTL int64 `sentinel:"" protobuf:"varint,2,opt,name=TTL,proto3" json:"TTL,omitempty"` - JWT bool `sentinel:"" protobuf:"varint,3,opt,name=JWT,proto3" json:"JWT,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseWrapDataArgs) Reset() { *m = ResponseWrapDataArgs{} } -func (m *ResponseWrapDataArgs) String() string { return proto.CompactTextString(m) } -func (*ResponseWrapDataArgs) ProtoMessage() {} -func (*ResponseWrapDataArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{36} -} - -func (m *ResponseWrapDataArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseWrapDataArgs.Unmarshal(m, b) -} -func (m *ResponseWrapDataArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseWrapDataArgs.Marshal(b, m, deterministic) -} -func (m *ResponseWrapDataArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseWrapDataArgs.Merge(m, src) -} -func (m *ResponseWrapDataArgs) XXX_Size() int { - return xxx_messageInfo_ResponseWrapDataArgs.Size(m) -} -func (m *ResponseWrapDataArgs) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseWrapDataArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseWrapDataArgs proto.InternalMessageInfo - -func (m *ResponseWrapDataArgs) GetData() string { - if m != nil { - return m.Data - } - return "" -} - -func (m *ResponseWrapDataArgs) GetTTL() int64 { - if m != nil { - return m.TTL - } - return 0 -} - -func (m *ResponseWrapDataArgs) GetJWT() bool { - if m != nil { - return m.JWT - } - return false -} - -type ResponseWrapDataReply struct { - WrapInfo *ResponseWrapInfo `sentinel:"" protobuf:"bytes,1,opt,name=wrap_info,json=wrapInfo,proto3" json:"wrap_info,omitempty"` - Err string `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseWrapDataReply) Reset() { *m = ResponseWrapDataReply{} } -func (m *ResponseWrapDataReply) String() string { return proto.CompactTextString(m) } -func (*ResponseWrapDataReply) ProtoMessage() {} -func (*ResponseWrapDataReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{37} -} - -func (m *ResponseWrapDataReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseWrapDataReply.Unmarshal(m, b) -} -func (m *ResponseWrapDataReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseWrapDataReply.Marshal(b, m, deterministic) -} -func (m *ResponseWrapDataReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseWrapDataReply.Merge(m, src) -} -func (m *ResponseWrapDataReply) XXX_Size() int { - return xxx_messageInfo_ResponseWrapDataReply.Size(m) -} -func (m *ResponseWrapDataReply) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseWrapDataReply.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseWrapDataReply proto.InternalMessageInfo - -func (m *ResponseWrapDataReply) GetWrapInfo() *ResponseWrapInfo { - if m != nil { - return m.WrapInfo - } - return nil -} - -func (m *ResponseWrapDataReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type MlockEnabledReply struct { - Enabled bool `sentinel:"" protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MlockEnabledReply) Reset() { *m = MlockEnabledReply{} } -func (m *MlockEnabledReply) String() string { return proto.CompactTextString(m) } -func (*MlockEnabledReply) ProtoMessage() {} -func (*MlockEnabledReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{38} -} - -func (m *MlockEnabledReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MlockEnabledReply.Unmarshal(m, b) -} -func (m *MlockEnabledReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MlockEnabledReply.Marshal(b, m, deterministic) -} -func (m *MlockEnabledReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_MlockEnabledReply.Merge(m, src) -} -func (m *MlockEnabledReply) XXX_Size() int { - return xxx_messageInfo_MlockEnabledReply.Size(m) -} -func (m *MlockEnabledReply) XXX_DiscardUnknown() { - xxx_messageInfo_MlockEnabledReply.DiscardUnknown(m) -} - -var xxx_messageInfo_MlockEnabledReply proto.InternalMessageInfo - -func (m *MlockEnabledReply) GetEnabled() bool { - if m != nil { - return m.Enabled - } - return false -} - -type LocalMountReply struct { - Local bool `sentinel:"" protobuf:"varint,1,opt,name=local,proto3" json:"local,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LocalMountReply) Reset() { *m = LocalMountReply{} } -func (m *LocalMountReply) String() string { return proto.CompactTextString(m) } -func (*LocalMountReply) ProtoMessage() {} -func (*LocalMountReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{39} -} - -func (m *LocalMountReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LocalMountReply.Unmarshal(m, b) -} -func (m *LocalMountReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LocalMountReply.Marshal(b, m, deterministic) -} -func (m *LocalMountReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_LocalMountReply.Merge(m, src) -} -func (m *LocalMountReply) XXX_Size() int { - return xxx_messageInfo_LocalMountReply.Size(m) -} -func (m *LocalMountReply) XXX_DiscardUnknown() { - xxx_messageInfo_LocalMountReply.DiscardUnknown(m) -} - -var xxx_messageInfo_LocalMountReply proto.InternalMessageInfo - -func (m *LocalMountReply) GetLocal() bool { - if m != nil { - return m.Local - } - return false -} - -type EntityInfoArgs struct { - EntityID string `sentinel:"" protobuf:"bytes,1,opt,name=entity_id,json=entityId,proto3" json:"entity_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EntityInfoArgs) Reset() { *m = EntityInfoArgs{} } -func (m *EntityInfoArgs) String() string { return proto.CompactTextString(m) } -func (*EntityInfoArgs) ProtoMessage() {} -func (*EntityInfoArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{40} -} - -func (m *EntityInfoArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EntityInfoArgs.Unmarshal(m, b) -} -func (m *EntityInfoArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EntityInfoArgs.Marshal(b, m, deterministic) -} -func (m *EntityInfoArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_EntityInfoArgs.Merge(m, src) -} -func (m *EntityInfoArgs) XXX_Size() int { - return xxx_messageInfo_EntityInfoArgs.Size(m) -} -func (m *EntityInfoArgs) XXX_DiscardUnknown() { - xxx_messageInfo_EntityInfoArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_EntityInfoArgs proto.InternalMessageInfo - -func (m *EntityInfoArgs) GetEntityID() string { - if m != nil { - return m.EntityID - } - return "" -} - -type EntityInfoReply struct { - Entity *logical.Entity `sentinel:"" protobuf:"bytes,1,opt,name=entity,proto3" json:"entity,omitempty"` - Err string `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EntityInfoReply) Reset() { *m = EntityInfoReply{} } -func (m *EntityInfoReply) String() string { return proto.CompactTextString(m) } -func (*EntityInfoReply) ProtoMessage() {} -func (*EntityInfoReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{41} -} - -func (m *EntityInfoReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EntityInfoReply.Unmarshal(m, b) -} -func (m *EntityInfoReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EntityInfoReply.Marshal(b, m, deterministic) -} -func (m *EntityInfoReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_EntityInfoReply.Merge(m, src) -} -func (m *EntityInfoReply) XXX_Size() int { - return xxx_messageInfo_EntityInfoReply.Size(m) -} -func (m *EntityInfoReply) XXX_DiscardUnknown() { - xxx_messageInfo_EntityInfoReply.DiscardUnknown(m) -} - -var xxx_messageInfo_EntityInfoReply proto.InternalMessageInfo - -func (m *EntityInfoReply) GetEntity() *logical.Entity { - if m != nil { - return m.Entity - } - return nil -} - -func (m *EntityInfoReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type PluginEnvReply struct { - PluginEnvironment *logical.PluginEnvironment `sentinel:"" protobuf:"bytes,1,opt,name=plugin_environment,json=pluginEnvironment,proto3" json:"plugin_environment,omitempty"` - Err string `sentinel:"" protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PluginEnvReply) Reset() { *m = PluginEnvReply{} } -func (m *PluginEnvReply) String() string { return proto.CompactTextString(m) } -func (*PluginEnvReply) ProtoMessage() {} -func (*PluginEnvReply) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{42} -} - -func (m *PluginEnvReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PluginEnvReply.Unmarshal(m, b) -} -func (m *PluginEnvReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PluginEnvReply.Marshal(b, m, deterministic) -} -func (m *PluginEnvReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_PluginEnvReply.Merge(m, src) -} -func (m *PluginEnvReply) XXX_Size() int { - return xxx_messageInfo_PluginEnvReply.Size(m) -} -func (m *PluginEnvReply) XXX_DiscardUnknown() { - xxx_messageInfo_PluginEnvReply.DiscardUnknown(m) -} - -var xxx_messageInfo_PluginEnvReply proto.InternalMessageInfo - -func (m *PluginEnvReply) GetPluginEnvironment() *logical.PluginEnvironment { - if m != nil { - return m.PluginEnvironment - } - return nil -} - -func (m *PluginEnvReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -type Connection struct { - // RemoteAddr is the network address that sent the request. - RemoteAddr string `sentinel:"" protobuf:"bytes,1,opt,name=remote_addr,json=remoteAddr,proto3" json:"remote_addr,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Connection) Reset() { *m = Connection{} } -func (m *Connection) String() string { return proto.CompactTextString(m) } -func (*Connection) ProtoMessage() {} -func (*Connection) Descriptor() ([]byte, []int) { - return fileDescriptor_25821d34acc7c5ef, []int{43} -} - -func (m *Connection) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Connection.Unmarshal(m, b) -} -func (m *Connection) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Connection.Marshal(b, m, deterministic) -} -func (m *Connection) XXX_Merge(src proto.Message) { - xxx_messageInfo_Connection.Merge(m, src) -} -func (m *Connection) XXX_Size() int { - return xxx_messageInfo_Connection.Size(m) -} -func (m *Connection) XXX_DiscardUnknown() { - xxx_messageInfo_Connection.DiscardUnknown(m) -} - -var xxx_messageInfo_Connection proto.InternalMessageInfo - -func (m *Connection) GetRemoteAddr() string { - if m != nil { - return m.RemoteAddr - } - return "" -} - -func init() { - proto.RegisterType((*Empty)(nil), "pb.Empty") - proto.RegisterType((*Header)(nil), "pb.Header") - proto.RegisterType((*ProtoError)(nil), "pb.ProtoError") - proto.RegisterType((*Paths)(nil), "pb.Paths") - proto.RegisterType((*Request)(nil), "pb.Request") - proto.RegisterMapType((map[string]*Header)(nil), "pb.Request.HeadersEntry") - proto.RegisterType((*Auth)(nil), "pb.Auth") - proto.RegisterMapType((map[string]string)(nil), "pb.Auth.MetadataEntry") - proto.RegisterType((*TokenEntry)(nil), "pb.TokenEntry") - proto.RegisterMapType((map[string]string)(nil), "pb.TokenEntry.MetaEntry") - proto.RegisterType((*LeaseOptions)(nil), "pb.LeaseOptions") - proto.RegisterType((*Secret)(nil), "pb.Secret") - proto.RegisterType((*Response)(nil), "pb.Response") - proto.RegisterType((*ResponseWrapInfo)(nil), "pb.ResponseWrapInfo") - proto.RegisterType((*RequestWrapInfo)(nil), "pb.RequestWrapInfo") - proto.RegisterType((*HandleRequestArgs)(nil), "pb.HandleRequestArgs") - proto.RegisterType((*HandleRequestReply)(nil), "pb.HandleRequestReply") - proto.RegisterType((*SpecialPathsReply)(nil), "pb.SpecialPathsReply") - proto.RegisterType((*HandleExistenceCheckArgs)(nil), "pb.HandleExistenceCheckArgs") - proto.RegisterType((*HandleExistenceCheckReply)(nil), "pb.HandleExistenceCheckReply") - proto.RegisterType((*SetupArgs)(nil), "pb.SetupArgs") - proto.RegisterMapType((map[string]string)(nil), "pb.SetupArgs.ConfigEntry") - proto.RegisterType((*SetupReply)(nil), "pb.SetupReply") - proto.RegisterType((*TypeReply)(nil), "pb.TypeReply") - proto.RegisterType((*InvalidateKeyArgs)(nil), "pb.InvalidateKeyArgs") - proto.RegisterType((*StorageEntry)(nil), "pb.StorageEntry") - proto.RegisterType((*StorageListArgs)(nil), "pb.StorageListArgs") - proto.RegisterType((*StorageListReply)(nil), "pb.StorageListReply") - proto.RegisterType((*StorageGetArgs)(nil), "pb.StorageGetArgs") - proto.RegisterType((*StorageGetReply)(nil), "pb.StorageGetReply") - proto.RegisterType((*StoragePutArgs)(nil), "pb.StoragePutArgs") - proto.RegisterType((*StoragePutReply)(nil), "pb.StoragePutReply") - proto.RegisterType((*StorageDeleteArgs)(nil), "pb.StorageDeleteArgs") - proto.RegisterType((*StorageDeleteReply)(nil), "pb.StorageDeleteReply") - proto.RegisterType((*TTLReply)(nil), "pb.TTLReply") - proto.RegisterType((*SudoPrivilegeArgs)(nil), "pb.SudoPrivilegeArgs") - proto.RegisterType((*SudoPrivilegeReply)(nil), "pb.SudoPrivilegeReply") - proto.RegisterType((*TaintedReply)(nil), "pb.TaintedReply") - proto.RegisterType((*CachingDisabledReply)(nil), "pb.CachingDisabledReply") - proto.RegisterType((*ReplicationStateReply)(nil), "pb.ReplicationStateReply") - proto.RegisterType((*ResponseWrapDataArgs)(nil), "pb.ResponseWrapDataArgs") - proto.RegisterType((*ResponseWrapDataReply)(nil), "pb.ResponseWrapDataReply") - proto.RegisterType((*MlockEnabledReply)(nil), "pb.MlockEnabledReply") - proto.RegisterType((*LocalMountReply)(nil), "pb.LocalMountReply") - proto.RegisterType((*EntityInfoArgs)(nil), "pb.EntityInfoArgs") - proto.RegisterType((*EntityInfoReply)(nil), "pb.EntityInfoReply") - proto.RegisterType((*PluginEnvReply)(nil), "pb.PluginEnvReply") - proto.RegisterType((*Connection)(nil), "pb.Connection") -} - -// 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 - -// BackendClient is the client API for Backend service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type BackendClient interface { - // HandleRequest is used to handle a request and generate a response. - // The plugins must check the operation type and handle appropriately. - HandleRequest(ctx context.Context, in *HandleRequestArgs, opts ...grpc.CallOption) (*HandleRequestReply, 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(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*SpecialPathsReply, error) - // 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(ctx context.Context, in *HandleExistenceCheckArgs, opts ...grpc.CallOption) (*HandleExistenceCheckReply, 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 is called right before Vault closes the plugin process. - Cleanup(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - // 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(ctx context.Context, in *InvalidateKeyArgs, opts ...grpc.CallOption) (*Empty, error) - // Setup is used to set up the backend based on the provided backend - // configuration. The plugin's setup implementation should use the provided - // broker_id to create a connection back to Vault for use with the Storage - // and SystemView clients. - Setup(ctx context.Context, in *SetupArgs, opts ...grpc.CallOption) (*SetupReply, error) - // Type returns the BackendType for the particular backend - Type(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TypeReply, error) -} - -type backendClient struct { - cc *grpc.ClientConn -} - -func NewBackendClient(cc *grpc.ClientConn) BackendClient { - return &backendClient{cc} -} - -func (c *backendClient) HandleRequest(ctx context.Context, in *HandleRequestArgs, opts ...grpc.CallOption) (*HandleRequestReply, error) { - out := new(HandleRequestReply) - err := c.cc.Invoke(ctx, "/pb.Backend/HandleRequest", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) SpecialPaths(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*SpecialPathsReply, error) { - out := new(SpecialPathsReply) - err := c.cc.Invoke(ctx, "/pb.Backend/SpecialPaths", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) HandleExistenceCheck(ctx context.Context, in *HandleExistenceCheckArgs, opts ...grpc.CallOption) (*HandleExistenceCheckReply, error) { - out := new(HandleExistenceCheckReply) - err := c.cc.Invoke(ctx, "/pb.Backend/HandleExistenceCheck", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) Cleanup(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/pb.Backend/Cleanup", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) InvalidateKey(ctx context.Context, in *InvalidateKeyArgs, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/pb.Backend/InvalidateKey", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) Setup(ctx context.Context, in *SetupArgs, opts ...grpc.CallOption) (*SetupReply, error) { - out := new(SetupReply) - err := c.cc.Invoke(ctx, "/pb.Backend/Setup", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendClient) Type(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TypeReply, error) { - out := new(TypeReply) - err := c.cc.Invoke(ctx, "/pb.Backend/Type", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// BackendServer is the server API for Backend service. -type BackendServer interface { - // HandleRequest is used to handle a request and generate a response. - // The plugins must check the operation type and handle appropriately. - HandleRequest(context.Context, *HandleRequestArgs) (*HandleRequestReply, 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(context.Context, *Empty) (*SpecialPathsReply, error) - // 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, *HandleExistenceCheckArgs) (*HandleExistenceCheckReply, 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 is called right before Vault closes the plugin process. - Cleanup(context.Context, *Empty) (*Empty, error) - // 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, *InvalidateKeyArgs) (*Empty, error) - // Setup is used to set up the backend based on the provided backend - // configuration. The plugin's setup implementation should use the provided - // broker_id to create a connection back to Vault for use with the Storage - // and SystemView clients. - Setup(context.Context, *SetupArgs) (*SetupReply, error) - // Type returns the BackendType for the particular backend - Type(context.Context, *Empty) (*TypeReply, error) -} - -func RegisterBackendServer(s *grpc.Server, srv BackendServer) { - s.RegisterService(&_Backend_serviceDesc, srv) -} - -func _Backend_HandleRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HandleRequestArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BackendServer).HandleRequest(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/HandleRequest", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).HandleRequest(ctx, req.(*HandleRequestArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_SpecialPaths_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.(BackendServer).SpecialPaths(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/SpecialPaths", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).SpecialPaths(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_HandleExistenceCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HandleExistenceCheckArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BackendServer).HandleExistenceCheck(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/HandleExistenceCheck", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).HandleExistenceCheck(ctx, req.(*HandleExistenceCheckArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_Cleanup_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.(BackendServer).Cleanup(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/Cleanup", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).Cleanup(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_InvalidateKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InvalidateKeyArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BackendServer).InvalidateKey(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/InvalidateKey", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).InvalidateKey(ctx, req.(*InvalidateKeyArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_Setup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SetupArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BackendServer).Setup(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/Setup", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).Setup(ctx, req.(*SetupArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Backend_Type_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.(BackendServer).Type(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Backend/Type", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServer).Type(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _Backend_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pb.Backend", - HandlerType: (*BackendServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "HandleRequest", - Handler: _Backend_HandleRequest_Handler, - }, - { - MethodName: "SpecialPaths", - Handler: _Backend_SpecialPaths_Handler, - }, - { - MethodName: "HandleExistenceCheck", - Handler: _Backend_HandleExistenceCheck_Handler, - }, - { - MethodName: "Cleanup", - Handler: _Backend_Cleanup_Handler, - }, - { - MethodName: "InvalidateKey", - Handler: _Backend_InvalidateKey_Handler, - }, - { - MethodName: "Setup", - Handler: _Backend_Setup_Handler, - }, - { - MethodName: "Type", - Handler: _Backend_Type_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "logical/plugin/pb/backend.proto", -} - -// StorageClient is the client API for Storage service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type StorageClient interface { - List(ctx context.Context, in *StorageListArgs, opts ...grpc.CallOption) (*StorageListReply, error) - Get(ctx context.Context, in *StorageGetArgs, opts ...grpc.CallOption) (*StorageGetReply, error) - Put(ctx context.Context, in *StoragePutArgs, opts ...grpc.CallOption) (*StoragePutReply, error) - Delete(ctx context.Context, in *StorageDeleteArgs, opts ...grpc.CallOption) (*StorageDeleteReply, error) -} - -type storageClient struct { - cc *grpc.ClientConn -} - -func NewStorageClient(cc *grpc.ClientConn) StorageClient { - return &storageClient{cc} -} - -func (c *storageClient) List(ctx context.Context, in *StorageListArgs, opts ...grpc.CallOption) (*StorageListReply, error) { - out := new(StorageListReply) - err := c.cc.Invoke(ctx, "/pb.Storage/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storageClient) Get(ctx context.Context, in *StorageGetArgs, opts ...grpc.CallOption) (*StorageGetReply, error) { - out := new(StorageGetReply) - err := c.cc.Invoke(ctx, "/pb.Storage/Get", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storageClient) Put(ctx context.Context, in *StoragePutArgs, opts ...grpc.CallOption) (*StoragePutReply, error) { - out := new(StoragePutReply) - err := c.cc.Invoke(ctx, "/pb.Storage/Put", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *storageClient) Delete(ctx context.Context, in *StorageDeleteArgs, opts ...grpc.CallOption) (*StorageDeleteReply, error) { - out := new(StorageDeleteReply) - err := c.cc.Invoke(ctx, "/pb.Storage/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// StorageServer is the server API for Storage service. -type StorageServer interface { - List(context.Context, *StorageListArgs) (*StorageListReply, error) - Get(context.Context, *StorageGetArgs) (*StorageGetReply, error) - Put(context.Context, *StoragePutArgs) (*StoragePutReply, error) - Delete(context.Context, *StorageDeleteArgs) (*StorageDeleteReply, error) -} - -func RegisterStorageServer(s *grpc.Server, srv StorageServer) { - s.RegisterService(&_Storage_serviceDesc, srv) -} - -func _Storage_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StorageListArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StorageServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Storage/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StorageServer).List(ctx, req.(*StorageListArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Storage_Get_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StorageGetArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StorageServer).Get(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Storage/Get", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StorageServer).Get(ctx, req.(*StorageGetArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Storage_Put_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StoragePutArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StorageServer).Put(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Storage/Put", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StorageServer).Put(ctx, req.(*StoragePutArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _Storage_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StorageDeleteArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(StorageServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Storage/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(StorageServer).Delete(ctx, req.(*StorageDeleteArgs)) - } - return interceptor(ctx, in, info, handler) -} - -var _Storage_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pb.Storage", - HandlerType: (*StorageServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "List", - Handler: _Storage_List_Handler, - }, - { - MethodName: "Get", - Handler: _Storage_Get_Handler, - }, - { - MethodName: "Put", - Handler: _Storage_Put_Handler, - }, - { - MethodName: "Delete", - Handler: _Storage_Delete_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "logical/plugin/pb/backend.proto", -} - -// SystemViewClient is the client API for SystemView service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type SystemViewClient interface { - // DefaultLeaseTTL returns the default lease TTL set in Vault configuration - DefaultLeaseTTL(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TTLReply, error) - // 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(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TTLReply, error) - // SudoPrivilege returns true if given path has sudo privileges - // for the given client token - SudoPrivilege(ctx context.Context, in *SudoPrivilegeArgs, opts ...grpc.CallOption) (*SudoPrivilegeReply, error) - // Tainted, 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(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TaintedReply, error) - // CachingDisabled returns true if caching is disabled. If true, no caches - // should be used, despite known slowdowns. - CachingDisabled(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CachingDisabledReply, error) - // ReplicationState indicates the state of cluster replication - ReplicationState(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ReplicationStateReply, error) - // ResponseWrapData wraps the given data in a cubbyhole and returns the - // token used to unwrap. - ResponseWrapData(ctx context.Context, in *ResponseWrapDataArgs, opts ...grpc.CallOption) (*ResponseWrapDataReply, error) - // MlockEnabled returns the configuration setting for enabling mlock on - // plugins. - MlockEnabled(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*MlockEnabledReply, error) - // LocalMount, when run from a system view attached to a request, indicates - // whether the request is affecting a local mount or not - LocalMount(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*LocalMountReply, error) - // EntityInfo returns the basic entity information for the given entity id - EntityInfo(ctx context.Context, in *EntityInfoArgs, opts ...grpc.CallOption) (*EntityInfoReply, error) - // PluginEnv returns Vault environment information used by plugins - PluginEnv(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*PluginEnvReply, error) -} - -type systemViewClient struct { - cc *grpc.ClientConn -} - -func NewSystemViewClient(cc *grpc.ClientConn) SystemViewClient { - return &systemViewClient{cc} -} - -func (c *systemViewClient) DefaultLeaseTTL(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TTLReply, error) { - out := new(TTLReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/DefaultLeaseTTL", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) MaxLeaseTTL(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TTLReply, error) { - out := new(TTLReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/MaxLeaseTTL", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) SudoPrivilege(ctx context.Context, in *SudoPrivilegeArgs, opts ...grpc.CallOption) (*SudoPrivilegeReply, error) { - out := new(SudoPrivilegeReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/SudoPrivilege", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) Tainted(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*TaintedReply, error) { - out := new(TaintedReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/Tainted", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) CachingDisabled(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CachingDisabledReply, error) { - out := new(CachingDisabledReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/CachingDisabled", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) ReplicationState(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ReplicationStateReply, error) { - out := new(ReplicationStateReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/ReplicationState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) ResponseWrapData(ctx context.Context, in *ResponseWrapDataArgs, opts ...grpc.CallOption) (*ResponseWrapDataReply, error) { - out := new(ResponseWrapDataReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/ResponseWrapData", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) MlockEnabled(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*MlockEnabledReply, error) { - out := new(MlockEnabledReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/MlockEnabled", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) LocalMount(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*LocalMountReply, error) { - out := new(LocalMountReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/LocalMount", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) EntityInfo(ctx context.Context, in *EntityInfoArgs, opts ...grpc.CallOption) (*EntityInfoReply, error) { - out := new(EntityInfoReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/EntityInfo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *systemViewClient) PluginEnv(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*PluginEnvReply, error) { - out := new(PluginEnvReply) - err := c.cc.Invoke(ctx, "/pb.SystemView/PluginEnv", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// SystemViewServer is the server API for SystemView service. -type SystemViewServer interface { - // DefaultLeaseTTL returns the default lease TTL set in Vault configuration - DefaultLeaseTTL(context.Context, *Empty) (*TTLReply, error) - // 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(context.Context, *Empty) (*TTLReply, error) - // SudoPrivilege returns true if given path has sudo privileges - // for the given client token - SudoPrivilege(context.Context, *SudoPrivilegeArgs) (*SudoPrivilegeReply, error) - // Tainted, 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(context.Context, *Empty) (*TaintedReply, error) - // CachingDisabled returns true if caching is disabled. If true, no caches - // should be used, despite known slowdowns. - CachingDisabled(context.Context, *Empty) (*CachingDisabledReply, error) - // ReplicationState indicates the state of cluster replication - ReplicationState(context.Context, *Empty) (*ReplicationStateReply, error) - // ResponseWrapData wraps the given data in a cubbyhole and returns the - // token used to unwrap. - ResponseWrapData(context.Context, *ResponseWrapDataArgs) (*ResponseWrapDataReply, error) - // MlockEnabled returns the configuration setting for enabling mlock on - // plugins. - MlockEnabled(context.Context, *Empty) (*MlockEnabledReply, error) - // LocalMount, when run from a system view attached to a request, indicates - // whether the request is affecting a local mount or not - LocalMount(context.Context, *Empty) (*LocalMountReply, error) - // EntityInfo returns the basic entity information for the given entity id - EntityInfo(context.Context, *EntityInfoArgs) (*EntityInfoReply, error) - // PluginEnv returns Vault environment information used by plugins - PluginEnv(context.Context, *Empty) (*PluginEnvReply, error) -} - -func RegisterSystemViewServer(s *grpc.Server, srv SystemViewServer) { - s.RegisterService(&_SystemView_serviceDesc, srv) -} - -func _SystemView_DefaultLeaseTTL_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.(SystemViewServer).DefaultLeaseTTL(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/DefaultLeaseTTL", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).DefaultLeaseTTL(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_MaxLeaseTTL_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.(SystemViewServer).MaxLeaseTTL(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/MaxLeaseTTL", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).MaxLeaseTTL(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_SudoPrivilege_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SudoPrivilegeArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SystemViewServer).SudoPrivilege(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/SudoPrivilege", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).SudoPrivilege(ctx, req.(*SudoPrivilegeArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_Tainted_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.(SystemViewServer).Tainted(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/Tainted", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).Tainted(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_CachingDisabled_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.(SystemViewServer).CachingDisabled(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/CachingDisabled", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).CachingDisabled(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_ReplicationState_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.(SystemViewServer).ReplicationState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/ReplicationState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).ReplicationState(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_ResponseWrapData_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ResponseWrapDataArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SystemViewServer).ResponseWrapData(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/ResponseWrapData", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).ResponseWrapData(ctx, req.(*ResponseWrapDataArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_MlockEnabled_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.(SystemViewServer).MlockEnabled(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/MlockEnabled", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).MlockEnabled(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_LocalMount_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.(SystemViewServer).LocalMount(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/LocalMount", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).LocalMount(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_EntityInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EntityInfoArgs) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SystemViewServer).EntityInfo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/EntityInfo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).EntityInfo(ctx, req.(*EntityInfoArgs)) - } - return interceptor(ctx, in, info, handler) -} - -func _SystemView_PluginEnv_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.(SystemViewServer).PluginEnv(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.SystemView/PluginEnv", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SystemViewServer).PluginEnv(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _SystemView_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pb.SystemView", - HandlerType: (*SystemViewServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "DefaultLeaseTTL", - Handler: _SystemView_DefaultLeaseTTL_Handler, - }, - { - MethodName: "MaxLeaseTTL", - Handler: _SystemView_MaxLeaseTTL_Handler, - }, - { - MethodName: "SudoPrivilege", - Handler: _SystemView_SudoPrivilege_Handler, - }, - { - MethodName: "Tainted", - Handler: _SystemView_Tainted_Handler, - }, - { - MethodName: "CachingDisabled", - Handler: _SystemView_CachingDisabled_Handler, - }, - { - MethodName: "ReplicationState", - Handler: _SystemView_ReplicationState_Handler, - }, - { - MethodName: "ResponseWrapData", - Handler: _SystemView_ResponseWrapData_Handler, - }, - { - MethodName: "MlockEnabled", - Handler: _SystemView_MlockEnabled_Handler, - }, - { - MethodName: "LocalMount", - Handler: _SystemView_LocalMount_Handler, - }, - { - MethodName: "EntityInfo", - Handler: _SystemView_EntityInfo_Handler, - }, - { - MethodName: "PluginEnv", - Handler: _SystemView_PluginEnv_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "logical/plugin/pb/backend.proto", -} - -func init() { proto.RegisterFile("logical/plugin/pb/backend.proto", fileDescriptor_25821d34acc7c5ef) } - -var fileDescriptor_25821d34acc7c5ef = []byte{ - // 2483 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x59, 0xcd, 0x72, 0x1b, 0xc7, - 0x11, 0x2e, 0x00, 0xc4, 0x5f, 0xe3, 0x8f, 0x18, 0xd1, 0xcc, 0x0a, 0x96, 0x23, 0x78, 0x1d, 0x49, - 0xb4, 0x22, 0x81, 0x12, 0x1d, 0xc7, 0x72, 0x52, 0x76, 0x8a, 0xa6, 0x68, 0x99, 0x31, 0x69, 0xb3, - 0x96, 0x50, 0x9c, 0xbf, 0x2a, 0x78, 0xb0, 0x3b, 0x04, 0xb7, 0xb8, 0xd8, 0xdd, 0xcc, 0xce, 0x52, - 0xc4, 0x29, 0x6f, 0x91, 0xd7, 0xc8, 0x35, 0x95, 0x4b, 0x6e, 0xa9, 0x54, 0x72, 0xce, 0x6b, 0xe4, - 0x19, 0x52, 0xd3, 0x33, 0xfb, 0x07, 0x80, 0x96, 0x5c, 0x95, 0xdc, 0x66, 0xba, 0x7b, 0x7a, 0x66, - 0x7a, 0xbe, 0xfe, 0xba, 0x17, 0x80, 0xbb, 0x5e, 0x30, 0x73, 0x6d, 0xea, 0xed, 0x86, 0x5e, 0x3c, - 0x73, 0xfd, 0xdd, 0x70, 0xba, 0x3b, 0xa5, 0xf6, 0x25, 0xf3, 0x9d, 0x51, 0xc8, 0x03, 0x11, 0x90, - 0x72, 0x38, 0x1d, 0xdc, 0x9d, 0x05, 0xc1, 0xcc, 0x63, 0xbb, 0x28, 0x99, 0xc6, 0xe7, 0xbb, 0xc2, - 0x9d, 0xb3, 0x48, 0xd0, 0x79, 0xa8, 0x8c, 0x06, 0xdb, 0x89, 0x17, 0xd7, 0x61, 0xbe, 0x70, 0xc5, - 0x42, 0xcb, 0xb7, 0x8a, 0xde, 0x95, 0xd4, 0xac, 0x43, 0xf5, 0x70, 0x1e, 0x8a, 0x85, 0x39, 0x84, - 0xda, 0x17, 0x8c, 0x3a, 0x8c, 0x93, 0x6d, 0xa8, 0x5d, 0xe0, 0xc8, 0x28, 0x0d, 0x2b, 0x3b, 0x4d, - 0x4b, 0xcf, 0xcc, 0xdf, 0x01, 0x9c, 0xca, 0x35, 0x87, 0x9c, 0x07, 0x9c, 0xdc, 0x86, 0x06, 0xe3, - 0x7c, 0x22, 0x16, 0x21, 0x33, 0x4a, 0xc3, 0xd2, 0x4e, 0xc7, 0xaa, 0x33, 0xce, 0xc7, 0x8b, 0x90, - 0x91, 0x1f, 0x80, 0x1c, 0x4e, 0xe6, 0xd1, 0xcc, 0x28, 0x0f, 0x4b, 0xd2, 0x03, 0xe3, 0xfc, 0x24, - 0x9a, 0x25, 0x6b, 0xec, 0xc0, 0x61, 0x46, 0x65, 0x58, 0xda, 0xa9, 0xe0, 0x9a, 0x83, 0xc0, 0x61, - 0xe6, 0x9f, 0x4a, 0x50, 0x3d, 0xa5, 0xe2, 0x22, 0x22, 0x04, 0x36, 0x78, 0x10, 0x08, 0xbd, 0x39, - 0x8e, 0xc9, 0x0e, 0xf4, 0x62, 0x9f, 0xc6, 0xe2, 0x42, 0xde, 0xc8, 0xa6, 0x82, 0x39, 0x46, 0x19, - 0xd5, 0xcb, 0x62, 0xf2, 0x1e, 0x74, 0xbc, 0xc0, 0xa6, 0xde, 0x24, 0x12, 0x01, 0xa7, 0x33, 0xb9, - 0x8f, 0xb4, 0x6b, 0xa3, 0xf0, 0x4c, 0xc9, 0xc8, 0x43, 0xe8, 0x47, 0x8c, 0x7a, 0x93, 0x57, 0x9c, - 0x86, 0xa9, 0xe1, 0x86, 0x72, 0x28, 0x15, 0xdf, 0x70, 0x1a, 0x6a, 0x5b, 0xf3, 0x6f, 0x35, 0xa8, - 0x5b, 0xec, 0x0f, 0x31, 0x8b, 0x04, 0xe9, 0x42, 0xd9, 0x75, 0xf0, 0xb6, 0x4d, 0xab, 0xec, 0x3a, - 0x64, 0x04, 0xc4, 0x62, 0xa1, 0x27, 0xb7, 0x76, 0x03, 0xff, 0xc0, 0x8b, 0x23, 0xc1, 0xb8, 0xbe, - 0xf3, 0x1a, 0x0d, 0xb9, 0x03, 0xcd, 0x20, 0x64, 0x1c, 0x65, 0x18, 0x80, 0xa6, 0x95, 0x09, 0xe4, - 0xc5, 0x43, 0x2a, 0x2e, 0x8c, 0x0d, 0x54, 0xe0, 0x58, 0xca, 0x1c, 0x2a, 0xa8, 0x51, 0x55, 0x32, - 0x39, 0x26, 0x26, 0xd4, 0x22, 0x66, 0x73, 0x26, 0x8c, 0xda, 0xb0, 0xb4, 0xd3, 0xda, 0x83, 0x51, - 0x38, 0x1d, 0x9d, 0xa1, 0xc4, 0xd2, 0x1a, 0x72, 0x07, 0x36, 0x64, 0x5c, 0x8c, 0x3a, 0x5a, 0x34, - 0xa4, 0xc5, 0x7e, 0x2c, 0x2e, 0x2c, 0x94, 0x92, 0x3d, 0xa8, 0xab, 0x37, 0x8d, 0x8c, 0xc6, 0xb0, - 0xb2, 0xd3, 0xda, 0x33, 0xa4, 0x81, 0xbe, 0xe5, 0x48, 0xc1, 0x20, 0x3a, 0xf4, 0x05, 0x5f, 0x58, - 0x89, 0x21, 0x79, 0x17, 0xda, 0xb6, 0xe7, 0x32, 0x5f, 0x4c, 0x44, 0x70, 0xc9, 0x7c, 0xa3, 0x89, - 0x27, 0x6a, 0x29, 0xd9, 0x58, 0x8a, 0xc8, 0x1e, 0xbc, 0x95, 0x37, 0x99, 0x50, 0xdb, 0x66, 0x51, - 0x14, 0x70, 0x03, 0xd0, 0xf6, 0x56, 0xce, 0x76, 0x5f, 0xab, 0xa4, 0x5b, 0xc7, 0x8d, 0x42, 0x8f, - 0x2e, 0x26, 0x3e, 0x9d, 0x33, 0xa3, 0xa5, 0xdc, 0x6a, 0xd9, 0x57, 0x74, 0xce, 0xc8, 0x5d, 0x68, - 0xcd, 0x83, 0xd8, 0x17, 0x93, 0x30, 0x70, 0x7d, 0x61, 0xb4, 0xd1, 0x02, 0x50, 0x74, 0x2a, 0x25, - 0xe4, 0x1d, 0x50, 0x33, 0x05, 0xc6, 0x8e, 0x8a, 0x2b, 0x4a, 0x10, 0x8e, 0xf7, 0xa0, 0xab, 0xd4, - 0xe9, 0x79, 0xba, 0x68, 0xd2, 0x41, 0x69, 0x7a, 0x92, 0x27, 0xd0, 0x44, 0x3c, 0xb8, 0xfe, 0x79, - 0x60, 0xf4, 0x30, 0x6e, 0xb7, 0x72, 0x61, 0x91, 0x98, 0x38, 0xf2, 0xcf, 0x03, 0xab, 0xf1, 0x4a, - 0x8f, 0xc8, 0x27, 0xf0, 0x76, 0xe1, 0xbe, 0x9c, 0xcd, 0xa9, 0xeb, 0xbb, 0xfe, 0x6c, 0x12, 0x47, - 0x2c, 0x32, 0x36, 0x11, 0xe1, 0x46, 0xee, 0xd6, 0x56, 0x62, 0xf0, 0x32, 0x62, 0x11, 0x79, 0x1b, - 0x9a, 0x2a, 0x41, 0x27, 0xae, 0x63, 0xf4, 0xf1, 0x48, 0x0d, 0x25, 0x38, 0x72, 0xc8, 0x03, 0xe8, - 0x85, 0x81, 0xe7, 0xda, 0x8b, 0x49, 0x70, 0xc5, 0x38, 0x77, 0x1d, 0x66, 0x90, 0x61, 0x69, 0xa7, - 0x61, 0x75, 0x95, 0xf8, 0x6b, 0x2d, 0x5d, 0x97, 0x1a, 0xb7, 0xd0, 0x70, 0x25, 0x35, 0x46, 0x00, - 0x76, 0xe0, 0xfb, 0xcc, 0x46, 0xf8, 0x6d, 0xe1, 0x0d, 0xbb, 0xf2, 0x86, 0x07, 0xa9, 0xd4, 0xca, - 0x59, 0x0c, 0x3e, 0x87, 0x76, 0x1e, 0x0a, 0x64, 0x13, 0x2a, 0x97, 0x6c, 0xa1, 0xe1, 0x2f, 0x87, - 0x64, 0x08, 0xd5, 0x2b, 0xea, 0xc5, 0x0c, 0x21, 0xaf, 0x81, 0xa8, 0x96, 0x58, 0x4a, 0xf1, 0xb3, - 0xf2, 0xb3, 0x92, 0xf9, 0xd7, 0x2a, 0x6c, 0x48, 0xf0, 0x91, 0x0f, 0xa1, 0xe3, 0x31, 0x1a, 0xb1, - 0x49, 0x10, 0xca, 0x0d, 0x22, 0x74, 0xd5, 0xda, 0xdb, 0x94, 0xcb, 0x8e, 0xa5, 0xe2, 0x6b, 0x25, - 0xb7, 0xda, 0x5e, 0x6e, 0x26, 0x53, 0xda, 0xf5, 0x05, 0xe3, 0x3e, 0xf5, 0x26, 0x98, 0x0c, 0x2a, - 0xc1, 0xda, 0x89, 0xf0, 0xb9, 0x4c, 0x8a, 0x65, 0x1c, 0x55, 0x56, 0x71, 0x34, 0x80, 0x06, 0xc6, - 0xce, 0x65, 0x91, 0x4e, 0xf6, 0x74, 0x4e, 0xf6, 0xa0, 0x31, 0x67, 0x82, 0xea, 0x5c, 0x93, 0x29, - 0xb1, 0x9d, 0xe4, 0xcc, 0xe8, 0x44, 0x2b, 0x54, 0x42, 0xa4, 0x76, 0x2b, 0x19, 0x51, 0x5b, 0xcd, - 0x88, 0x01, 0x34, 0x52, 0xd0, 0xd5, 0xd5, 0x0b, 0x27, 0x73, 0x49, 0xb3, 0x21, 0xe3, 0x6e, 0xe0, - 0x18, 0x0d, 0x04, 0x8a, 0x9e, 0x49, 0x92, 0xf4, 0xe3, 0xb9, 0x82, 0x50, 0x53, 0x91, 0xa4, 0x1f, - 0xcf, 0x57, 0x11, 0x03, 0x4b, 0x88, 0xf9, 0x11, 0x54, 0xa9, 0xe7, 0xd2, 0x08, 0x53, 0x48, 0xbe, - 0xac, 0xe6, 0xfb, 0xd1, 0xbe, 0x94, 0x5a, 0x4a, 0x49, 0x3e, 0x80, 0xce, 0x8c, 0x07, 0x71, 0x38, - 0xc1, 0x29, 0x8b, 0x8c, 0x36, 0xde, 0x76, 0xd9, 0xba, 0x8d, 0x46, 0xfb, 0xca, 0x46, 0x66, 0xe0, - 0x34, 0x88, 0x7d, 0x67, 0x62, 0xbb, 0x0e, 0x8f, 0x8c, 0x0e, 0x06, 0x0f, 0x50, 0x74, 0x20, 0x25, - 0x32, 0xc5, 0x54, 0x0a, 0xa4, 0x01, 0xee, 0xa2, 0x4d, 0x07, 0xa5, 0xa7, 0x49, 0x94, 0x7f, 0x0c, - 0xfd, 0xa4, 0x28, 0x65, 0x96, 0x3d, 0xb4, 0xdc, 0x4c, 0x14, 0xa9, 0xf1, 0x0e, 0x6c, 0xb2, 0x6b, - 0x49, 0xa1, 0xae, 0x98, 0xcc, 0xe9, 0xf5, 0x44, 0x08, 0x4f, 0xa7, 0x54, 0x37, 0x91, 0x9f, 0xd0, - 0xeb, 0xb1, 0xf0, 0x64, 0xfe, 0xab, 0xdd, 0x31, 0xff, 0xfb, 0x58, 0x8c, 0x9a, 0x28, 0x91, 0xf9, - 0x3f, 0xf8, 0x39, 0x74, 0x0a, 0x4f, 0xb8, 0x06, 0xc8, 0x5b, 0x79, 0x20, 0x37, 0xf3, 0xe0, 0xfd, - 0xe7, 0x06, 0x00, 0xbe, 0xa5, 0x5a, 0xba, 0x5c, 0x01, 0xf2, 0x0f, 0x5c, 0x5e, 0xf3, 0xc0, 0x94, - 0x33, 0x5f, 0x68, 0x30, 0xea, 0xd9, 0x77, 0xe2, 0x30, 0xa9, 0x01, 0xd5, 0x5c, 0x0d, 0x78, 0x04, - 0x1b, 0x12, 0x73, 0x46, 0x2d, 0xa3, 0xea, 0xec, 0x44, 0x88, 0x4e, 0x85, 0x4c, 0xb4, 0x5a, 0x49, - 0x84, 0xfa, 0x6a, 0x22, 0xe4, 0x11, 0xd6, 0x28, 0x22, 0xec, 0x3d, 0xe8, 0xd8, 0x9c, 0x61, 0x3d, - 0x9a, 0xc8, 0xc6, 0x42, 0x23, 0xb0, 0x9d, 0x08, 0xc7, 0xee, 0x9c, 0xc9, 0xf8, 0xc9, 0xc7, 0x00, - 0x54, 0xc9, 0xe1, 0xda, 0xb7, 0x6a, 0xad, 0x7d, 0x2b, 0xac, 0xee, 0x1e, 0xd3, 0x2c, 0x8e, 0xe3, - 0x5c, 0x26, 0x74, 0x0a, 0x99, 0x50, 0x80, 0x7b, 0x77, 0x09, 0xee, 0x4b, 0x98, 0xec, 0xad, 0x60, - 0xf2, 0x5d, 0x68, 0xcb, 0x00, 0x44, 0x21, 0xb5, 0x99, 0x74, 0xb0, 0xa9, 0x02, 0x91, 0xca, 0x8e, - 0x1c, 0xcc, 0xe0, 0x78, 0x3a, 0x5d, 0x5c, 0x04, 0x1e, 0xcb, 0x48, 0xb8, 0x95, 0xca, 0x8e, 0x1c, - 0x79, 0x5e, 0x44, 0x15, 0x41, 0x54, 0xe1, 0x78, 0xf0, 0x11, 0x34, 0xd3, 0xa8, 0x7f, 0x2f, 0x30, - 0xfd, 0xb9, 0x04, 0xed, 0x3c, 0xd1, 0xc9, 0xc5, 0xe3, 0xf1, 0x31, 0x2e, 0xae, 0x58, 0x72, 0x28, - 0x5b, 0x04, 0xce, 0x7c, 0xf6, 0x8a, 0x4e, 0x3d, 0xe5, 0xa0, 0x61, 0x65, 0x02, 0xa9, 0x75, 0x7d, - 0x9b, 0xb3, 0x79, 0x82, 0xaa, 0x8a, 0x95, 0x09, 0xc8, 0xc7, 0x00, 0x6e, 0x14, 0xc5, 0x4c, 0xbd, - 0xdc, 0x06, 0xd2, 0xc0, 0x60, 0xa4, 0xfa, 0xc5, 0x51, 0xd2, 0x2f, 0x8e, 0xc6, 0x49, 0xbf, 0x68, - 0x35, 0xd1, 0x1a, 0x9f, 0x74, 0x1b, 0x6a, 0xf2, 0x81, 0xc6, 0xc7, 0x88, 0xbc, 0x8a, 0xa5, 0x67, - 0xe6, 0x1f, 0xa1, 0xa6, 0x3a, 0x8b, 0xff, 0x2b, 0x79, 0xdf, 0x86, 0x86, 0xf2, 0xed, 0x3a, 0x3a, - 0x57, 0xea, 0x38, 0x3f, 0x72, 0xcc, 0x7f, 0x95, 0xa0, 0x61, 0xb1, 0x28, 0x0c, 0xfc, 0x88, 0xe5, - 0x3a, 0x9f, 0xd2, 0x6b, 0x3b, 0x9f, 0xf2, 0xda, 0xce, 0x27, 0xe9, 0xa7, 0x2a, 0xb9, 0x7e, 0x6a, - 0x00, 0x0d, 0xce, 0x1c, 0x97, 0x33, 0x5b, 0xe8, 0xde, 0x2b, 0x9d, 0x4b, 0xdd, 0x2b, 0xca, 0x65, - 0xc9, 0x8e, 0xb0, 0x2e, 0x34, 0xad, 0x74, 0x4e, 0x9e, 0xe6, 0x1b, 0x06, 0xd5, 0x8a, 0x6d, 0xa9, - 0x86, 0x41, 0x1d, 0x77, 0xb5, 0x63, 0x30, 0xff, 0x51, 0x86, 0xcd, 0x65, 0xf5, 0x1a, 0x10, 0x6c, - 0x41, 0x55, 0x95, 0x14, 0x8d, 0x20, 0xb1, 0x52, 0x4c, 0x2a, 0x4b, 0x5c, 0xf3, 0x8b, 0xe5, 0xbc, - 0x7d, 0xfd, 0xeb, 0x17, 0x73, 0xfa, 0x7d, 0xd8, 0x94, 0xa7, 0x0c, 0x99, 0x93, 0xb5, 0x49, 0x8a, - 0x84, 0x7a, 0x5a, 0x9e, 0x36, 0x4a, 0x0f, 0xa1, 0x9f, 0x98, 0x66, 0xe9, 0x59, 0x2b, 0xd8, 0x1e, - 0x26, 0x59, 0xba, 0x0d, 0xb5, 0xf3, 0x80, 0xcf, 0xa9, 0xd0, 0x3c, 0xa4, 0x67, 0x05, 0x9e, 0x41, - 0xc2, 0x6b, 0x28, 0x58, 0x24, 0x42, 0xf9, 0x29, 0x20, 0xf3, 0x3f, 0x6d, 0xd3, 0x91, 0x88, 0x1a, - 0x56, 0x23, 0x69, 0xcf, 0xcd, 0x5f, 0x43, 0x6f, 0xa9, 0x33, 0x5b, 0x13, 0xc8, 0x6c, 0xfb, 0x72, - 0x61, 0xfb, 0x82, 0xe7, 0xca, 0x92, 0xe7, 0xdf, 0x40, 0xff, 0x0b, 0xea, 0x3b, 0x1e, 0xd3, 0xfe, - 0xf7, 0xf9, 0x2c, 0x92, 0x35, 0x46, 0x7f, 0x28, 0x4c, 0x74, 0x01, 0xe8, 0x58, 0x4d, 0x2d, 0x39, - 0x72, 0xc8, 0x3d, 0xa8, 0x73, 0x65, 0xad, 0x81, 0xd7, 0xca, 0xb5, 0x8e, 0x56, 0xa2, 0x33, 0xbf, - 0x05, 0x52, 0x70, 0x2d, 0xbf, 0x11, 0x16, 0x64, 0x47, 0x02, 0x50, 0x81, 0x42, 0x03, 0xbb, 0x9d, - 0xc7, 0x91, 0x95, 0x6a, 0xc9, 0x10, 0x2a, 0x8c, 0x73, 0xbd, 0x05, 0xf6, 0x6e, 0xd9, 0x17, 0x99, - 0x25, 0x55, 0xe6, 0x4f, 0xa0, 0x7f, 0x16, 0x32, 0xdb, 0xa5, 0x1e, 0x7e, 0x4d, 0xa9, 0x0d, 0xee, - 0x42, 0x55, 0x06, 0x39, 0xc9, 0xd9, 0x26, 0x2e, 0x44, 0xb5, 0x92, 0x9b, 0xdf, 0x82, 0xa1, 0xce, - 0x75, 0x78, 0xed, 0x46, 0x82, 0xf9, 0x36, 0x3b, 0xb8, 0x60, 0xf6, 0xe5, 0xff, 0xf0, 0xe6, 0x57, - 0x70, 0x7b, 0xdd, 0x0e, 0xc9, 0xf9, 0x5a, 0xb6, 0x9c, 0x4d, 0xce, 0x25, 0x7d, 0xe3, 0x1e, 0x0d, - 0x0b, 0x50, 0xf4, 0xb9, 0x94, 0xc8, 0x77, 0x64, 0x72, 0x5d, 0xa4, 0x29, 0x51, 0xcf, 0x92, 0x78, - 0x54, 0x6e, 0x8e, 0xc7, 0x5f, 0x4a, 0xd0, 0x3c, 0x63, 0x22, 0x0e, 0xf1, 0x2e, 0x6f, 0x43, 0x73, - 0xca, 0x83, 0x4b, 0xc6, 0xb3, 0xab, 0x34, 0x94, 0xe0, 0xc8, 0x21, 0x4f, 0xa1, 0x76, 0x10, 0xf8, - 0xe7, 0xee, 0x0c, 0xbf, 0x2d, 0x5b, 0x7b, 0xb7, 0x15, 0xbb, 0xe8, 0xb5, 0x23, 0xa5, 0x53, 0xa5, - 0x56, 0x1b, 0x92, 0x21, 0xb4, 0xf4, 0x17, 0xfa, 0xcb, 0x97, 0x47, 0xcf, 0x93, 0xa6, 0x33, 0x27, - 0x1a, 0x7c, 0x0c, 0xad, 0xdc, 0xc2, 0xef, 0x55, 0x2d, 0x7e, 0x08, 0x80, 0xbb, 0xab, 0x18, 0x6d, - 0xaa, 0xab, 0xea, 0x95, 0xf2, 0x6a, 0x77, 0xa1, 0x29, 0xfb, 0x1b, 0xa5, 0x4e, 0xea, 0x54, 0x29, - 0xab, 0x53, 0xe6, 0x3d, 0xe8, 0x1f, 0xf9, 0x57, 0xd4, 0x73, 0x1d, 0x2a, 0xd8, 0x97, 0x6c, 0x81, - 0x21, 0x58, 0x39, 0x81, 0x79, 0x06, 0x6d, 0xfd, 0xb1, 0xfb, 0x46, 0x67, 0x6c, 0xeb, 0x33, 0x7e, - 0x77, 0x12, 0xbd, 0x0f, 0x3d, 0xed, 0xf4, 0xd8, 0xd5, 0x29, 0x24, 0xcb, 0x3c, 0x67, 0xe7, 0xee, - 0xb5, 0x76, 0xad, 0x67, 0xe6, 0x33, 0xd8, 0xcc, 0x99, 0xa6, 0xd7, 0xb9, 0x64, 0x8b, 0x28, 0xf9, - 0x11, 0x40, 0x8e, 0x93, 0x08, 0x94, 0xb3, 0x08, 0x98, 0xd0, 0xd5, 0x2b, 0x5f, 0x30, 0x71, 0xc3, - 0xed, 0xbe, 0x4c, 0x0f, 0xf2, 0x82, 0x69, 0xe7, 0xf7, 0xa1, 0xca, 0xe4, 0x4d, 0xf3, 0x25, 0x2c, - 0x1f, 0x01, 0x4b, 0xa9, 0xd7, 0x6c, 0xf8, 0x2c, 0xdd, 0xf0, 0x34, 0x56, 0x1b, 0xbe, 0xa1, 0x2f, - 0xf3, 0xbd, 0xf4, 0x18, 0xa7, 0xb1, 0xb8, 0xe9, 0x45, 0xef, 0x41, 0x5f, 0x1b, 0x3d, 0x67, 0x1e, - 0x13, 0xec, 0x86, 0x2b, 0xdd, 0x07, 0x52, 0x30, 0xbb, 0xc9, 0xdd, 0x1d, 0x68, 0x8c, 0xc7, 0xc7, - 0xa9, 0xb6, 0xc8, 0x8d, 0xe6, 0x27, 0xd0, 0x3f, 0x8b, 0x9d, 0xe0, 0x94, 0xbb, 0x57, 0xae, 0xc7, - 0x66, 0x6a, 0xb3, 0xa4, 0xff, 0x2c, 0xe5, 0xfa, 0xcf, 0xb5, 0xd5, 0xc8, 0xdc, 0x01, 0x52, 0x58, - 0x9e, 0xbe, 0x5b, 0x14, 0x3b, 0x81, 0x4e, 0x61, 0x1c, 0x9b, 0x3b, 0xd0, 0x1e, 0x53, 0x59, 0xef, - 0x1d, 0x65, 0x63, 0x40, 0x5d, 0xa8, 0xb9, 0x36, 0x4b, 0xa6, 0xe6, 0x1e, 0x6c, 0x1d, 0x50, 0xfb, - 0xc2, 0xf5, 0x67, 0xcf, 0xdd, 0x48, 0x36, 0x3c, 0x7a, 0xc5, 0x00, 0x1a, 0x8e, 0x16, 0xe8, 0x25, - 0xe9, 0xdc, 0x7c, 0x0c, 0x6f, 0xe5, 0x7e, 0x69, 0x39, 0x13, 0x34, 0x89, 0xc7, 0x16, 0x54, 0x23, - 0x39, 0xc3, 0x15, 0x55, 0x4b, 0x4d, 0xcc, 0xaf, 0x60, 0x2b, 0x5f, 0x80, 0x65, 0xfb, 0x91, 0x5c, - 0x1c, 0x1b, 0x83, 0x52, 0xae, 0x31, 0xd0, 0x31, 0x2b, 0x67, 0xf5, 0x64, 0x13, 0x2a, 0xbf, 0xfc, - 0x66, 0xac, 0xc1, 0x2e, 0x87, 0xe6, 0xef, 0xe5, 0xf6, 0x45, 0x7f, 0x6a, 0xfb, 0x42, 0x77, 0x50, - 0x7a, 0x93, 0xee, 0x60, 0x0d, 0xde, 0x1e, 0x43, 0xff, 0xc4, 0x0b, 0xec, 0xcb, 0x43, 0x3f, 0x17, - 0x0d, 0x03, 0xea, 0xcc, 0xcf, 0x07, 0x23, 0x99, 0x9a, 0x0f, 0xa0, 0x77, 0x1c, 0xd8, 0xd4, 0x3b, - 0x09, 0x62, 0x5f, 0xa4, 0x51, 0xc0, 0x9f, 0xbe, 0xb4, 0xa9, 0x9a, 0x98, 0x8f, 0xa1, 0xab, 0x4b, - 0xb4, 0x7f, 0x1e, 0x24, 0xcc, 0x98, 0x15, 0xf3, 0x52, 0xb1, 0xd7, 0x36, 0x8f, 0xa1, 0x97, 0x99, - 0x2b, 0xbf, 0x0f, 0xa0, 0xa6, 0xd4, 0xfa, 0x6e, 0xbd, 0xf4, 0x03, 0x52, 0x59, 0x5a, 0x5a, 0xbd, - 0xe6, 0x52, 0x73, 0xe8, 0x9e, 0xe2, 0x4f, 0x90, 0x87, 0xfe, 0x95, 0x72, 0x76, 0x04, 0x44, 0xfd, - 0x28, 0x39, 0x61, 0xfe, 0x95, 0xcb, 0x03, 0x1f, 0xfb, 0xdb, 0x92, 0x6e, 0x61, 0x12, 0xc7, 0xe9, - 0xa2, 0xc4, 0xc2, 0xea, 0x87, 0xcb, 0xa2, 0xb5, 0x31, 0x84, 0xec, 0x07, 0x0e, 0x59, 0x6a, 0x38, - 0x9b, 0x07, 0x82, 0x4d, 0xa8, 0xe3, 0x24, 0xd9, 0x02, 0x4a, 0xb4, 0xef, 0x38, 0x7c, 0xef, 0x3f, - 0x65, 0xa8, 0x7f, 0xa6, 0x08, 0x9c, 0x7c, 0x0a, 0x9d, 0x42, 0xb9, 0x26, 0x6f, 0xe1, 0x2f, 0x1c, - 0xcb, 0xcd, 0xc1, 0x60, 0x7b, 0x45, 0xac, 0xee, 0xf5, 0x04, 0xda, 0xf9, 0x62, 0x4c, 0xb0, 0xf0, - 0xe2, 0xcf, 0xad, 0x03, 0xf4, 0xb4, 0x5a, 0xa9, 0xcf, 0x60, 0x6b, 0x5d, 0x99, 0x24, 0x77, 0xb2, - 0x1d, 0x56, 0x4b, 0xf4, 0xe0, 0x9d, 0x9b, 0xb4, 0x49, 0x79, 0xad, 0x1f, 0x78, 0x8c, 0xfa, 0x71, - 0x98, 0x3f, 0x41, 0x36, 0x24, 0x4f, 0xa1, 0x53, 0x28, 0x14, 0xea, 0x9e, 0x2b, 0xb5, 0x23, 0xbf, - 0xe4, 0x3e, 0x54, 0xb1, 0x38, 0x91, 0x4e, 0xa1, 0x4a, 0x0e, 0xba, 0xe9, 0x54, 0xed, 0x3d, 0x84, - 0x0d, 0xfc, 0x11, 0x2e, 0xb7, 0x31, 0xae, 0x48, 0x2b, 0xd7, 0xde, 0xbf, 0x4b, 0x50, 0x4f, 0x7e, - 0x98, 0x7d, 0x0a, 0x1b, 0xb2, 0x06, 0x90, 0x5b, 0x39, 0x1a, 0x4d, 0xea, 0xc7, 0x60, 0x6b, 0x49, - 0xa8, 0x36, 0x18, 0x41, 0xe5, 0x05, 0x13, 0x84, 0xe4, 0x94, 0xba, 0x18, 0x0c, 0x6e, 0x15, 0x65, - 0xa9, 0xfd, 0x69, 0x5c, 0xb4, 0xd7, 0x5c, 0x5e, 0xb0, 0x4f, 0x59, 0xfa, 0x23, 0xa8, 0x29, 0x96, - 0x55, 0x41, 0x59, 0xe1, 0x67, 0xf5, 0xf8, 0xab, 0x7c, 0xbc, 0xf7, 0xf7, 0x0d, 0x80, 0xb3, 0x45, - 0x24, 0xd8, 0xfc, 0x57, 0x2e, 0x7b, 0x45, 0x1e, 0x42, 0xef, 0x39, 0x3b, 0xa7, 0xb1, 0x27, 0xf0, - 0x6b, 0x49, 0xb2, 0x49, 0x2e, 0x26, 0xd8, 0xf0, 0xa5, 0x64, 0x7d, 0x1f, 0x5a, 0x27, 0xf4, 0xfa, - 0xf5, 0x76, 0x9f, 0x42, 0xa7, 0xc0, 0xc1, 0xfa, 0x88, 0xcb, 0xac, 0xae, 0x8f, 0xb8, 0xca, 0xd6, - 0xf7, 0xa1, 0xae, 0x99, 0x39, 0xbf, 0x07, 0xd6, 0xb0, 0x02, 0x63, 0xff, 0x14, 0x7a, 0x4b, 0xbc, - 0x9c, 0xb7, 0xc7, 0x5f, 0x24, 0xd6, 0xf2, 0xf6, 0x33, 0xf9, 0xb5, 0x53, 0xe4, 0xe6, 0xfc, 0xc2, - 0xdb, 0x8a, 0x0f, 0xd7, 0x91, 0xf7, 0x8b, 0xe2, 0x77, 0x12, 0x7e, 0x25, 0x1a, 0xcb, 0xf4, 0x99, - 0x90, 0x77, 0xe2, 0x68, 0x1d, 0x0d, 0x3f, 0x81, 0x76, 0x9e, 0x41, 0x57, 0x52, 0x70, 0x95, 0x5e, - 0x1f, 0x01, 0x64, 0x24, 0x9a, 0xb7, 0x47, 0x78, 0x2c, 0xf3, 0xeb, 0x87, 0x00, 0x19, 0x35, 0x2a, - 0x54, 0x15, 0x99, 0x55, 0x2d, 0x5b, 0xa6, 0xcf, 0x87, 0xd0, 0x4c, 0xe9, 0x2c, 0xbf, 0x07, 0x3a, - 0x28, 0xb2, 0xe3, 0x67, 0xa3, 0xdf, 0x3e, 0x9a, 0xb9, 0xe2, 0x22, 0x9e, 0x8e, 0xec, 0x60, 0xbe, - 0x7b, 0x41, 0xa3, 0x0b, 0xd7, 0x0e, 0x78, 0xb8, 0x7b, 0x25, 0xc1, 0xb4, 0xbb, 0xf2, 0x9f, 0xd1, - 0xb4, 0x86, 0x1f, 0x7b, 0x1f, 0xfc, 0x37, 0x00, 0x00, 0xff, 0xff, 0x93, 0x15, 0xb9, 0x42, 0x4f, - 0x1a, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.proto b/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.proto deleted file mode 100644 index e02cc1f9..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/pb/backend.proto +++ /dev/null @@ -1,594 +0,0 @@ -syntax = "proto3"; -package pb; - -option go_package = "github.com/hashicorp/vault/logical/plugin/pb"; - -import "google/protobuf/timestamp.proto"; -import "logical/identity.proto"; -import "logical/plugin.proto"; - -message Empty {} - -message Header { - repeated string header = 1; -} - -message ProtoError { - // Error type can be one of: - // ErrTypeUnknown uint32 = iota - // ErrTypeUserError - // ErrTypeInternalError - // ErrTypeCodedError - // ErrTypeStatusBadRequest - // ErrTypeUnsupportedOperation - // ErrTypeUnsupportedPath - // ErrTypeInvalidRequest - // ErrTypePermissionDenied - // ErrTypeMultiAuthzPending - uint32 err_type = 1; - string err_msg = 2; - int64 err_code = 3; -} - -// Paths is the structure of special paths that is used for SpecialPaths. -message Paths { - // Root are the paths that require a root token to access - repeated string root = 1; - - // Unauthenticated are the paths that can be accessed without any auth. - repeated string unauthenticated = 2; - - // LocalStorage are paths (prefixes) that are local to this instance; this - // indicates that these paths should not be replicated - repeated string local_storage = 3; - - // 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. - repeated string seal_wrap_storage = 4; -} - -message Request { - // Id is the uuid associated with each request - string id = 1; - - // If set, the name given to the replication secondary where this request - // originated - string ReplicationCluster = 2; - - // Operation is the requested operation type - string operation = 3; - - // Path is the part of the request path not consumed by the - // routing. As an example, if the original request path is "prod/aws/foo" - // and the AWS logical backend is mounted at "prod/aws/", then the - // final path is "foo" since the mount prefix is trimmed. - string path = 4; - - // Request data is a JSON object that must have keys with string type. - string data = 5; - - // Secret will be non-nil only for Revoke and Renew operations - // to represent the secret that was returned prior. - Secret secret = 6; - - // Auth will be non-nil only for Renew operations - // to represent the auth that was returned prior. - Auth auth = 7; - - // 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. - map headers = 8; - - // 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. - string client_token = 9; - - // ClientTokenAccessor is provided to the core so that the it can get - // logged as part of request audit logging. - string client_token_accessor = 10; - - // 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. - string display_name = 11; - - // 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. - string mount_point = 12; - - // 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) - string mount_type = 13; - - // MountAccessor is provided so that identities returned by the authentication - // backends can be tied to the mount it belongs to. - string mount_accessor = 14; - - // WrapInfo contains requested response wrapping parameters - RequestWrapInfo wrap_info = 15; - - // ClientTokenRemainingUses represents the allowed number of uses left on the - // token supplied - int64 client_token_remaining_uses = 16; - - // EntityID is the identity of the caller extracted out of the token used - // to make this request - string entity_id = 17; - - // PolicyOverride indicates that the requestor wishes to override - // soft-mandatory Sentinel policies - bool policy_override = 18; - - // Whether the request is unauthenticated, as in, had no client token - // attached. Useful in some situations where the client token is not made - // accessible. - bool unauthenticated = 19; - - // Connection will be non-nil only for credential providers to - // inspect the connection information and potentially use it for - // authentication/protection. - Connection connection = 20; -} - -message Auth { - LeaseOptions lease_options = 1; - - // InternalData is a JSON object that is stored with the auth struct. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - string internal_data = 2; - - // 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. - string display_name = 3; - - // Policies is the list of policies that the authenticated user - // is associated with. - repeated string policies = 4; - - // Metadata is used to attach arbitrary string-type metadata to - // an authenticated user. This metadata will be outputted into the - // audit log. - map metadata = 5; - - // 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. - string client_token = 6; - - // 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. - string accessor = 7; - - // 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. - int64 period = 8; - - // Number of allowed uses of the issued token - int64 num_uses = 9; - - // EntityID is the identifier of the entity in identity store to which the - // identity of the authenticating client belongs to. - string entity_id = 10; - - // Alias is the information about the authenticated client returned by - // the auth backend - logical.Alias alias = 11; - - // 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. - repeated logical.Alias group_aliases = 12; - - // If set, restricts usage of the certificates to client IPs falling within - // the range of the specified CIDR(s). - repeated string bound_cidrs = 13; - - // TokenPolicies and IdentityPolicies break down the list in Policies to - // help determine where a policy was sourced - repeated string token_policies = 14; - repeated string identity_policies = 15; - - // Explicit maximum lifetime for the token. Unlike normal TTLs, the maximum - // TTL is a hard limit and cannot be exceeded, also counts for periodic tokens. - int64 explicit_max_ttl = 16; - - // TokenType is the type of token being requested - uint32 token_type = 17; -} - -message TokenEntry { - string id = 1; - string accessor = 2; - string parent = 3; - repeated string policies = 4; - string path = 5; - map meta = 6; - string display_name = 7; - int64 num_uses = 8; - int64 creation_time = 9; - int64 ttl = 10; - int64 explicit_max_ttl = 11; - string role = 12; - int64 period = 13; - string entity_id = 14; - repeated string bound_cidrs = 15; - string namespace_id = 16; - string cubbyhole_id = 17; - uint32 type = 18; -} - -message LeaseOptions { - int64 TTL = 1; - - bool renewable = 2; - - int64 increment = 3; - - google.protobuf.Timestamp issue_time = 4; - - int64 MaxTTL = 5; -} - -message Secret { - LeaseOptions lease_options = 1; - - // InternalData is a JSON object that is stored with the secret. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - string internal_data = 2; - - // 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. - string lease_id = 3; -} - -message Response { - // Secret, if not nil, denotes that this response represents a secret. - Secret secret = 1; - - // Auth, if not nil, contains the authentication information for - // this response. This is only checked and means something for - // credential backends. - Auth auth = 2; - - // Response data is a JSON object 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. - string data = 3; - - // 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. - string redirect = 4; - - // Warnings allow operations or backends to return warnings in response - // to user actions without failing the action outright. - repeated string warnings = 5; - - // Information for wrapping the response in a cubbyhole - ResponseWrapInfo wrap_info = 6; -} - -message ResponseWrapInfo { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - int64 TTL = 1; - - // The token containing the wrapped response - string token = 2; - - // The token accessor for the wrapped response token - string accessor = 3; - - // The creation time. This can be used with the TTL to figure out an - // expected expiration. - google.protobuf.Timestamp creation_time = 4; - - // If the contained response is the output of a token creation call, the - // created token's accessor will be accessible here - string wrapped_accessor = 5; - - // WrappedEntityID is the entity identifier of the caller who initiated the - // wrapping request - string wrapped_entity_id = 6; - - // The format to use. This doesn't get returned, it's only internal. - string format = 7; - - // CreationPath is the original request path that was used to create - // the wrapped response. - string creation_path = 8; - - // Controls seal wrapping behavior downstream for specific use cases - bool seal_wrap = 9; -} - -message RequestWrapInfo { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - int64 TTL = 1; - - // The format to use for the wrapped response; if not specified it's a bare - // token - string format = 2; - - // A flag to conforming backends that data for a given request should be - // seal wrapped - bool seal_wrap = 3; -} - -// HandleRequestArgs is the args for HandleRequest method. -message HandleRequestArgs { - uint32 storage_id = 1; - Request request = 2; -} - -// HandleRequestReply is the reply for HandleRequest method. -message HandleRequestReply { - Response response = 1; - ProtoError err = 2; -} - -// SpecialPathsReply is the reply for SpecialPaths method. -message SpecialPathsReply { - Paths paths = 1; -} - -// HandleExistenceCheckArgs is the args for HandleExistenceCheck method. -message HandleExistenceCheckArgs { - uint32 storage_id = 1; - Request request = 2; -} - -// HandleExistenceCheckReply is the reply for HandleExistenceCheck method. -message HandleExistenceCheckReply { - bool check_found = 1; - bool exists = 2; - ProtoError err = 3; -} - -// SetupArgs is the args for Setup method. -message SetupArgs { - uint32 broker_id = 1; - map Config = 2; - string backendUUID = 3; -} - -// SetupReply is the reply for Setup method. -message SetupReply { - string err = 1; -} - -// TypeReply is the reply for the Type method. -message TypeReply { - uint32 type = 1; -} - -message InvalidateKeyArgs { - string key = 1; -} - -// Backend is the interface that plugins must satisfy. The plugin should -// implement the server for this service. Requests will first run the -// HandleExistenceCheck rpc then run the HandleRequests rpc. -service Backend { - // HandleRequest is used to handle a request and generate a response. - // The plugins must check the operation type and handle appropriately. - rpc HandleRequest(HandleRequestArgs) returns (HandleRequestReply); - - // 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. - rpc SpecialPaths(Empty) returns (SpecialPathsReply); - - // 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. - rpc HandleExistenceCheck(HandleExistenceCheckArgs) returns (HandleExistenceCheckReply); - - // 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 is called right before Vault closes the plugin process. - rpc Cleanup(Empty) returns (Empty); - - // 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. - rpc InvalidateKey(InvalidateKeyArgs) returns (Empty); - - // Setup is used to set up the backend based on the provided backend - // configuration. The plugin's setup implementation should use the provided - // broker_id to create a connection back to Vault for use with the Storage - // and SystemView clients. - rpc Setup(SetupArgs) returns (SetupReply); - - // Type returns the BackendType for the particular backend - rpc Type(Empty) returns (TypeReply); -} - -message StorageEntry { - string key = 1; - bytes value = 2; - bool seal_wrap = 3; -} - -message StorageListArgs { - string prefix = 1; -} - -message StorageListReply { - repeated string keys = 1; - string err = 2; -} - -message StorageGetArgs { - string key = 1; -} - -message StorageGetReply { - StorageEntry entry = 1; - string err = 2; -} - -message StoragePutArgs { - StorageEntry entry = 1; -} - -message StoragePutReply { - string err = 1; -} - -message StorageDeleteArgs { - string key = 1; -} - -message StorageDeleteReply { - string err = 1; -} - -// Storage is the way that plugins are able read/write data. Plugins should -// implement the client for this service. -service Storage { - rpc List(StorageListArgs) returns (StorageListReply); - rpc Get(StorageGetArgs) returns (StorageGetReply); - rpc Put(StoragePutArgs) returns (StoragePutReply); - rpc Delete(StorageDeleteArgs) returns (StorageDeleteReply); -} - -message TTLReply { - int64 TTL = 1; -} - -message SudoPrivilegeArgs { - string path = 1; - string token = 2; -} - -message SudoPrivilegeReply { - bool sudo = 1; -} - -message TaintedReply { - bool tainted = 1; -} - -message CachingDisabledReply { - bool disabled = 1; -} - -message ReplicationStateReply { - int32 state = 1; -} - -message ResponseWrapDataArgs { - string data = 1; - int64 TTL = 2; - bool JWT = 3; -} - -message ResponseWrapDataReply { - ResponseWrapInfo wrap_info = 1; - string err = 2; -} - -message MlockEnabledReply { - bool enabled = 1; -} - -message LocalMountReply { - bool local = 1; -} - -message EntityInfoArgs { - string entity_id = 1; -} - -message EntityInfoReply { - logical.Entity entity = 1; - string err = 2; -} - -message PluginEnvReply { - logical.PluginEnvironment plugin_environment = 1; - string err = 2; -} - -// SystemView exposes system configuration information in a safe way for plugins -// to consume. Plugins should implement the client for this service. -service SystemView { - // DefaultLeaseTTL returns the default lease TTL set in Vault configuration - rpc DefaultLeaseTTL(Empty) returns (TTLReply); - - // 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 - rpc MaxLeaseTTL(Empty) returns (TTLReply); - - // SudoPrivilege returns true if given path has sudo privileges - // for the given client token - rpc SudoPrivilege(SudoPrivilegeArgs) returns (SudoPrivilegeReply); - - // Tainted, 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. - rpc Tainted(Empty) returns (TaintedReply); - - // CachingDisabled returns true if caching is disabled. If true, no caches - // should be used, despite known slowdowns. - rpc CachingDisabled(Empty) returns (CachingDisabledReply); - - // ReplicationState indicates the state of cluster replication - rpc ReplicationState(Empty) returns (ReplicationStateReply); - - // ResponseWrapData wraps the given data in a cubbyhole and returns the - // token used to unwrap. - rpc ResponseWrapData(ResponseWrapDataArgs) returns (ResponseWrapDataReply); - - // MlockEnabled returns the configuration setting for enabling mlock on - // plugins. - rpc MlockEnabled(Empty) returns (MlockEnabledReply); - - // LocalMount, when run from a system view attached to a request, indicates - // whether the request is affecting a local mount or not - rpc LocalMount(Empty) returns (LocalMountReply); - - // EntityInfo returns the basic entity information for the given entity id - rpc EntityInfo(EntityInfoArgs) returns (EntityInfoReply); - - // PluginEnv returns Vault environment information used by plugins - rpc PluginEnv(Empty) returns (PluginEnvReply); -} - -message Connection { - // RemoteAddr is the network address that sent the request. - string remote_addr = 1; -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/pb/translation.go b/vendor/github.com/hashicorp/vault/logical/plugin/pb/translation.go deleted file mode 100644 index c777cae5..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/pb/translation.go +++ /dev/null @@ -1,622 +0,0 @@ -package pb - -import ( - "encoding/json" - "errors" - "time" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" -) - -const ( - ErrTypeUnknown uint32 = iota - ErrTypeUserError - ErrTypeInternalError - ErrTypeCodedError - ErrTypeStatusBadRequest - ErrTypeUnsupportedOperation - ErrTypeUnsupportedPath - ErrTypeInvalidRequest - ErrTypePermissionDenied - ErrTypeMultiAuthzPending -) - -func ProtoErrToErr(e *ProtoError) error { - if e == nil { - return nil - } - - var err error - switch e.ErrType { - case ErrTypeUnknown: - err = errors.New(e.ErrMsg) - case ErrTypeUserError: - err = errutil.UserError{Err: e.ErrMsg} - case ErrTypeInternalError: - err = errutil.InternalError{Err: e.ErrMsg} - case ErrTypeCodedError: - err = logical.CodedError(int(e.ErrCode), e.ErrMsg) - case ErrTypeStatusBadRequest: - err = &logical.StatusBadRequest{Err: e.ErrMsg} - case ErrTypeUnsupportedOperation: - err = logical.ErrUnsupportedOperation - case ErrTypeUnsupportedPath: - err = logical.ErrUnsupportedPath - case ErrTypeInvalidRequest: - err = logical.ErrInvalidRequest - case ErrTypePermissionDenied: - err = logical.ErrPermissionDenied - case ErrTypeMultiAuthzPending: - err = logical.ErrMultiAuthzPending - } - - return err -} - -func ErrToProtoErr(e error) *ProtoError { - if e == nil { - return nil - } - pbErr := &ProtoError{ - ErrMsg: e.Error(), - ErrType: ErrTypeUnknown, - } - - switch e.(type) { - case errutil.UserError: - pbErr.ErrType = ErrTypeUserError - case errutil.InternalError: - pbErr.ErrType = ErrTypeInternalError - case logical.HTTPCodedError: - pbErr.ErrType = ErrTypeCodedError - pbErr.ErrCode = int64(e.(logical.HTTPCodedError).Code()) - case *logical.StatusBadRequest: - pbErr.ErrType = ErrTypeStatusBadRequest - } - - switch { - case e == logical.ErrUnsupportedOperation: - pbErr.ErrType = ErrTypeUnsupportedOperation - case e == logical.ErrUnsupportedPath: - pbErr.ErrType = ErrTypeUnsupportedPath - case e == logical.ErrInvalidRequest: - pbErr.ErrType = ErrTypeInvalidRequest - case e == logical.ErrPermissionDenied: - pbErr.ErrType = ErrTypePermissionDenied - case e == logical.ErrMultiAuthzPending: - pbErr.ErrType = ErrTypeMultiAuthzPending - } - - return pbErr -} - -func ErrToString(e error) string { - if e == nil { - return "" - } - - return e.Error() -} - -func LogicalStorageEntryToProtoStorageEntry(e *logical.StorageEntry) *StorageEntry { - if e == nil { - return nil - } - - return &StorageEntry{ - Key: e.Key, - Value: e.Value, - SealWrap: e.SealWrap, - } -} - -func ProtoStorageEntryToLogicalStorageEntry(e *StorageEntry) *logical.StorageEntry { - if e == nil { - return nil - } - - return &logical.StorageEntry{ - Key: e.Key, - Value: e.Value, - SealWrap: e.SealWrap, - } -} - -func ProtoLeaseOptionsToLogicalLeaseOptions(l *LeaseOptions) (logical.LeaseOptions, error) { - if l == nil { - return logical.LeaseOptions{}, nil - } - - t, err := ptypes.Timestamp(l.IssueTime) - return logical.LeaseOptions{ - TTL: time.Duration(l.TTL), - Renewable: l.Renewable, - Increment: time.Duration(l.Increment), - IssueTime: t, - MaxTTL: time.Duration(l.MaxTTL), - }, err -} - -func LogicalLeaseOptionsToProtoLeaseOptions(l logical.LeaseOptions) (*LeaseOptions, error) { - t, err := ptypes.TimestampProto(l.IssueTime) - if err != nil { - return nil, err - } - - return &LeaseOptions{ - TTL: int64(l.TTL), - Renewable: l.Renewable, - Increment: int64(l.Increment), - IssueTime: t, - MaxTTL: int64(l.MaxTTL), - }, err -} - -func ProtoSecretToLogicalSecret(s *Secret) (*logical.Secret, error) { - if s == nil { - return nil, nil - } - - data := map[string]interface{}{} - err := json.Unmarshal([]byte(s.InternalData), &data) - if err != nil { - return nil, err - } - - lease, err := ProtoLeaseOptionsToLogicalLeaseOptions(s.LeaseOptions) - if err != nil { - return nil, err - } - - return &logical.Secret{ - LeaseOptions: lease, - InternalData: data, - LeaseID: s.LeaseID, - }, nil -} - -func LogicalSecretToProtoSecret(s *logical.Secret) (*Secret, error) { - if s == nil { - return nil, nil - } - - buf, err := json.Marshal(s.InternalData) - if err != nil { - return nil, err - } - - lease, err := LogicalLeaseOptionsToProtoLeaseOptions(s.LeaseOptions) - if err != nil { - return nil, err - } - - return &Secret{ - LeaseOptions: lease, - InternalData: string(buf[:]), - LeaseID: s.LeaseID, - }, err -} - -func LogicalRequestToProtoRequest(r *logical.Request) (*Request, error) { - if r == nil { - return nil, nil - } - - buf, err := json.Marshal(r.Data) - if err != nil { - return nil, err - } - - secret, err := LogicalSecretToProtoSecret(r.Secret) - if err != nil { - return nil, err - } - - auth, err := LogicalAuthToProtoAuth(r.Auth) - if err != nil { - return nil, err - } - - headers := map[string]*Header{} - for k, v := range r.Headers { - headers[k] = &Header{Header: v} - } - - return &Request{ - ID: r.ID, - ReplicationCluster: r.ReplicationCluster, - Operation: string(r.Operation), - Path: r.Path, - Data: string(buf[:]), - Secret: secret, - Auth: auth, - Headers: headers, - ClientToken: r.ClientToken, - ClientTokenAccessor: r.ClientTokenAccessor, - DisplayName: r.DisplayName, - MountPoint: r.MountPoint, - MountType: r.MountType, - MountAccessor: r.MountAccessor, - WrapInfo: LogicalRequestWrapInfoToProtoRequestWrapInfo(r.WrapInfo), - ClientTokenRemainingUses: int64(r.ClientTokenRemainingUses), - Connection: LogicalConnectionToProtoConnection(r.Connection), - EntityID: r.EntityID, - PolicyOverride: r.PolicyOverride, - Unauthenticated: r.Unauthenticated, - }, nil -} - -func ProtoRequestToLogicalRequest(r *Request) (*logical.Request, error) { - if r == nil { - return nil, nil - } - - data := map[string]interface{}{} - err := json.Unmarshal([]byte(r.Data), &data) - if err != nil { - return nil, err - } - - secret, err := ProtoSecretToLogicalSecret(r.Secret) - if err != nil { - return nil, err - } - - auth, err := ProtoAuthToLogicalAuth(r.Auth) - if err != nil { - return nil, err - } - - var headers map[string][]string - if len(r.Headers) > 0 { - headers = make(map[string][]string, len(r.Headers)) - for k, v := range r.Headers { - headers[k] = v.Header - } - } - - return &logical.Request{ - ID: r.ID, - ReplicationCluster: r.ReplicationCluster, - Operation: logical.Operation(r.Operation), - Path: r.Path, - Data: data, - Secret: secret, - Auth: auth, - Headers: headers, - ClientToken: r.ClientToken, - ClientTokenAccessor: r.ClientTokenAccessor, - DisplayName: r.DisplayName, - MountPoint: r.MountPoint, - MountType: r.MountType, - MountAccessor: r.MountAccessor, - WrapInfo: ProtoRequestWrapInfoToLogicalRequestWrapInfo(r.WrapInfo), - ClientTokenRemainingUses: int(r.ClientTokenRemainingUses), - Connection: ProtoConnectionToLogicalConnection(r.Connection), - EntityID: r.EntityID, - PolicyOverride: r.PolicyOverride, - Unauthenticated: r.Unauthenticated, - }, nil -} - -func LogicalConnectionToProtoConnection(c *logical.Connection) *Connection { - if c == nil { - return nil - } - - return &Connection{ - RemoteAddr: c.RemoteAddr, - } -} - -func ProtoConnectionToLogicalConnection(c *Connection) *logical.Connection { - if c == nil { - return nil - } - - return &logical.Connection{ - RemoteAddr: c.RemoteAddr, - } -} - -func LogicalRequestWrapInfoToProtoRequestWrapInfo(i *logical.RequestWrapInfo) *RequestWrapInfo { - if i == nil { - return nil - } - - return &RequestWrapInfo{ - TTL: int64(i.TTL), - Format: i.Format, - SealWrap: i.SealWrap, - } -} - -func ProtoRequestWrapInfoToLogicalRequestWrapInfo(i *RequestWrapInfo) *logical.RequestWrapInfo { - if i == nil { - return nil - } - - return &logical.RequestWrapInfo{ - TTL: time.Duration(i.TTL), - Format: i.Format, - SealWrap: i.SealWrap, - } -} - -func ProtoResponseToLogicalResponse(r *Response) (*logical.Response, error) { - if r == nil { - return nil, nil - } - - secret, err := ProtoSecretToLogicalSecret(r.Secret) - if err != nil { - return nil, err - } - - auth, err := ProtoAuthToLogicalAuth(r.Auth) - if err != nil { - return nil, err - } - - data := map[string]interface{}{} - err = json.Unmarshal([]byte(r.Data), &data) - if err != nil { - return nil, err - } - - wrapInfo, err := ProtoResponseWrapInfoToLogicalResponseWrapInfo(r.WrapInfo) - if err != nil { - return nil, err - } - - return &logical.Response{ - Secret: secret, - Auth: auth, - Data: data, - Redirect: r.Redirect, - Warnings: r.Warnings, - WrapInfo: wrapInfo, - }, nil -} - -func ProtoResponseWrapInfoToLogicalResponseWrapInfo(i *ResponseWrapInfo) (*wrapping.ResponseWrapInfo, error) { - if i == nil { - return nil, nil - } - - t, err := ptypes.Timestamp(i.CreationTime) - if err != nil { - return nil, err - } - - return &wrapping.ResponseWrapInfo{ - TTL: time.Duration(i.TTL), - Token: i.Token, - Accessor: i.Accessor, - CreationTime: t, - WrappedAccessor: i.WrappedAccessor, - WrappedEntityID: i.WrappedEntityID, - Format: i.Format, - CreationPath: i.CreationPath, - SealWrap: i.SealWrap, - }, nil -} - -func LogicalResponseWrapInfoToProtoResponseWrapInfo(i *wrapping.ResponseWrapInfo) (*ResponseWrapInfo, error) { - if i == nil { - return nil, nil - } - - t, err := ptypes.TimestampProto(i.CreationTime) - if err != nil { - return nil, err - } - - return &ResponseWrapInfo{ - TTL: int64(i.TTL), - Token: i.Token, - Accessor: i.Accessor, - CreationTime: t, - WrappedAccessor: i.WrappedAccessor, - WrappedEntityID: i.WrappedEntityID, - Format: i.Format, - CreationPath: i.CreationPath, - SealWrap: i.SealWrap, - }, nil -} - -func LogicalResponseToProtoResponse(r *logical.Response) (*Response, error) { - if r == nil { - return nil, nil - } - - secret, err := LogicalSecretToProtoSecret(r.Secret) - if err != nil { - return nil, err - } - - auth, err := LogicalAuthToProtoAuth(r.Auth) - if err != nil { - return nil, err - } - - buf, err := json.Marshal(r.Data) - if err != nil { - return nil, err - } - - wrapInfo, err := LogicalResponseWrapInfoToProtoResponseWrapInfo(r.WrapInfo) - if err != nil { - return nil, err - } - - return &Response{ - Secret: secret, - Auth: auth, - Data: string(buf[:]), - Redirect: r.Redirect, - Warnings: r.Warnings, - WrapInfo: wrapInfo, - }, nil -} - -func LogicalAuthToProtoAuth(a *logical.Auth) (*Auth, error) { - if a == nil { - return nil, nil - } - - buf, err := json.Marshal(a.InternalData) - if err != nil { - return nil, err - } - - lo, err := LogicalLeaseOptionsToProtoLeaseOptions(a.LeaseOptions) - if err != nil { - return nil, err - } - - boundCIDRs := make([]string, len(a.BoundCIDRs)) - for i, cidr := range a.BoundCIDRs { - boundCIDRs[i] = cidr.String() - } - - return &Auth{ - LeaseOptions: lo, - TokenType: uint32(a.TokenType), - InternalData: string(buf[:]), - DisplayName: a.DisplayName, - Policies: a.Policies, - TokenPolicies: a.TokenPolicies, - IdentityPolicies: a.IdentityPolicies, - Metadata: a.Metadata, - ClientToken: a.ClientToken, - Accessor: a.Accessor, - Period: int64(a.Period), - NumUses: int64(a.NumUses), - EntityID: a.EntityID, - Alias: a.Alias, - GroupAliases: a.GroupAliases, - BoundCIDRs: boundCIDRs, - ExplicitMaxTTL: int64(a.ExplicitMaxTTL), - }, nil -} - -func ProtoAuthToLogicalAuth(a *Auth) (*logical.Auth, error) { - if a == nil { - return nil, nil - } - - data := map[string]interface{}{} - err := json.Unmarshal([]byte(a.InternalData), &data) - if err != nil { - return nil, err - } - - lo, err := ProtoLeaseOptionsToLogicalLeaseOptions(a.LeaseOptions) - if err != nil { - return nil, err - } - - boundCIDRs, err := parseutil.ParseAddrs(a.BoundCIDRs) - if err != nil { - return nil, err - } - if len(boundCIDRs) == 0 { - // On inbound auths, if auth.BoundCIDRs is empty, it will be nil. - // Let's match that behavior outbound. - boundCIDRs = nil - } - - return &logical.Auth{ - LeaseOptions: lo, - TokenType: logical.TokenType(a.TokenType), - InternalData: data, - DisplayName: a.DisplayName, - Policies: a.Policies, - TokenPolicies: a.TokenPolicies, - IdentityPolicies: a.IdentityPolicies, - Metadata: a.Metadata, - ClientToken: a.ClientToken, - Accessor: a.Accessor, - Period: time.Duration(a.Period), - NumUses: int(a.NumUses), - EntityID: a.EntityID, - Alias: a.Alias, - GroupAliases: a.GroupAliases, - BoundCIDRs: boundCIDRs, - ExplicitMaxTTL: time.Duration(a.ExplicitMaxTTL), - }, nil -} - -func LogicalTokenEntryToProtoTokenEntry(t *logical.TokenEntry) *TokenEntry { - if t == nil { - return nil - } - - boundCIDRs := make([]string, len(t.BoundCIDRs)) - for i, cidr := range t.BoundCIDRs { - boundCIDRs[i] = cidr.String() - } - - return &TokenEntry{ - ID: t.ID, - Accessor: t.Accessor, - Parent: t.Parent, - Policies: t.Policies, - Path: t.Path, - Meta: t.Meta, - DisplayName: t.DisplayName, - NumUses: int64(t.NumUses), - CreationTime: t.CreationTime, - TTL: int64(t.TTL), - ExplicitMaxTTL: int64(t.ExplicitMaxTTL), - Role: t.Role, - Period: int64(t.Period), - EntityID: t.EntityID, - BoundCIDRs: boundCIDRs, - NamespaceID: t.NamespaceID, - CubbyholeID: t.CubbyholeID, - Type: uint32(t.Type), - } -} - -func ProtoTokenEntryToLogicalTokenEntry(t *TokenEntry) (*logical.TokenEntry, error) { - if t == nil { - return nil, nil - } - - boundCIDRs, err := parseutil.ParseAddrs(t.BoundCIDRs) - if err != nil { - return nil, err - } - if len(boundCIDRs) == 0 { - // On inbound auths, if auth.BoundCIDRs is empty, it will be nil. - // Let's match that behavior outbound. - boundCIDRs = nil - } - - return &logical.TokenEntry{ - ID: t.ID, - Accessor: t.Accessor, - Parent: t.Parent, - Policies: t.Policies, - Path: t.Path, - Meta: t.Meta, - DisplayName: t.DisplayName, - NumUses: int(t.NumUses), - CreationTime: t.CreationTime, - TTL: time.Duration(t.TTL), - ExplicitMaxTTL: time.Duration(t.ExplicitMaxTTL), - Role: t.Role, - Period: time.Duration(t.Period), - EntityID: t.EntityID, - BoundCIDRs: boundCIDRs, - NamespaceID: t.NamespaceID, - CubbyholeID: t.CubbyholeID, - Type: logical.TokenType(t.Type), - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go b/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go deleted file mode 100644 index 250097c2..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go +++ /dev/null @@ -1,187 +0,0 @@ -package plugin - -import ( - "context" - "crypto/ecdsa" - "crypto/rsa" - "encoding/gob" - "errors" - "fmt" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -// init registers basic structs with gob which will be used to transport complex -// types through the plugin server and client. -func init() { - // Common basic structs - gob.Register([]interface{}{}) - gob.Register(map[string]interface{}{}) - gob.Register(map[string]string{}) - gob.Register(map[string]int{}) - - // Register these types since we have to serialize and de-serialize - // tls.ConnectionState over the wire as part of logical.Request.Connection. - gob.Register(rsa.PublicKey{}) - gob.Register(ecdsa.PublicKey{}) - gob.Register(time.Duration(0)) - - // Custom common error types for requests. If you add something here, you must - // also add it to the switch statement in `wrapError`! - gob.Register(&plugin.BasicError{}) - gob.Register(logical.CodedError(0, "")) - gob.Register(&logical.StatusBadRequest{}) -} - -// BackendPluginClient is a wrapper around backendPluginClient -// that also contains its plugin.Client instance. It's primarily -// used to cleanly kill the client on Cleanup() -type BackendPluginClient struct { - client *plugin.Client - sync.Mutex - - logical.Backend -} - -// Cleanup calls the RPC client's Cleanup() func and also calls -// the go-plugin's client Kill() func -func (b *BackendPluginClient) Cleanup(ctx context.Context) { - b.Backend.Cleanup(ctx) - b.client.Kill() -} - -// NewBackend will return an instance of an RPC-based client implementation of the backend for -// external plugins, or a concrete implementation of the backend if it is a builtin backend. -// The backend is returned as a logical.Backend interface. The isMetadataMode param determines whether -// the plugin should run in metadata mode. -func NewBackend(ctx context.Context, pluginName string, pluginType consts.PluginType, sys pluginutil.LookRunnerUtil, conf *logical.BackendConfig, isMetadataMode bool) (logical.Backend, error) { - // Look for plugin in the plugin catalog - pluginRunner, err := sys.LookupPlugin(ctx, pluginName, pluginType) - if err != nil { - return nil, err - } - - var backend logical.Backend - if pluginRunner.Builtin { - // Plugin is builtin so we can retrieve an instance of the interface - // from the pluginRunner. Then cast it to logical.Factory. - rawFactory, err := pluginRunner.BuiltinFactory() - if err != nil { - return nil, errwrap.Wrapf("error getting plugin type: {{err}}", err) - } - - if factory, ok := rawFactory.(logical.Factory); !ok { - return nil, fmt.Errorf("unsupported backend type: %q", pluginName) - } else { - if backend, err = factory(ctx, conf); err != nil { - return nil, err - } - } - } else { - // create a backendPluginClient instance - backend, err = NewPluginClient(ctx, sys, pluginRunner, conf.Logger, isMetadataMode) - if err != nil { - return nil, err - } - } - - return backend, nil -} - -func NewPluginClient(ctx context.Context, sys pluginutil.RunnerUtil, pluginRunner *pluginutil.PluginRunner, logger log.Logger, isMetadataMode bool) (logical.Backend, error) { - // pluginMap is the map of plugins we can dispense. - pluginSet := map[int]plugin.PluginSet{ - 3: plugin.PluginSet{ - "backend": &BackendPlugin{ - GRPCBackendPlugin: &GRPCBackendPlugin{ - MetadataMode: isMetadataMode, - }, - }, - }, - 4: plugin.PluginSet{ - "backend": &GRPCBackendPlugin{ - MetadataMode: isMetadataMode, - }, - }, - } - - namedLogger := logger.Named(pluginRunner.Name) - - var client *plugin.Client - var err error - if isMetadataMode { - client, err = pluginRunner.RunMetadataMode(ctx, sys, pluginSet, handshakeConfig, []string{}, namedLogger) - } else { - client, err = pluginRunner.Run(ctx, sys, pluginSet, handshakeConfig, []string{}, namedLogger) - } - if err != nil { - return nil, err - } - - // Connect via RPC - rpcClient, err := client.Client() - if err != nil { - return nil, err - } - - // Request the plugin - raw, err := rpcClient.Dispense("backend") - if err != nil { - return nil, err - } - - var backend logical.Backend - var transport string - // We should have a logical backend type now. This feels like a normal interface - // implementation but is in fact over an RPC connection. - switch raw.(type) { - case *backendPluginClient: - logger.Warn("plugin is using deprecated netRPC transport, recompile plugin to upgrade to gRPC", "plugin", pluginRunner.Name) - backend = raw.(*backendPluginClient) - transport = "netRPC" - case *backendGRPCPluginClient: - backend = raw.(*backendGRPCPluginClient) - transport = "gRPC" - default: - return nil, errors.New("unsupported plugin client type") - } - - // Wrap the backend in a tracing middleware - if namedLogger.IsTrace() { - backend = &backendTracingMiddleware{ - logger: namedLogger.With("transport", transport), - next: backend, - } - } - - return &BackendPluginClient{ - client: client, - Backend: backend, - }, nil -} - -// wrapError takes a generic error type and makes it usable with the plugin -// interface. Only errors which have exported fields and have been registered -// with gob can be unwrapped and transported. This checks error types and, if -// none match, wrap the error in a plugin.BasicError. -func wrapError(err error) error { - if err == nil { - return nil - } - - switch err.(type) { - case *plugin.BasicError, - logical.HTTPCodedError, - *logical.StatusBadRequest: - return err - } - - return plugin.NewBasicError(err) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/serve.go b/vendor/github.com/hashicorp/vault/logical/plugin/serve.go deleted file mode 100644 index 97b9f28b..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/serve.go +++ /dev/null @@ -1,97 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "math" - "os" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -// BackendPluginName is the name of the plugin that can be -// dispensed from the plugin server. -const BackendPluginName = "backend" - -type TLSProviderFunc func() (*tls.Config, error) - -type ServeOpts struct { - BackendFactoryFunc logical.Factory - TLSProviderFunc TLSProviderFunc - Logger log.Logger -} - -// Serve is a helper function used to serve a backend plugin. This -// should be ran on the plugin's main process. -func Serve(opts *ServeOpts) error { - logger := opts.Logger - if logger == nil { - logger = log.New(&log.LoggerOptions{ - Level: log.Trace, - Output: os.Stderr, - JSONFormat: true, - }) - } - - // pluginMap is the map of plugins we can dispense. - pluginSets := map[int]plugin.PluginSet{ - 3: plugin.PluginSet{ - "backend": &BackendPlugin{ - GRPCBackendPlugin: &GRPCBackendPlugin{ - Factory: opts.BackendFactoryFunc, - Logger: logger, - }, - }, - }, - 4: plugin.PluginSet{ - "backend": &GRPCBackendPlugin{ - Factory: opts.BackendFactoryFunc, - Logger: logger, - }, - }, - } - - err := pluginutil.OptionallyEnableMlock() - if err != nil { - return err - } - - serveOpts := &plugin.ServeConfig{ - HandshakeConfig: handshakeConfig, - VersionedPlugins: pluginSets, - TLSProvider: opts.TLSProviderFunc, - Logger: logger, - - // A non-nil value here enables gRPC serving for this plugin... - GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { - opts = append(opts, grpc.MaxRecvMsgSize(math.MaxInt32)) - opts = append(opts, grpc.MaxSendMsgSize(math.MaxInt32)) - return plugin.DefaultGRPCServer(opts) - }, - } - - // If we do not have gRPC support fallback to version 3 - // Remove this block in 0.13 - if !pluginutil.GRPCSupport() { - serveOpts.GRPCServer = nil - delete(pluginSets, 4) - } - - plugin.Serve(serveOpts) - - return nil -} - -// handshakeConfigs are used to just do a basic handshake between -// a plugin and host. If the handshake fails, a user friendly error is shown. -// This prevents users from executing bad plugins or executing a plugin -// directory. It is a UX feature, not a security feature. -var handshakeConfig = plugin.HandshakeConfig{ - ProtocolVersion: 4, - MagicCookieKey: "VAULT_BACKEND_PLUGIN", - MagicCookieValue: "6669da05-b1c8-4f49-97d9-c8e5bed98e20", -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/storage.go b/vendor/github.com/hashicorp/vault/logical/plugin/storage.go deleted file mode 100644 index 75cda550..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/storage.go +++ /dev/null @@ -1,139 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - - "github.com/hashicorp/vault/logical" -) - -// StorageClient is an implementation of logical.Storage that communicates -// over RPC. -type StorageClient struct { - client *rpc.Client -} - -func (s *StorageClient) List(_ context.Context, prefix string) ([]string, error) { - var reply StorageListReply - err := s.client.Call("Plugin.List", prefix, &reply) - if err != nil { - return reply.Keys, err - } - if reply.Error != nil { - return reply.Keys, reply.Error - } - return reply.Keys, nil -} - -func (s *StorageClient) Get(_ context.Context, key string) (*logical.StorageEntry, error) { - var reply StorageGetReply - err := s.client.Call("Plugin.Get", key, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - return reply.StorageEntry, nil -} - -func (s *StorageClient) Put(_ context.Context, entry *logical.StorageEntry) error { - var reply StoragePutReply - err := s.client.Call("Plugin.Put", entry, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - return nil -} - -func (s *StorageClient) Delete(_ context.Context, key string) error { - var reply StorageDeleteReply - err := s.client.Call("Plugin.Delete", key, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - return nil -} - -// StorageServer is a net/rpc compatible structure for serving -type StorageServer struct { - impl logical.Storage -} - -func (s *StorageServer) List(prefix string, reply *StorageListReply) error { - keys, err := s.impl.List(context.Background(), prefix) - *reply = StorageListReply{ - Keys: keys, - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Get(key string, reply *StorageGetReply) error { - storageEntry, err := s.impl.Get(context.Background(), key) - *reply = StorageGetReply{ - StorageEntry: storageEntry, - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Put(entry *logical.StorageEntry, reply *StoragePutReply) error { - err := s.impl.Put(context.Background(), entry) - *reply = StoragePutReply{ - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Delete(key string, reply *StorageDeleteReply) error { - err := s.impl.Delete(context.Background(), key) - *reply = StorageDeleteReply{ - Error: wrapError(err), - } - return nil -} - -type StorageListReply struct { - Keys []string - Error error -} - -type StorageGetReply struct { - StorageEntry *logical.StorageEntry - Error error -} - -type StoragePutReply struct { - Error error -} - -type StorageDeleteReply struct { - Error error -} - -// NOOPStorage is used to deny access to the storage interface while running a -// backend plugin in metadata mode. -type NOOPStorage struct{} - -func (s *NOOPStorage) List(_ context.Context, prefix string) ([]string, error) { - return []string{}, nil -} - -func (s *NOOPStorage) Get(_ context.Context, key string) (*logical.StorageEntry, error) { - return nil, nil -} - -func (s *NOOPStorage) Put(_ context.Context, entry *logical.StorageEntry) error { - return nil -} - -func (s *NOOPStorage) Delete(_ context.Context, key string) error { - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/system.go b/vendor/github.com/hashicorp/vault/logical/plugin/system.go deleted file mode 100644 index 148f39a9..00000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/system.go +++ /dev/null @@ -1,351 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - "time" - - "fmt" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" -) - -type SystemViewClient struct { - client *rpc.Client -} - -func (s *SystemViewClient) DefaultLeaseTTL() time.Duration { - var reply DefaultLeaseTTLReply - err := s.client.Call("Plugin.DefaultLeaseTTL", new(interface{}), &reply) - if err != nil { - return 0 - } - - return reply.DefaultLeaseTTL -} - -func (s *SystemViewClient) MaxLeaseTTL() time.Duration { - var reply MaxLeaseTTLReply - err := s.client.Call("Plugin.MaxLeaseTTL", new(interface{}), &reply) - if err != nil { - return 0 - } - - return reply.MaxLeaseTTL -} - -func (s *SystemViewClient) SudoPrivilege(ctx context.Context, path string, token string) bool { - var reply SudoPrivilegeReply - args := &SudoPrivilegeArgs{ - Path: path, - Token: token, - } - - err := s.client.Call("Plugin.SudoPrivilege", args, &reply) - if err != nil { - return false - } - - return reply.Sudo -} - -func (s *SystemViewClient) Tainted() bool { - var reply TaintedReply - - err := s.client.Call("Plugin.Tainted", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.Tainted -} - -func (s *SystemViewClient) CachingDisabled() bool { - var reply CachingDisabledReply - - err := s.client.Call("Plugin.CachingDisabled", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.CachingDisabled -} - -func (s *SystemViewClient) ReplicationState() consts.ReplicationState { - var reply ReplicationStateReply - - err := s.client.Call("Plugin.ReplicationState", new(interface{}), &reply) - if err != nil { - return consts.ReplicationUnknown - } - - return reply.ReplicationState -} - -func (s *SystemViewClient) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - var reply ResponseWrapDataReply - // Do not allow JWTs to be returned - args := &ResponseWrapDataArgs{ - Data: data, - TTL: ttl, - JWT: false, - } - - err := s.client.Call("Plugin.ResponseWrapData", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.ResponseWrapInfo, nil -} - -func (s *SystemViewClient) LookupPlugin(_ context.Context, _ string, _ consts.PluginType) (*pluginutil.PluginRunner, error) { - return nil, fmt.Errorf("cannot call LookupPlugin from a plugin backend") -} - -func (s *SystemViewClient) HasFeature(feature license.Features) bool { - // Not implemented - return false -} - -func (s *SystemViewClient) MlockEnabled() bool { - var reply MlockEnabledReply - err := s.client.Call("Plugin.MlockEnabled", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.MlockEnabled -} - -func (s *SystemViewClient) LocalMount() bool { - var reply LocalMountReply - err := s.client.Call("Plugin.LocalMount", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.Local -} - -func (s *SystemViewClient) EntityInfo(entityID string) (*logical.Entity, error) { - var reply EntityInfoReply - args := &EntityInfoArgs{ - EntityID: entityID, - } - - err := s.client.Call("Plugin.EntityInfo", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.Entity, nil -} - -func (s *SystemViewClient) PluginEnv(_ context.Context) (*logical.PluginEnvironment, error) { - var reply PluginEnvReply - - err := s.client.Call("Plugin.PluginEnv", new(interface{}), &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.PluginEnvironment, nil -} - -type SystemViewServer struct { - impl logical.SystemView -} - -func (s *SystemViewServer) DefaultLeaseTTL(_ interface{}, reply *DefaultLeaseTTLReply) error { - ttl := s.impl.DefaultLeaseTTL() - *reply = DefaultLeaseTTLReply{ - DefaultLeaseTTL: ttl, - } - - return nil -} - -func (s *SystemViewServer) MaxLeaseTTL(_ interface{}, reply *MaxLeaseTTLReply) error { - ttl := s.impl.MaxLeaseTTL() - *reply = MaxLeaseTTLReply{ - MaxLeaseTTL: ttl, - } - - return nil -} - -func (s *SystemViewServer) SudoPrivilege(args *SudoPrivilegeArgs, reply *SudoPrivilegeReply) error { - sudo := s.impl.SudoPrivilege(context.Background(), args.Path, args.Token) - *reply = SudoPrivilegeReply{ - Sudo: sudo, - } - - return nil -} - -func (s *SystemViewServer) Tainted(_ interface{}, reply *TaintedReply) error { - tainted := s.impl.Tainted() - *reply = TaintedReply{ - Tainted: tainted, - } - - return nil -} - -func (s *SystemViewServer) CachingDisabled(_ interface{}, reply *CachingDisabledReply) error { - cachingDisabled := s.impl.CachingDisabled() - *reply = CachingDisabledReply{ - CachingDisabled: cachingDisabled, - } - - return nil -} - -func (s *SystemViewServer) ReplicationState(_ interface{}, reply *ReplicationStateReply) error { - replicationState := s.impl.ReplicationState() - *reply = ReplicationStateReply{ - ReplicationState: replicationState, - } - - return nil -} - -func (s *SystemViewServer) ResponseWrapData(args *ResponseWrapDataArgs, reply *ResponseWrapDataReply) error { - // Do not allow JWTs to be returned - info, err := s.impl.ResponseWrapData(context.Background(), args.Data, args.TTL, false) - if err != nil { - *reply = ResponseWrapDataReply{ - Error: wrapError(err), - } - return nil - } - *reply = ResponseWrapDataReply{ - ResponseWrapInfo: info, - } - - return nil -} - -func (s *SystemViewServer) MlockEnabled(_ interface{}, reply *MlockEnabledReply) error { - enabled := s.impl.MlockEnabled() - *reply = MlockEnabledReply{ - MlockEnabled: enabled, - } - - return nil -} - -func (s *SystemViewServer) LocalMount(_ interface{}, reply *LocalMountReply) error { - local := s.impl.LocalMount() - *reply = LocalMountReply{ - Local: local, - } - - return nil -} - -func (s *SystemViewServer) EntityInfo(args *EntityInfoArgs, reply *EntityInfoReply) error { - entity, err := s.impl.EntityInfo(args.EntityID) - if err != nil { - *reply = EntityInfoReply{ - Error: wrapError(err), - } - return nil - } - *reply = EntityInfoReply{ - Entity: entity, - } - - return nil -} - -func (s *SystemViewServer) PluginEnv(_ interface{}, reply *PluginEnvReply) error { - pluginEnv, err := s.impl.PluginEnv(context.Background()) - if err != nil { - *reply = PluginEnvReply{ - Error: wrapError(err), - } - return nil - } - *reply = PluginEnvReply{ - PluginEnvironment: pluginEnv, - } - - return nil -} - -type DefaultLeaseTTLReply struct { - DefaultLeaseTTL time.Duration -} - -type MaxLeaseTTLReply struct { - MaxLeaseTTL time.Duration -} - -type SudoPrivilegeArgs struct { - Path string - Token string -} - -type SudoPrivilegeReply struct { - Sudo bool -} - -type TaintedReply struct { - Tainted bool -} - -type CachingDisabledReply struct { - CachingDisabled bool -} - -type ReplicationStateReply struct { - ReplicationState consts.ReplicationState -} - -type ResponseWrapDataArgs struct { - Data map[string]interface{} - TTL time.Duration - JWT bool -} - -type ResponseWrapDataReply struct { - ResponseWrapInfo *wrapping.ResponseWrapInfo - Error error -} - -type MlockEnabledReply struct { - MlockEnabled bool -} - -type LocalMountReply struct { - Local bool -} - -type EntityInfoArgs struct { - EntityID string -} - -type EntityInfoReply struct { - Entity *logical.Entity - Error error -} - -type PluginEnvReply struct { - PluginEnvironment *logical.PluginEnvironment - Error error -} diff --git a/vendor/github.com/hashicorp/vault/logical/request.go b/vendor/github.com/hashicorp/vault/logical/request.go deleted file mode 100644 index 8380270d..00000000 --- a/vendor/github.com/hashicorp/vault/logical/request.go +++ /dev/null @@ -1,282 +0,0 @@ -package logical - -import ( - "fmt" - "strings" - "time" -) - -// 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", - } -} - -// 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 { - entReq - - // 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 part of the request path not consumed by the - // routing. As an example, if the original request path is "prod/aws/foo" - // and the AWS logical backend is mounted at "prod/aws/", then the - // final path is "foo" since the mount prefix is trimmed. - 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 -} - -// 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) 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" - DeleteOperation = "delete" - ListOperation = "list" - HelpOperation = "help" - AliasLookaheadOperation = "alias-lookahead" - - // The operations below are called globally, the path is less relevant. - RevokeOperation Operation = "revoke" - RenewOperation = "renew" - RollbackOperation = "rollback" -) - -type MFACreds map[string][]string diff --git a/vendor/github.com/hashicorp/vault/logical/request_util.go b/vendor/github.com/hashicorp/vault/logical/request_util.go deleted file mode 100644 index 38d6e3d5..00000000 --- a/vendor/github.com/hashicorp/vault/logical/request_util.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !enterprise - -package logical - -type entReq struct { - ControlGroup interface{} -} - -func (r *Request) EntReq() *entReq { - return &entReq{} -} - -func (r *Request) SetEntReq(*entReq) { -} diff --git a/vendor/github.com/hashicorp/vault/logical/response.go b/vendor/github.com/hashicorp/vault/logical/response.go deleted file mode 100644 index 02ffa34c..00000000 --- a/vendor/github.com/hashicorp/vault/logical/response.go +++ /dev/null @@ -1,171 +0,0 @@ -package logical - -import ( - "encoding/json" - "errors" - - "github.com/hashicorp/vault/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" -) - -// 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"` -} - -// 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 { - return r != nil && r.Data != nil && len(r.Data) == 1 && r.Data["error"] != nil -} - -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) *Response { - 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 -} diff --git a/vendor/github.com/hashicorp/vault/logical/response_util.go b/vendor/github.com/hashicorp/vault/logical/response_util.go deleted file mode 100644 index b4df6323..00000000 --- a/vendor/github.com/hashicorp/vault/logical/response_util.go +++ /dev/null @@ -1,147 +0,0 @@ -package logical - -import ( - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/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.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(errors.New(fmt.Sprintf("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, 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 - } - } - - 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 - } - - // 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() - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/secret.go b/vendor/github.com/hashicorp/vault/logical/secret.go deleted file mode 100644 index a2128d86..00000000 --- a/vendor/github.com/hashicorp/vault/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/logical/storage.go b/vendor/github.com/hashicorp/vault/logical/storage.go deleted file mode 100644 index 116fd301..00000000 --- a/vendor/github.com/hashicorp/vault/logical/storage.go +++ /dev/null @@ -1,121 +0,0 @@ -package logical - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/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 { - 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) { - // Accumulate the keys - var existing []string - cb := func(path string) { - existing = append(existing, path) - } - - // Scan for all the keys - if err := ScanView(ctx, view, cb); err != nil { - return nil, err - } - return existing, nil -} - -// ClearView is used to delete all the keys in a view -func ClearView(ctx context.Context, view ClearableView) error { - if view == nil { - return nil - } - - // Collect all the keys - keys, err := CollectKeys(ctx, view) - if err != nil { - return err - } - - // Delete all the keys - for _, key := range keys { - if err := view.Delete(ctx, key); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/storage_inmem.go b/vendor/github.com/hashicorp/vault/logical/storage_inmem.go deleted file mode 100644 index e0ff75f1..00000000 --- a/vendor/github.com/hashicorp/vault/logical/storage_inmem.go +++ /dev/null @@ -1,67 +0,0 @@ -package logical - -import ( - "context" - "sync" - - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/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) init() { - s.underlying, _ = inmem.NewInmem(nil, nil) -} diff --git a/vendor/github.com/hashicorp/vault/logical/system_view.go b/vendor/github.com/hashicorp/vault/logical/system_view.go deleted file mode 100644 index dff258b1..00000000 --- a/vendor/github.com/hashicorp/vault/logical/system_view.go +++ /dev/null @@ -1,139 +0,0 @@ -package logical - -import ( - "context" - "errors" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/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 - - // SudoPrivilege returns true if given path has sudo privileges - // for the given client token - SudoPrivilege(ctx context.Context, path string, token string) bool - - // 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(context.Context, string, consts.PluginType) (*pluginutil.PluginRunner, 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) - - // PluginEnv returns Vault environment information used by plugins - PluginEnv(context.Context) (*PluginEnvironment, 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 - Features license.Features - VaultVersion string - PluginEnvironment *PluginEnvironment -} - -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) 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) MlockEnabled() bool { - return d.EnableMlock -} - -func (d StaticSystemView) EntityInfo(entityID string) (*Entity, error) { - return d.EntityVal, 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 -} diff --git a/vendor/github.com/hashicorp/vault/logical/testing.go b/vendor/github.com/hashicorp/vault/logical/testing.go deleted file mode 100644 index 7c773899..00000000 --- a/vendor/github.com/hashicorp/vault/logical/testing.go +++ /dev/null @@ -1,84 +0,0 @@ -package logical - -import ( - "context" - "reflect" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/logging" - "github.com/mitchellh/go-testing-interface" -) - -// 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), - } -} - -// 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, - } -} - -func TestBackendConfig() *BackendConfig { - bc := &BackendConfig{ - Logger: logging.NewVaultLogger(log.Trace), - System: TestSystemView(), - } - - return bc -} diff --git a/vendor/github.com/hashicorp/vault/logical/token.go b/vendor/github.com/hashicorp/vault/logical/token.go deleted file mode 100644 index c6212a36..00000000 --- a/vendor/github.com/hashicorp/vault/logical/token.go +++ /dev/null @@ -1,181 +0,0 @@ -package logical - -import ( - "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 -) - -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:""` - - // 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"` - - // 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"` - - // 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 string `json:"entity_id" mapstructure:"entity_id" structs:"entity_id"` - - // The set of CIDRs that this token can be used with - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` - - // 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:""` -} - -func (te *TokenEntry) SentinelGet(key string) (interface{}, error) { - if te == nil { - return nil, nil - } - switch key { - 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", - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/translate_response.go b/vendor/github.com/hashicorp/vault/logical/translate_response.go deleted file mode 100644 index 11714c22..00000000 --- a/vendor/github.com/hashicorp/vault/logical/translate_response.go +++ /dev/null @@ -1,151 +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, - } - - 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(), - } - } - - return httpResp -} - -func HTTPResponseToLogicalResponse(input *HTTPResponse) *Response { - logicalResp := &Response{ - Data: input.Data, - Warnings: input.Warnings, - } - - 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, - } - 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"` - 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"` -} - -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 - // Make a guess at the capacity, and write the object opener - buf := bytes.NewBuffer(make([]byte, 0, len(j)*2)) - 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/physical/cache.go b/vendor/github.com/hashicorp/vault/physical/cache.go deleted file mode 100644 index af6a39b8..00000000 --- a/vendor/github.com/hashicorp/vault/physical/cache.go +++ /dev/null @@ -1,219 +0,0 @@ -package physical - -import ( - "context" - "sync/atomic" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/golang-lru" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/pathmanager" -) - -const ( - // DefaultCacheSize is used if no cache size is specified for NewCache - DefaultCacheSize = 128 * 1024 -) - -// 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", -} - -// 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 -} - -// 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) -var _ ToggleablePurgemonster = (*TransactionalCache)(nil) -var _ Backend = (*Cache)(nil) -var _ 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) *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, - } - return c -} - -func NewTransactionalCache(b Backend, size int, logger log.Logger) *TransactionalCache { - c := &TransactionalCache{ - Cache: NewCache(b, size, logger), - 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) - } - 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 raw, ok := c.lru.Get(key); ok { - if raw == nil { - return nil, nil - } - return raw.(*Entry), nil - } - - // Read from the underlying backend - ent, err := c.backend.Get(ctx, key) - if err != nil { - return nil, err - } - - // Cache the result - 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) 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) - case DeleteOperation: - c.lru.Remove(txn.Entry.Key) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/encoding.go b/vendor/github.com/hashicorp/vault/physical/encoding.go deleted file mode 100644 index d2f93478..00000000 --- a/vendor/github.com/hashicorp/vault/physical/encoding.go +++ /dev/null @@ -1,104 +0,0 @@ -package physical - -import ( - "context" - "errors" - "strings" - "unicode" - "unicode/utf8" -) - -var ErrNonUTF8 = errors.New("key contains invalid UTF-8 characters") -var 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) -var _ 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/physical/error.go b/vendor/github.com/hashicorp/vault/physical/error.go deleted file mode 100644 index d4c6f80e..00000000 --- a/vendor/github.com/hashicorp/vault/physical/error.go +++ /dev/null @@ -1,103 +0,0 @@ -package physical - -import ( - "context" - "errors" - "math/rand" - "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 - 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) -var _ 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, - 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 { - roll := e.random.Intn(100) - 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/physical/inmem/inmem.go b/vendor/github.com/hashicorp/vault/physical/inmem/inmem.go deleted file mode 100644 index d1433d8a..00000000 --- a/vendor/github.com/hashicorp/vault/physical/inmem/inmem.go +++ /dev/null @@ -1,263 +0,0 @@ -package inmem - -import ( - "context" - "errors" - "os" - "strings" - "sync" - "sync/atomic" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" - - "github.com/armon/go-radix" -) - -// Verify interfaces are satisfied -var _ physical.Backend = (*InmemBackend)(nil) -var _ physical.HABackend = (*InmemHABackend)(nil) -var _ physical.HABackend = (*TransactionalInmemHABackend)(nil) -var _ physical.Lock = (*InmemLock)(nil) -var _ physical.Transactional = (*TransactionalInmemBackend)(nil) -var _ 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") -) - -// 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 - logOps bool -} - -type TransactionalInmemBackend struct { - InmemBackend -} - -// NewInmem constructs a new in-memory backend -func NewInmem(_ map[string]string, logger log.Logger) (physical.Backend, error) { - in := &InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - logOps: os.Getenv("VAULT_INMEM_LOG_ALL_OPS") != "", - } - return in, nil -} - -// Basically for now just creates a permit pool of size 1 so only one operation -// can run at a time -func NewTransactionalInmem(_ map[string]string, logger log.Logger) (physical.Backend, error) { - in := &TransactionalInmemBackend{ - InmemBackend: InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(1), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - logOps: os.Getenv("VAULT_INMEM_LOG_ALL_OPS") != "", - }, - } - return in, 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: - } - - 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) -} - -// 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 ot 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) -} - -// 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() - - return physical.GenericTransactionHandler(ctx, t, txns) -} diff --git a/vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go b/vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go deleted file mode 100644 index 67551007..00000000 --- a/vendor/github.com/hashicorp/vault/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/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/physical/latency.go b/vendor/github.com/hashicorp/vault/physical/latency.go deleted file mode 100644 index 18829714..00000000 --- a/vendor/github.com/hashicorp/vault/physical/latency.go +++ /dev/null @@ -1,98 +0,0 @@ -package physical - -import ( - "context" - "math/rand" - "time" - - log "github.com/hashicorp/go-hclog" -) - -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 { - backend Backend - latency time.Duration - jitterPercent int - 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) -var _ 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{ - backend: b, - latency: latency, - jitterPercent: jitter, - 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) addLatency() { - // Calculate a value between 1 +- jitter% - percent := 100 - if l.jitterPercent > 0 { - min := 100 - l.jitterPercent - max := 100 + l.jitterPercent - percent = l.random.Intn(max-min) + min - } - latencyDuration := time.Duration(int(l.latency) * 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/physical/physical.go b/vendor/github.com/hashicorp/vault/physical/physical.go deleted file mode 100644 index 0f4b0002..00000000 --- a/vendor/github.com/hashicorp/vault/physical/physical.go +++ /dev/null @@ -1,157 +0,0 @@ -package physical - -import ( - "context" - "strings" - "sync" - - 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" -) - -// ShutdownSignal -type ShutdownChannel chan struct{} - -// 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) -} - -// Callback signatures for RunServiceDiscovery -type ActiveFunction func() bool -type SealedFunction func() bool -type PerformanceStandbyFunction func() bool - -// ServiceDiscovery is an optional interface that an HABackend can implement. -// If they do, the state of a backend is advertised to the service discovery -// network. -type ServiceDiscovery interface { - // NotifyActiveStateChange is used by Core to notify a backend - // capable of ServiceDiscovery that this Vault instance has changed - // its status to active or standby. - NotifyActiveStateChange() error - - // NotifySealedStateChange is used by Core to notify a backend - // capable of ServiceDiscovery that Vault has changed its Sealed - // status to sealed or unsealed. - NotifySealedStateChange() error - - // NotifyPerformanceStandbyStateChange is used by Core to notify a backend - // capable of ServiceDiscovery that this Vault instance has changed it - // status to performance standby or standby. - NotifyPerformanceStandbyStateChange() error - - // Run executes any background service discovery tasks until the - // shutdown channel is closed. - RunServiceDiscovery(waitGroup *sync.WaitGroup, shutdownCh ShutdownChannel, redirectAddr string, activeFunc ActiveFunction, sealedFunc SealedFunction, perfStandbyFunc PerformanceStandbyFunction) 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 -} - -// 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/physical/physical_access.go b/vendor/github.com/hashicorp/vault/physical/physical_access.go deleted file mode 100644 index 7497313a..00000000 --- a/vendor/github.com/hashicorp/vault/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/physical/physical_util.go b/vendor/github.com/hashicorp/vault/physical/physical_util.go deleted file mode 100644 index c4863339..00000000 --- a/vendor/github.com/hashicorp/vault/physical/physical_util.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !enterprise - -package physical - -// Entry is used to represent data stored by the physical backend -type Entry struct { - Key string - Value []byte - SealWrap bool `json:"seal_wrap,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/physical/physical_view.go b/vendor/github.com/hashicorp/vault/physical/physical_view.go deleted file mode 100644 index da505a4f..00000000 --- a/vendor/github.com/hashicorp/vault/physical/physical_view.go +++ /dev/null @@ -1,98 +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 - } - if entry != 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/physical/testing.go b/vendor/github.com/hashicorp/vault/physical/testing.go deleted file mode 100644 index 6bff9d22..00000000 --- a/vendor/github.com/hashicorp/vault/physical/testing.go +++ /dev/null @@ -1,488 +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) - } - - 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{ - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar2"), - }, - }, - &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme", - }, - }, - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar3"), - }, - }, - &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme2", - }, - }, - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "zip", - Value: []byte("zap3"), - }, - }, - } - - return txns -} diff --git a/vendor/github.com/hashicorp/vault/physical/transactions.go b/vendor/github.com/hashicorp/vault/physical/transactions.go deleted file mode 100644 index 19f0d2cb..00000000 --- a/vendor/github.com/hashicorp/vault/physical/transactions.go +++ /dev/null @@ -1,131 +0,0 @@ -package physical - -import ( - "context" - - multierror "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 -} - -// 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 - - // 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/vault/physical/types.pb.go b/vendor/github.com/hashicorp/vault/physical/types.pb.go deleted file mode 100644 index 91fbb0e8..00000000 --- a/vendor/github.com/hashicorp/vault/physical/types.pb.go +++ /dev/null @@ -1,221 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: physical/types.proto - -package physical - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// 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 EncryptedBlobInfo struct { - Ciphertext []byte `protobuf:"bytes,1,opt,name=ciphertext,proto3" json:"ciphertext,omitempty"` - IV []byte `protobuf:"bytes,2,opt,name=iv,proto3" json:"iv,omitempty"` - HMAC []byte `protobuf:"bytes,3,opt,name=hmac,proto3" json:"hmac,omitempty"` - Wrapped bool `protobuf:"varint,4,opt,name=wrapped,proto3" json:"wrapped,omitempty"` - KeyInfo *SealKeyInfo `protobuf:"bytes,5,opt,name=key_info,json=keyInfo,proto3" json:"key_info,omitempty"` - // Key is the Key value for the entry that corresponds to - // physical.Entry.Key's value - Key string `protobuf:"bytes,6,opt,name=key,proto3" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EncryptedBlobInfo) Reset() { *m = EncryptedBlobInfo{} } -func (m *EncryptedBlobInfo) String() string { return proto.CompactTextString(m) } -func (*EncryptedBlobInfo) ProtoMessage() {} -func (*EncryptedBlobInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_deea33bd14ea5328, []int{0} -} - -func (m *EncryptedBlobInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EncryptedBlobInfo.Unmarshal(m, b) -} -func (m *EncryptedBlobInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EncryptedBlobInfo.Marshal(b, m, deterministic) -} -func (m *EncryptedBlobInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_EncryptedBlobInfo.Merge(m, src) -} -func (m *EncryptedBlobInfo) XXX_Size() int { - return xxx_messageInfo_EncryptedBlobInfo.Size(m) -} -func (m *EncryptedBlobInfo) XXX_DiscardUnknown() { - xxx_messageInfo_EncryptedBlobInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_EncryptedBlobInfo proto.InternalMessageInfo - -func (m *EncryptedBlobInfo) GetCiphertext() []byte { - if m != nil { - return m.Ciphertext - } - return nil -} - -func (m *EncryptedBlobInfo) GetIV() []byte { - if m != nil { - return m.IV - } - return nil -} - -func (m *EncryptedBlobInfo) GetHMAC() []byte { - if m != nil { - return m.HMAC - } - return nil -} - -func (m *EncryptedBlobInfo) GetWrapped() bool { - if m != nil { - return m.Wrapped - } - return false -} - -func (m *EncryptedBlobInfo) GetKeyInfo() *SealKeyInfo { - if m != nil { - return m.KeyInfo - } - return nil -} - -func (m *EncryptedBlobInfo) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -// SealKeyInfo contains information regarding the seal used to encrypt the entry. -type SealKeyInfo struct { - // Mechanism is the method used by the seal to encrypt and sign the - // data as defined by the seal. - Mechanism uint64 `protobuf:"varint,1,opt,name=Mechanism,proto3" json:"Mechanism,omitempty"` - HMACMechanism uint64 `protobuf:"varint,2,opt,name=HMACMechanism,proto3" json:"HMACMechanism,omitempty"` - // This is an opaque ID used by the seal to identify the specific - // key to use as defined by the seal. This could be a version, key - // label, or something else. - KeyID string `protobuf:"bytes,3,opt,name=KeyID,proto3" json:"KeyID,omitempty"` - HMACKeyID string `protobuf:"bytes,4,opt,name=HMACKeyID,proto3" json:"HMACKeyID,omitempty"` - // These value are used when generating our own data encryption keys - // and encrypting them using the autoseal - WrappedKey []byte `protobuf:"bytes,5,opt,name=WrappedKey,proto3" json:"WrappedKey,omitempty"` - // Mechanism specific flags - Flags uint64 `protobuf:"varint,6,opt,name=Flags,proto3" json:"Flags,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SealKeyInfo) Reset() { *m = SealKeyInfo{} } -func (m *SealKeyInfo) String() string { return proto.CompactTextString(m) } -func (*SealKeyInfo) ProtoMessage() {} -func (*SealKeyInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_deea33bd14ea5328, []int{1} -} - -func (m *SealKeyInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SealKeyInfo.Unmarshal(m, b) -} -func (m *SealKeyInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SealKeyInfo.Marshal(b, m, deterministic) -} -func (m *SealKeyInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SealKeyInfo.Merge(m, src) -} -func (m *SealKeyInfo) XXX_Size() int { - return xxx_messageInfo_SealKeyInfo.Size(m) -} -func (m *SealKeyInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SealKeyInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SealKeyInfo proto.InternalMessageInfo - -func (m *SealKeyInfo) GetMechanism() uint64 { - if m != nil { - return m.Mechanism - } - return 0 -} - -func (m *SealKeyInfo) GetHMACMechanism() uint64 { - if m != nil { - return m.HMACMechanism - } - return 0 -} - -func (m *SealKeyInfo) GetKeyID() string { - if m != nil { - return m.KeyID - } - return "" -} - -func (m *SealKeyInfo) GetHMACKeyID() string { - if m != nil { - return m.HMACKeyID - } - return "" -} - -func (m *SealKeyInfo) GetWrappedKey() []byte { - if m != nil { - return m.WrappedKey - } - return nil -} - -func (m *SealKeyInfo) GetFlags() uint64 { - if m != nil { - return m.Flags - } - return 0 -} - -func init() { - proto.RegisterType((*EncryptedBlobInfo)(nil), "physical.EncryptedBlobInfo") - proto.RegisterType((*SealKeyInfo)(nil), "physical.SealKeyInfo") -} - -func init() { proto.RegisterFile("physical/types.proto", fileDescriptor_deea33bd14ea5328) } - -var fileDescriptor_deea33bd14ea5328 = []byte{ - // 312 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x91, 0x5f, 0x4b, 0xc3, 0x30, - 0x14, 0xc5, 0x69, 0xd7, 0xfd, 0xbb, 0x9b, 0xa2, 0x61, 0x42, 0x1e, 0x44, 0xca, 0x54, 0xe8, 0x53, - 0x2b, 0xfa, 0x09, 0x9c, 0x7f, 0x50, 0xc6, 0x5e, 0xe2, 0x83, 0xe0, 0x8b, 0x64, 0x59, 0xb6, 0x84, - 0x75, 0x4d, 0x68, 0xb3, 0x69, 0x3e, 0x98, 0x4f, 0x7e, 0x39, 0x49, 0x4a, 0xd9, 0x7c, 0xbb, 0xf7, - 0x97, 0xc3, 0xe1, 0x9c, 0x1b, 0x18, 0x69, 0x61, 0x2b, 0xc9, 0x68, 0x9e, 0x19, 0xab, 0x79, 0x95, - 0xea, 0x52, 0x19, 0x85, 0x7a, 0x0d, 0x1d, 0xff, 0x04, 0x70, 0xfa, 0x54, 0xb0, 0xd2, 0x6a, 0xc3, - 0x17, 0x93, 0x5c, 0xcd, 0x5f, 0x8b, 0xa5, 0x42, 0x17, 0x00, 0x4c, 0x6a, 0xc1, 0x4b, 0xc3, 0xbf, - 0x0d, 0x0e, 0xe2, 0x20, 0x19, 0x92, 0x03, 0x82, 0x8e, 0x21, 0x94, 0x3b, 0x1c, 0x7a, 0x1e, 0xca, - 0x1d, 0x42, 0x10, 0x89, 0x0d, 0x65, 0xb8, 0xe5, 0x89, 0x9f, 0x11, 0x86, 0xee, 0x57, 0x49, 0xb5, - 0xe6, 0x0b, 0x1c, 0xc5, 0x41, 0xd2, 0x23, 0xcd, 0x8a, 0x6e, 0xa0, 0xb7, 0xe6, 0xf6, 0x53, 0x16, - 0x4b, 0x85, 0xdb, 0x71, 0x90, 0x0c, 0x6e, 0xcf, 0xd2, 0x26, 0x50, 0xfa, 0xc6, 0x69, 0x3e, 0xe5, - 0xd6, 0xc5, 0x20, 0xdd, 0x75, 0x3d, 0xa0, 0x13, 0x68, 0xad, 0xb9, 0xc5, 0x9d, 0x38, 0x48, 0xfa, - 0xc4, 0x8d, 0xe3, 0xdf, 0x00, 0x06, 0x07, 0x52, 0x74, 0x0e, 0xfd, 0x19, 0x67, 0x82, 0x16, 0xb2, - 0xda, 0xf8, 0xc0, 0x11, 0xd9, 0x03, 0x74, 0x05, 0x47, 0x2f, 0xb3, 0xfb, 0x87, 0xbd, 0x22, 0xf4, - 0x8a, 0xff, 0x10, 0x8d, 0xa0, 0xed, 0xec, 0x1e, 0x7d, 0x8d, 0x3e, 0xa9, 0x17, 0xe7, 0xec, 0x64, - 0xf5, 0x4b, 0xe4, 0x5f, 0xf6, 0xc0, 0x5d, 0xea, 0xbd, 0xae, 0x35, 0xe5, 0xd6, 0xb7, 0x19, 0x92, - 0x03, 0xe2, 0x3c, 0x9f, 0x73, 0xba, 0xaa, 0x7c, 0xf6, 0x88, 0xd4, 0xcb, 0xe4, 0xfa, 0xe3, 0x72, - 0x25, 0x8d, 0xd8, 0xce, 0x53, 0xa6, 0x36, 0x99, 0xa0, 0x95, 0x90, 0x4c, 0x95, 0x3a, 0xdb, 0xd1, - 0x6d, 0x6e, 0xb2, 0xe6, 0x16, 0xf3, 0x8e, 0xff, 0xad, 0xbb, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x01, 0x95, 0xea, 0x9d, 0xc5, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/physical/types.proto b/vendor/github.com/hashicorp/vault/physical/types.proto deleted file mode 100644 index 0cc2eb53..00000000 --- a/vendor/github.com/hashicorp/vault/physical/types.proto +++ /dev/null @@ -1,38 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/physical"; - -package physical; - -message EncryptedBlobInfo { - bytes ciphertext = 1; - bytes iv = 2; - bytes hmac = 3; - bool wrapped = 4; - SealKeyInfo key_info = 5; - - // Key is the Key value for the entry that corresponds to - // physical.Entry.Key's value - string key = 6; -} - -// SealKeyInfo contains information regarding the seal used to encrypt the entry. -message SealKeyInfo { - // Mechanism is the method used by the seal to encrypt and sign the - // data as defined by the seal. - uint64 Mechanism = 1; - uint64 HMACMechanism = 2; - - // This is an opaque ID used by the seal to identify the specific - // key to use as defined by the seal. This could be a version, key - // label, or something else. - string KeyID = 3; - string HMACKeyID = 4; - - // These value are used when generating our own data encryption keys - // and encrypting them using the autoseal - bytes WrappedKey = 5; - - // Mechanism specific flags - uint64 Flags = 6; -} diff --git a/vendor/github.com/hashicorp/vault/plugins/database/mysql/mysql.go b/vendor/github.com/hashicorp/vault/plugins/database/mysql/mysql.go deleted file mode 100644 index a36f1a86..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/database/mysql/mysql.go +++ /dev/null @@ -1,317 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - "errors" - "strings" - "time" - - stdmysql "github.com/go-sql-driver/mysql" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/plugins" - "github.com/hashicorp/vault/plugins/helper/database/connutil" - "github.com/hashicorp/vault/plugins/helper/database/credsutil" - "github.com/hashicorp/vault/plugins/helper/database/dbutil" -) - -const ( - defaultMysqlRevocationStmts = ` - REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%'; - DROP USER '{{name}}'@'%' - ` - - defaultMySQLRotateRootCredentialsSQL = ` - ALTER USER '{{username}}'@'%' IDENTIFIED BY '{{password}}'; - ` - - mySQLTypeName = "mysql" -) - -var ( - MetadataLen int = 10 - LegacyMetadataLen int = 4 - UsernameLen int = 32 - LegacyUsernameLen int = 16 -) - -var _ dbplugin.Database = &MySQL{} - -type MySQL struct { - *connutil.SQLConnectionProducer - credsutil.CredentialsProducer -} - -// New implements builtinplugins.BuiltinFactory -func New(displayNameLen, roleNameLen, usernameLen int) func() (interface{}, error) { - return func() (interface{}, error) { - db := new(displayNameLen, roleNameLen, usernameLen) - // Wrap the plugin with middleware to sanitize errors - dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.SecretValues) - - return dbType, nil - } -} - -func new(displayNameLen, roleNameLen, usernameLen int) *MySQL { - connProducer := &connutil.SQLConnectionProducer{} - connProducer.Type = mySQLTypeName - - credsProducer := &credsutil.SQLCredentialsProducer{ - DisplayNameLen: displayNameLen, - RoleNameLen: roleNameLen, - UsernameLen: usernameLen, - Separator: "-", - } - - return &MySQL{ - SQLConnectionProducer: connProducer, - CredentialsProducer: credsProducer, - } -} - -// Run instantiates a MySQL object, and runs the RPC server for the plugin -func Run(apiTLSConfig *api.TLSConfig) error { - return runCommon(false, apiTLSConfig) -} - -// Run instantiates a MySQL object, and runs the RPC server for the plugin -func RunLegacy(apiTLSConfig *api.TLSConfig) error { - return runCommon(true, apiTLSConfig) -} - -func runCommon(legacy bool, apiTLSConfig *api.TLSConfig) error { - var f func() (interface{}, error) - if legacy { - f = New(credsutil.NoneLength, LegacyMetadataLen, LegacyUsernameLen) - } else { - f = New(MetadataLen, MetadataLen, UsernameLen) - } - dbType, err := f() - if err != nil { - return err - } - - plugins.Serve(dbType.(dbplugin.Database), apiTLSConfig) - - return nil -} - -func (m *MySQL) Type() (string, error) { - return mySQLTypeName, nil -} - -func (m *MySQL) getConnection(ctx context.Context) (*sql.DB, error) { - db, err := m.Connection(ctx) - if err != nil { - return nil, err - } - - return db.(*sql.DB), nil -} - -func (m *MySQL) CreateUser(ctx context.Context, statements dbplugin.Statements, usernameConfig dbplugin.UsernameConfig, expiration time.Time) (username string, password string, err error) { - // Grab the lock - m.Lock() - defer m.Unlock() - - statements = dbutil.StatementCompatibilityHelper(statements) - - // Get the connection - db, err := m.getConnection(ctx) - if err != nil { - return "", "", err - } - - if len(statements.Creation) == 0 { - return "", "", dbutil.ErrEmptyCreationStatement - } - - username, err = m.GenerateUsername(usernameConfig) - if err != nil { - return "", "", err - } - - password, err = m.GeneratePassword() - if err != nil { - return "", "", err - } - - expirationStr, err := m.GenerateExpiration(expiration) - if err != nil { - return "", "", err - } - - // Start a transaction - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return "", "", err - } - defer tx.Rollback() - - // Execute each query - for _, stmt := range statements.Creation { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - query = dbutil.QueryHelper(query, map[string]string{ - "name": username, - "password": password, - "expiration": expirationStr, - }) - - stmt, err := tx.PrepareContext(ctx, query) - if err != nil { - // If the error code we get back is Error 1295: This command is not - // supported in the prepared statement protocol yet, we will execute - // the statement without preparing it. This allows the caller to - // manually prepare statements, as well as run other not yet - // prepare supported commands. If there is no error when running we - // will continue to the next statement. - if e, ok := err.(*stdmysql.MySQLError); ok && e.Number == 1295 { - _, err = tx.ExecContext(ctx, query) - if err != nil { - return "", "", err - } - continue - } - - return "", "", err - } - if _, err := stmt.ExecContext(ctx); err != nil { - stmt.Close() - return "", "", err - } - stmt.Close() - } - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return "", "", err - } - - return username, password, nil -} - -// NOOP -func (m *MySQL) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error { - return nil -} - -func (m *MySQL) RevokeUser(ctx context.Context, statements dbplugin.Statements, username string) error { - // Grab the read lock - m.Lock() - defer m.Unlock() - - statements = dbutil.StatementCompatibilityHelper(statements) - - // Get the connection - db, err := m.getConnection(ctx) - if err != nil { - return err - } - - revocationStmts := statements.Revocation - // Use a default SQL statement for revocation if one cannot be fetched from the role - if len(revocationStmts) == 0 { - revocationStmts = []string{defaultMysqlRevocationStmts} - } - - // Start a transaction - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer tx.Rollback() - - for _, stmt := range revocationStmts { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - // This is not a prepared statement because not all commands are supported - // 1295: This command is not supported in the prepared statement protocol yet - // Reference https://mariadb.com/kb/en/mariadb/prepare-statement/ - query = strings.Replace(query, "{{name}}", username, -1) - _, err = tx.ExecContext(ctx, query) - if err != nil { - return err - } - } - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return err - } - - return nil -} - -func (m *MySQL) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) { - m.Lock() - defer m.Unlock() - - if len(m.Username) == 0 || len(m.Password) == 0 { - return nil, errors.New("username and password are required to rotate") - } - - rotateStatents := statements - if len(rotateStatents) == 0 { - rotateStatents = []string{defaultMySQLRotateRootCredentialsSQL} - } - - db, err := m.getConnection(ctx) - if err != nil { - return nil, err - } - - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return nil, err - } - defer func() { - tx.Rollback() - }() - - password, err := m.GeneratePassword() - if err != nil { - return nil, err - } - - for _, stmt := range rotateStatents { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "username": m.Username, - "password": password, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - } - - if err := tx.Commit(); err != nil { - return nil, err - } - - if err := db.Close(); err != nil { - return nil, err - } - - m.RawConfig["password"] = password - return m.RawConfig, nil -} diff --git a/vendor/github.com/hashicorp/vault/plugins/database/postgresql/postgresql.go b/vendor/github.com/hashicorp/vault/plugins/database/postgresql/postgresql.go deleted file mode 100644 index 36dd0036..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/database/postgresql/postgresql.go +++ /dev/null @@ -1,427 +0,0 @@ -package postgresql - -import ( - "context" - "database/sql" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/plugins" - "github.com/hashicorp/vault/plugins/helper/database/connutil" - "github.com/hashicorp/vault/plugins/helper/database/credsutil" - "github.com/hashicorp/vault/plugins/helper/database/dbutil" - "github.com/lib/pq" -) - -const ( - postgreSQLTypeName = "postgres" - defaultPostgresRenewSQL = ` -ALTER ROLE "{{name}}" VALID UNTIL '{{expiration}}'; -` - defaultPostgresRotateRootCredentialsSQL = ` -ALTER ROLE "{{username}}" WITH PASSWORD '{{password}}'; -` -) - -var _ dbplugin.Database = &PostgreSQL{} - -// New implements builtinplugins.BuiltinFactory -func New() (interface{}, error) { - db := new() - // Wrap the plugin with middleware to sanitize errors - dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.SecretValues) - return dbType, nil -} - -func new() *PostgreSQL { - connProducer := &connutil.SQLConnectionProducer{} - connProducer.Type = postgreSQLTypeName - - credsProducer := &credsutil.SQLCredentialsProducer{ - DisplayNameLen: 8, - RoleNameLen: 8, - UsernameLen: 63, - Separator: "-", - } - - db := &PostgreSQL{ - SQLConnectionProducer: connProducer, - CredentialsProducer: credsProducer, - } - - return db -} - -// Run instantiates a PostgreSQL object, and runs the RPC server for the plugin -func Run(apiTLSConfig *api.TLSConfig) error { - dbType, err := New() - if err != nil { - return err - } - - plugins.Serve(dbType.(dbplugin.Database), apiTLSConfig) - - return nil -} - -type PostgreSQL struct { - *connutil.SQLConnectionProducer - credsutil.CredentialsProducer -} - -func (p *PostgreSQL) Type() (string, error) { - return postgreSQLTypeName, nil -} - -func (p *PostgreSQL) getConnection(ctx context.Context) (*sql.DB, error) { - db, err := p.Connection(ctx) - if err != nil { - return nil, err - } - - return db.(*sql.DB), nil -} - -func (p *PostgreSQL) CreateUser(ctx context.Context, statements dbplugin.Statements, usernameConfig dbplugin.UsernameConfig, expiration time.Time) (username string, password string, err error) { - statements = dbutil.StatementCompatibilityHelper(statements) - - if len(statements.Creation) == 0 { - return "", "", dbutil.ErrEmptyCreationStatement - } - - // Grab the lock - p.Lock() - defer p.Unlock() - - username, err = p.GenerateUsername(usernameConfig) - if err != nil { - return "", "", err - } - - password, err = p.GeneratePassword() - if err != nil { - return "", "", err - } - - expirationStr, err := p.GenerateExpiration(expiration) - if err != nil { - return "", "", err - } - - // Get the connection - db, err := p.getConnection(ctx) - if err != nil { - return "", "", err - } - - // Start a transaction - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return "", "", err - - } - defer func() { - tx.Rollback() - }() - // Return the secret - - // Execute each query - for _, stmt := range statements.Creation { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - "password": password, - "expiration": expirationStr, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return "", "", err - } - } - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return "", "", err - } - - return username, password, nil -} - -func (p *PostgreSQL) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error { - p.Lock() - defer p.Unlock() - - statements = dbutil.StatementCompatibilityHelper(statements) - - renewStmts := statements.Renewal - if len(renewStmts) == 0 { - renewStmts = []string{defaultPostgresRenewSQL} - } - - db, err := p.getConnection(ctx) - if err != nil { - return err - } - - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer func() { - tx.Rollback() - }() - - expirationStr, err := p.GenerateExpiration(expiration) - if err != nil { - return err - } - - for _, stmt := range renewStmts { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - "expiration": expirationStr, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return err - } - } - } - - return tx.Commit() -} - -func (p *PostgreSQL) RevokeUser(ctx context.Context, statements dbplugin.Statements, username string) error { - // Grab the lock - p.Lock() - defer p.Unlock() - - statements = dbutil.StatementCompatibilityHelper(statements) - - if len(statements.Revocation) == 0 { - return p.defaultRevokeUser(ctx, username) - } - - return p.customRevokeUser(ctx, username, statements.Revocation) -} - -func (p *PostgreSQL) customRevokeUser(ctx context.Context, username string, revocationStmts []string) error { - db, err := p.getConnection(ctx) - if err != nil { - return err - } - - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer func() { - tx.Rollback() - }() - - for _, stmt := range revocationStmts { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return err - } - } - } - - return tx.Commit() -} - -func (p *PostgreSQL) defaultRevokeUser(ctx context.Context, username string) error { - db, err := p.getConnection(ctx) - if err != nil { - return err - } - - // Check if the role exists - var exists bool - err = db.QueryRowContext(ctx, "SELECT exists (SELECT rolname FROM pg_roles WHERE rolname=$1);", username).Scan(&exists) - if err != nil && err != sql.ErrNoRows { - return err - } - - if exists == false { - return nil - } - - // Query for permissions; we need to revoke permissions before we can drop - // the role - // This isn't done in a transaction because even if we fail along the way, - // we want to remove as much access as possible - stmt, err := db.PrepareContext(ctx, "SELECT DISTINCT table_schema FROM information_schema.role_column_grants WHERE grantee=$1;") - if err != nil { - return err - } - defer stmt.Close() - - rows, err := stmt.QueryContext(ctx, username) - if err != nil { - return err - } - defer rows.Close() - - const initialNumRevocations = 16 - revocationStmts := make([]string, 0, initialNumRevocations) - for rows.Next() { - var schema string - err = rows.Scan(&schema) - if err != nil { - // keep going; remove as many permissions as possible right now - continue - } - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %s FROM %s;`, - pq.QuoteIdentifier(schema), - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE USAGE ON SCHEMA %s FROM %s;`, - pq.QuoteIdentifier(schema), - pq.QuoteIdentifier(username))) - } - - // for good measure, revoke all privileges and usage on schema public - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM %s;`, - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - "REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM %s;", - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - "REVOKE USAGE ON SCHEMA public FROM %s;", - pq.QuoteIdentifier(username))) - - // get the current database name so we can issue a REVOKE CONNECT for - // this username - var dbname sql.NullString - if err := db.QueryRowContext(ctx, "SELECT current_database();").Scan(&dbname); err != nil { - return err - } - - if dbname.Valid { - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE CONNECT ON DATABASE %s FROM %s;`, - pq.QuoteIdentifier(dbname.String), - pq.QuoteIdentifier(username))) - } - - // again, here, we do not stop on error, as we want to remove as - // many permissions as possible right now - var lastStmtError error - for _, query := range revocationStmts { - if err := dbtxn.ExecuteDBQuery(ctx, db, nil, query); err != nil { - lastStmtError = err - } - } - - // can't drop if not all privileges are revoked - if rows.Err() != nil { - return errwrap.Wrapf("could not generate revocation statements for all rows: {{err}}", rows.Err()) - } - if lastStmtError != nil { - return errwrap.Wrapf("could not perform all revocation statements: {{err}}", lastStmtError) - } - - // Drop this user - stmt, err = db.PrepareContext(ctx, fmt.Sprintf( - `DROP ROLE IF EXISTS %s;`, pq.QuoteIdentifier(username))) - if err != nil { - return err - } - defer stmt.Close() - if _, err := stmt.ExecContext(ctx); err != nil { - return err - } - - return nil -} - -func (p *PostgreSQL) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) { - p.Lock() - defer p.Unlock() - - if len(p.Username) == 0 || len(p.Password) == 0 { - return nil, errors.New("username and password are required to rotate") - } - - rotateStatents := statements - if len(rotateStatents) == 0 { - rotateStatents = []string{defaultPostgresRotateRootCredentialsSQL} - } - - db, err := p.getConnection(ctx) - if err != nil { - return nil, err - } - - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return nil, err - } - defer func() { - tx.Rollback() - }() - - password, err := p.GeneratePassword() - if err != nil { - return nil, err - } - - for _, stmt := range rotateStatents { - for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - m := map[string]string{ - "username": p.Username, - "password": password, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - } - - if err := tx.Commit(); err != nil { - return nil, err - } - - // Close the database connection to ensure no new connections come in - if err := db.Close(); err != nil { - return nil, err - } - - p.RawConfig["password"] = password - return p.RawConfig, nil -} diff --git a/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/connutil.go b/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/connutil.go deleted file mode 100644 index 45f6fa0a..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/connutil.go +++ /dev/null @@ -1,25 +0,0 @@ -package connutil - -import ( - "context" - "errors" - "sync" -) - -var ( - ErrNotInitialized = errors.New("connection has not been initalized") -) - -// ConnectionProducer can be used as an embeded interface in the Database -// definition. It implements the methods dealing with individual database -// connections and is used in all the builtin database types. -type ConnectionProducer interface { - Close() error - Init(context.Context, map[string]interface{}, bool) (map[string]interface{}, error) - Connection(context.Context) (interface{}, error) - - sync.Locker - - // DEPRECATED, will be removed in 0.12 - Initialize(context.Context, map[string]interface{}, bool) error -} diff --git a/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/sql.go b/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/sql.go deleted file mode 100644 index 38685d0b..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/helper/database/connutil/sql.go +++ /dev/null @@ -1,164 +0,0 @@ -package connutil - -import ( - "context" - "database/sql" - "fmt" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/plugins/helper/database/dbutil" - "github.com/mitchellh/mapstructure" -) - -var _ ConnectionProducer = &SQLConnectionProducer{} - -// SQLConnectionProducer implements ConnectionProducer and provides a generic producer for most sql databases -type SQLConnectionProducer struct { - ConnectionURL string `json:"connection_url" mapstructure:"connection_url" structs:"connection_url"` - MaxOpenConnections int `json:"max_open_connections" mapstructure:"max_open_connections" structs:"max_open_connections"` - MaxIdleConnections int `json:"max_idle_connections" mapstructure:"max_idle_connections" structs:"max_idle_connections"` - MaxConnectionLifetimeRaw interface{} `json:"max_connection_lifetime" mapstructure:"max_connection_lifetime" structs:"max_connection_lifetime"` - Username string `json:"username" mapstructure:"username" structs:"username"` - Password string `json:"password" mapstructure:"password" structs:"password"` - - Type string - RawConfig map[string]interface{} - maxConnectionLifetime time.Duration - Initialized bool - db *sql.DB - sync.Mutex -} - -func (c *SQLConnectionProducer) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error { - _, err := c.Init(ctx, conf, verifyConnection) - return err -} - -func (c *SQLConnectionProducer) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) { - c.Lock() - defer c.Unlock() - - c.RawConfig = conf - - err := mapstructure.WeakDecode(conf, &c) - if err != nil { - return nil, err - } - - if len(c.ConnectionURL) == 0 { - return nil, fmt.Errorf("connection_url cannot be empty") - } - - c.ConnectionURL = dbutil.QueryHelper(c.ConnectionURL, map[string]string{ - "username": c.Username, - "password": c.Password, - }) - - if c.MaxOpenConnections == 0 { - c.MaxOpenConnections = 2 - } - - if c.MaxIdleConnections == 0 { - c.MaxIdleConnections = c.MaxOpenConnections - } - if c.MaxIdleConnections > c.MaxOpenConnections { - c.MaxIdleConnections = c.MaxOpenConnections - } - if c.MaxConnectionLifetimeRaw == nil { - c.MaxConnectionLifetimeRaw = "0s" - } - - c.maxConnectionLifetime, err = parseutil.ParseDurationSecond(c.MaxConnectionLifetimeRaw) - if err != nil { - return nil, errwrap.Wrapf("invalid max_connection_lifetime: {{err}}", err) - } - - // Set initialized to true at this point since all fields are set, - // and the connection can be established at a later time. - c.Initialized = true - - if verifyConnection { - if _, err := c.Connection(ctx); err != nil { - return nil, errwrap.Wrapf("error verifying connection: {{err}}", err) - } - - if err := c.db.PingContext(ctx); err != nil { - return nil, errwrap.Wrapf("error verifying connection: {{err}}", err) - } - } - - return c.RawConfig, nil -} - -func (c *SQLConnectionProducer) Connection(ctx context.Context) (interface{}, error) { - if !c.Initialized { - return nil, ErrNotInitialized - } - - // If we already have a DB, test it and return - if c.db != nil { - if err := c.db.PingContext(ctx); err == nil { - return c.db, nil - } - // If the ping was unsuccessful, close it and ignore errors as we'll be - // reestablishing anyways - c.db.Close() - } - - // For mssql backend, switch to sqlserver instead - dbType := c.Type - if c.Type == "mssql" { - dbType = "sqlserver" - } - - // Otherwise, attempt to make connection - conn := c.ConnectionURL - - // Ensure timezone is set to UTC for all the connections - if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") { - if strings.Contains(conn, "?") { - conn += "&timezone=utc" - } else { - conn += "?timezone=utc" - } - } - - var err error - c.db, err = sql.Open(dbType, conn) - if err != nil { - return nil, err - } - - // Set some connection pool settings. We don't need much of this, - // since the request rate shouldn't be high. - c.db.SetMaxOpenConns(c.MaxOpenConnections) - c.db.SetMaxIdleConns(c.MaxIdleConnections) - c.db.SetConnMaxLifetime(c.maxConnectionLifetime) - - return c.db, nil -} - -func (c *SQLConnectionProducer) SecretValues() map[string]interface{} { - return map[string]interface{}{ - c.Password: "[password]", - } -} - -// Close attempts to close the connection -func (c *SQLConnectionProducer) Close() error { - // Grab the write lock - c.Lock() - defer c.Unlock() - - if c.db != nil { - c.db.Close() - } - - c.db = nil - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/credsutil.go b/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/credsutil.go deleted file mode 100644 index 65046028..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/credsutil.go +++ /dev/null @@ -1,46 +0,0 @@ -package credsutil - -import ( - "time" - - "fmt" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/base62" -) - -// CredentialsProducer can be used as an embeded interface in the Database -// definition. It implements the methods for generating user information for a -// particular database type and is used in all the builtin database types. -type CredentialsProducer interface { - GenerateUsername(usernameConfig dbplugin.UsernameConfig) (string, error) - GeneratePassword() (string, error) - GenerateExpiration(ttl time.Time) (string, error) -} - -const ( - reqStr = `A1a-` - minStrLen = 10 -) - -// RandomAlphaNumeric returns a random string of characters [A-Za-z0-9-] -// of the provided length. The string generated takes up to 4 characters -// of space that are predefined and prepended to ensure password -// character requirements. It also requires a min length of 10 characters. -func RandomAlphaNumeric(length int, prependA1a bool) (string, error) { - if length < minStrLen { - return "", fmt.Errorf("minimum length of %d is required", minStrLen) - } - - var prefix string - if prependA1a { - prefix = reqStr - } - - randomStr, err := base62.Random(length-len(prefix), true) - if err != nil { - return "", err - } - - return prefix + randomStr, nil -} diff --git a/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/sql.go b/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/sql.go deleted file mode 100644 index 2f9cc7d1..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/helper/database/credsutil/sql.go +++ /dev/null @@ -1,72 +0,0 @@ -package credsutil - -import ( - "fmt" - "time" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" -) - -const ( - NoneLength int = -1 -) - -// SQLCredentialsProducer implements CredentialsProducer and provides a generic credentials producer for most sql database types. -type SQLCredentialsProducer struct { - DisplayNameLen int - RoleNameLen int - UsernameLen int - Separator string -} - -func (scp *SQLCredentialsProducer) GenerateUsername(config dbplugin.UsernameConfig) (string, error) { - username := "v" - - displayName := config.DisplayName - if scp.DisplayNameLen > 0 && len(displayName) > scp.DisplayNameLen { - displayName = displayName[:scp.DisplayNameLen] - } else if scp.DisplayNameLen == NoneLength { - displayName = "" - } - - if len(displayName) > 0 { - username = fmt.Sprintf("%s%s%s", username, scp.Separator, displayName) - } - - roleName := config.RoleName - if scp.RoleNameLen > 0 && len(roleName) > scp.RoleNameLen { - roleName = roleName[:scp.RoleNameLen] - } else if scp.RoleNameLen == NoneLength { - roleName = "" - } - - if len(roleName) > 0 { - username = fmt.Sprintf("%s%s%s", username, scp.Separator, roleName) - } - - userUUID, err := RandomAlphaNumeric(20, false) - if err != nil { - return "", err - } - - username = fmt.Sprintf("%s%s%s", username, scp.Separator, userUUID) - username = fmt.Sprintf("%s%s%s", username, scp.Separator, fmt.Sprint(time.Now().Unix())) - if scp.UsernameLen > 0 && len(username) > scp.UsernameLen { - username = username[:scp.UsernameLen] - } - - return username, nil -} - -func (scp *SQLCredentialsProducer) GeneratePassword() (string, error) { - password, err := RandomAlphaNumeric(20, true) - if err != nil { - return "", err - } - - return password, nil -} - -func (scp *SQLCredentialsProducer) GenerateExpiration(ttl time.Time) (string, error) { - return ttl.Format("2006-01-02 15:04:05-0700"), nil -} diff --git a/vendor/github.com/hashicorp/vault/plugins/helper/database/dbutil/dbutil.go b/vendor/github.com/hashicorp/vault/plugins/helper/database/dbutil/dbutil.go deleted file mode 100644 index 42257053..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/helper/database/dbutil/dbutil.go +++ /dev/null @@ -1,52 +0,0 @@ -package dbutil - -import ( - "errors" - "fmt" - "strings" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" -) - -var ( - ErrEmptyCreationStatement = errors.New("empty creation statements") -) - -// Query templates a query for us. -func QueryHelper(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} - -// StatementCompatibilityHelper will populate the statements fields to support -// compatibility -func StatementCompatibilityHelper(statements dbplugin.Statements) dbplugin.Statements { - switch { - case len(statements.Creation) > 0 && len(statements.CreationStatements) == 0: - statements.CreationStatements = strings.Join(statements.Creation, ";") - case len(statements.CreationStatements) > 0: - statements.Creation = []string{statements.CreationStatements} - } - switch { - case len(statements.Revocation) > 0 && len(statements.RevocationStatements) == 0: - statements.RevocationStatements = strings.Join(statements.Revocation, ";") - case len(statements.RevocationStatements) > 0: - statements.Revocation = []string{statements.RevocationStatements} - } - switch { - case len(statements.Renewal) > 0 && len(statements.RenewStatements) == 0: - statements.RenewStatements = strings.Join(statements.Renewal, ";") - case len(statements.RenewStatements) > 0: - statements.Renewal = []string{statements.RenewStatements} - } - switch { - case len(statements.Rollback) > 0 && len(statements.RollbackStatements) == 0: - statements.RollbackStatements = strings.Join(statements.Rollback, ";") - case len(statements.RollbackStatements) > 0: - statements.Rollback = []string{statements.RollbackStatements} - } - return statements -} diff --git a/vendor/github.com/hashicorp/vault/plugins/serve.go b/vendor/github.com/hashicorp/vault/plugins/serve.go deleted file mode 100644 index 0bc3bc4e..00000000 --- a/vendor/github.com/hashicorp/vault/plugins/serve.go +++ /dev/null @@ -1,31 +0,0 @@ -package plugins - -import ( - "fmt" - - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/pluginutil" -) - -// Serve is used to start a plugin's RPC server. It takes an interface that must -// implement a known plugin interface to vault and an optional api.TLSConfig for -// use during the inital unwrap request to vault. The api config is particularly -// useful when vault is setup to require client cert checking. -func Serve(plugin interface{}, tlsConfig *api.TLSConfig) { - tlsProvider := pluginutil.VaultPluginTLSProvider(tlsConfig) - - err := pluginutil.OptionallyEnableMlock() - if err != nil { - fmt.Println(err) - return - } - - switch p := plugin.(type) { - case dbplugin.Database: - dbplugin.Serve(p, tlsProvider) - default: - fmt.Println("Unsupported plugin type") - } - -} diff --git a/vendor/github.com/hashicorp/vault/shamir/shamir.go b/vendor/github.com/hashicorp/vault/shamir/shamir.go deleted file mode 100644 index 04650868..00000000 --- a/vendor/github.com/hashicorp/vault/shamir/shamir.go +++ /dev/null @@ -1,262 +0,0 @@ -package shamir - -import ( - "crypto/rand" - "crypto/subtle" - "fmt" - mathrand "math/rand" - "time" - - "github.com/hashicorp/errwrap" -) - -const ( - // ShareOverhead is the byte size overhead of each share - // when using Split on a secret. This is caused by appending - // a one byte tag to the share. - ShareOverhead = 1 -) - -// polynomial represents a polynomial of arbitrary degree -type polynomial struct { - coefficients []uint8 -} - -// makePolynomial constructs a random polynomial of the given -// degree but with the provided intercept value. -func makePolynomial(intercept, degree uint8) (polynomial, error) { - // Create a wrapper - p := polynomial{ - coefficients: make([]byte, degree+1), - } - - // Ensure the intercept is set - p.coefficients[0] = intercept - - // Assign random co-efficients to the polynomial - if _, err := rand.Read(p.coefficients[1:]); err != nil { - return p, err - } - - return p, nil -} - -// evaluate returns the value of the polynomial for the given x -func (p *polynomial) evaluate(x uint8) uint8 { - // Special case the origin - if x == 0 { - return p.coefficients[0] - } - - // Compute the polynomial value using Horner's method. - degree := len(p.coefficients) - 1 - out := p.coefficients[degree] - for i := degree - 1; i >= 0; i-- { - coeff := p.coefficients[i] - out = add(mult(out, x), coeff) - } - return out -} - -// interpolatePolynomial takes N sample points and returns -// the value at a given x using a lagrange interpolation. -func interpolatePolynomial(x_samples, y_samples []uint8, x uint8) uint8 { - limit := len(x_samples) - var result, basis uint8 - for i := 0; i < limit; i++ { - basis = 1 - for j := 0; j < limit; j++ { - if i == j { - continue - } - num := add(x, x_samples[j]) - denom := add(x_samples[i], x_samples[j]) - term := div(num, denom) - basis = mult(basis, term) - } - group := mult(y_samples[i], basis) - result = add(result, group) - } - return result -} - -// div divides two numbers in GF(2^8) -func div(a, b uint8) uint8 { - if b == 0 { - // leaks some timing information but we don't care anyways as this - // should never happen, hence the panic - panic("divide by zero") - } - - var goodVal, zero uint8 - log_a := logTable[a] - log_b := logTable[b] - diff := (int(log_a) - int(log_b)) % 255 - if diff < 0 { - diff += 255 - } - - ret := expTable[diff] - - // Ensure we return zero if a is zero but aren't subject to timing attacks - goodVal = ret - - if subtle.ConstantTimeByteEq(a, 0) == 1 { - ret = zero - } else { - ret = goodVal - } - - return ret -} - -// mult multiplies two numbers in GF(2^8) -func mult(a, b uint8) (out uint8) { - var goodVal, zero uint8 - log_a := logTable[a] - log_b := logTable[b] - sum := (int(log_a) + int(log_b)) % 255 - - ret := expTable[sum] - - // Ensure we return zero if either a or be are zero but aren't subject to - // timing attacks - goodVal = ret - - if subtle.ConstantTimeByteEq(a, 0) == 1 { - ret = zero - } else { - ret = goodVal - } - - if subtle.ConstantTimeByteEq(b, 0) == 1 { - ret = zero - } else { - // This operation does not do anything logically useful. It - // only ensures a constant number of assignments to thwart - // timing attacks. - goodVal = zero - } - - return ret -} - -// add combines two numbers in GF(2^8) -// This can also be used for subtraction since it is symmetric. -func add(a, b uint8) uint8 { - return a ^ b -} - -// Split takes an arbitrarily long secret and generates a `parts` -// number of shares, `threshold` of which are required to reconstruct -// the secret. The parts and threshold must be at least 2, and less -// than 256. The returned shares are each one byte longer than the secret -// as they attach a tag used to reconstruct the secret. -func Split(secret []byte, parts, threshold int) ([][]byte, error) { - // Sanity check the input - if parts < threshold { - return nil, fmt.Errorf("parts cannot be less than threshold") - } - if parts > 255 { - return nil, fmt.Errorf("parts cannot exceed 255") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold must be at least 2") - } - if threshold > 255 { - return nil, fmt.Errorf("threshold cannot exceed 255") - } - if len(secret) == 0 { - return nil, fmt.Errorf("cannot split an empty secret") - } - - // Generate random list of x coordinates - mathrand.Seed(time.Now().UnixNano()) - xCoordinates := mathrand.Perm(255) - - // Allocate the output array, initialize the final byte - // of the output with the offset. The representation of each - // output is {y1, y2, .., yN, x}. - out := make([][]byte, parts) - for idx := range out { - out[idx] = make([]byte, len(secret)+1) - out[idx][len(secret)] = uint8(xCoordinates[idx]) + 1 - } - - // Construct a random polynomial for each byte of the secret. - // Because we are using a field of size 256, we can only represent - // a single byte as the intercept of the polynomial, so we must - // use a new polynomial for each byte. - for idx, val := range secret { - p, err := makePolynomial(val, uint8(threshold-1)) - if err != nil { - return nil, errwrap.Wrapf("failed to generate polynomial: {{err}}", err) - } - - // Generate a `parts` number of (x,y) pairs - // We cheat by encoding the x value once as the final index, - // so that it only needs to be stored once. - for i := 0; i < parts; i++ { - x := uint8(xCoordinates[i]) + 1 - y := p.evaluate(x) - out[i][idx] = y - } - } - - // Return the encoded secrets - return out, nil -} - -// Combine is used to reverse a Split and reconstruct a secret -// once a `threshold` number of parts are available. -func Combine(parts [][]byte) ([]byte, error) { - // Verify enough parts provided - if len(parts) < 2 { - return nil, fmt.Errorf("less than two parts cannot be used to reconstruct the secret") - } - - // Verify the parts are all the same length - firstPartLen := len(parts[0]) - if firstPartLen < 2 { - return nil, fmt.Errorf("parts must be at least two bytes") - } - for i := 1; i < len(parts); i++ { - if len(parts[i]) != firstPartLen { - return nil, fmt.Errorf("all parts must be the same length") - } - } - - // Create a buffer to store the reconstructed secret - secret := make([]byte, firstPartLen-1) - - // Buffer to store the samples - x_samples := make([]uint8, len(parts)) - y_samples := make([]uint8, len(parts)) - - // Set the x value for each sample and ensure no x_sample values are the same, - // otherwise div() can be unhappy - checkMap := map[byte]bool{} - for i, part := range parts { - samp := part[firstPartLen-1] - if exists := checkMap[samp]; exists { - return nil, fmt.Errorf("duplicate part detected") - } - checkMap[samp] = true - x_samples[i] = samp - } - - // Reconstruct each byte - for idx := range secret { - // Set the y value for each sample - for i, part := range parts { - y_samples[i] = part[idx] - } - - // Interpolate the polynomial and compute the value at 0 - val := interpolatePolynomial(x_samples, y_samples, 0) - - // Evaluate the 0th value to get the intercept - secret[idx] = val - } - return secret, nil -} diff --git a/vendor/github.com/hashicorp/vault/shamir/tables.go b/vendor/github.com/hashicorp/vault/shamir/tables.go deleted file mode 100644 index 76c245e7..00000000 --- a/vendor/github.com/hashicorp/vault/shamir/tables.go +++ /dev/null @@ -1,77 +0,0 @@ -package shamir - -// Tables taken from http://www.samiam.org/galois.html -// They use 0xe5 (229) as the generator - -var ( - // logTable provides the log(X)/log(g) at each index X - logTable = [256]uint8{ - 0x00, 0xff, 0xc8, 0x08, 0x91, 0x10, 0xd0, 0x36, - 0x5a, 0x3e, 0xd8, 0x43, 0x99, 0x77, 0xfe, 0x18, - 0x23, 0x20, 0x07, 0x70, 0xa1, 0x6c, 0x0c, 0x7f, - 0x62, 0x8b, 0x40, 0x46, 0xc7, 0x4b, 0xe0, 0x0e, - 0xeb, 0x16, 0xe8, 0xad, 0xcf, 0xcd, 0x39, 0x53, - 0x6a, 0x27, 0x35, 0x93, 0xd4, 0x4e, 0x48, 0xc3, - 0x2b, 0x79, 0x54, 0x28, 0x09, 0x78, 0x0f, 0x21, - 0x90, 0x87, 0x14, 0x2a, 0xa9, 0x9c, 0xd6, 0x74, - 0xb4, 0x7c, 0xde, 0xed, 0xb1, 0x86, 0x76, 0xa4, - 0x98, 0xe2, 0x96, 0x8f, 0x02, 0x32, 0x1c, 0xc1, - 0x33, 0xee, 0xef, 0x81, 0xfd, 0x30, 0x5c, 0x13, - 0x9d, 0x29, 0x17, 0xc4, 0x11, 0x44, 0x8c, 0x80, - 0xf3, 0x73, 0x42, 0x1e, 0x1d, 0xb5, 0xf0, 0x12, - 0xd1, 0x5b, 0x41, 0xa2, 0xd7, 0x2c, 0xe9, 0xd5, - 0x59, 0xcb, 0x50, 0xa8, 0xdc, 0xfc, 0xf2, 0x56, - 0x72, 0xa6, 0x65, 0x2f, 0x9f, 0x9b, 0x3d, 0xba, - 0x7d, 0xc2, 0x45, 0x82, 0xa7, 0x57, 0xb6, 0xa3, - 0x7a, 0x75, 0x4f, 0xae, 0x3f, 0x37, 0x6d, 0x47, - 0x61, 0xbe, 0xab, 0xd3, 0x5f, 0xb0, 0x58, 0xaf, - 0xca, 0x5e, 0xfa, 0x85, 0xe4, 0x4d, 0x8a, 0x05, - 0xfb, 0x60, 0xb7, 0x7b, 0xb8, 0x26, 0x4a, 0x67, - 0xc6, 0x1a, 0xf8, 0x69, 0x25, 0xb3, 0xdb, 0xbd, - 0x66, 0xdd, 0xf1, 0xd2, 0xdf, 0x03, 0x8d, 0x34, - 0xd9, 0x92, 0x0d, 0x63, 0x55, 0xaa, 0x49, 0xec, - 0xbc, 0x95, 0x3c, 0x84, 0x0b, 0xf5, 0xe6, 0xe7, - 0xe5, 0xac, 0x7e, 0x6e, 0xb9, 0xf9, 0xda, 0x8e, - 0x9a, 0xc9, 0x24, 0xe1, 0x0a, 0x15, 0x6b, 0x3a, - 0xa0, 0x51, 0xf4, 0xea, 0xb2, 0x97, 0x9e, 0x5d, - 0x22, 0x88, 0x94, 0xce, 0x19, 0x01, 0x71, 0x4c, - 0xa5, 0xe3, 0xc5, 0x31, 0xbb, 0xcc, 0x1f, 0x2d, - 0x3b, 0x52, 0x6f, 0xf6, 0x2e, 0x89, 0xf7, 0xc0, - 0x68, 0x1b, 0x64, 0x04, 0x06, 0xbf, 0x83, 0x38} - - // expTable provides the anti-log or exponentiation value - // for the equivalent index - expTable = [256]uint8{ - 0x01, 0xe5, 0x4c, 0xb5, 0xfb, 0x9f, 0xfc, 0x12, - 0x03, 0x34, 0xd4, 0xc4, 0x16, 0xba, 0x1f, 0x36, - 0x05, 0x5c, 0x67, 0x57, 0x3a, 0xd5, 0x21, 0x5a, - 0x0f, 0xe4, 0xa9, 0xf9, 0x4e, 0x64, 0x63, 0xee, - 0x11, 0x37, 0xe0, 0x10, 0xd2, 0xac, 0xa5, 0x29, - 0x33, 0x59, 0x3b, 0x30, 0x6d, 0xef, 0xf4, 0x7b, - 0x55, 0xeb, 0x4d, 0x50, 0xb7, 0x2a, 0x07, 0x8d, - 0xff, 0x26, 0xd7, 0xf0, 0xc2, 0x7e, 0x09, 0x8c, - 0x1a, 0x6a, 0x62, 0x0b, 0x5d, 0x82, 0x1b, 0x8f, - 0x2e, 0xbe, 0xa6, 0x1d, 0xe7, 0x9d, 0x2d, 0x8a, - 0x72, 0xd9, 0xf1, 0x27, 0x32, 0xbc, 0x77, 0x85, - 0x96, 0x70, 0x08, 0x69, 0x56, 0xdf, 0x99, 0x94, - 0xa1, 0x90, 0x18, 0xbb, 0xfa, 0x7a, 0xb0, 0xa7, - 0xf8, 0xab, 0x28, 0xd6, 0x15, 0x8e, 0xcb, 0xf2, - 0x13, 0xe6, 0x78, 0x61, 0x3f, 0x89, 0x46, 0x0d, - 0x35, 0x31, 0x88, 0xa3, 0x41, 0x80, 0xca, 0x17, - 0x5f, 0x53, 0x83, 0xfe, 0xc3, 0x9b, 0x45, 0x39, - 0xe1, 0xf5, 0x9e, 0x19, 0x5e, 0xb6, 0xcf, 0x4b, - 0x38, 0x04, 0xb9, 0x2b, 0xe2, 0xc1, 0x4a, 0xdd, - 0x48, 0x0c, 0xd0, 0x7d, 0x3d, 0x58, 0xde, 0x7c, - 0xd8, 0x14, 0x6b, 0x87, 0x47, 0xe8, 0x79, 0x84, - 0x73, 0x3c, 0xbd, 0x92, 0xc9, 0x23, 0x8b, 0x97, - 0x95, 0x44, 0xdc, 0xad, 0x40, 0x65, 0x86, 0xa2, - 0xa4, 0xcc, 0x7f, 0xec, 0xc0, 0xaf, 0x91, 0xfd, - 0xf7, 0x4f, 0x81, 0x2f, 0x5b, 0xea, 0xa8, 0x1c, - 0x02, 0xd1, 0x98, 0x71, 0xed, 0x25, 0xe3, 0x24, - 0x06, 0x68, 0xb3, 0x93, 0x2c, 0x6f, 0x3e, 0x6c, - 0x0a, 0xb8, 0xce, 0xae, 0x74, 0xb1, 0x42, 0xb4, - 0x1e, 0xd3, 0x49, 0xe9, 0x9c, 0xc8, 0xc6, 0xc7, - 0x22, 0x6e, 0xdb, 0x20, 0xbf, 0x43, 0x51, 0x52, - 0x66, 0xb2, 0x76, 0x60, 0xda, 0xc5, 0xf3, 0xf6, - 0xaa, 0xcd, 0x9a, 0xa0, 0x75, 0x54, 0x0e, 0x01} -) diff --git a/vendor/github.com/hashicorp/vault/vault/acl.go b/vendor/github.com/hashicorp/vault/vault/acl.go deleted file mode 100644 index e16cf1ae..00000000 --- a/vendor/github.com/hashicorp/vault/vault/acl.go +++ /dev/null @@ -1,523 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "reflect" - "strings" - - radix "github.com/armon/go-radix" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -// ACL is used to wrap a set of policies to provide -// an efficient interface for access control. -type ACL struct { - // exactRules contains the path policies that are exact - exactRules *radix.Tree - - // globRules contains the path policies that glob - globRules *radix.Tree - - // root is enabled if the "root" named policy is present. - root bool - - // Stores policies that are actually RGPs for later fetching - rgpPolicies []*Policy -} - -type PolicyCheckOpts struct { - RootPrivsRequired bool - Unauth bool -} - -type AuthResults struct { - ACLResults *ACLResults - Allowed bool - RootPrivs bool - DeniedError bool - Error *multierror.Error -} - -type ACLResults struct { - Allowed bool - RootPrivs bool - IsRoot bool - MFAMethods []string - ControlGroup *ControlGroup - CapabilitiesBitmap uint32 -} - -// NewACL is used to construct a policy based ACL from a set of policies. -func NewACL(ctx context.Context, policies []*Policy) (*ACL, error) { - // Initialize - a := &ACL{ - exactRules: radix.New(), - globRules: radix.New(), - root: false, - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns == nil { - return nil, namespace.ErrNoNamespace - } - - // Inject each policy - for _, policy := range policies { - // Ignore a nil policy object - if policy == nil { - continue - } - - switch policy.Type { - case PolicyTypeACL: - case PolicyTypeRGP: - a.rgpPolicies = append(a.rgpPolicies, policy) - continue - default: - return nil, fmt.Errorf("unable to parse policy (wrong type)") - } - - // Check if this is root - if policy.Name == "root" { - if ns.ID != namespace.RootNamespaceID { - return nil, fmt.Errorf("root policy is only allowed in root namespace") - } - - if len(policies) != 1 { - return nil, fmt.Errorf("other policies present along with root") - } - a.root = true - } - - for _, pc := range policy.Paths { - // Check which tree to use - tree := a.exactRules - if pc.Glob { - tree = a.globRules - } - - // Check for an existing policy - raw, ok := tree.Get(pc.Prefix) - if !ok { - clonedPerms, err := pc.Permissions.Clone() - if err != nil { - return nil, errwrap.Wrapf("error cloning ACL permissions: {{err}}", err) - } - tree.Insert(pc.Prefix, clonedPerms) - continue - } - - // these are the ones already in the tree - existingPerms := raw.(*ACLPermissions) - - switch { - case existingPerms.CapabilitiesBitmap&DenyCapabilityInt > 0: - // If we are explicitly denied in the existing capability set, - // don't save anything else - continue - - case pc.Permissions.CapabilitiesBitmap&DenyCapabilityInt > 0: - // If this new policy explicitly denies, only save the deny value - existingPerms.CapabilitiesBitmap = DenyCapabilityInt - existingPerms.AllowedParameters = nil - existingPerms.DeniedParameters = nil - goto INSERT - - default: - // Insert the capabilities in this new policy into the existing - // value - existingPerms.CapabilitiesBitmap = existingPerms.CapabilitiesBitmap | pc.Permissions.CapabilitiesBitmap - } - - // Note: In these stanzas, we're preferring minimum lifetimes. So - // we take the lesser of two specified max values, or we take the - // lesser of two specified min values, the idea being, allowing - // token lifetime to be minimum possible. - // - // If we have an existing max, and we either don't have a current - // max, or the current is greater than the previous, use the - // existing. - if pc.Permissions.MaxWrappingTTL > 0 && - (existingPerms.MaxWrappingTTL == 0 || - pc.Permissions.MaxWrappingTTL < existingPerms.MaxWrappingTTL) { - existingPerms.MaxWrappingTTL = pc.Permissions.MaxWrappingTTL - } - // If we have an existing min, and we either don't have a current - // min, or the current is greater than the previous, use the - // existing - if pc.Permissions.MinWrappingTTL > 0 && - (existingPerms.MinWrappingTTL == 0 || - pc.Permissions.MinWrappingTTL < existingPerms.MinWrappingTTL) { - existingPerms.MinWrappingTTL = pc.Permissions.MinWrappingTTL - } - - if len(pc.Permissions.AllowedParameters) > 0 { - if existingPerms.AllowedParameters == nil { - clonedAllowed, err := copystructure.Copy(pc.Permissions.AllowedParameters) - if err != nil { - return nil, err - } - existingPerms.AllowedParameters = clonedAllowed.(map[string][]interface{}) - } else { - for key, value := range pc.Permissions.AllowedParameters { - pcValue, ok := existingPerms.AllowedParameters[key] - // If an empty array exist it should overwrite any other - // value. - if len(value) == 0 || (ok && len(pcValue) == 0) { - existingPerms.AllowedParameters[key] = []interface{}{} - } else { - // Merge the two maps, appending values on key conflict. - existingPerms.AllowedParameters[key] = append(value, existingPerms.AllowedParameters[key]...) - } - } - } - } - - if len(pc.Permissions.DeniedParameters) > 0 { - if existingPerms.DeniedParameters == nil { - clonedDenied, err := copystructure.Copy(pc.Permissions.DeniedParameters) - if err != nil { - return nil, err - } - existingPerms.DeniedParameters = clonedDenied.(map[string][]interface{}) - } else { - for key, value := range pc.Permissions.DeniedParameters { - pcValue, ok := existingPerms.DeniedParameters[key] - // If an empty array exist it should overwrite any other - // value. - if len(value) == 0 || (ok && len(pcValue) == 0) { - existingPerms.DeniedParameters[key] = []interface{}{} - } else { - // Merge the two maps, appending values on key conflict. - existingPerms.DeniedParameters[key] = append(value, existingPerms.DeniedParameters[key]...) - } - } - } - } - - if len(pc.Permissions.RequiredParameters) > 0 { - if len(existingPerms.RequiredParameters) == 0 { - existingPerms.RequiredParameters = pc.Permissions.RequiredParameters - } else { - for _, v := range pc.Permissions.RequiredParameters { - if !strutil.StrListContains(existingPerms.RequiredParameters, v) { - existingPerms.RequiredParameters = append(existingPerms.RequiredParameters, v) - } - } - } - } - - if len(pc.Permissions.MFAMethods) > 0 { - if existingPerms.MFAMethods == nil { - existingPerms.MFAMethods = pc.Permissions.MFAMethods - } else { - for _, method := range pc.Permissions.MFAMethods { - existingPerms.MFAMethods = append(existingPerms.MFAMethods, method) - } - } - existingPerms.MFAMethods = strutil.RemoveDuplicates(existingPerms.MFAMethods, false) - } - - // No need to dedupe this list since any authorization can satisfy any factor - if pc.Permissions.ControlGroup != nil { - if len(pc.Permissions.ControlGroup.Factors) > 0 { - if existingPerms.ControlGroup == nil { - existingPerms.ControlGroup = pc.Permissions.ControlGroup - } else { - for _, authz := range pc.Permissions.ControlGroup.Factors { - existingPerms.ControlGroup.Factors = append(existingPerms.ControlGroup.Factors, authz) - } - } - } - } - - INSERT: - tree.Insert(pc.Prefix, existingPerms) - } - } - return a, nil -} - -func (a *ACL) Capabilities(ctx context.Context, path string) (pathCapabilities []string) { - req := &logical.Request{ - Path: path, - // doesn't matter, but use List to trigger fallback behavior so we can - // model real behavior - Operation: logical.ListOperation, - } - - res := a.AllowOperation(ctx, req, true) - if res.IsRoot { - return []string{RootCapability} - } - - capabilities := res.CapabilitiesBitmap - - if capabilities&SudoCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, SudoCapability) - } - if capabilities&ReadCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, ReadCapability) - } - if capabilities&ListCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, ListCapability) - } - if capabilities&UpdateCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, UpdateCapability) - } - if capabilities&DeleteCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, DeleteCapability) - } - if capabilities&CreateCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, CreateCapability) - } - - // If "deny" is explicitly set or if the path has no capabilities at all, - // set the path capabilities to "deny" - if capabilities&DenyCapabilityInt > 0 || len(pathCapabilities) == 0 { - pathCapabilities = []string{DenyCapability} - } - return -} - -// AllowOperation is used to check if the given operation is permitted. -func (a *ACL) AllowOperation(ctx context.Context, req *logical.Request, capCheckOnly bool) (ret *ACLResults) { - ret = new(ACLResults) - - // Fast-path root - if a.root { - ret.Allowed = true - ret.RootPrivs = true - ret.IsRoot = true - return - } - op := req.Operation - - // Help is always allowed - if op == logical.HelpOperation { - ret.Allowed = true - return - } - - var permissions *ACLPermissions - - ns, err := namespace.FromContext(ctx) - if err != nil { - return - } - path := ns.Path + req.Path - - // Find an exact matching rule, look for glob if no match - var capabilities uint32 - raw, ok := a.exactRules.Get(path) - if ok { - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - goto CHECK - } - if op == logical.ListOperation { - raw, ok = a.exactRules.Get(strings.TrimSuffix(path, "/")) - if ok { - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - goto CHECK - } - } - - // Find a glob rule, default deny if no match - _, raw, ok = a.globRules.LongestPrefix(path) - if !ok { - return - } - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - -CHECK: - // Check if the minimum permissions are met - // If "deny" has been explicitly set, only deny will be in the map, so we - // only need to check for the existence of other values - ret.RootPrivs = capabilities&SudoCapabilityInt > 0 - - // This is after the RootPrivs check so we can gate on it being from sudo - // rather than policy root - if capCheckOnly { - ret.CapabilitiesBitmap = capabilities - return ret - } - - ret.MFAMethods = permissions.MFAMethods - ret.ControlGroup = permissions.ControlGroup - - operationAllowed := false - switch op { - case logical.ReadOperation: - operationAllowed = capabilities&ReadCapabilityInt > 0 - case logical.ListOperation: - operationAllowed = capabilities&ListCapabilityInt > 0 - case logical.UpdateOperation: - operationAllowed = capabilities&UpdateCapabilityInt > 0 - case logical.DeleteOperation: - operationAllowed = capabilities&DeleteCapabilityInt > 0 - case logical.CreateOperation: - operationAllowed = capabilities&CreateCapabilityInt > 0 - - // These three re-use UpdateCapabilityInt since that's the most appropriate - // capability/operation mapping - case logical.RevokeOperation, logical.RenewOperation, logical.RollbackOperation: - operationAllowed = capabilities&UpdateCapabilityInt > 0 - - default: - return - } - - if !operationAllowed { - return - } - - if permissions.MaxWrappingTTL > 0 { - if req.WrapInfo == nil || req.WrapInfo.TTL > permissions.MaxWrappingTTL { - return - } - } - if permissions.MinWrappingTTL > 0 { - if req.WrapInfo == nil || req.WrapInfo.TTL < permissions.MinWrappingTTL { - return - } - } - // This situation can happen because of merging, even though in a single - // path statement we check on ingress - if permissions.MinWrappingTTL != 0 && - permissions.MaxWrappingTTL != 0 && - permissions.MaxWrappingTTL < permissions.MinWrappingTTL { - return - } - - // Only check parameter permissions for operations that can modify - // parameters. - if op == logical.ReadOperation || op == logical.UpdateOperation || op == logical.CreateOperation { - for _, parameter := range permissions.RequiredParameters { - if _, ok := req.Data[strings.ToLower(parameter)]; !ok { - return - } - } - - // If there are no data fields, allow - if len(req.Data) == 0 { - ret.Allowed = true - return - } - - if len(permissions.DeniedParameters) == 0 { - goto ALLOWED_PARAMETERS - } - - // Check if all parameters have been denied - if _, ok := permissions.DeniedParameters["*"]; ok { - return - } - - for parameter, value := range req.Data { - // Check if parameter has been explicitly denied - if valueSlice, ok := permissions.DeniedParameters[strings.ToLower(parameter)]; ok { - // If the value exists in denied values slice, deny - if valueInParameterList(value, valueSlice) { - return - } - } - } - - ALLOWED_PARAMETERS: - // If we don't have any allowed parameters set, allow - if len(permissions.AllowedParameters) == 0 { - ret.Allowed = true - return - } - - _, allowedAll := permissions.AllowedParameters["*"] - if len(permissions.AllowedParameters) == 1 && allowedAll { - ret.Allowed = true - return - } - - for parameter, value := range req.Data { - valueSlice, ok := permissions.AllowedParameters[strings.ToLower(parameter)] - // Requested parameter is not in allowed list - if !ok && !allowedAll { - return - } - - // If the value doesn't exists in the allowed values slice, - // deny - if ok && !valueInParameterList(value, valueSlice) { - return - } - } - } - - ret.Allowed = true - return -} - -func (c *Core) performPolicyChecks(ctx context.Context, acl *ACL, te *logical.TokenEntry, req *logical.Request, inEntity *identity.Entity, opts *PolicyCheckOpts) *AuthResults { - ret := new(AuthResults) - - // First, perform normal ACL checks if requested. The only time no ACL - // should be applied is if we are only processing EGPs against a login - // path in which case opts.Unauth will be set. - if acl != nil && !opts.Unauth { - ret.ACLResults = acl.AllowOperation(ctx, req, false) - ret.RootPrivs = ret.ACLResults.RootPrivs - // Root is always allowed; skip Sentinel/MFA checks - if ret.ACLResults.IsRoot { - //logger.Warn("token is root, skipping checks") - ret.Allowed = true - return ret - } - if !ret.ACLResults.Allowed { - return ret - } - if !ret.RootPrivs && opts.RootPrivsRequired { - return ret - } - } - - c.performEntPolicyChecks(ctx, acl, te, req, inEntity, opts, ret) - - return ret -} - -func valueInParameterList(v interface{}, list []interface{}) bool { - // Empty list is equivalent to the item always existing in the list - if len(list) == 0 { - return true - } - - return valueInSlice(v, list) -} - -func valueInSlice(v interface{}, list []interface{}) bool { - for _, el := range list { - if reflect.TypeOf(el).String() == "string" && reflect.TypeOf(v).String() == "string" { - item := el.(string) - val := v.(string) - - if strutil.GlobbedStringsMatch(item, val) { - return true - } - } else if reflect.DeepEqual(el, v) { - return true - } - } - - return false -} diff --git a/vendor/github.com/hashicorp/vault/vault/acl_util.go b/vendor/github.com/hashicorp/vault/vault/acl_util.go deleted file mode 100644 index ade4c724..00000000 --- a/vendor/github.com/hashicorp/vault/vault/acl_util.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/logical" -) - -func (c *Core) performEntPolicyChecks(ctx context.Context, acl *ACL, te *logical.TokenEntry, req *logical.Request, inEntity *identity.Entity, opts *PolicyCheckOpts, ret *AuthResults) { - ret.Allowed = true -} diff --git a/vendor/github.com/hashicorp/vault/vault/audit.go b/vendor/github.com/hashicorp/vault/vault/audit.go deleted file mode 100644 index cc4c8d8d..00000000 --- a/vendor/github.com/hashicorp/vault/vault/audit.go +++ /dev/null @@ -1,502 +0,0 @@ -package vault - -import ( - "context" - "crypto/sha256" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -const ( - // coreAuditConfigPath is used to store the audit configuration. - // Audit configuration is protected within the Vault itself, which means it - // can only be viewed or modified after an unseal. - coreAuditConfigPath = "core/audit" - - // coreLocalAuditConfigPath is used to store audit information for local - // (non-replicated) mounts - coreLocalAuditConfigPath = "core/local-audit" - - // auditBarrierPrefix is the prefix to the UUID used in the - // barrier view for the audit backends. - auditBarrierPrefix = "audit/" - - // auditTableType is the value we expect to find for the audit table and - // corresponding entries - auditTableType = "audit" -) - -var ( - // loadAuditFailed if loading audit tables encounters an error - errLoadAuditFailed = errors.New("failed to setup audit table") -) - -// enableAudit is used to enable a new audit backend -func (c *Core) enableAudit(ctx context.Context, entry *MountEntry, updateStorage bool) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Ensure there is a name - if entry.Path == "/" { - return fmt.Errorf("backend path must be specified") - } - - // Update the audit table - c.auditLock.Lock() - defer c.auditLock.Unlock() - - // Look for matching name - for _, ent := range c.audit.Entries { - switch { - // Existing is sql/mysql/ new is sql/ or - // existing is sql/ and new is sql/mysql/ - case strings.HasPrefix(ent.Path, entry.Path): - fallthrough - case strings.HasPrefix(entry.Path, ent.Path): - return fmt.Errorf("path already in use") - } - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("audit_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - viewPath := entry.ViewPath() - view := NewBarrierView(c.barrier, viewPath) - addAuditPathChecker(c, entry, view, viewPath) - origViewReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - defer view.setReadOnlyErr(origViewReadOnlyErr) - - // Lookup the new backend - backend, err := c.newAuditBackend(ctx, entry, view, entry.Options) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil audit backend of type %q returned from factory", entry.Type) - } - - newTable := c.audit.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - entry.NamespaceID = ns.ID - entry.namespace = ns - - if updateStorage { - if err := c.persistAudit(ctx, newTable, entry.Local); err != nil { - return errors.New("failed to update audit table") - } - } - - c.audit = newTable - - // Register the backend - c.auditBroker.Register(entry.Path, backend, view, entry.Local) - if c.logger.IsInfo() { - c.logger.Info("enabled audit backend", "path", entry.Path, "type", entry.Type) - } - - return nil -} - -// disableAudit is used to disable an existing audit backend -func (c *Core) disableAudit(ctx context.Context, path string, updateStorage bool) (bool, error) { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Remove the entry from the mount table - c.auditLock.Lock() - defer c.auditLock.Unlock() - - newTable := c.audit.shallowClone() - entry, err := newTable.remove(ctx, path) - if err != nil { - return false, err - } - - // Ensure there was a match - if entry == nil { - return false, fmt.Errorf("no matching backend") - } - - c.removeAuditReloadFunc(entry) - - // When unmounting all entries the JSON code will load back up from storage - // as a nil slice, which kills tests...just set it nil explicitly - if len(newTable.Entries) == 0 { - newTable.Entries = nil - } - - if updateStorage { - // Update the audit table - if err := c.persistAudit(ctx, newTable, entry.Local); err != nil { - return true, errors.New("failed to update audit table") - } - } - - c.audit = newTable - - // Unmount the backend - c.auditBroker.Deregister(path) - if c.logger.IsInfo() { - c.logger.Info("disabled audit backend", "path", path) - } - - removeAuditPathChecker(c, entry) - - return true, nil -} - -// loadAudits is invoked as part of postUnseal to load the audit table -func (c *Core) loadAudits(ctx context.Context) error { - auditTable := &MountTable{} - localAuditTable := &MountTable{} - - // Load the existing audit table - raw, err := c.barrier.Get(ctx, coreAuditConfigPath) - if err != nil { - c.logger.Error("failed to read audit table", "error", err) - return errLoadAuditFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalAuditConfigPath) - if err != nil { - c.logger.Error("failed to read local audit table", "error", err) - return errLoadAuditFailed - } - - c.auditLock.Lock() - defer c.auditLock.Unlock() - - if raw != nil { - if err := jsonutil.DecodeJSON(raw.Value, auditTable); err != nil { - c.logger.Error("failed to decode audit table", "error", err) - return errLoadAuditFailed - } - c.audit = auditTable - } - - var needPersist bool - if c.audit == nil { - c.audit = defaultAuditTable() - needPersist = true - } - - if rawLocal != nil { - if err := jsonutil.DecodeJSON(rawLocal.Value, localAuditTable); err != nil { - c.logger.Error("failed to decode local audit table", "error", err) - return errLoadAuditFailed - } - if localAuditTable != nil && len(localAuditTable.Entries) > 0 { - c.audit.Entries = append(c.audit.Entries, localAuditTable.Entries...) - } - } - - // Upgrade to typed auth table - if c.audit.Type == "" { - c.audit.Type = auditTableType - needPersist = true - } - - // Upgrade to table-scoped entries - for _, entry := range c.audit.Entries { - if entry.Table == "" { - entry.Table = c.audit.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("audit_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - - if entry.NamespaceID == "" { - entry.NamespaceID = namespace.RootNamespaceID - needPersist = true - } - // Get the namespace from the namespace ID and load it in memory - ns, err := NamespaceByID(ctx, entry.NamespaceID, c) - if err != nil { - return err - } - if ns == nil { - return namespace.ErrNoNamespace - } - entry.namespace = ns - } - - if !needPersist || c.perfStandby { - return nil - } - - if err := c.persistAudit(ctx, c.audit, false); err != nil { - return errLoadAuditFailed - } - return nil -} - -// persistAudit is used to persist the audit table after modification -func (c *Core) persistAudit(ctx context.Context, table *MountTable, localOnly bool) error { - if table.Type != auditTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", auditTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in audit table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid audit entry found, not persisting") - } - } - - nonLocalAudit := &MountTable{ - Type: auditTableType, - } - - localAudit := &MountTable{ - Type: auditTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localAudit.Entries = append(localAudit.Entries, entry) - } else { - nonLocalAudit.Entries = append(nonLocalAudit.Entries, entry) - } - } - - if !localOnly { - // Marshal the table - compressedBytes, err := jsonutil.EncodeJSONAndCompress(nonLocalAudit, nil) - if err != nil { - c.logger.Error("failed to encode and/or compress audit table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: coreAuditConfigPath, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist audit table", "error", err) - return err - } - } - - // Repeat with local audit - compressedBytes, err := jsonutil.EncodeJSONAndCompress(localAudit, nil) - if err != nil { - c.logger.Error("failed to encode and/or compress local audit table", "error", err) - return err - } - - entry := &Entry{ - Key: coreLocalAuditConfigPath, - Value: compressedBytes, - } - - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist local audit table", "error", err) - return err - } - - return nil -} - -// setupAudit is invoked after we've loaded the audit able to -// initialize the audit backends -func (c *Core) setupAudits(ctx context.Context) error { - brokerLogger := c.baseLogger.Named("audit") - c.AddLogger(brokerLogger) - broker := NewAuditBroker(brokerLogger) - - c.auditLock.Lock() - defer c.auditLock.Unlock() - - var successCount int - - for _, entry := range c.audit.Entries { - // Create a barrier view using the UUID - viewPath := entry.ViewPath() - view := NewBarrierView(c.barrier, viewPath) - addAuditPathChecker(c, entry, view, viewPath) - origViewReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(origViewReadOnlyErr) - }) - - // Initialize the backend - backend, err := c.newAuditBackend(ctx, entry, view, entry.Options) - if err != nil { - c.logger.Error("failed to create audit entry", "path", entry.Path, "error", err) - continue - } - if backend == nil { - c.logger.Error("created audit entry was nil", "path", entry.Path, "type", entry.Type) - continue - } - - // Mount the backend - broker.Register(entry.Path, backend, view, entry.Local) - - successCount++ - } - - if len(c.audit.Entries) > 0 && successCount == 0 { - return errLoadAuditFailed - } - - c.auditBroker = broker - return nil -} - -// teardownAudit is used before we seal the vault to reset the audit -// backends to their unloaded state. This is reversed by loadAudits. -func (c *Core) teardownAudits() error { - c.auditLock.Lock() - defer c.auditLock.Unlock() - - if c.audit != nil { - for _, entry := range c.audit.Entries { - c.removeAuditReloadFunc(entry) - removeAuditPathChecker(c, entry) - } - } - - c.audit = nil - c.auditBroker = nil - return nil -} - -// removeAuditReloadFunc removes the reload func from the working set. The -// audit lock needs to be held before calling this. -func (c *Core) removeAuditReloadFunc(entry *MountEntry) { - switch entry.Type { - case "file": - key := "audit_file|" + entry.Path - c.reloadFuncsLock.Lock() - - if c.logger.IsDebug() { - c.baseLogger.Named("audit").Debug("removing reload function", "path", entry.Path) - } - - delete(c.reloadFuncs, key) - - c.reloadFuncsLock.Unlock() - } -} - -// newAuditBackend is used to create and configure a new audit backend by name -func (c *Core) newAuditBackend(ctx context.Context, entry *MountEntry, view logical.Storage, conf map[string]string) (audit.Backend, error) { - f, ok := c.auditBackends[entry.Type] - if !ok { - return nil, fmt.Errorf("unknown backend type: %q", entry.Type) - } - saltConfig := &salt.Config{ - HMAC: sha256.New, - HMACType: "hmac-sha256", - Location: salt.DefaultLocation, - } - - be, err := f(ctx, &audit.BackendConfig{ - SaltView: view, - SaltConfig: saltConfig, - Config: conf, - }) - if err != nil { - return nil, err - } - if be == nil { - return nil, fmt.Errorf("nil backend returned from %q factory function", entry.Type) - } - - auditLogger := c.baseLogger.Named("audit") - c.AddLogger(auditLogger) - - switch entry.Type { - case "file": - key := "audit_file|" + entry.Path - - c.reloadFuncsLock.Lock() - - if auditLogger.IsDebug() { - auditLogger.Debug("adding reload function", "path", entry.Path) - if entry.Options != nil { - auditLogger.Debug("file backend options", "path", entry.Path, "file_path", entry.Options["file_path"]) - } - } - - c.reloadFuncs[key] = append(c.reloadFuncs[key], func(map[string]interface{}) error { - if auditLogger.IsInfo() { - auditLogger.Info("reloading file audit backend", "path", entry.Path) - } - return be.Reload(ctx) - }) - - c.reloadFuncsLock.Unlock() - case "socket": - if auditLogger.IsDebug() { - if entry.Options != nil { - auditLogger.Debug("socket backend options", "path", entry.Path, "address", entry.Options["address"], "socket type", entry.Options["socket_type"]) - } - } - case "syslog": - if auditLogger.IsDebug() { - if entry.Options != nil { - auditLogger.Debug("syslog backend options", "path", entry.Path, "facility", entry.Options["facility"], "tag", entry.Options["tag"]) - } - } - } - - return be, err -} - -// defaultAuditTable creates a default audit table -func defaultAuditTable() *MountTable { - table := &MountTable{ - Type: auditTableType, - } - return table -} diff --git a/vendor/github.com/hashicorp/vault/vault/audit_broker.go b/vendor/github.com/hashicorp/vault/vault/audit_broker.go deleted file mode 100644 index c5b56527..00000000 --- a/vendor/github.com/hashicorp/vault/vault/audit_broker.go +++ /dev/null @@ -1,213 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "sync" - "time" - - metrics "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/audit" -) - -type backendEntry struct { - backend audit.Backend - view *BarrierView - local bool -} - -// AuditBroker is used to provide a single ingest interface to auditable -// events given that multiple backends may be configured. -type AuditBroker struct { - sync.RWMutex - backends map[string]backendEntry - logger log.Logger -} - -// NewAuditBroker creates a new audit broker -func NewAuditBroker(log log.Logger) *AuditBroker { - b := &AuditBroker{ - backends: make(map[string]backendEntry), - logger: log, - } - return b -} - -// Register is used to add new audit backend to the broker -func (a *AuditBroker) Register(name string, b audit.Backend, v *BarrierView, local bool) { - a.Lock() - defer a.Unlock() - a.backends[name] = backendEntry{ - backend: b, - view: v, - local: local, - } -} - -// Deregister is used to remove an audit backend from the broker -func (a *AuditBroker) Deregister(name string) { - a.Lock() - defer a.Unlock() - delete(a.backends, name) -} - -// IsRegistered is used to check if a given audit backend is registered -func (a *AuditBroker) IsRegistered(name string) bool { - a.RLock() - defer a.RUnlock() - _, ok := a.backends[name] - return ok -} - -// IsLocal is used to check if a given audit backend is registered -func (a *AuditBroker) IsLocal(name string) (bool, error) { - a.RLock() - defer a.RUnlock() - be, ok := a.backends[name] - if ok { - return be.local, nil - } - return false, fmt.Errorf("unknown audit backend %q", name) -} - -// GetHash returns a hash using the salt of the given backend -func (a *AuditBroker) GetHash(ctx context.Context, name string, input string) (string, error) { - a.RLock() - defer a.RUnlock() - be, ok := a.backends[name] - if !ok { - return "", fmt.Errorf("unknown audit backend %q", name) - } - - return be.backend.GetHash(ctx, input) -} - -// LogRequest is used to ensure all the audit backends have an opportunity to -// log the given request and that *at least one* succeeds. -func (a *AuditBroker) LogRequest(ctx context.Context, in *audit.LogInput, headersConfig *AuditedHeadersConfig) (ret error) { - defer metrics.MeasureSince([]string{"audit", "log_request"}, time.Now()) - a.RLock() - defer a.RUnlock() - - var retErr *multierror.Error - - defer func() { - if r := recover(); r != nil { - a.logger.Error("panic during logging", "request_path", in.Request.Path, "error", r) - retErr = multierror.Append(retErr, fmt.Errorf("panic generating audit log")) - } - - ret = retErr.ErrorOrNil() - failure := float32(0.0) - if ret != nil { - failure = 1.0 - } - metrics.IncrCounter([]string{"audit", "log_request_failure"}, failure) - }() - - // All logged requests must have an identifier - //if req.ID == "" { - // a.logger.Error("missing identifier in request object", "request_path", req.Path) - // retErr = multierror.Append(retErr, fmt.Errorf("missing identifier in request object: %s", req.Path)) - // return - //} - - headers := in.Request.Headers - defer func() { - in.Request.Headers = headers - }() - - // Ensure at least one backend logs - anyLogged := false - for name, be := range a.backends { - in.Request.Headers = nil - transHeaders, thErr := headersConfig.ApplyConfig(ctx, headers, be.backend.GetHash) - if thErr != nil { - a.logger.Error("backend failed to include headers", "backend", name, "error", thErr) - continue - } - in.Request.Headers = transHeaders - - start := time.Now() - lrErr := be.backend.LogRequest(ctx, in) - metrics.MeasureSince([]string{"audit", name, "log_request"}, start) - if lrErr != nil { - a.logger.Error("backend failed to log request", "backend", name, "error", lrErr) - } else { - anyLogged = true - } - } - if !anyLogged && len(a.backends) > 0 { - retErr = multierror.Append(retErr, fmt.Errorf("no audit backend succeeded in logging the request")) - } - - return retErr.ErrorOrNil() -} - -// LogResponse is used to ensure all the audit backends have an opportunity to -// log the given response and that *at least one* succeeds. -func (a *AuditBroker) LogResponse(ctx context.Context, in *audit.LogInput, headersConfig *AuditedHeadersConfig) (ret error) { - defer metrics.MeasureSince([]string{"audit", "log_response"}, time.Now()) - a.RLock() - defer a.RUnlock() - - var retErr *multierror.Error - - defer func() { - if r := recover(); r != nil { - a.logger.Error("panic during logging", "request_path", in.Request.Path, "error", r) - retErr = multierror.Append(retErr, fmt.Errorf("panic generating audit log")) - } - - ret = retErr.ErrorOrNil() - - failure := float32(0.0) - if ret != nil { - failure = 1.0 - } - metrics.IncrCounter([]string{"audit", "log_response_failure"}, failure) - }() - - headers := in.Request.Headers - defer func() { - in.Request.Headers = headers - }() - - // Ensure at least one backend logs - anyLogged := false - for name, be := range a.backends { - in.Request.Headers = nil - transHeaders, thErr := headersConfig.ApplyConfig(ctx, headers, be.backend.GetHash) - if thErr != nil { - a.logger.Error("backend failed to include headers", "backend", name, "error", thErr) - continue - } - in.Request.Headers = transHeaders - - start := time.Now() - lrErr := be.backend.LogResponse(ctx, in) - metrics.MeasureSince([]string{"audit", name, "log_response"}, start) - if lrErr != nil { - a.logger.Error("backend failed to log response", "backend", name, "error", lrErr) - } else { - anyLogged = true - } - } - if !anyLogged && len(a.backends) > 0 { - retErr = multierror.Append(retErr, fmt.Errorf("no audit backend succeeded in logging the response")) - } - - return retErr.ErrorOrNil() -} - -func (a *AuditBroker) Invalidate(ctx context.Context, key string) { - // For now we ignore the key as this would only apply to salts. We just - // sort of brute force it on each one. - a.Lock() - defer a.Unlock() - for _, be := range a.backends { - be.backend.Invalidate(ctx) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/audited_headers.go b/vendor/github.com/hashicorp/vault/vault/audited_headers.go deleted file mode 100644 index ca8383ea..00000000 --- a/vendor/github.com/hashicorp/vault/vault/audited_headers.go +++ /dev/null @@ -1,162 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" -) - -// N.B.: While we could use textproto to get the canonical mime header, HTTP/2 -// requires all headers to be converted to lower case, so we just do that. - -const ( - // Key used in the BarrierView to store and retrieve the header config - auditedHeadersEntry = "audited-headers" - // Path used to create a sub view off of BarrierView - auditedHeadersSubPath = "audited-headers-config/" -) - -type auditedHeaderSettings struct { - HMAC bool `json:"hmac"` -} - -// AuditedHeadersConfig is used by the Audit Broker to write only approved -// headers to the audit logs. It uses a BarrierView to persist the settings. -type AuditedHeadersConfig struct { - Headers map[string]*auditedHeaderSettings - - view *BarrierView - sync.RWMutex -} - -// add adds or overwrites a header in the config and updates the barrier view -func (a *AuditedHeadersConfig) add(ctx context.Context, header string, hmac bool) error { - if header == "" { - return fmt.Errorf("header value cannot be empty") - } - - // Grab a write lock - a.Lock() - defer a.Unlock() - - if a.Headers == nil { - a.Headers = make(map[string]*auditedHeaderSettings, 1) - } - - a.Headers[strings.ToLower(header)] = &auditedHeaderSettings{hmac} - entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) - if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - return nil -} - -// remove deletes a header out of the header config and updates the barrier view -func (a *AuditedHeadersConfig) remove(ctx context.Context, header string) error { - if header == "" { - return fmt.Errorf("header value cannot be empty") - } - - // Grab a write lock - a.Lock() - defer a.Unlock() - - // Nothing to delete - if len(a.Headers) == 0 { - return nil - } - - delete(a.Headers, strings.ToLower(header)) - entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) - if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - return nil -} - -// ApplyConfig returns a map of approved headers and their values, either -// hmac'ed or plaintext -func (a *AuditedHeadersConfig) ApplyConfig(ctx context.Context, headers map[string][]string, hashFunc func(context.Context, string) (string, error)) (result map[string][]string, retErr error) { - // Grab a read lock - a.RLock() - defer a.RUnlock() - - // Make a copy of the incoming headers with everything lower so we can - // case-insensitively compare - lowerHeaders := make(map[string][]string, len(headers)) - for k, v := range headers { - lowerHeaders[strings.ToLower(k)] = v - } - - result = make(map[string][]string, len(a.Headers)) - for key, settings := range a.Headers { - if val, ok := lowerHeaders[key]; ok { - // copy the header values so we don't overwrite them - hVals := make([]string, len(val)) - copy(hVals, val) - - // Optionally hmac the values - if settings.HMAC { - for i, el := range hVals { - hVal, err := hashFunc(ctx, el) - if err != nil { - return nil, err - } - hVals[i] = hVal - } - } - - result[key] = hVals - } - } - - return result, nil -} - -// Initialize the headers config by loading from the barrier view -func (c *Core) setupAuditedHeadersConfig(ctx context.Context) error { - // Create a sub-view - view := c.systemBarrierView.SubView(auditedHeadersSubPath) - - // Create the config - out, err := view.Get(ctx, auditedHeadersEntry) - if err != nil { - return errwrap.Wrapf("failed to read config: {{err}}", err) - } - - headers := make(map[string]*auditedHeaderSettings) - if out != nil { - err = out.DecodeJSON(&headers) - if err != nil { - return err - } - } - - // Ensure that we are able to case-sensitively access the headers; - // necessary for the upgrade case - lowerHeaders := make(map[string]*auditedHeaderSettings, len(headers)) - for k, v := range headers { - lowerHeaders[strings.ToLower(k)] = v - } - - c.auditedHeaders = &AuditedHeadersConfig{ - Headers: lowerHeaders, - view: view, - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/auth.go b/vendor/github.com/hashicorp/vault/vault/auth.go deleted file mode 100644 index 3a3f8014..00000000 --- a/vendor/github.com/hashicorp/vault/vault/auth.go +++ /dev/null @@ -1,776 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/builtin/plugin" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - // coreAuthConfigPath is used to store the auth configuration. - // Auth configuration is protected within the Vault itself, which means it - // can only be viewed or modified after an unseal. - coreAuthConfigPath = "core/auth" - - // coreLocalAuthConfigPath is used to store credential configuration for - // local (non-replicated) mounts - coreLocalAuthConfigPath = "core/local-auth" - - // credentialBarrierPrefix is the prefix to the UUID used in the - // barrier view for the credential backends. - credentialBarrierPrefix = "auth/" - - // credentialRoutePrefix is the mount prefix used for the router - credentialRoutePrefix = "auth/" - - // credentialTableType is the value we expect to find for the credential - // table and corresponding entries - credentialTableType = "auth" -) - -var ( - // errLoadAuthFailed if loadCredentials encounters an error - errLoadAuthFailed = errors.New("failed to setup auth table") - - // credentialAliases maps old backend names to new backend names, allowing us - // to move/rename backends but maintain backwards compatibility - credentialAliases = map[string]string{"aws-ec2": "aws"} -) - -// enableCredential is used to enable a new credential backend -func (c *Core) enableCredential(ctx context.Context, entry *MountEntry) error { - return c.enableCredentialInternal(ctx, entry, MountTableUpdateStorage) -} - -// enableCredential is used to enable a new credential backend -func (c *Core) enableCredentialInternal(ctx context.Context, entry *MountEntry, updateStorage bool) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Ensure there is a name - if entry.Path == "/" { - return fmt.Errorf("backend path must be specified") - } - - c.authLock.Lock() - defer c.authLock.Unlock() - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - entry.NamespaceID = ns.ID - entry.namespace = ns - - // Populate cache - NamespaceByID(ctx, ns.ID, c) - - // Look for matching name - for _, ent := range c.auth.Entries { - if ns.ID == ent.NamespaceID { - switch { - // Existing is oauth/github/ new is oauth/ or - // existing is oauth/ and new is oauth/github/ - case strings.HasPrefix(ent.Path, entry.Path): - fallthrough - case strings.HasPrefix(entry.Path, ent.Path): - return logical.CodedError(409, "path is already in use") - } - } - } - - // Ensure the token backend is a singleton - if entry.Type == "token" { - return fmt.Errorf("token credential backend cannot be instantiated") - } - - if conflict := c.router.MountConflict(ctx, credentialRoutePrefix+entry.Path); conflict != "" { - return logical.CodedError(409, fmt.Sprintf("existing mount at %s", conflict)) - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("auth_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - // Sync values to the cache - entry.SyncCache() - - viewPath := entry.ViewPath() - view := NewBarrierView(c.barrier, viewPath) - - nilMount, err := preprocessMount(c, entry, view) - if err != nil { - return err - } - origViewReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - defer view.setReadOnlyErr(origViewReadOnlyErr) - - var backend logical.Backend - // Create the new backend - sysView := c.mountEntrySysView(entry) - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend returned from %q factory", entry.Type) - } - - // Check for the correct backend type - backendType := backend.Type() - if backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount %q of type %q as an auth backend", entry.Type, backendType) - } - - addPathCheckers(c, entry, backend, viewPath) - - // If the mount is filtered or we are on a DR secondary we don't want to - // keep the actual backend running, so we clean it up and set it to nil - // so the router does not have a pointer to the object. - if nilMount { - backend.Cleanup(ctx) - backend = nil - } - - // Update the auth table - newTable := c.auth.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - if updateStorage { - if err := c.persistAuth(ctx, newTable, &entry.Local); err != nil { - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - return errors.New("failed to update auth table") - } - } - - c.auth = newTable - - if err := c.router.Mount(backend, credentialRoutePrefix+entry.Path, entry, view); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("enabled credential backend", "path", entry.Path, "type", entry.Type) - } - return nil -} - -// disableCredential is used to disable an existing credential backend; the -// boolean indicates if it existed -func (c *Core) disableCredential(ctx context.Context, path string) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Ensure the token backend is not affected - if path == "token/" { - return fmt.Errorf("token credential backend cannot be disabled") - } - - return c.disableCredentialInternal(ctx, path, MountTableUpdateStorage) -} - -func (c *Core) disableCredentialInternal(ctx context.Context, path string, updateStorage bool) error { - path = credentialRoutePrefix + path - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - // Verify exact match of the route - match := c.router.MatchingMount(ctx, path) - if match == "" || ns.Path+path != match { - return fmt.Errorf("no matching mount") - } - - // Store the view for this backend - view := c.router.MatchingStorageByAPIPath(ctx, path) - if view == nil { - return fmt.Errorf("no matching backend %q", path) - } - - // Get the backend/mount entry for this path, used to remove ignored - // replication prefixes - backend := c.router.MatchingBackend(ctx, path) - entry := c.router.MatchingMountEntry(ctx, path) - - // Mark the entry as tainted - if err := c.taintCredEntry(ctx, path, updateStorage); err != nil { - return err - } - - // Taint the router path to prevent routing - if err := c.router.Taint(ctx, path); err != nil { - return err - } - - if c.expiration != nil && backend != nil { - // Revoke credentials from this path - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - revokeCtx := namespace.ContextWithNamespace(c.activeContext, ns) - if err := c.expiration.RevokePrefix(revokeCtx, path, true); err != nil { - return err - } - } - - if backend != nil { - // Call cleanup function if it exists - backend.Cleanup(ctx) - } - - // Unmount the backend - if err := c.router.Unmount(ctx, path); err != nil { - return err - } - - viewPath := entry.ViewPath() - switch { - case !updateStorage: - case c.IsDRSecondary(), entry.Local, !c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - // Have writable storage, remove the whole thing - if err := logical.ClearView(ctx, view); err != nil { - c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path) - return err - } - - case !entry.Local && c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - if err := clearIgnoredPaths(ctx, c, backend, viewPath); err != nil { - return err - } - } - - // Remove the mount table entry - if err := c.removeCredEntry(ctx, strings.TrimPrefix(path, credentialRoutePrefix), updateStorage); err != nil { - return err - } - - removePathCheckers(c, entry, viewPath) - - if c.logger.IsInfo() { - c.logger.Info("disabled credential backend", "path", path) - } - - return nil -} - -// removeCredEntry is used to remove an entry in the auth table -func (c *Core) removeCredEntry(ctx context.Context, path string, updateStorage bool) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - // Taint the entry from the auth table - newTable := c.auth.shallowClone() - entry, err := newTable.remove(ctx, path) - if err != nil { - return err - } - if entry == nil { - c.logger.Error("nil entry found removing entry in auth table", "path", path) - return logical.CodedError(500, "failed to remove entry in auth table") - } - - if updateStorage { - // Update the auth table - if err := c.persistAuth(ctx, newTable, &entry.Local); err != nil { - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - - return errors.New("failed to update auth table") - } - } - - c.auth = newTable - - return nil -} - -// remountCredEntryForce takes a copy of the mount entry for the path and fully -// unmounts and remounts the backend to pick up any changes, such as filtered -// paths -func (c *Core) remountCredEntryForce(ctx context.Context, path string) error { - fullPath := credentialRoutePrefix + path - me := c.router.MatchingMountEntry(ctx, fullPath) - if me == nil { - return fmt.Errorf("cannot find mount for path %q", path) - } - - me, err := me.Clone() - if err != nil { - return err - } - - if err := c.disableCredential(ctx, path); err != nil { - return err - } - return c.enableCredential(ctx, me) -} - -// taintCredEntry is used to mark an entry in the auth table as tainted -func (c *Core) taintCredEntry(ctx context.Context, path string, updateStorage bool) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - // Taint the entry from the auth table - // We do this on the original since setting the taint operates - // on the entries which a shallow clone shares anyways - entry, err := c.auth.setTaint(ctx, strings.TrimPrefix(path, credentialRoutePrefix), true) - if err != nil { - return err - } - - // Ensure there was a match - if entry == nil { - return fmt.Errorf("no matching backend") - } - - if updateStorage { - // Update the auth table - if err := c.persistAuth(ctx, c.auth, &entry.Local); err != nil { - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - return errors.New("failed to update auth table") - } - } - - return nil -} - -// loadCredentials is invoked as part of postUnseal to load the auth table -func (c *Core) loadCredentials(ctx context.Context) error { - // Load the existing mount table - raw, err := c.barrier.Get(ctx, coreAuthConfigPath) - if err != nil { - c.logger.Error("failed to read auth table", "error", err) - return errLoadAuthFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalAuthConfigPath) - if err != nil { - c.logger.Error("failed to read local auth table", "error", err) - return errLoadAuthFailed - } - - c.authLock.Lock() - defer c.authLock.Unlock() - - if raw != nil { - authTable, err := c.decodeMountTable(ctx, raw.Value) - if err != nil { - c.logger.Error("failed to decompress and/or decode the auth table", "error", err) - return err - } - c.auth = authTable - } - - var needPersist bool - if c.auth == nil { - c.auth = c.defaultAuthTable() - needPersist = true - } - - if rawLocal != nil { - localAuthTable, err := c.decodeMountTable(ctx, rawLocal.Value) - if err != nil { - c.logger.Error("failed to decompress and/or decode the local mount table", "error", err) - return err - } - if localAuthTable != nil && len(localAuthTable.Entries) > 0 { - c.auth.Entries = append(c.auth.Entries, localAuthTable.Entries...) - } - } - - // Upgrade to typed auth table - if c.auth.Type == "" { - c.auth.Type = credentialTableType - needPersist = true - } - - // Upgrade to table-scoped entries - for _, entry := range c.auth.Entries { - if entry.Table == "" { - entry.Table = c.auth.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("auth_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - needPersist = true - } - - if entry.NamespaceID == "" { - entry.NamespaceID = namespace.RootNamespaceID - needPersist = true - } - ns, err := NamespaceByID(ctx, entry.NamespaceID, c) - if err != nil { - return err - } - if ns == nil { - return namespace.ErrNoNamespace - } - entry.namespace = ns - - // Sync values to the cache - entry.SyncCache() - } - - if !needPersist { - return nil - } - - if err := c.persistAuth(ctx, c.auth, nil); err != nil { - c.logger.Error("failed to persist auth table", "error", err) - return errLoadAuthFailed - } - - return nil -} - -// persistAuth is used to persist the auth table after modification -func (c *Core) persistAuth(ctx context.Context, table *MountTable, local *bool) error { - if table.Type != credentialTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", credentialTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in auth table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid auth entry found, not persisting") - } - } - - nonLocalAuth := &MountTable{ - Type: credentialTableType, - } - - localAuth := &MountTable{ - Type: credentialTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localAuth.Entries = append(localAuth.Entries, entry) - } else { - nonLocalAuth.Entries = append(nonLocalAuth.Entries, entry) - } - } - - writeTable := func(mt *MountTable, path string) error { - // Encode the mount table into JSON and compress it (lzw). - compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil) - if err != nil { - c.logger.Error("failed to encode or compress auth mount table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: path, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist auth mount table", "error", err) - return err - } - return nil - } - - var err error - switch { - case local == nil: - // Write non-local mounts - err := writeTable(nonLocalAuth, coreAuthConfigPath) - if err != nil { - return err - } - - // Write local mounts - err = writeTable(localAuth, coreLocalAuthConfigPath) - if err != nil { - return err - } - case *local: - err = writeTable(localAuth, coreLocalAuthConfigPath) - default: - err = writeTable(nonLocalAuth, coreAuthConfigPath) - } - - return err -} - -// setupCredentials is invoked after we've loaded the auth table to -// initialize the credential backends and setup the router -func (c *Core) setupCredentials(ctx context.Context) error { - var persistNeeded bool - - c.authLock.Lock() - defer c.authLock.Unlock() - - for _, entry := range c.auth.sortEntriesByPathDepth().Entries { - var backend logical.Backend - - // Create a barrier view using the UUID - viewPath := entry.ViewPath() - - // Singleton mounts cannot be filtered on a per-secondary basis - // from replication - if strutil.StrListContains(singletonMounts, entry.Type) { - addFilterablePath(c, viewPath) - } - - view := NewBarrierView(c.barrier, viewPath) - - // Determining the replicated state of the mount - nilMount, err := preprocessMount(c, entry, view) - if err != nil { - return err - } - origViewReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - if strutil.StrListContains(singletonMounts, entry.Type) { - defer view.setReadOnlyErr(origViewReadOnlyErr) - } else { - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(origViewReadOnlyErr) - }) - } - - // Initialize the backend - sysView := c.mountEntrySysView(entry) - - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - if err != nil { - c.logger.Error("failed to create credential entry", "path", entry.Path, "error", err) - if !c.builtinRegistry.Contains(entry.Type, consts.PluginTypeCredential) { - // If we encounter an error instantiating the backend due to an error, - // skip backend initialization but register the entry to the mount table - // to preserve storage and path. - c.logger.Warn("skipping plugin-based credential entry", "path", entry.Path) - goto ROUTER_MOUNT - } - return errLoadAuthFailed - } - if backend == nil { - return fmt.Errorf("nil backend returned from %q factory", entry.Type) - } - - { - // Check for the correct backend type - backendType := backend.Type() - if backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount %q of type %q as an auth backend", entry.Type, backendType) - } - - addPathCheckers(c, entry, backend, viewPath) - } - - // If the mount is filtered or we are on a DR secondary we don't want to - // keep the actual backend running, so we clean it up and set it to nil - // so the router does not have a pointer to the object. - if nilMount { - backend.Cleanup(ctx) - backend = nil - } - - ROUTER_MOUNT: - // Mount the backend - path := credentialRoutePrefix + entry.Path - err = c.router.Mount(backend, path, entry, view) - if err != nil { - c.logger.Error("failed to mount auth entry", "path", entry.Path, "error", err) - return errLoadAuthFailed - } - - if c.logger.IsInfo() { - c.logger.Info("successfully enabled credential backend", "type", entry.Type, "path", entry.Path) - } - - // Ensure the path is tainted if set in the mount table - if entry.Tainted { - c.router.Taint(ctx, path) - } - - // Check if this is the token store - if entry.Type == "token" { - c.tokenStore = backend.(*TokenStore) - - // At some point when this isn't beta we may persist this but for - // now always set it on mount - entry.Config.TokenType = logical.TokenTypeDefaultService - - // this is loaded *after* the normal mounts, including cubbyhole - c.router.tokenStoreSaltFunc = c.tokenStore.Salt - if !c.IsDRSecondary() { - c.tokenStore.cubbyholeBackend = c.router.MatchingBackend(ctx, cubbyholeMountPath).(*CubbyholeBackend) - } - } - - // Populate cache - NamespaceByID(ctx, entry.NamespaceID, c) - } - - if persistNeeded { - // persist non-local auth - return c.persistAuth(ctx, c.auth, nil) - } - - return nil -} - -// teardownCredentials is used before we seal the vault to reset the credential -// backends to their unloaded state. This is reversed by loadCredentials. -func (c *Core) teardownCredentials(ctx context.Context) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - if c.auth != nil { - authTable := c.auth.shallowClone() - for _, e := range authTable.Entries { - backend := c.router.MatchingBackend(namespace.ContextWithNamespace(ctx, e.namespace), credentialRoutePrefix+e.Path) - if backend != nil { - backend.Cleanup(ctx) - } - - viewPath := e.ViewPath() - removePathCheckers(c, e, viewPath) - } - } - - c.auth = nil - c.tokenStore = nil - return nil -} - -// newCredentialBackend is used to create and configure a new credential backend by name -func (c *Core) newCredentialBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) { - t := entry.Type - if alias, ok := credentialAliases[t]; ok { - t = alias - } - - f, ok := c.credentialBackends[t] - if !ok { - f = plugin.Factory - } - - // Set up conf to pass in plugin_name - conf := make(map[string]string, len(entry.Options)+1) - for k, v := range entry.Options { - conf[k] = v - } - - switch { - case entry.Type == "plugin": - conf["plugin_name"] = entry.Config.PluginName - default: - conf["plugin_name"] = t - } - - conf["plugin_type"] = consts.PluginTypeCredential.String() - - authLogger := c.baseLogger.Named(fmt.Sprintf("auth.%s.%s", t, entry.Accessor)) - c.AddLogger(authLogger) - config := &logical.BackendConfig{ - StorageView: view, - Logger: authLogger, - Config: conf, - System: sysView, - BackendUUID: entry.BackendAwareUUID, - } - - b, err := f(ctx, config) - if err != nil { - return nil, err - } - - return b, nil -} - -// defaultAuthTable creates a default auth table -func (c *Core) defaultAuthTable() *MountTable { - table := &MountTable{ - Type: credentialTableType, - } - tokenUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not generate UUID for default auth table token entry: %v", err)) - } - tokenAccessor, err := c.generateMountAccessor("auth_token") - if err != nil { - panic(fmt.Sprintf("could not generate accessor for default auth table token entry: %v", err)) - } - tokenBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity backend UUID: %v", err)) - } - tokenAuth := &MountEntry{ - Table: credentialTableType, - Path: "token/", - Type: "token", - Description: "token based credentials", - UUID: tokenUUID, - Accessor: tokenAccessor, - BackendAwareUUID: tokenBackendUUID, - } - table.Entries = append(table.Entries, tokenAuth) - return table -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier.go b/vendor/github.com/hashicorp/vault/vault/barrier.go deleted file mode 100644 index 7f8a3138..00000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier.go +++ /dev/null @@ -1,183 +0,0 @@ -package vault - -import ( - "context" - "errors" - "time" - - "github.com/hashicorp/vault/logical" -) - -var ( - // ErrBarrierSealed is returned if an operation is performed on - // a sealed barrier. No operation is expected to succeed before unsealing - ErrBarrierSealed = errors.New("Vault is sealed") - - // ErrBarrierAlreadyInit is returned if the barrier is already - // initialized. This prevents a re-initialization. - ErrBarrierAlreadyInit = errors.New("Vault is already initialized") - - // ErrBarrierNotInit is returned if a non-initialized barrier - // is attempted to be unsealed. - ErrBarrierNotInit = errors.New("Vault is not initialized") - - // ErrBarrierInvalidKey is returned if the Unseal key is invalid - ErrBarrierInvalidKey = errors.New("Unseal failed, invalid key") -) - -const ( - // barrierInitPath is the path used to store our init sentinel file - barrierInitPath = "barrier/init" - - // keyringPath is the location of the keyring data. This is encrypted - // by the master key. - keyringPath = "core/keyring" - keyringPrefix = "core/" - - // keyringUpgradePrefix is the path used to store keyring update entries. - // When running in HA mode, the active instance will install the new key - // and re-write the keyring. For standby instances, they need an upgrade - // path from key N to N+1. They cannot just use the master key because - // in the event of a rekey, that master key can no longer decrypt the keyring. - // When key N+1 is installed, we create an entry at "prefix/N" which uses - // encryption key N to provide the N+1 key. The standby instances scan - // for this periodically and refresh their keyring. The upgrade keys - // are deleted after a few minutes, but this provides enough time for the - // standby instances to upgrade without causing any disruption. - keyringUpgradePrefix = "core/upgrade/" - - // masterKeyPath is the location of the master key. This is encrypted - // by the latest key in the keyring. This is only used by standby instances - // to handle the case of a rekey. If the active instance does a rekey, - // the standby instances can no longer reload the keyring since they - // have the old master key. This key can be decrypted if you have the - // keyring to discover the new master key. The new master key is then - // used to reload the keyring itself. - masterKeyPath = "core/master" -) - -// SecurityBarrier is a critical component of Vault. It is used to wrap -// an untrusted physical backend and provide a single point of encryption, -// decryption and checksum verification. The goal is to ensure that any -// data written to the barrier is confidential and that integrity is preserved. -// As a real-world analogy, this is the steel and concrete wrapper around -// a Vault. The barrier should only be Unlockable given its key. -type SecurityBarrier interface { - // Initialized checks if the barrier has been initialized - // and has a master key set. - Initialized(ctx context.Context) (bool, error) - - // Initialize works only if the barrier has not been initialized - // and makes use of the given master key. - Initialize(context.Context, []byte) error - - // GenerateKey is used to generate a new key - GenerateKey() ([]byte, error) - - // KeyLength is used to sanity check a key - KeyLength() (int, int) - - // Sealed checks if the barrier has been unlocked yet. The Barrier - // is not expected to be able to perform any CRUD until it is unsealed. - Sealed() (bool, error) - - // Unseal is used to provide the master key which permits the barrier - // to be unsealed. If the key is not correct, the barrier remains sealed. - Unseal(ctx context.Context, key []byte) error - - // VerifyMaster is used to check if the given key matches the master key - VerifyMaster(key []byte) error - - // SetMasterKey is used to directly set a new master key. This is used in - // replicated scenarios due to the chicken and egg problem of reloading the - // keyring from disk before we have the master key to decrypt it. - SetMasterKey(key []byte) error - - // ReloadKeyring is used to re-read the underlying keyring. - // This is used for HA deployments to ensure the latest keyring - // is present in the leader. - ReloadKeyring(ctx context.Context) error - - // ReloadMasterKey is used to re-read the underlying masterkey. - // This is used for HA deployments to ensure the latest master key - // is available for keyring reloading. - ReloadMasterKey(ctx context.Context) error - - // Seal is used to re-seal the barrier. This requires the barrier to - // be unsealed again to perform any further operations. - Seal() error - - // Rotate is used to create a new encryption key. All future writes - // should use the new key, while old values should still be decryptable. - Rotate(ctx context.Context) (uint32, error) - - // CreateUpgrade creates an upgrade path key to the given term from the previous term - CreateUpgrade(ctx context.Context, term uint32) error - - // DestroyUpgrade destroys the upgrade path key to the given term - DestroyUpgrade(ctx context.Context, term uint32) error - - // CheckUpgrade looks for an upgrade to the current term and installs it - CheckUpgrade(ctx context.Context) (bool, uint32, error) - - // ActiveKeyInfo is used to inform details about the active key - ActiveKeyInfo() (*KeyInfo, error) - - // Rekey is used to change the master key used to protect the keyring - Rekey(context.Context, []byte) error - - // For replication we must send over the keyring, so this must be available - Keyring() (*Keyring, error) - - // SecurityBarrier must provide the storage APIs - BarrierStorage - - // SecurityBarrier must provide the encryption APIs - BarrierEncryptor -} - -// BarrierStorage is the storage only interface required for a Barrier. -type BarrierStorage 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 ot list all the keys under a given - // prefix, up to the next prefix. - List(ctx context.Context, prefix string) ([]string, error) -} - -// BarrierEncryptor is the in memory only interface that does not actually -// use the underlying barrier. It is used for lower level modules like the -// Write-Ahead-Log and Merkle index to allow them to use the barrier. -type BarrierEncryptor interface { - Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) - Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) -} - -// Entry is used to represent data stored by the security barrier -type Entry struct { - Key string - Value []byte - SealWrap bool -} - -// Logical turns the Entry into a logical storage entry. -func (e *Entry) Logical() *logical.StorageEntry { - return &logical.StorageEntry{ - Key: e.Key, - Value: e.Value, - SealWrap: e.SealWrap, - } -} - -// KeyInfo is used to convey information about the encryption key -type KeyInfo struct { - Term int - InstallTime time.Time -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_access.go b/vendor/github.com/hashicorp/vault/vault/barrier_access.go deleted file mode 100644 index 84e6e747..00000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_access.go +++ /dev/null @@ -1,24 +0,0 @@ -package vault - -import "context" - -// BarrierEncryptorAccess is a wrapper around BarrierEncryptor that allows Core -// to expose its barrier encrypt/decrypt operations through BarrierEncryptorAccess() -// while restricting the ability to modify Core.barrier itself. -type BarrierEncryptorAccess struct { - barrierEncryptor BarrierEncryptor -} - -var _ BarrierEncryptor = (*BarrierEncryptorAccess)(nil) - -func NewBarrierEncryptorAccess(barrierEncryptor BarrierEncryptor) *BarrierEncryptorAccess { - return &BarrierEncryptorAccess{barrierEncryptor: barrierEncryptor} -} - -func (b *BarrierEncryptorAccess) Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) { - return b.barrierEncryptor.Encrypt(ctx, key, plaintext) -} - -func (b *BarrierEncryptorAccess) Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) { - return b.barrierEncryptor.Decrypt(ctx, key, ciphertext) -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go b/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go deleted file mode 100644 index 8ddae289..00000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go +++ /dev/null @@ -1,949 +0,0 @@ -package vault - -import ( - "context" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/subtle" - "encoding/binary" - "errors" - "fmt" - "strings" - "sync" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -const ( - // initialKeyTerm is the hard coded initial key term. This is - // used only for values that are not encrypted with the keyring. - initialKeyTerm = 1 - - // termSize the number of bytes used for the key term. - termSize = 4 -) - -// Versions of the AESGCM storage methodology -const ( - AESGCMVersion1 = 0x1 - AESGCMVersion2 = 0x2 -) - -// barrierInit is the JSON encoded value stored -type barrierInit struct { - Version int // Version is the current format version - Key []byte // Key is the primary encryption key -} - -// Validate AESGCMBarrier satisfies SecurityBarrier interface -var _ SecurityBarrier = &AESGCMBarrier{} - -// AESGCMBarrier is a SecurityBarrier implementation that uses the AES -// cipher core and the Galois Counter Mode block mode. It defaults to -// the golang NONCE default value of 12 and a key size of 256 -// bit. AES-GCM is high performance, and provides both confidentiality -// and integrity. -type AESGCMBarrier struct { - backend physical.Backend - - l sync.RWMutex - sealed bool - - // keyring is used to maintain all of the encryption keys, including - // the active key used for encryption, but also prior keys to allow - // decryption of keys encrypted under previous terms. - keyring *Keyring - - // cache is used to reduce the number of AEAD constructions we do - cache map[uint32]cipher.AEAD - cacheLock sync.RWMutex - - // currentAESGCMVersionByte is prefixed to a message to allow for - // future versioning of barrier implementations. It's var instead - // of const to allow for testing - currentAESGCMVersionByte byte -} - -// NewAESGCMBarrier is used to construct a new barrier that uses -// the provided physical backend for storage. -func NewAESGCMBarrier(physical physical.Backend) (*AESGCMBarrier, error) { - b := &AESGCMBarrier{ - backend: physical, - sealed: true, - cache: make(map[uint32]cipher.AEAD), - currentAESGCMVersionByte: byte(AESGCMVersion2), - } - return b, nil -} - -// Initialized checks if the barrier has been initialized -// and has a master key set. -func (b *AESGCMBarrier) Initialized(ctx context.Context) (bool, error) { - // Read the keyring file - keys, err := b.backend.List(ctx, keyringPrefix) - if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - if strutil.StrListContains(keys, "keyring") { - return true, nil - } - - // Fallback, check for the old sentinel file - out, err := b.backend.Get(ctx, barrierInitPath) - if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - return out != nil, nil -} - -// Initialize works only if the barrier has not been initialized -// and makes use of the given master key. -func (b *AESGCMBarrier) Initialize(ctx context.Context, key []byte) error { - // Verify the key size - min, max := b.KeyLength() - if len(key) < min || len(key) > max { - return fmt.Errorf("key size must be %d or %d", min, max) - } - - // Check if already initialized - if alreadyInit, err := b.Initialized(ctx); err != nil { - return err - } else if alreadyInit { - return ErrBarrierAlreadyInit - } - - // Generate encryption key - encrypt, err := b.GenerateKey() - if err != nil { - return errwrap.Wrapf("failed to generate encryption key: {{err}}", err) - } - - // Create a new keyring, install the keys - keyring := NewKeyring() - keyring = keyring.SetMasterKey(key) - keyring, err = keyring.AddKey(&Key{ - Term: 1, - Version: 1, - Value: encrypt, - }) - if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) - } - return b.persistKeyring(ctx, keyring) -} - -// persistKeyring is used to write out the keyring using the -// master key to encrypt it. -func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) error { - // Create the keyring entry - keyringBuf, err := keyring.Serialize() - defer memzero(keyringBuf) - if err != nil { - return errwrap.Wrapf("failed to serialize keyring: {{err}}", err) - } - - // Create the AES-GCM - gcm, err := b.aeadFromKey(keyring.MasterKey()) - if err != nil { - return err - } - - // Encrypt the barrier init value - value, err := b.encrypt(keyringPath, initialKeyTerm, gcm, keyringBuf) - if err != nil { - return err - } - - // Create the keyring physical entry - pe := &physical.Entry{ - Key: keyringPath, - Value: value, - } - if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist keyring: {{err}}", err) - } - - // Serialize the master key value - key := &Key{ - Term: 1, - Version: 1, - Value: keyring.MasterKey(), - } - keyBuf, err := key.Serialize() - defer memzero(keyBuf) - if err != nil { - return errwrap.Wrapf("failed to serialize master key: {{err}}", err) - } - - // Encrypt the master key - activeKey := keyring.ActiveKey() - aead, err := b.aeadFromKey(activeKey.Value) - if err != nil { - return err - } - value, err = b.encrypt(masterKeyPath, activeKey.Term, aead, keyBuf) - if err != nil { - return err - } - - // Update the masterKeyPath for standby instances - pe = &physical.Entry{ - Key: masterKeyPath, - Value: value, - } - if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist master key: {{err}}", err) - } - return nil -} - -// GenerateKey is used to generate a new key -func (b *AESGCMBarrier) GenerateKey() ([]byte, error) { - // Generate a 256bit key - buf := make([]byte, 2*aes.BlockSize) - _, err := rand.Read(buf) - return buf, err -} - -// KeyLength is used to sanity check a key -func (b *AESGCMBarrier) KeyLength() (int, int) { - return aes.BlockSize, 2 * aes.BlockSize -} - -// Sealed checks if the barrier has been unlocked yet. The Barrier -// is not expected to be able to perform any CRUD until it is unsealed. -func (b *AESGCMBarrier) Sealed() (bool, error) { - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - return sealed, nil -} - -// VerifyMaster is used to check if the given key matches the master key -func (b *AESGCMBarrier) VerifyMaster(key []byte) error { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return ErrBarrierSealed - } - if subtle.ConstantTimeCompare(key, b.keyring.MasterKey()) != 1 { - return ErrBarrierInvalidKey - } - return nil -} - -// ReloadKeyring is used to re-read the underlying keyring. -// This is used for HA deployments to ensure the latest keyring -// is present in the leader. -func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { - b.l.Lock() - defer b.l.Unlock() - - // Create the AES-GCM - gcm, err := b.aeadFromKey(b.keyring.MasterKey()) - if err != nil { - return err - } - - // Read in the keyring - out, err := b.backend.Get(ctx, keyringPath) - if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) - } - - // Ensure that the keyring exists. This should never happen, - // and indicates something really bad has happened. - if out == nil { - return errors.New("keyring unexpectedly missing") - } - - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(keyringPath, gcm, out.Value) - defer memzero(plain) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - - // Recover the keyring - keyring, err := DeserializeKeyring(plain) - if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) - } - - // Setup the keyring and finish - b.keyring = keyring - return nil -} - -// ReloadMasterKey is used to re-read the underlying masterkey. -// This is used for HA deployments to ensure the latest master key -// is available for keyring reloading. -func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { - // Read the masterKeyPath upgrade - out, err := b.Get(ctx, masterKeyPath) - if err != nil { - return errwrap.Wrapf("failed to read master key path: {{err}}", err) - } - - // The masterKeyPath could be missing (backwards incompatible), - // we can ignore this and attempt to make progress with the current - // master key. - if out == nil { - return nil - } - - defer memzero(out.Value) - - // Deserialize the master key - key, err := DeserializeKey(out.Value) - if err != nil { - return errwrap.Wrapf("failed to deserialize key: {{err}}", err) - } - - b.l.Lock() - defer b.l.Unlock() - - // Check if the master key is the same - if subtle.ConstantTimeCompare(b.keyring.MasterKey(), key.Value) == 1 { - return nil - } - - // Update the master key - oldKeyring := b.keyring - b.keyring = b.keyring.SetMasterKey(key.Value) - oldKeyring.Zeroize(false) - return nil -} - -// Unseal is used to provide the master key which permits the barrier -// to be unsealed. If the key is not correct, the barrier remains sealed. -func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - // Do nothing if already unsealed - if !b.sealed { - return nil - } - - // Create the AES-GCM - gcm, err := b.aeadFromKey(key) - if err != nil { - return err - } - - // Read in the keyring - out, err := b.backend.Get(ctx, keyringPath) - if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) - } - if out != nil { - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(keyringPath, gcm, out.Value) - defer memzero(plain) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - - // Recover the keyring - keyring, err := DeserializeKeyring(plain) - if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) - } - - // Setup the keyring and finish - b.keyring = keyring - b.sealed = false - return nil - } - - // Read the barrier initialization key - out, err = b.backend.Get(ctx, barrierInitPath) - if err != nil { - return errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - if out == nil { - return ErrBarrierNotInit - } - - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(barrierInitPath, gcm, out.Value) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - defer memzero(plain) - - // Unmarshal the barrier init - var init barrierInit - if err := jsonutil.DecodeJSON(plain, &init); err != nil { - return fmt.Errorf("failed to unmarshal barrier init file") - } - - // Setup a new keyring, this is for backwards compatibility - keyringNew := NewKeyring() - keyring := keyringNew.SetMasterKey(key) - - // AddKey reuses the master, so we are only zeroizing after this call - defer keyringNew.Zeroize(false) - - keyring, err = keyring.AddKey(&Key{ - Term: 1, - Version: 1, - Value: init.Key, - }) - if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) - } - if err := b.persistKeyring(ctx, keyring); err != nil { - return err - } - - // Delete the old barrier entry - if err := b.backend.Delete(ctx, barrierInitPath); err != nil { - return errwrap.Wrapf("failed to delete barrier init file: {{err}}", err) - } - - // Set the vault as unsealed - b.keyring = keyring - b.sealed = false - return nil -} - -// Seal is used to re-seal the barrier. This requires the barrier to -// be unsealed again to perform any further operations. -func (b *AESGCMBarrier) Seal() error { - b.l.Lock() - defer b.l.Unlock() - - // Remove the primary key, and seal the vault - b.cache = make(map[uint32]cipher.AEAD) - b.keyring.Zeroize(true) - b.keyring = nil - b.sealed = true - return nil -} - -// Rotate is used to create a new encryption key. All future writes -// should use the new key, while old values should still be decryptable. -func (b *AESGCMBarrier) Rotate(ctx context.Context) (uint32, error) { - b.l.Lock() - defer b.l.Unlock() - if b.sealed { - return 0, ErrBarrierSealed - } - - // Generate a new key - encrypt, err := b.GenerateKey() - if err != nil { - return 0, errwrap.Wrapf("failed to generate encryption key: {{err}}", err) - } - - // Get the next term - term := b.keyring.ActiveTerm() - newTerm := term + 1 - - // Add a new encryption key - newKeyring, err := b.keyring.AddKey(&Key{ - Term: newTerm, - Version: 1, - Value: encrypt, - }) - if err != nil { - return 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) - } - - // Persist the new keyring - if err := b.persistKeyring(ctx, newKeyring); err != nil { - return 0, err - } - - // Swap the keyrings - b.keyring = newKeyring - return newTerm, nil -} - -// CreateUpgrade creates an upgrade path key to the given term from the previous term -func (b *AESGCMBarrier) CreateUpgrade(ctx context.Context, term uint32) error { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return ErrBarrierSealed - } - - // Get the key for this term - termKey := b.keyring.TermKey(term) - buf, err := termKey.Serialize() - defer memzero(buf) - if err != nil { - return err - } - - // Get the AEAD for the previous term - prevTerm := term - 1 - primary, err := b.aeadForTerm(prevTerm) - if err != nil { - return err - } - - key := fmt.Sprintf("%s%d", keyringUpgradePrefix, prevTerm) - value, err := b.encrypt(key, prevTerm, primary, buf) - if err != nil { - return err - } - // Create upgrade key - pe := &physical.Entry{ - Key: key, - Value: value, - } - return b.backend.Put(ctx, pe) -} - -// DestroyUpgrade destroys the upgrade path key to the given term -func (b *AESGCMBarrier) DestroyUpgrade(ctx context.Context, term uint32) error { - path := fmt.Sprintf("%s%d", keyringUpgradePrefix, term-1) - return b.Delete(ctx, path) -} - -// CheckUpgrade looks for an upgrade to the current term and installs it -func (b *AESGCMBarrier) CheckUpgrade(ctx context.Context) (bool, uint32, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return false, 0, ErrBarrierSealed - } - - // Get the current term - activeTerm := b.keyring.ActiveTerm() - - // Check for an upgrade key - upgrade := fmt.Sprintf("%s%d", keyringUpgradePrefix, activeTerm) - entry, err := b.Get(ctx, upgrade) - if err != nil { - return false, 0, err - } - - // Nothing to do if no upgrade - if entry == nil { - return false, 0, nil - } - - defer memzero(entry.Value) - - // Deserialize the key - key, err := DeserializeKey(entry.Value) - if err != nil { - return false, 0, err - } - - // Upgrade from read lock to write lock - b.l.RUnlock() - defer b.l.RLock() - b.l.Lock() - defer b.l.Unlock() - - // Update the keyring - newKeyring, err := b.keyring.AddKey(key) - if err != nil { - return false, 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) - } - b.keyring = newKeyring - - // Done! - return true, key.Term, nil -} - -// ActiveKeyInfo is used to inform details about the active key -func (b *AESGCMBarrier) ActiveKeyInfo() (*KeyInfo, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return nil, ErrBarrierSealed - } - - // Determine the key install time - term := b.keyring.ActiveTerm() - key := b.keyring.TermKey(term) - - // Return the key info - info := &KeyInfo{ - Term: int(term), - InstallTime: key.InstallTime, - } - return info, nil -} - -// Rekey is used to change the master key used to protect the keyring -func (b *AESGCMBarrier) Rekey(ctx context.Context, key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - newKeyring, err := b.updateMasterKeyCommon(key) - if err != nil { - return err - } - - // Persist the new keyring - if err := b.persistKeyring(ctx, newKeyring); err != nil { - return err - } - - // Swap the keyrings - oldKeyring := b.keyring - b.keyring = newKeyring - oldKeyring.Zeroize(false) - return nil -} - -// SetMasterKey updates the keyring's in-memory master key but does not persist -// anything to storage -func (b *AESGCMBarrier) SetMasterKey(key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - newKeyring, err := b.updateMasterKeyCommon(key) - if err != nil { - return err - } - - // Swap the keyrings - oldKeyring := b.keyring - b.keyring = newKeyring - oldKeyring.Zeroize(false) - return nil -} - -// Performs common tasks related to updating the master key; note that the lock -// must be held before calling this function -func (b *AESGCMBarrier) updateMasterKeyCommon(key []byte) (*Keyring, error) { - if b.sealed { - return nil, ErrBarrierSealed - } - - // Verify the key size - min, max := b.KeyLength() - if len(key) < min || len(key) > max { - return nil, fmt.Errorf("key size must be %d or %d", min, max) - } - - return b.keyring.SetMasterKey(key), nil -} - -// Put is used to insert or update an entry -func (b *AESGCMBarrier) Put(ctx context.Context, entry *Entry) error { - defer metrics.MeasureSince([]string{"barrier", "put"}, time.Now()) - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return ErrBarrierSealed - } - - term := b.keyring.ActiveTerm() - primary, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return err - } - - value, err := b.encrypt(entry.Key, term, primary, entry.Value) - if err != nil { - return err - } - pe := &physical.Entry{ - Key: entry.Key, - Value: value, - SealWrap: entry.SealWrap, - } - return b.backend.Put(ctx, pe) -} - -// Get is used to fetch an entry -func (b *AESGCMBarrier) Get(ctx context.Context, key string) (*Entry, error) { - defer metrics.MeasureSince([]string{"barrier", "get"}, time.Now()) - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - // Read the key from the backend - pe, err := b.backend.Get(ctx, key) - if err != nil { - b.l.RUnlock() - return nil, err - } else if pe == nil { - b.l.RUnlock() - return nil, nil - } - - if len(pe.Value) < 4 { - b.l.RUnlock() - return nil, errors.New("invalid value") - } - - // Verify the term - term := binary.BigEndian.Uint32(pe.Value[:4]) - - // Get the GCM by term - // It is expensive to do this first but it is not a - // normal case that this won't match - gcm, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - if gcm == nil { - return nil, fmt.Errorf("no decryption key available for term %d", term) - } - - // Decrypt the ciphertext - plain, err := b.decrypt(key, gcm, pe.Value) - if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) - } - - // Wrap in a logical entry - entry := &Entry{ - Key: key, - Value: plain, - SealWrap: pe.SealWrap, - } - return entry, nil -} - -// Delete is used to permanently delete an entry -func (b *AESGCMBarrier) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"barrier", "delete"}, time.Now()) - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - if sealed { - return ErrBarrierSealed - } - - return b.backend.Delete(ctx, key) -} - -// List is used ot list all the keys under a given -// prefix, up to the next prefix. -func (b *AESGCMBarrier) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"barrier", "list"}, time.Now()) - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - if sealed { - return nil, ErrBarrierSealed - } - - return b.backend.List(ctx, prefix) -} - -// aeadForTerm returns the AES-GCM AEAD for the given term -func (b *AESGCMBarrier) aeadForTerm(term uint32) (cipher.AEAD, error) { - // Check for the keyring - keyring := b.keyring - if keyring == nil { - return nil, nil - } - - // Check the cache for the aead - b.cacheLock.RLock() - aead, ok := b.cache[term] - b.cacheLock.RUnlock() - if ok { - return aead, nil - } - - // Read the underlying key - key := keyring.TermKey(term) - if key == nil { - return nil, nil - } - - // Create a new aead - aead, err := b.aeadFromKey(key.Value) - if err != nil { - return nil, err - } - - // Update the cache - b.cacheLock.Lock() - b.cache[term] = aead - b.cacheLock.Unlock() - return aead, nil -} - -// aeadFromKey returns an AES-GCM AEAD using the given key. -func (b *AESGCMBarrier) aeadFromKey(key []byte) (cipher.AEAD, error) { - // Create the AES cipher - aesCipher, err := aes.NewCipher(key) - if err != nil { - return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err) - } - - // Create the GCM mode AEAD - gcm, err := cipher.NewGCM(aesCipher) - if err != nil { - return nil, fmt.Errorf("failed to initialize GCM mode") - } - return gcm, nil -} - -// encrypt is used to encrypt a value -func (b *AESGCMBarrier) encrypt(path string, term uint32, gcm cipher.AEAD, plain []byte) ([]byte, error) { - // Allocate the output buffer with room for tern, version byte, - // nonce, GCM tag and the plaintext - capacity := termSize + 1 + gcm.NonceSize() + gcm.Overhead() + len(plain) - size := termSize + 1 + gcm.NonceSize() - out := make([]byte, size, capacity) - - // Set the key term - binary.BigEndian.PutUint32(out[:4], term) - - // Set the version byte - out[4] = b.currentAESGCMVersionByte - - // Generate a random nonce - nonce := out[5 : 5+gcm.NonceSize()] - n, err := rand.Read(nonce) - if err != nil { - return nil, err - } - if n != len(nonce) { - return nil, errors.New("unable to read enough random bytes to fill gcm nonce") - } - - // Seal the output - switch b.currentAESGCMVersionByte { - case AESGCMVersion1: - out = gcm.Seal(out, nonce, plain, nil) - case AESGCMVersion2: - aad := []byte(nil) - if path != "" { - aad = []byte(path) - } - out = gcm.Seal(out, nonce, plain, aad) - default: - panic("Unknown AESGCM version") - } - - return out, nil -} - -// decrypt is used to decrypt a value using the keyring -func (b *AESGCMBarrier) decrypt(path string, gcm cipher.AEAD, cipher []byte) ([]byte, error) { - // Capture the parts - nonce := cipher[5 : 5+gcm.NonceSize()] - raw := cipher[5+gcm.NonceSize():] - out := make([]byte, 0, len(raw)-gcm.NonceSize()) - - // Attempt to open - switch cipher[4] { - case AESGCMVersion1: - return gcm.Open(out, nonce, raw, nil) - case AESGCMVersion2: - aad := []byte(nil) - if path != "" { - aad = []byte(path) - } - return gcm.Open(out, nonce, raw, aad) - default: - return nil, fmt.Errorf("version bytes mis-match") - } -} - -// Encrypt is used to encrypt in-memory for the BarrierEncryptor interface -func (b *AESGCMBarrier) Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) { - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - term := b.keyring.ActiveTerm() - primary, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - - ciphertext, err := b.encrypt(key, term, primary, plaintext) - if err != nil { - return nil, err - } - return ciphertext, nil -} - -// Decrypt is used to decrypt in-memory for the BarrierEncryptor interface -func (b *AESGCMBarrier) Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) { - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - // Verify the term - term := binary.BigEndian.Uint32(ciphertext[:4]) - - // Get the GCM by term - // It is expensive to do this first but it is not a - // normal case that this won't match - gcm, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - if gcm == nil { - return nil, fmt.Errorf("no decryption key available for term %d", term) - } - - // Decrypt the ciphertext - plain, err := b.decrypt(key, gcm, ciphertext) - if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) - } - - return plain, nil -} - -func (b *AESGCMBarrier) Keyring() (*Keyring, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return nil, ErrBarrierSealed - } - - return b.keyring.Clone(), nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_view.go b/vendor/github.com/hashicorp/vault/vault/barrier_view.go deleted file mode 100644 index 94fbac9a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_view.go +++ /dev/null @@ -1,154 +0,0 @@ -package vault - -import ( - "context" - "errors" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" -) - -// BarrierView wraps a SecurityBarrier and ensures all access is automatically -// prefixed. This is used to prevent anyone with access to the view to access -// any data in the durable storage outside of their prefix. Conceptually this -// is like a "chroot" into the barrier. -// -// BarrierView implements logical.Storage so it can be passed in as the -// durable storage mechanism for logical views. -type BarrierView struct { - barrier BarrierStorage - prefix string - readOnlyErr error - readOnlyErrLock sync.RWMutex - iCheck interface{} -} - -var ( - ErrRelativePath = errors.New("relative paths not supported") -) - -// NewBarrierView takes an underlying security barrier and returns -// a view of it that can only operate with the given prefix. -func NewBarrierView(barrier BarrierStorage, prefix string) *BarrierView { - return &BarrierView{ - barrier: barrier, - prefix: prefix, - } -} - -func (v *BarrierView) setICheck(iCheck interface{}) { - v.iCheck = iCheck -} - -func (v *BarrierView) setReadOnlyErr(readOnlyErr error) { - v.readOnlyErrLock.Lock() - defer v.readOnlyErrLock.Unlock() - v.readOnlyErr = readOnlyErr -} - -func (v *BarrierView) getReadOnlyErr() error { - v.readOnlyErrLock.RLock() - defer v.readOnlyErrLock.RUnlock() - return v.readOnlyErr -} - -// sanityCheck is used to perform a sanity check on a key -func (v *BarrierView) sanityCheck(key string) error { - if strings.Contains(key, "..") { - return ErrRelativePath - } - return nil -} - -// logical.Storage impl. -func (v *BarrierView) List(ctx context.Context, prefix string) ([]string, error) { - if err := v.sanityCheck(prefix); err != nil { - return nil, err - } - return v.barrier.List(ctx, v.expandKey(prefix)) -} - -// logical.Storage impl. -func (v *BarrierView) Get(ctx context.Context, key string) (*logical.StorageEntry, error) { - if err := v.sanityCheck(key); err != nil { - return nil, err - } - entry, err := v.barrier.Get(ctx, v.expandKey(key)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - if entry != nil { - entry.Key = v.truncateKey(entry.Key) - } - - return &logical.StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -// logical.Storage impl. -func (v *BarrierView) Put(ctx context.Context, entry *logical.StorageEntry) error { - if entry == nil { - return errors.New("cannot write nil entry") - } - - if err := v.sanityCheck(entry.Key); err != nil { - return err - } - - expandedKey := v.expandKey(entry.Key) - - roErr := v.getReadOnlyErr() - if roErr != nil { - if runICheck(v, expandedKey, roErr) { - return roErr - } - } - - nested := &Entry{ - Key: expandedKey, - Value: entry.Value, - SealWrap: entry.SealWrap, - } - return v.barrier.Put(ctx, nested) -} - -// logical.Storage impl. -func (v *BarrierView) Delete(ctx context.Context, key string) error { - if err := v.sanityCheck(key); err != nil { - return err - } - - expandedKey := v.expandKey(key) - - roErr := v.getReadOnlyErr() - if roErr != nil { - if runICheck(v, expandedKey, roErr) { - return roErr - } - } - - return v.barrier.Delete(ctx, expandedKey) -} - -// SubView constructs a nested sub-view using the given prefix -func (v *BarrierView) SubView(prefix string) *BarrierView { - sub := v.expandKey(prefix) - return &BarrierView{barrier: v.barrier, prefix: sub, readOnlyErr: v.getReadOnlyErr(), iCheck: v.iCheck} -} - -// expandKey is used to expand to the full key path with the prefix -func (v *BarrierView) expandKey(suffix string) string { - return v.prefix + suffix -} - -// truncateKey is used to remove the prefix of the key -func (v *BarrierView) truncateKey(full string) string { - return strings.TrimPrefix(full, v.prefix) -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_view_util.go b/vendor/github.com/hashicorp/vault/vault/barrier_view_util.go deleted file mode 100644 index f7c63405..00000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_view_util.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !enterprise - -package vault - -func runICheck(v *BarrierView, expandedKey string, roErr error) bool { return true } diff --git a/vendor/github.com/hashicorp/vault/vault/capabilities.go b/vendor/github.com/hashicorp/vault/vault/capabilities.go deleted file mode 100644 index 36e17bde..00000000 --- a/vendor/github.com/hashicorp/vault/vault/capabilities.go +++ /dev/null @@ -1,76 +0,0 @@ -package vault - -import ( - "context" - "sort" - - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -// Capabilities is used to fetch the capabilities of the given token on the -// given path -func (c *Core) Capabilities(ctx context.Context, token, path string) ([]string, error) { - if path == "" { - return nil, &logical.StatusBadRequest{Err: "missing path"} - } - - if token == "" { - return nil, &logical.StatusBadRequest{Err: "missing token"} - } - - te, err := c.tokenStore.Lookup(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, &logical.StatusBadRequest{Err: "invalid token"} - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, c) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - var policyCount int - policyNames := make(map[string][]string) - policyNames[tokenNS.ID] = te.Policies - policyCount += len(te.Policies) - - entity, identityPolicies, err := c.fetchEntityAndDerivedPolicies(ctx, tokenNS, te.EntityID) - if err != nil { - return nil, err - } - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - return nil, logical.ErrPermissionDenied - } - if te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - - for nsID, nsPolicies := range identityPolicies { - policyNames[nsID] = append(policyNames[nsID], nsPolicies...) - policyCount += len(nsPolicies) - } - - if policyCount == 0 { - return []string{DenyCapability}, nil - } - - // Construct the corresponding ACL object. ACL construction should be - // performed on the token's namespace. - tokenCtx := namespace.ContextWithNamespace(ctx, tokenNS) - acl, err := c.policyStore.ACL(tokenCtx, entity, policyNames) - if err != nil { - return nil, err - } - - capabilities := acl.Capabilities(ctx, path) - sort.Strings(capabilities) - return capabilities, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/cluster.go b/vendor/github.com/hashicorp/vault/vault/cluster.go deleted file mode 100644 index 356722a0..00000000 --- a/vendor/github.com/hashicorp/vault/vault/cluster.go +++ /dev/null @@ -1,382 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/json" - "errors" - "fmt" - "math/big" - mathrand "math/rand" - "net" - "net/http" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/jsonutil" -) - -const ( - // Storage path where the local cluster name and identifier are stored - coreLocalClusterInfoPath = "core/cluster/local/info" - - corePrivateKeyTypeP521 = "p521" - corePrivateKeyTypeED25519 = "ed25519" - - // Internal so as not to log a trace message - IntNoForwardingHeaderName = "X-Vault-Internal-No-Request-Forwarding" -) - -var ( - ErrCannotForward = errors.New("cannot forward request; no connection or address not known") -) - -type ReplicatedClusters struct { - DR *ReplicatedCluster - Performance *ReplicatedCluster -} - -// 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"` -} - -// Structure representing the storage entry that holds cluster information -type Cluster struct { - // Name of the cluster - Name string `json:"name" structs:"name" mapstructure:"name"` - - // Identifier of the cluster - ID string `json:"id" structs:"id" mapstructure:"id"` -} - -// Cluster fetches the details of the local cluster. This method errors out -// when Vault is sealed. -func (c *Core) Cluster(ctx context.Context) (*Cluster, error) { - var cluster Cluster - - // Fetch the storage entry. This call fails when Vault is sealed. - entry, err := c.barrier.Get(ctx, coreLocalClusterInfoPath) - if err != nil { - return nil, err - } - if entry == nil { - return &cluster, nil - } - - // Decode the cluster information - if err = jsonutil.DecodeJSON(entry.Value, &cluster); err != nil { - return nil, errwrap.Wrapf("failed to decode cluster details: {{err}}", err) - } - - // Set in config file - if c.clusterName != "" { - cluster.Name = c.clusterName - } - - return &cluster, nil -} - -// This sets our local cluster cert and private key based on the advertisement. -// It also ensures the cert is in our local cluster cert pool. -func (c *Core) loadLocalClusterTLS(adv activeAdvertisement) (retErr error) { - defer func() { - if retErr != nil { - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - } - }() - - switch { - case adv.ClusterAddr == "": - // Clustering disabled on the server, don't try to look for params - return nil - - case adv.ClusterKeyParams == nil: - c.logger.Error("no key params found loading local cluster TLS information") - return fmt.Errorf("no local cluster key params found") - - case adv.ClusterKeyParams.X == nil, adv.ClusterKeyParams.Y == nil, adv.ClusterKeyParams.D == nil: - c.logger.Error("failed to parse local cluster key due to missing params") - return fmt.Errorf("failed to parse local cluster key") - - case adv.ClusterKeyParams.Type != corePrivateKeyTypeP521: - c.logger.Error("unknown local cluster key type", "key_type", adv.ClusterKeyParams.Type) - return fmt.Errorf("failed to find valid local cluster key type") - - case adv.ClusterCert == nil || len(adv.ClusterCert) == 0: - c.logger.Error("no local cluster cert found") - return fmt.Errorf("no local cluster cert found") - - } - - c.localClusterPrivateKey.Store(&ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: adv.ClusterKeyParams.X, - Y: adv.ClusterKeyParams.Y, - }, - D: adv.ClusterKeyParams.D, - }) - - locCert := make([]byte, len(adv.ClusterCert)) - copy(locCert, adv.ClusterCert) - c.localClusterCert.Store(locCert) - - cert, err := x509.ParseCertificate(adv.ClusterCert) - if err != nil { - c.logger.Error("failed parsing local cluster certificate", "error", err) - return errwrap.Wrapf("error parsing local cluster certificate: {{err}}", err) - } - - c.localClusterParsedCert.Store(cert) - - return nil -} - -// setupCluster creates storage entries for holding Vault cluster information. -// Entries will be created only if they are not already present. If clusterName -// is not supplied, this method will auto-generate it. -func (c *Core) setupCluster(ctx context.Context) error { - // Prevent data races with the TLS parameters - c.clusterParamsLock.Lock() - defer c.clusterParamsLock.Unlock() - - // Check if storage index is already present or not - cluster, err := c.Cluster(ctx) - if err != nil { - c.logger.Error("failed to get cluster details", "error", err) - return err - } - - var modified bool - - if cluster == nil { - cluster = &Cluster{} - } - - if cluster.Name == "" { - // If cluster name is not supplied, generate one - if c.clusterName == "" { - c.logger.Debug("cluster name not found/set, generating new") - clusterNameBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - c.logger.Error("failed to generate cluster name", "error", err) - return err - } - - c.clusterName = fmt.Sprintf("vault-cluster-%08x", clusterNameBytes) - } - - cluster.Name = c.clusterName - if c.logger.IsDebug() { - c.logger.Debug("cluster name set", "name", cluster.Name) - } - modified = true - } - - if cluster.ID == "" { - c.logger.Debug("cluster ID not found, generating new") - // Generate a clusterID - cluster.ID, err = uuid.GenerateUUID() - if err != nil { - c.logger.Error("failed to generate cluster identifier", "error", err) - return err - } - if c.logger.IsDebug() { - c.logger.Debug("cluster ID set", "id", cluster.ID) - } - modified = true - } - - // If we're using HA, generate server-to-server parameters - if c.ha != nil { - // Create a private key - if c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey) == nil { - c.logger.Debug("generating cluster private key") - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - c.logger.Error("failed to generate local cluster key", "error", err) - return err - } - - c.localClusterPrivateKey.Store(key) - } - - // Create a certificate - if c.localClusterCert.Load().([]byte) == nil { - c.logger.Debug("generating local cluster certificate") - - host, err := uuid.GenerateUUID() - if err != nil { - return err - } - host = fmt.Sprintf("fw-%s", host) - template := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: host, - }, - DNSNames: []string{host}, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageServerAuth, - x509.ExtKeyUsageClientAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign, - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - // 30 years of single-active uptime ought to be enough for anybody - NotAfter: time.Now().Add(262980 * time.Hour), - BasicConstraintsValid: true, - IsCA: true, - } - - certBytes, err := x509.CreateCertificate(rand.Reader, template, template, c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey).Public(), c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey)) - if err != nil { - c.logger.Error("error generating self-signed cert", "error", err) - return errwrap.Wrapf("unable to generate local cluster certificate: {{err}}", err) - } - - parsedCert, err := x509.ParseCertificate(certBytes) - if err != nil { - c.logger.Error("error parsing self-signed cert", "error", err) - return errwrap.Wrapf("error parsing generated certificate: {{err}}", err) - } - - c.localClusterCert.Store(certBytes) - c.localClusterParsedCert.Store(parsedCert) - } - } - - if modified { - // Encode the cluster information into as a JSON string - rawCluster, err := json.Marshal(cluster) - if err != nil { - c.logger.Error("failed to encode cluster details", "error", err) - return err - } - - // Store it - err = c.barrier.Put(ctx, &Entry{ - Key: coreLocalClusterInfoPath, - Value: rawCluster, - }) - if err != nil { - c.logger.Error("failed to store cluster details", "error", err) - return err - } - } - - return nil -} - -// startClusterListener starts cluster request listeners during postunseal. It -// is assumed that the state lock is held while this is run. Right now this -// only starts forwarding listeners; it's TBD whether other request types will -// be built in the same mechanism or started independently. -func (c *Core) startClusterListener(ctx context.Context) error { - if c.clusterAddr == "" { - c.logger.Info("clustering disabled, not starting listeners") - return nil - } - - if c.clusterListenerAddrs == nil || len(c.clusterListenerAddrs) == 0 { - c.logger.Warn("clustering not disabled but no addresses to listen on") - return fmt.Errorf("cluster addresses not found") - } - - c.logger.Debug("starting cluster listeners") - - err := c.startForwarding(ctx) - if err != nil { - return err - } - - return nil -} - -// stopClusterListener stops any existing listeners during preseal. It is -// assumed that the state lock is held while this is run. -func (c *Core) stopClusterListener() { - if c.clusterAddr == "" { - - c.logger.Debug("clustering disabled, not stopping listeners") - return - } - - if !c.clusterListenersRunning { - c.logger.Info("cluster listeners not running") - return - } - c.logger.Info("stopping cluster listeners") - - // Tell the goroutine managing the listeners to perform the shutdown - // process - c.clusterListenerShutdownCh <- struct{}{} - - // The reason for this loop-de-loop is that we may be unsealing again - // quickly, and if the listeners are not yet closed, we will get socket - // bind errors. This ensures proper ordering. - - c.logger.Debug("waiting for success notification while stopping cluster listeners") - <-c.clusterListenerShutdownSuccessCh - c.clusterListenersRunning = false - - c.logger.Info("cluster listeners successfully shut down") -} - -// ClusterTLSConfig generates a TLS configuration based on the local/replicated -// cluster key and cert. -func (c *Core) ClusterTLSConfig(ctx context.Context, repClusters *ReplicatedClusters, perfStandbyCluster *ReplicatedCluster) (*tls.Config, error) { - // Using lookup functions allows just-in-time lookup of the current state - // of clustering as connections come and go - - tlsConfig := &tls.Config{ - ClientAuth: tls.RequireAndVerifyClientCert, - GetCertificate: clusterTLSServerLookup(ctx, c, repClusters, perfStandbyCluster), - GetClientCertificate: clusterTLSClientLookup(ctx, c, repClusters, perfStandbyCluster), - GetConfigForClient: clusterTLSServerConfigLookup(ctx, c, repClusters, perfStandbyCluster), - MinVersion: tls.VersionTLS12, - CipherSuites: c.clusterCipherSuites, - } - - parsedCert := c.localClusterParsedCert.Load().(*x509.Certificate) - currCert := c.localClusterCert.Load().([]byte) - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - if parsedCert != nil { - tlsConfig.ServerName = parsedCert.Subject.CommonName - - pool := x509.NewCertPool() - pool.AddCert(parsedCert) - tlsConfig.RootCAs = pool - tlsConfig.ClientCAs = pool - } - - return tlsConfig, nil -} - -func (c *Core) SetClusterListenerAddrs(addrs []*net.TCPAddr) { - c.clusterListenerAddrs = addrs - if c.clusterAddr == "" && len(addrs) == 1 { - c.clusterAddr = fmt.Sprintf("https://%s", addrs[0].String()) - } -} - -func (c *Core) SetClusterHandler(handler http.Handler) { - c.clusterHandler = handler -} diff --git a/vendor/github.com/hashicorp/vault/vault/cluster_tls.go b/vendor/github.com/hashicorp/vault/vault/cluster_tls.go deleted file mode 100644 index 4a63ecfa..00000000 --- a/vendor/github.com/hashicorp/vault/vault/cluster_tls.go +++ /dev/null @@ -1,85 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/tls" - "crypto/x509" - "fmt" -) - -var ( - clusterTLSServerLookup = func(ctx context.Context, c *Core, repClusters *ReplicatedClusters, _ *ReplicatedCluster) func(*tls.ClientHelloInfo) (*tls.Certificate, error) { - return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { - c.logger.Debug("performing server cert lookup") - - switch { - default: - currCert := c.localClusterCert.Load().([]byte) - if len(currCert) == 0 { - return nil, fmt.Errorf("got forwarding connection but no local cert") - } - - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - return &tls.Certificate{ - Certificate: [][]byte{localCert}, - PrivateKey: c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey), - Leaf: c.localClusterParsedCert.Load().(*x509.Certificate), - }, nil - } - } - } - - clusterTLSClientLookup = func(ctx context.Context, c *Core, repClusters *ReplicatedClusters, _ *ReplicatedCluster) func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { - return func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) { - if len(requestInfo.AcceptableCAs) != 1 { - return nil, fmt.Errorf("expected only a single acceptable CA") - } - - currCert := c.localClusterCert.Load().([]byte) - if len(currCert) == 0 { - return nil, fmt.Errorf("forwarding connection client but no local cert") - } - - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - return &tls.Certificate{ - Certificate: [][]byte{localCert}, - PrivateKey: c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey), - Leaf: c.localClusterParsedCert.Load().(*x509.Certificate), - }, nil - } - } - - clusterTLSServerConfigLookup = func(ctx context.Context, c *Core, repClusters *ReplicatedClusters, repCluster *ReplicatedCluster) func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) { - return func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) { - //c.logger.Trace("performing server config lookup") - - caPool := x509.NewCertPool() - - ret := &tls.Config{ - ClientAuth: tls.RequireAndVerifyClientCert, - GetCertificate: clusterTLSServerLookup(ctx, c, repClusters, repCluster), - GetClientCertificate: clusterTLSClientLookup(ctx, c, repClusters, repCluster), - MinVersion: tls.VersionTLS12, - RootCAs: caPool, - ClientCAs: caPool, - NextProtos: clientHello.SupportedProtos, - CipherSuites: c.clusterCipherSuites, - } - - parsedCert := c.localClusterParsedCert.Load().(*x509.Certificate) - - if parsedCert == nil { - return nil, fmt.Errorf("forwarding connection client but no local cert") - } - - caPool.AddCert(parsedCert) - - return ret, nil - } - } -) diff --git a/vendor/github.com/hashicorp/vault/vault/core.go b/vendor/github.com/hashicorp/vault/vault/core.go deleted file mode 100644 index 90cc8d56..00000000 --- a/vendor/github.com/hashicorp/vault/vault/core.go +++ /dev/null @@ -1,1713 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "path/filepath" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - "github.com/patrickmn/go-cache" - - "google.golang.org/grpc" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/mlock" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/reload" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/shamir" -) - -const ( - // CoreLockPath is the path used to acquire a coordinating lock - // for a highly-available deploy. - CoreLockPath = "core/lock" - - // The poison pill is used as a check during certain scenarios to indicate - // to standby nodes that they should seal - poisonPillPath = "core/poison-pill" - - // coreLeaderPrefix is the prefix used for the UUID that contains - // the currently elected leader. - coreLeaderPrefix = "core/leader/" - - // knownPrimaryAddrsPrefix is used to store last-known cluster address - // information for primaries - knownPrimaryAddrsPrefix = "core/primary-addrs/" - - // coreKeyringCanaryPath is used as a canary to indicate to replicated - // clusters that they need to perform a rekey operation synchronously; this - // isn't keyring-canary to avoid ignoring it when ignoring core/keyring - coreKeyringCanaryPath = "core/canary-keyring" -) - -var ( - // ErrAlreadyInit is returned if the core is already - // initialized. This prevents a re-initialization. - ErrAlreadyInit = errors.New("Vault is already initialized") - - // ErrNotInit is returned if a non-initialized barrier - // is attempted to be unsealed. - ErrNotInit = errors.New("Vault is not initialized") - - // ErrInternalError is returned when we don't want to leak - // any information about an internal error - ErrInternalError = errors.New("internal error") - - // ErrHANotEnabled is returned if the operation only makes sense - // in an HA setting - ErrHANotEnabled = errors.New("Vault is not configured for highly-available mode") - - // manualStepDownSleepPeriod is how long to sleep after a user-initiated - // step down of the active node, to prevent instantly regrabbing the lock. - // It's var not const so that tests can manipulate it. - manualStepDownSleepPeriod = 10 * time.Second - - // Functions only in the Enterprise version - enterprisePostUnseal = enterprisePostUnsealImpl - enterprisePreSeal = enterprisePreSealImpl - startReplication = startReplicationImpl - stopReplication = stopReplicationImpl - LastWAL = lastWALImpl - LastRemoteWAL = lastRemoteWALImpl - WaitUntilWALShipped = waitUntilWALShippedImpl -) - -// NonFatalError is an error that can be returned during NewCore that should be -// displayed but not cause a program exit -type NonFatalError struct { - Err error -} - -func (e *NonFatalError) WrappedErrors() []error { - return []error{e.Err} -} - -func (e *NonFatalError) Error() string { - return e.Err.Error() -} - -// ErrInvalidKey is returned if there is a user-based error with a provided -// unseal key. This will be shown to the user, so should not contain -// information that is sensitive. -type ErrInvalidKey struct { - Reason string -} - -func (e *ErrInvalidKey) Error() string { - return fmt.Sprintf("invalid key: %v", e.Reason) -} - -type RegisterAuthFunc func(context.Context, time.Duration, string, *logical.Auth) error - -type activeAdvertisement struct { - RedirectAddr string `json:"redirect_addr"` - ClusterAddr string `json:"cluster_addr,omitempty"` - ClusterCert []byte `json:"cluster_cert,omitempty"` - ClusterKeyParams *clusterKeyParams `json:"cluster_key_params,omitempty"` -} - -type unlockInformation struct { - Parts [][]byte - Nonce string -} - -// Core is used as the central manager of Vault activity. It is the primary point of -// interface for API handlers and is responsible for managing the logical and physical -// backends, router, security barrier, and audit trails. -type Core struct { - entCore - - // The registry of builtin plugins is passed in here as an interface because - // if it's used directly, it results in import cycles. - builtinRegistry BuiltinRegistry - - // N.B.: This is used to populate a dev token down replication, as - // otherwise, after replication is started, a dev would have to go through - // the generate-root process simply to talk to the new follower cluster. - devToken string - - // HABackend may be available depending on the physical backend - ha physical.HABackend - - // redirectAddr is the address we advertise as leader if held - redirectAddr string - - // clusterAddr is the address we use for clustering - clusterAddr string - - // physical backend is the un-trusted backend with durable data - physical physical.Backend - - // seal is our seal, for seal configuration information - seal Seal - - // migrationSeal is the seal to use during a migration operation. It is the - // seal we're migrating *from*. - migrationSeal Seal - - // barrier is the security barrier wrapping the physical backend - barrier SecurityBarrier - - // router is responsible for managing the mount points for logical backends. - router *Router - - // logicalBackends is the mapping of backends to use for this core - logicalBackends map[string]logical.Factory - - // credentialBackends is the mapping of backends to use for this core - credentialBackends map[string]logical.Factory - - // auditBackends is the mapping of backends to use for this core - auditBackends map[string]audit.Factory - - // stateLock protects mutable state - stateLock sync.RWMutex - sealed *uint32 - - standby bool - perfStandby bool - standbyDoneCh chan struct{} - standbyStopCh chan struct{} - manualStepDownCh chan struct{} - keepHALockOnStepDown *uint32 - heldHALock physical.Lock - - // unlockInfo has the keys provided to Unseal until the threshold number of parts is available, as well as the operation nonce - unlockInfo *unlockInformation - - // generateRootProgress holds the shares until we reach enough - // to verify the master key - generateRootConfig *GenerateRootConfig - generateRootProgress [][]byte - generateRootLock sync.Mutex - - // These variables holds the config and shares we have until we reach - // enough to verify the appropriate master key. Note that the same lock is - // used; this isn't time-critical so this shouldn't be a problem. - barrierRekeyConfig *SealConfig - recoveryRekeyConfig *SealConfig - rekeyLock sync.RWMutex - - // mounts is loaded after unseal since it is a protected - // configuration - mounts *MountTable - - // mountsLock is used to ensure that the mounts table does not - // change underneath a calling function - mountsLock sync.RWMutex - - // auth is loaded after unseal since it is a protected - // configuration - auth *MountTable - - // authLock is used to ensure that the auth table does not - // change underneath a calling function - authLock sync.RWMutex - - // audit is loaded after unseal since it is a protected - // configuration - audit *MountTable - - // auditLock is used to ensure that the audit table does not - // change underneath a calling function - auditLock sync.RWMutex - - // auditBroker is used to ingest the audit events and fan - // out into the configured audit backends - auditBroker *AuditBroker - - // auditedHeaders is used to configure which http headers - // can be output in the audit logs - auditedHeaders *AuditedHeadersConfig - - // systemBackend is the backend which is used to manage internal operations - systemBackend *SystemBackend - - // cubbyholeBackend is the backend which manages the per-token storage - cubbyholeBackend *CubbyholeBackend - - // systemBarrierView is the barrier view for the system backend - systemBarrierView *BarrierView - - // expiration manager is used for managing LeaseIDs, - // renewal, expiration and revocation - expiration *ExpirationManager - - // rollback manager is used to run rollbacks periodically - rollback *RollbackManager - - // policy store is used to manage named ACL policies - policyStore *PolicyStore - - // token store is used to manage authentication tokens - tokenStore *TokenStore - - // identityStore is used to manage client entities - identityStore *IdentityStore - - // metricsCh is used to stop the metrics streaming - metricsCh chan struct{} - - // metricsMutex is used to prevent a race condition between - // metrics emission and sealing leading to a nil pointer - metricsMutex sync.Mutex - - defaultLeaseTTL time.Duration - maxLeaseTTL time.Duration - - // baseLogger is used to avoid ResetNamed as it strips useful prefixes in - // e.g. testing - baseLogger log.Logger - logger log.Logger - - // cachingDisabled indicates whether caches are disabled - cachingDisabled bool - // Cache stores the actual cache; we always have this but may bypass it if - // disabled - physicalCache physical.ToggleablePurgemonster - - // reloadFuncs is a map containing reload functions - reloadFuncs map[string][]reload.ReloadFunc - - // reloadFuncsLock controls access to the funcs - reloadFuncsLock sync.RWMutex - - // wrappingJWTKey is the key used for generating JWTs containing response - // wrapping information - wrappingJWTKey *ecdsa.PrivateKey - - // - // Cluster information - // - // Name - clusterName string - // Specific cipher suites to use for clustering, if any - clusterCipherSuites []uint16 - // Used to modify cluster parameters - clusterParamsLock sync.RWMutex - // The private key stored in the barrier used for establishing - // mutually-authenticated connections between Vault cluster members - localClusterPrivateKey *atomic.Value - // The local cluster cert - localClusterCert *atomic.Value - // The parsed form of the local cluster cert - localClusterParsedCert *atomic.Value - // The TCP addresses we should use for clustering - clusterListenerAddrs []*net.TCPAddr - // The handler to use for request forwarding - clusterHandler http.Handler - // Tracks whether cluster listeners are running, e.g. it's safe to send a - // shutdown down the channel - clusterListenersRunning bool - // Shutdown channel for the cluster listeners - clusterListenerShutdownCh chan struct{} - // Shutdown success channel. We need this to be done serially to ensure - // that binds are removed before they might be reinstated. - clusterListenerShutdownSuccessCh chan struct{} - // Write lock used to ensure that we don't have multiple connections adjust - // this value at the same time - requestForwardingConnectionLock sync.RWMutex - // Most recent leader UUID. Used to avoid repeatedly JSON parsing the same - // values. - clusterLeaderUUID string - // Most recent leader redirect addr - clusterLeaderRedirectAddr string - // Most recent leader cluster addr - clusterLeaderClusterAddr string - // Lock for the cluster leader values - clusterLeaderParamsLock sync.RWMutex - // Info on cluster members - clusterPeerClusterAddrsCache *cache.Cache - // Stores whether we currently have a server running - rpcServerActive *uint32 - // The context for the client - rpcClientConnContext context.Context - // The function for canceling the client connection - rpcClientConnCancelFunc context.CancelFunc - // The grpc ClientConn for RPC calls - rpcClientConn *grpc.ClientConn - // The grpc forwarding client - rpcForwardingClient *forwardingClient - - // CORS Information - corsConfig *CORSConfig - - // The active set of upstream cluster addresses; stored via the Echo - // mechanism, loaded by the balancer - atomicPrimaryClusterAddrs *atomic.Value - - atomicPrimaryFailoverAddrs *atomic.Value - - // replicationState keeps the current replication state cached for quick - // lookup; activeNodeReplicationState stores the active value on standbys - replicationState *uint32 - activeNodeReplicationState *uint32 - - // uiConfig contains UI configuration - uiConfig *UIConfig - - // rawEnabled indicates whether the Raw endpoint is enabled - rawEnabled bool - - // pluginDirectory is the location vault will look for plugin binaries - pluginDirectory string - - // pluginCatalog is used to manage plugin configurations - pluginCatalog *PluginCatalog - - enableMlock bool - - // This can be used to trigger operations to stop running when Vault is - // going to be shut down, stepped down, or sealed - activeContext context.Context - activeContextCancelFunc *atomic.Value - - // Stores the sealunwrapper for downgrade needs - sealUnwrapper physical.Backend - - // Stores any funcs that should be run on successful postUnseal - postUnsealFuncs []func() - - // replicationFailure is used to mark when replication has entered an - // unrecoverable failure. - replicationFailure *uint32 - - // disablePerfStanby is used to tell a standby not to attempt to become a - // perf standby - disablePerfStandby bool - - licensingStopCh chan struct{} - - // Stores loggers so we can reset the level - allLoggers []log.Logger - allLoggersLock sync.RWMutex -} - -// CoreConfig is used to parameterize a core -type CoreConfig struct { - DevToken string `json:"dev_token" structs:"dev_token" mapstructure:"dev_token"` - - BuiltinRegistry BuiltinRegistry `json:"builtin_registry" structs:"builtin_registry" mapstructure:"builtin_registry"` - - LogicalBackends map[string]logical.Factory `json:"logical_backends" structs:"logical_backends" mapstructure:"logical_backends"` - - CredentialBackends map[string]logical.Factory `json:"credential_backends" structs:"credential_backends" mapstructure:"credential_backends"` - - AuditBackends map[string]audit.Factory `json:"audit_backends" structs:"audit_backends" mapstructure:"audit_backends"` - - Physical physical.Backend `json:"physical" structs:"physical" mapstructure:"physical"` - - // May be nil, which disables HA operations - HAPhysical physical.HABackend `json:"ha_physical" structs:"ha_physical" mapstructure:"ha_physical"` - - Seal Seal `json:"seal" structs:"seal" mapstructure:"seal"` - - Logger log.Logger `json:"logger" structs:"logger" mapstructure:"logger"` - - // Disables the LRU cache on the physical backend - DisableCache bool `json:"disable_cache" structs:"disable_cache" mapstructure:"disable_cache"` - - // Disables mlock syscall - DisableMlock bool `json:"disable_mlock" structs:"disable_mlock" mapstructure:"disable_mlock"` - - // Custom cache size for the LRU cache on the physical backend, or zero for default - CacheSize int `json:"cache_size" structs:"cache_size" mapstructure:"cache_size"` - - // Set as the leader address for HA - RedirectAddr string `json:"redirect_addr" structs:"redirect_addr" mapstructure:"redirect_addr"` - - // Set as the cluster address for HA - ClusterAddr string `json:"cluster_addr" structs:"cluster_addr" mapstructure:"cluster_addr"` - - DefaultLeaseTTL time.Duration `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` - - MaxLeaseTTL time.Duration `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` - - ClusterName string `json:"cluster_name" structs:"cluster_name" mapstructure:"cluster_name"` - - ClusterCipherSuites string `json:"cluster_cipher_suites" structs:"cluster_cipher_suites" mapstructure:"cluster_cipher_suites"` - - EnableUI bool `json:"ui" structs:"ui" mapstructure:"ui"` - - // Enable the raw endpoint - EnableRaw bool `json:"enable_raw" structs:"enable_raw" mapstructure:"enable_raw"` - - PluginDirectory string `json:"plugin_directory" structs:"plugin_directory" mapstructure:"plugin_directory"` - - DisableSealWrap bool `json:"disable_sealwrap" structs:"disable_sealwrap" mapstructure:"disable_sealwrap"` - - ReloadFuncs *map[string][]reload.ReloadFunc - ReloadFuncsLock *sync.RWMutex - - // Licensing - LicensingConfig *LicensingConfig - // Don't set this unless in dev mode, ideally only when using inmem - DevLicenseDuration time.Duration - - DisablePerformanceStandby bool - DisableIndexing bool - DisableKeyEncodingChecks bool - - AllLoggers []log.Logger -} - -func (c *CoreConfig) Clone() *CoreConfig { - return &CoreConfig{ - DevToken: c.DevToken, - LogicalBackends: c.LogicalBackends, - CredentialBackends: c.CredentialBackends, - AuditBackends: c.AuditBackends, - Physical: c.Physical, - HAPhysical: c.HAPhysical, - Seal: c.Seal, - Logger: c.Logger, - DisableCache: c.DisableCache, - DisableMlock: c.DisableMlock, - CacheSize: c.CacheSize, - RedirectAddr: c.RedirectAddr, - ClusterAddr: c.ClusterAddr, - DefaultLeaseTTL: c.DefaultLeaseTTL, - MaxLeaseTTL: c.MaxLeaseTTL, - ClusterName: c.ClusterName, - ClusterCipherSuites: c.ClusterCipherSuites, - EnableUI: c.EnableUI, - EnableRaw: c.EnableRaw, - PluginDirectory: c.PluginDirectory, - DisableSealWrap: c.DisableSealWrap, - ReloadFuncs: c.ReloadFuncs, - ReloadFuncsLock: c.ReloadFuncsLock, - LicensingConfig: c.LicensingConfig, - DevLicenseDuration: c.DevLicenseDuration, - DisablePerformanceStandby: c.DisablePerformanceStandby, - DisableIndexing: c.DisableIndexing, - AllLoggers: c.AllLoggers, - } -} - -// NewCore is used to construct a new core -func NewCore(conf *CoreConfig) (*Core, error) { - if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() { - if conf.RedirectAddr == "" { - return nil, fmt.Errorf("missing API address, please set in configuration or via environment") - } - } - - if conf.DefaultLeaseTTL == 0 { - conf.DefaultLeaseTTL = defaultLeaseTTL - } - if conf.MaxLeaseTTL == 0 { - conf.MaxLeaseTTL = maxLeaseTTL - } - if conf.DefaultLeaseTTL > conf.MaxLeaseTTL { - return nil, fmt.Errorf("cannot have DefaultLeaseTTL larger than MaxLeaseTTL") - } - - // Validate the advertise addr if its given to us - if conf.RedirectAddr != "" { - u, err := url.Parse(conf.RedirectAddr) - if err != nil { - return nil, errwrap.Wrapf("redirect address is not valid url: {{err}}", err) - } - - if u.Scheme == "" { - return nil, fmt.Errorf("redirect address must include scheme (ex. 'http')") - } - } - - // Make a default logger if not provided - if conf.Logger == nil { - conf.Logger = logging.NewVaultLogger(log.Trace) - } - - // Setup the core - c := &Core{ - entCore: entCore{}, - devToken: conf.DevToken, - physical: conf.Physical, - redirectAddr: conf.RedirectAddr, - clusterAddr: conf.ClusterAddr, - seal: conf.Seal, - router: NewRouter(), - sealed: new(uint32), - standby: true, - baseLogger: conf.Logger, - logger: conf.Logger.Named("core"), - defaultLeaseTTL: conf.DefaultLeaseTTL, - maxLeaseTTL: conf.MaxLeaseTTL, - cachingDisabled: conf.DisableCache, - clusterName: conf.ClusterName, - clusterListenerShutdownCh: make(chan struct{}), - clusterListenerShutdownSuccessCh: make(chan struct{}), - clusterPeerClusterAddrsCache: cache.New(3*HeartbeatInterval, time.Second), - enableMlock: !conf.DisableMlock, - rawEnabled: conf.EnableRaw, - replicationState: new(uint32), - rpcServerActive: new(uint32), - atomicPrimaryClusterAddrs: new(atomic.Value), - atomicPrimaryFailoverAddrs: new(atomic.Value), - localClusterPrivateKey: new(atomic.Value), - localClusterCert: new(atomic.Value), - localClusterParsedCert: new(atomic.Value), - activeNodeReplicationState: new(uint32), - keepHALockOnStepDown: new(uint32), - replicationFailure: new(uint32), - disablePerfStandby: true, - activeContextCancelFunc: new(atomic.Value), - allLoggers: conf.AllLoggers, - builtinRegistry: conf.BuiltinRegistry, - } - - atomic.StoreUint32(c.sealed, 1) - c.allLoggers = append(c.allLoggers, c.logger) - - atomic.StoreUint32(c.replicationState, uint32(consts.ReplicationDRDisabled|consts.ReplicationPerformanceDisabled)) - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - c.activeContextCancelFunc.Store((context.CancelFunc)(nil)) - - if conf.ClusterCipherSuites != "" { - suites, err := tlsutil.ParseCiphers(conf.ClusterCipherSuites) - if err != nil { - return nil, errwrap.Wrapf("error parsing cluster cipher suites: {{err}}", err) - } - c.clusterCipherSuites = suites - } - - // Load CORS config and provide a value for the core field. - c.corsConfig = &CORSConfig{ - core: c, - Enabled: new(uint32), - } - - if c.seal == nil { - c.seal = NewDefaultSeal() - } - c.seal.SetCore(c) - - if err := coreInit(c, conf); err != nil { - return nil, err - } - - if !conf.DisableMlock { - // Ensure our memory usage is locked into physical RAM - if err := mlock.LockMemory(); err != nil { - return nil, fmt.Errorf( - "Failed to lock memory: %v\n\n"+ - "This usually means that the mlock syscall is not available.\n"+ - "Vault uses mlock to prevent memory from being swapped to\n"+ - "disk. This requires root privileges as well as a machine\n"+ - "that supports mlock. Please enable mlock on your system or\n"+ - "disable Vault from using it. To disable Vault from using it,\n"+ - "set the `disable_mlock` configuration option in your configuration\n"+ - "file.", - err) - } - } - - var err error - - if conf.PluginDirectory != "" { - c.pluginDirectory, err = filepath.Abs(conf.PluginDirectory) - if err != nil { - return nil, errwrap.Wrapf("core setup failed, could not verify plugin directory: {{err}}", err) - } - } - - // Construct a new AES-GCM barrier - c.barrier, err = NewAESGCMBarrier(c.physical) - if err != nil { - return nil, errwrap.Wrapf("barrier setup failed: {{err}}", err) - } - - createSecondaries(c, conf) - - if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() { - c.ha = conf.HAPhysical - } - - // We create the funcs here, then populate the given config with it so that - // the caller can share state - conf.ReloadFuncsLock = &c.reloadFuncsLock - c.reloadFuncsLock.Lock() - c.reloadFuncs = make(map[string][]reload.ReloadFunc) - c.reloadFuncsLock.Unlock() - conf.ReloadFuncs = &c.reloadFuncs - - logicalBackends := make(map[string]logical.Factory) - for k, f := range conf.LogicalBackends { - logicalBackends[k] = f - } - _, ok := logicalBackends["kv"] - if !ok { - logicalBackends["kv"] = PassthroughBackendFactory - } - - logicalBackends["cubbyhole"] = CubbyholeBackendFactory - logicalBackends[systemMountType] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - sysBackendLogger := conf.Logger.Named("system") - c.AddLogger(sysBackendLogger) - b := NewSystemBackend(c, sysBackendLogger) - if err := b.Setup(ctx, config); err != nil { - return nil, err - } - return b, nil - } - logicalBackends["identity"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - identityLogger := conf.Logger.Named("identity") - c.AddLogger(identityLogger) - return NewIdentityStore(ctx, c, config, identityLogger) - } - addExtraLogicalBackends(c, logicalBackends) - c.logicalBackends = logicalBackends - - credentialBackends := make(map[string]logical.Factory) - for k, f := range conf.CredentialBackends { - credentialBackends[k] = f - } - credentialBackends["token"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - tsLogger := conf.Logger.Named("token") - c.AddLogger(tsLogger) - return NewTokenStore(ctx, tsLogger, c, config) - } - addExtraCredentialBackends(c, credentialBackends) - c.credentialBackends = credentialBackends - - auditBackends := make(map[string]audit.Factory) - for k, f := range conf.AuditBackends { - auditBackends[k] = f - } - c.auditBackends = auditBackends - - uiStoragePrefix := systemBarrierPrefix + "ui" - c.uiConfig = NewUIConfig(conf.EnableUI, physical.NewView(c.physical, uiStoragePrefix), NewBarrierView(c.barrier, uiStoragePrefix)) - - return c, nil -} - -// Shutdown is invoked when the Vault instance is about to be terminated. It -// should not be accessible as part of an API call as it will cause an availability -// problem. It is only used to gracefully quit in the case of HA so that failover -// happens as quickly as possible. -func (c *Core) Shutdown() error { - c.logger.Debug("shutdown called") - return c.sealInternal() -} - -// CORSConfig returns the current CORS configuration -func (c *Core) CORSConfig() *CORSConfig { - return c.corsConfig -} - -func (c *Core) GetContext() (context.Context, context.CancelFunc) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - - return context.WithCancel(namespace.RootContext(c.activeContext)) -} - -// Sealed checks if the Vault is current sealed -func (c *Core) Sealed() bool { - return atomic.LoadUint32(c.sealed) == 1 -} - -// SecretProgress returns the number of keys provided so far -func (c *Core) SecretProgress() (int, string) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - switch c.unlockInfo { - case nil: - return 0, "" - default: - return len(c.unlockInfo.Parts), c.unlockInfo.Nonce - } -} - -// ResetUnsealProcess removes the current unlock parts from memory, to reset -// the unsealing process -func (c *Core) ResetUnsealProcess() { - c.stateLock.Lock() - defer c.stateLock.Unlock() - c.unlockInfo = nil -} - -// Unseal is used to provide one of the key parts to unseal the Vault. -// -// They key given as a parameter will automatically be zerod after -// this method is done with it. If you want to keep the key around, a copy -// should be made. -func (c *Core) Unseal(key []byte) (bool, error) { - return c.unseal(key, false) -} - -func (c *Core) UnsealWithRecoveryKeys(key []byte) (bool, error) { - return c.unseal(key, true) -} - -func (c *Core) unseal(key []byte, useRecoveryKeys bool) (bool, error) { - defer metrics.MeasureSince([]string{"core", "unseal"}, time.Now()) - - c.stateLock.Lock() - defer c.stateLock.Unlock() - - ctx := context.Background() - - // Explicitly check for init status. This also checks if the seal - // configuration is valid (i.e. non-nil). - init, err := c.Initialized(ctx) - if err != nil { - return false, err - } - if !init { - return false, ErrNotInit - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return false, &ErrInvalidKey{fmt.Sprintf("key is shorter than minimum %d bytes", min)} - } - if len(key) > max { - return false, &ErrInvalidKey{fmt.Sprintf("key is longer than maximum %d bytes", max)} - } - - // Check if already unsealed - if !c.Sealed() { - return true, nil - } - - sealToUse := c.seal - if c.migrationSeal != nil { - sealToUse = c.migrationSeal - } - - masterKey, err := c.unsealPart(ctx, sealToUse, key, useRecoveryKeys) - if err != nil { - return false, err - } - if masterKey != nil { - return c.unsealInternal(ctx, masterKey) - } - - return false, nil -} - -// unsealPart takes in a key share, and returns the master key if the threshold -// is met. If recovery keys are supported, recovery key shares may be provided. -func (c *Core) unsealPart(ctx context.Context, seal Seal, key []byte, useRecoveryKeys bool) ([]byte, error) { - // Check if we already have this piece - if c.unlockInfo != nil { - for _, existing := range c.unlockInfo.Parts { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, nil - } - } - } else { - uuid, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - c.unlockInfo = &unlockInformation{ - Nonce: uuid, - } - } - - // Store this key - c.unlockInfo.Parts = append(c.unlockInfo.Parts, key) - - var config *SealConfig - var err error - if seal.RecoveryKeySupported() && (useRecoveryKeys || c.migrationSeal != nil) { - config, err = seal.RecoveryConfig(ctx) - } else { - config, err = seal.BarrierConfig(ctx) - } - if err != nil { - return nil, err - } - - // Check if we don't have enough keys to unlock, proceed through the rest of - // the call only if we have met the threshold - if len(c.unlockInfo.Parts) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot unseal, not enough keys", "keys", len(c.unlockInfo.Parts), "threshold", config.SecretThreshold, "nonce", c.unlockInfo.Nonce) - } - return nil, nil - } - - // Best-effort memzero of unlock parts once we're done with them - defer func() { - for i := range c.unlockInfo.Parts { - memzero(c.unlockInfo.Parts[i]) - } - c.unlockInfo = nil - }() - - // Recover the split key. recoveredKey is the shamir combined - // key, or the single provided key if the threshold is 1. - var recoveredKey []byte - var masterKey []byte - var recoveryKey []byte - if config.SecretThreshold == 1 { - recoveredKey = make([]byte, len(c.unlockInfo.Parts[0])) - copy(recoveredKey, c.unlockInfo.Parts[0]) - } else { - recoveredKey, err = shamir.Combine(c.unlockInfo.Parts) - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - - if seal.RecoveryKeySupported() && (useRecoveryKeys || c.migrationSeal != nil) { - // Verify recovery key - if err := seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil { - return nil, err - } - recoveryKey = recoveredKey - - // Get stored keys and shamir combine into single master key. Unsealing with - // recovery keys currently does not support: 1) mixed stored and non-stored - // keys setup, nor 2) seals that support recovery keys but not stored keys. - // If insufficient shares are provided, shamir.Combine will error, and if - // no stored keys are found it will return masterKey as nil. - if seal.StoredKeysSupported() { - masterKeyShares, err := seal.GetStoredKeys(ctx) - if err != nil { - return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err) - } - - if len(masterKeyShares) == 1 { - masterKey = masterKeyShares[0] - } else { - masterKey, err = shamir.Combine(masterKeyShares) - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - } - } else { - masterKey = recoveredKey - } - - // If we have a migration seal, now's the time! - if c.migrationSeal != nil { - // Unseal the barrier so we can rekey - if err := c.barrier.Unseal(ctx, masterKey); err != nil { - return nil, errwrap.Wrapf("error unsealing barrier with constructed master key: {{err}}", err) - } - defer c.barrier.Seal() - - // The seal used in this function will have been the migration seal, - // and c.seal will be the opposite type, so there are two - // possibilities: Shamir to auto, and auto to Shamir. - if !seal.RecoveryKeySupported() { - // The new seal will have recovery keys; we set it to the existing - // master key, so barrier key shares -> recovery key shares - if err := c.seal.SetRecoveryKey(ctx, masterKey); err != nil { - return nil, errwrap.Wrapf("error setting new recovery key information: {{err}}", err) - } - - // Generate a new master key - newMasterKey, err := c.barrier.GenerateKey() - if err != nil { - return nil, errwrap.Wrapf("error generating new master key: {{err}}", err) - } - - // Rekey the barrier - if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { - return nil, errwrap.Wrapf("error rekeying barrier during migration: {{err}}", err) - } - - // Store the new master key - if err := c.seal.SetStoredKeys(ctx, [][]byte{newMasterKey}); err != nil { - return nil, errwrap.Wrapf("error storing new master key: {[err}}", err) - } - - // Return the new key so it can be used to unlock the barrier - masterKey = newMasterKey - } else { - // In this case we have to ensure that the recovery information was - // set properly. - if recoveryKey == nil { - return nil, errors.New("did not get expected recovery information to set new seal during migration") - } - - // Auto to Shamir. We have recovery keys; we're going to use them - // as the new barrier key - if err := c.barrier.Rekey(ctx, recoveryKey); err != nil { - return nil, errwrap.Wrapf("error rekeying barrier during migration: {{err}}", err) - } - - if err := c.barrier.Delete(ctx, StoredBarrierKeysPath); err != nil { - // Don't actually exit here as successful deletion isn't critical - c.logger.Error("error deleting stored barrier keys after migration; continuing anyways", "error", err) - } - - masterKey = recoveryKey - } - - // At this point we've swapped things around and need to ensure we - // don't migrate again - c.migrationSeal = nil - - // Ensure we populate the new values - bc, err := c.seal.BarrierConfig(ctx) - if err != nil { - return nil, errwrap.Wrapf("error fetching barrier config after migration: {{err}}", err) - } - if err := c.seal.SetBarrierConfig(ctx, bc); err != nil { - return nil, errwrap.Wrapf("error storing barrier config after migration: {{err}}", err) - } - - if c.seal.RecoveryKeySupported() { - rc, err := c.seal.RecoveryConfig(ctx) - if err != nil { - return nil, errwrap.Wrapf("error fetching recovery config after migration: {{err}}", err) - } - if err := c.seal.SetRecoveryConfig(ctx, rc); err != nil { - return nil, errwrap.Wrapf("error storing recovery config after migration: {{err}}", err) - } - } - } - - return masterKey, nil -} - -// unsealInternal takes in the master key and attempts to unseal the barrier. -// N.B.: This must be called with the state write lock held. -func (c *Core) unsealInternal(ctx context.Context, masterKey []byte) (bool, error) { - defer memzero(masterKey) - - // Attempt to unlock - if err := c.barrier.Unseal(ctx, masterKey); err != nil { - return false, err - } - if c.logger.IsInfo() { - c.logger.Info("vault is unsealed") - } - - if err := preUnsealInternal(ctx, c); err != nil { - return false, err - } - - // Do post-unseal setup if HA is not enabled - if c.ha == nil { - // We still need to set up cluster info even if it's not part of a - // cluster right now. This also populates the cached cluster object. - if err := c.setupCluster(ctx); err != nil { - c.logger.Error("cluster setup failed", "error", err) - c.barrier.Seal() - c.logger.Warn("vault is sealed") - return false, err - } - - ctx, ctxCancel := context.WithCancel(namespace.RootContext(nil)) - if err := c.postUnseal(ctx, ctxCancel, standardUnsealStrategy{}); err != nil { - c.logger.Error("post-unseal setup failed", "error", err) - c.barrier.Seal() - c.logger.Warn("vault is sealed") - return false, err - } - - c.standby = false - } else { - // Go to standby mode, wait until we are active to unseal - c.standbyDoneCh = make(chan struct{}) - c.manualStepDownCh = make(chan struct{}) - c.standbyStopCh = make(chan struct{}) - go c.runStandby(c.standbyDoneCh, c.manualStepDownCh, c.standbyStopCh) - } - - // Force a cache bust here, which will also run migration code - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(ctx, nil) - } - - // Success! - atomic.StoreUint32(c.sealed, 0) - - if c.ha != nil { - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifySealedStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify unsealed status", "error", err) - } - } - } - } - return true, nil -} - -// SealWithRequest takes in a logical.Request, acquires the lock, and passes -// through to sealInternal -func (c *Core) SealWithRequest(httpCtx context.Context, req *logical.Request) error { - defer metrics.MeasureSince([]string{"core", "seal-with-request"}, time.Now()) - - if c.Sealed() { - return nil - } - - c.stateLock.RLock() - - // This will unlock the read lock - // We use background context since we may not be active - ctx, cancel := context.WithCancel(namespace.RootContext(nil)) - defer cancel() - - go func() { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }() - - // This will unlock the read lock - return c.sealInitCommon(ctx, req) -} - -// Seal takes in a token and creates a logical.Request, acquires the lock, and -// passes through to sealInternal -func (c *Core) Seal(token string) error { - defer metrics.MeasureSince([]string{"core", "seal"}, time.Now()) - - if c.Sealed() { - return nil - } - - c.stateLock.RLock() - - req := &logical.Request{ - Operation: logical.UpdateOperation, - Path: "sys/seal", - ClientToken: token, - } - - // This will unlock the read lock - // We use background context since we may not be active - return c.sealInitCommon(namespace.RootContext(nil), req) -} - -// sealInitCommon is common logic for Seal and SealWithRequest and is used to -// re-seal the Vault. This requires the Vault to be unsealed again to perform -// any further operations. Note: this function will read-unlock the state lock. -func (c *Core) sealInitCommon(ctx context.Context, req *logical.Request) (retErr error) { - defer metrics.MeasureSince([]string{"core", "seal-internal"}, time.Now()) - - if req == nil { - retErr = multierror.Append(retErr, errors.New("nil request to seal")) - c.stateLock.RUnlock() - return retErr - } - - // Since there is no token store in standby nodes, sealing cannot be done. - // Ideally, the request has to be forwarded to leader node for validation - // and the operation should be performed. But for now, just returning with - // an error and recommending a vault restart, which essentially does the - // same thing. - if c.standby { - c.logger.Error("vault cannot seal when in standby mode; please restart instead") - retErr = multierror.Append(retErr, errors.New("vault cannot seal when in standby mode; please restart instead")) - c.stateLock.RUnlock() - return retErr - } - - acl, te, entity, identityPolicies, err := c.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - retErr = multierror.Append(retErr, err) - c.stateLock.RUnlock() - return retErr - } - - req.SetTokenEntry(te) - - // Audit-log the request before going any further - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Accessor: req.ClientTokenAccessor, - } - if te != nil { - auth.IdentityPolicies = identityPolicies[te.NamespaceID] - delete(identityPolicies, te.NamespaceID) - auth.ExternalNamespacePolicies = identityPolicies - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies[te.NamespaceID]...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - auth.TokenType = te.Type - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, errors.New("failed to audit request, cannot continue")) - c.stateLock.RUnlock() - return retErr - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - // Attempt to use the token (decrement num_uses) - // On error bail out; if the token has been revoked, bail out too - if te != nil { - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - c.stateLock.RUnlock() - return retErr - } - if te == nil { - // Token is no longer valid - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - } - - // Verify that this operation is allowed - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - RootPrivsRequired: true, - }) - if !authResults.Allowed { - c.stateLock.RUnlock() - retErr = multierror.Append(retErr, authResults.Error) - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return retErr - } - - if te != nil && te.NumUses == tokenRevocationPending { - // Token needs to be revoked. We do this immediately here because - // we won't have a token store after sealing. - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(c.activeContext, te) - if err == nil { - err = c.expiration.Revoke(c.activeContext, leaseID) - } - if err != nil { - c.logger.Error("token needed revocation before seal but failed to revoke", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - } - } - - // Unlock; sealing will grab the lock when needed - c.stateLock.RUnlock() - - sealErr := c.sealInternal() - - if sealErr != nil { - retErr = multierror.Append(retErr, sealErr) - } - - return -} - -// UIEnabled returns if the UI is enabled -func (c *Core) UIEnabled() bool { - return c.uiConfig.Enabled() -} - -// UIHeaders returns configured UI headers -func (c *Core) UIHeaders() (http.Header, error) { - return c.uiConfig.Headers(context.Background()) -} - -// sealInternal is an internal method used to seal the vault. It does not do -// any authorization checking. -func (c *Core) sealInternal() error { - return c.sealInternalWithOptions(true, false) -} - -func (c *Core) sealInternalWithOptions(grabStateLock, keepHALock bool) error { - // Mark sealed, and if already marked return - if swapped := atomic.CompareAndSwapUint32(c.sealed, 0, 1); !swapped { - return nil - } - - c.logger.Info("marked as sealed") - - // Clear forwarding clients - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - activeCtxCancel := c.activeContextCancelFunc.Load().(context.CancelFunc) - cancelCtxAndLock := func() { - doneCh := make(chan struct{}) - go func() { - select { - case <-doneCh: - // Attempt to drain any inflight requests - case <-time.After(DefaultMaxRequestDuration): - if activeCtxCancel != nil { - activeCtxCancel() - } - } - }() - - c.stateLock.Lock() - close(doneCh) - // Stop requests from processing - if activeCtxCancel != nil { - activeCtxCancel() - } - } - - // Do pre-seal teardown if HA is not enabled - if c.ha == nil { - if grabStateLock { - cancelCtxAndLock() - defer c.stateLock.Unlock() - } - // Even in a non-HA context we key off of this for some things - c.standby = true - - // Stop requests from processing - if activeCtxCancel != nil { - activeCtxCancel() - } - - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - return fmt.Errorf("internal error") - } - } else { - // If we are keeping the lock we already have the state write lock - // held. Otherwise grab it here so that when stopCh is triggered we are - // locked. - if keepHALock { - atomic.StoreUint32(c.keepHALockOnStepDown, 1) - } - if grabStateLock { - cancelCtxAndLock() - defer c.stateLock.Unlock() - } - - // If we are trying to acquire the lock, force it to return with nil so - // runStandby will exit - // If we are active, signal the standby goroutine to shut down and wait - // for completion. We have the state lock here so nothing else should - // be toggling standby status. - close(c.standbyStopCh) - c.logger.Debug("finished triggering standbyStopCh for runStandby") - - // Wait for runStandby to stop - <-c.standbyDoneCh - atomic.StoreUint32(c.keepHALockOnStepDown, 0) - c.logger.Debug("runStandby done") - } - - c.logger.Debug("sealing barrier") - if err := c.barrier.Seal(); err != nil { - c.logger.Error("error sealing barrier", "error", err) - return err - } - - if c.ha != nil { - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifySealedStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify sealed status", "error", err) - } - } - } - } - - postSealInternal(c) - - c.logger.Info("vault is sealed") - - return nil -} - -type UnsealStrategy interface { - unseal(context.Context, log.Logger, *Core) error -} - -type standardUnsealStrategy struct{} - -func (s standardUnsealStrategy) unseal(ctx context.Context, logger log.Logger, c *Core) error { - // Clear forwarding clients; we're active - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - if err := postUnsealPhysical(c); err != nil { - return err - } - - if err := enterprisePostUnseal(c); err != nil { - return err - } - - if !c.IsDRSecondary() { - if err := c.ensureWrappingKey(ctx); err != nil { - return err - } - } - if err := c.setupPluginCatalog(ctx); err != nil { - return err - } - if err := c.loadMounts(ctx); err != nil { - return err - } - if err := c.setupMounts(ctx); err != nil { - return err - } - if err := c.setupPolicyStore(ctx); err != nil { - return err - } - if err := c.loadCORSConfig(ctx); err != nil { - return err - } - if err := c.loadCredentials(ctx); err != nil { - return err - } - if err := c.setupCredentials(ctx); err != nil { - return err - } - if !c.IsDRSecondary() { - if err := c.startRollback(); err != nil { - return err - } - if err := c.setupExpiration(expireLeaseStrategyRevoke); err != nil { - return err - } - if err := c.loadAudits(ctx); err != nil { - return err - } - if err := c.setupAudits(ctx); err != nil { - return err - } - if err := c.loadIdentityStoreArtifacts(ctx); err != nil { - return err - } - if err := loadMFAConfigs(ctx, c); err != nil { - return err - } - if err := c.setupAuditedHeadersConfig(ctx); err != nil { - return err - } - } else { - c.auditBroker = NewAuditBroker(c.logger) - } - - if c.ha != nil || shouldStartClusterListener(c) { - if err := c.startClusterListener(ctx); err != nil { - return err - } - } - - c.clusterParamsLock.Lock() - defer c.clusterParamsLock.Unlock() - if err := startReplication(c); err != nil { - return err - } - - return nil -} - -// postUnseal is invoked after the barrier is unsealed, but before -// allowing any user operations. This allows us to setup any state that -// requires the Vault to be unsealed such as mount tables, logical backends, -// credential stores, etc. -func (c *Core) postUnseal(ctx context.Context, ctxCancelFunc context.CancelFunc, unsealer UnsealStrategy) (retErr error) { - defer metrics.MeasureSince([]string{"core", "post_unseal"}, time.Now()) - - // Clear any out - c.postUnsealFuncs = nil - - // Create a new request context - c.activeContext = ctx - c.activeContextCancelFunc.Store(ctxCancelFunc) - - defer func() { - if retErr != nil { - ctxCancelFunc() - c.preSeal() - } - }() - c.logger.Info("post-unseal setup starting") - - // Enable the cache - c.physicalCache.Purge(ctx) - if !c.cachingDisabled { - c.physicalCache.SetEnabled(true) - } - - // Purge these for safety in case of a rekey - c.seal.SetBarrierConfig(ctx, nil) - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(ctx, nil) - } - - if err := unsealer.unseal(ctx, c.logger, c); err != nil { - return err - } - - c.metricsCh = make(chan struct{}) - go c.emitMetrics(c.metricsCh) - - // This is intentionally the last block in this function. We want to allow - // writes just before allowing client requests, to ensure everything has - // been set up properly before any writes can have happened. - for _, v := range c.postUnsealFuncs { - v() - } - - c.logger.Info("post-unseal setup complete") - return nil -} - -// preSeal is invoked before the barrier is sealed, allowing -// for any state teardown required. -func (c *Core) preSeal() error { - defer metrics.MeasureSince([]string{"core", "pre_seal"}, time.Now()) - c.logger.Info("pre-seal teardown starting") - - // Clear any pending funcs - c.postUnsealFuncs = nil - - // Clear any rekey progress - c.barrierRekeyConfig = nil - c.recoveryRekeyConfig = nil - - if c.metricsCh != nil { - close(c.metricsCh) - c.metricsCh = nil - } - var result error - - c.clusterParamsLock.Lock() - if err := stopReplication(c); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping replication: {{err}}", err)) - } - c.clusterParamsLock.Unlock() - - c.stopClusterListener() - - if err := c.teardownAudits(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down audits: {{err}}", err)) - } - if err := c.stopExpiration(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping expiration: {{err}}", err)) - } - if err := c.teardownCredentials(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down credentials: {{err}}", err)) - } - if err := c.teardownPolicyStore(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down policy store: {{err}}", err)) - } - if err := c.stopRollback(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping rollback: {{err}}", err)) - } - if err := c.unloadMounts(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error unloading mounts: {{err}}", err)) - } - if err := enterprisePreSeal(c); err != nil { - result = multierror.Append(result, err) - } - - preSealPhysical(c) - - c.logger.Info("pre-seal teardown complete") - return result -} - -func enterprisePostUnsealImpl(c *Core) error { - return nil -} - -func enterprisePreSealImpl(c *Core) error { - return nil -} - -func startReplicationImpl(c *Core) error { - return nil -} - -func stopReplicationImpl(c *Core) error { - return nil -} - -// emitMetrics is used to periodically expose metrics while running -func (c *Core) emitMetrics(stopCh chan struct{}) { - for { - select { - case <-time.After(time.Second): - c.metricsMutex.Lock() - if c.expiration != nil { - c.expiration.emitMetrics() - } - c.metricsMutex.Unlock() - case <-stopCh: - return - } - } -} - -func (c *Core) ReplicationState() consts.ReplicationState { - return consts.ReplicationState(atomic.LoadUint32(c.replicationState)) -} - -func (c *Core) ActiveNodeReplicationState() consts.ReplicationState { - return consts.ReplicationState(atomic.LoadUint32(c.activeNodeReplicationState)) -} - -func (c *Core) SealAccess() *SealAccess { - return NewSealAccess(c.seal) -} - -func (c *Core) Logger() log.Logger { - return c.logger -} - -func (c *Core) BarrierKeyLength() (min, max int) { - min, max = c.barrier.KeyLength() - max += shamir.ShareOverhead - return -} - -func (c *Core) AuditedHeadersConfig() *AuditedHeadersConfig { - return c.auditedHeaders -} - -func waitUntilWALShippedImpl(ctx context.Context, c *Core, index uint64) bool { - return true -} - -func lastWALImpl(c *Core) uint64 { - return 0 -} - -func lastRemoteWALImpl(c *Core) uint64 { - return 0 -} - -func (c *Core) PhysicalSealConfigs(ctx context.Context) (*SealConfig, *SealConfig, error) { - pe, err := c.physical.Get(ctx, barrierSealConfigPath) - if err != nil { - return nil, nil, errwrap.Wrapf("failed to fetch barrier seal configuration at migration check time: {{err}}", err) - } - if pe == nil { - return nil, nil, nil - } - - barrierConf := new(SealConfig) - - if err := jsonutil.DecodeJSON(pe.Value, barrierConf); err != nil { - return nil, nil, errwrap.Wrapf("failed to decode barrier seal configuration at migration check time: {{err}}", err) - } - - var recoveryConf *SealConfig - pe, err = c.physical.Get(ctx, recoverySealConfigPlaintextPath) - if err != nil { - return nil, nil, errwrap.Wrapf("failed to fetch seal configuration at migration check time: {{err}}", err) - } - if pe != nil { - recoveryConf = &SealConfig{} - if err := jsonutil.DecodeJSON(pe.Value, recoveryConf); err != nil { - return nil, nil, errwrap.Wrapf("failed to decode seal configuration at migration check time: {{err}}", err) - } - } - - return barrierConf, recoveryConf, nil -} - -func (c *Core) SetSealsForMigration(migrationSeal, newSeal Seal) { - c.stateLock.Lock() - defer c.stateLock.Unlock() - c.migrationSeal = migrationSeal - c.seal = newSeal - c.logger.Warn("entering seal migration mode; Vault will not automatically unseal even if using an autoseal") -} - -func (c *Core) IsInSealMigration() bool { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - return c.migrationSeal != nil -} - -func (c *Core) BarrierEncryptorAccess() *BarrierEncryptorAccess { - return NewBarrierEncryptorAccess(c.barrier) -} - -func (c *Core) PhysicalAccess() *physical.PhysicalAccess { - return physical.NewPhysicalAccess(c.physical) -} - -func (c *Core) RouterAccess() *RouterAccess { - return NewRouterAccess(c) -} - -// IsDRSecondary returns if the current cluster state is a DR secondary. -func (c *Core) IsDRSecondary() bool { - return c.ReplicationState().HasState(consts.ReplicationDRSecondary) -} - -func (c *Core) AddLogger(logger log.Logger) { - c.allLoggersLock.Lock() - defer c.allLoggersLock.Unlock() - c.allLoggers = append(c.allLoggers, logger) -} - -func (c *Core) SetLogLevel(level log.Level) { - c.allLoggersLock.RLock() - defer c.allLoggersLock.RUnlock() - for _, logger := range c.allLoggers { - logger.SetLevel(level) - } -} - -// BuiltinRegistry is an interface that allows the "vault" package to use -// the registry of builtin plugins without getting an import cycle. It -// also allows for mocking the registry easily. -type BuiltinRegistry interface { - Contains(name string, pluginType consts.PluginType) bool - Get(name string, pluginType consts.PluginType) (func() (interface{}, error), bool) - Keys(pluginType consts.PluginType) []string -} diff --git a/vendor/github.com/hashicorp/vault/vault/core_util.go b/vendor/github.com/hashicorp/vault/vault/core_util.go deleted file mode 100644 index af3fff1a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/core_util.go +++ /dev/null @@ -1,106 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" -) - -type entCore struct{} - -type LicensingConfig struct{} - -func coreInit(c *Core, conf *CoreConfig) error { - phys := conf.Physical - _, txnOK := phys.(physical.Transactional) - sealUnwrapperLogger := conf.Logger.Named("storage.sealunwrapper") - c.allLoggers = append(c.allLoggers, sealUnwrapperLogger) - c.sealUnwrapper = NewSealUnwrapper(phys, sealUnwrapperLogger) - // Wrap the physical backend in a cache layer if enabled - cacheLogger := c.baseLogger.Named("storage.cache") - c.allLoggers = append(c.allLoggers, cacheLogger) - if txnOK { - c.physical = physical.NewTransactionalCache(c.sealUnwrapper, conf.CacheSize, cacheLogger) - } else { - c.physical = physical.NewCache(c.sealUnwrapper, conf.CacheSize, cacheLogger) - } - c.physicalCache = c.physical.(physical.ToggleablePurgemonster) - - // Wrap in encoding checks - if !conf.DisableKeyEncodingChecks { - c.physical = physical.NewStorageEncoding(c.physical) - } - return nil -} - -func createSecondaries(*Core, *CoreConfig) {} - -func addExtraLogicalBackends(*Core, map[string]logical.Factory) {} - -func addExtraCredentialBackends(*Core, map[string]logical.Factory) {} - -func preUnsealInternal(context.Context, *Core) error { return nil } - -func postSealInternal(*Core) {} - -func preSealPhysical(c *Core) { - switch c.sealUnwrapper.(type) { - case *sealUnwrapper: - c.sealUnwrapper.(*sealUnwrapper).stopUnwraps() - case *transactionalSealUnwrapper: - c.sealUnwrapper.(*transactionalSealUnwrapper).stopUnwraps() - } - - // Purge the cache - c.physicalCache.SetEnabled(false) - c.physicalCache.Purge(context.Background()) -} - -func postUnsealPhysical(c *Core) error { - switch c.sealUnwrapper.(type) { - case *sealUnwrapper: - c.sealUnwrapper.(*sealUnwrapper).runUnwraps() - case *transactionalSealUnwrapper: - c.sealUnwrapper.(*transactionalSealUnwrapper).runUnwraps() - } - return nil -} - -func loadMFAConfigs(context.Context, *Core) error { return nil } - -func shouldStartClusterListener(*Core) bool { return true } - -func hasNamespaces(*Core) bool { return false } - -func (c *Core) Features() license.Features { - return license.FeatureNone -} - -func (c *Core) HasFeature(license.Features) bool { - return false -} - -func (c *Core) namepaceByPath(string) *namespace.Namespace { - return namespace.RootNamespace -} - -func (c *Core) setupReplicatedClusterPrimary(*ReplicatedCluster) error { return nil } - -func (c *Core) perfStandbyCount() int { return 0 } - -func (c *Core) removePrefixFromFilteredPaths(context.Context, string) error { - return nil -} - -func (c *Core) checkReplicatedFiltering(context.Context, *MountEntry, string) (bool, error) { - return false, nil -} - -func (c *Core) invalidateSentinelPolicy(PolicyType, string) {} - -func (c *Core) removePerfStandbySecondary(context.Context, string) {} diff --git a/vendor/github.com/hashicorp/vault/vault/cors.go b/vendor/github.com/hashicorp/vault/vault/cors.go deleted file mode 100644 index 9cbecc77..00000000 --- a/vendor/github.com/hashicorp/vault/vault/cors.go +++ /dev/null @@ -1,163 +0,0 @@ -package vault - -import ( - "context" - "errors" - "sync" - "sync/atomic" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - CORSDisabled uint32 = iota - CORSEnabled -) - -var StdAllowedHeaders = []string{ - "Content-Type", - "X-Requested-With", - "X-Vault-AWS-IAM-Server-ID", - "X-Vault-MFA", - "X-Vault-No-Request-Forwarding", - "X-Vault-Wrap-Format", - "X-Vault-Wrap-TTL", - "X-Vault-Policy-Override", - "Authorization", - consts.AuthHeaderName, -} - -// CORSConfig stores the state of the CORS configuration. -type CORSConfig struct { - sync.RWMutex `json:"-"` - core *Core - Enabled *uint32 `json:"enabled"` - AllowedOrigins []string `json:"allowed_origins,omitempty"` - AllowedHeaders []string `json:"allowed_headers,omitempty"` -} - -func (c *Core) saveCORSConfig(ctx context.Context) error { - view := c.systemBarrierView.SubView("config/") - - enabled := atomic.LoadUint32(c.corsConfig.Enabled) - localConfig := &CORSConfig{ - Enabled: &enabled, - } - c.corsConfig.RLock() - localConfig.AllowedOrigins = c.corsConfig.AllowedOrigins - localConfig.AllowedHeaders = c.corsConfig.AllowedHeaders - c.corsConfig.RUnlock() - - entry, err := logical.StorageEntryJSON("cors", localConfig) - if err != nil { - return errwrap.Wrapf("failed to create CORS config entry: {{err}}", err) - } - - if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to save CORS config: {{err}}", err) - } - - return nil -} - -// This should only be called with the core state lock held for writing -func (c *Core) loadCORSConfig(ctx context.Context) error { - view := c.systemBarrierView.SubView("config/") - - // Load the config in - out, err := view.Get(ctx, "cors") - if err != nil { - return errwrap.Wrapf("failed to read CORS config: {{err}}", err) - } - if out == nil { - return nil - } - - newConfig := new(CORSConfig) - err = out.DecodeJSON(newConfig) - if err != nil { - return err - } - - if newConfig.Enabled == nil { - newConfig.Enabled = new(uint32) - } - - newConfig.core = c - - c.corsConfig = newConfig - - return nil -} - -// Enable takes either a '*' or a comma-separated list of URLs that can make -// cross-origin requests to Vault. -func (c *CORSConfig) Enable(ctx context.Context, urls []string, headers []string) error { - if len(urls) == 0 { - return errors.New("at least one origin or the wildcard must be provided") - } - - if strutil.StrListContains(urls, "*") && len(urls) > 1 { - return errors.New("to allow all origins the '*' must be the only value for allowed_origins") - } - - c.Lock() - c.AllowedOrigins = urls - - // Start with the standard headers to Vault accepts. - c.AllowedHeaders = append(c.AllowedHeaders, StdAllowedHeaders...) - - // Allow the user to add additional headers to the list of - // headers allowed on cross-origin requests. - if len(headers) > 0 { - c.AllowedHeaders = append(c.AllowedHeaders, headers...) - } - c.Unlock() - - atomic.StoreUint32(c.Enabled, CORSEnabled) - - return c.core.saveCORSConfig(ctx) -} - -// IsEnabled returns the value of CORSConfig.isEnabled -func (c *CORSConfig) IsEnabled() bool { - return atomic.LoadUint32(c.Enabled) == CORSEnabled -} - -// Disable sets CORS to disabled and clears the allowed origins & headers. -func (c *CORSConfig) Disable(ctx context.Context) error { - atomic.StoreUint32(c.Enabled, CORSDisabled) - c.Lock() - - c.AllowedOrigins = nil - c.AllowedHeaders = nil - - c.Unlock() - - return c.core.saveCORSConfig(ctx) -} - -// IsValidOrigin determines if the origin of the request is allowed to make -// cross-origin requests based on the CORSConfig. -func (c *CORSConfig) IsValidOrigin(origin string) bool { - // If we aren't enabling CORS then all origins are valid - if !c.IsEnabled() { - return true - } - - c.RLock() - defer c.RUnlock() - - if len(c.AllowedOrigins) == 0 { - return false - } - - if len(c.AllowedOrigins) == 1 && (c.AllowedOrigins)[0] == "*" { - return true - } - - return strutil.StrListContains(c.AllowedOrigins, origin) -} diff --git a/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go b/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go deleted file mode 100644 index eef5e19c..00000000 --- a/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go +++ /dev/null @@ -1,255 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/license" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/version" -) - -type dynamicSystemView struct { - core *Core - mountEntry *MountEntry -} - -func (d dynamicSystemView) DefaultLeaseTTL() time.Duration { - def, _ := d.fetchTTLs() - return def -} - -func (d dynamicSystemView) MaxLeaseTTL() time.Duration { - _, max := d.fetchTTLs() - return max -} - -func (d dynamicSystemView) SudoPrivilege(ctx context.Context, path string, token string) bool { - // Resolve the token policy - te, err := d.core.tokenStore.Lookup(ctx, token) - if err != nil { - d.core.logger.Error("failed to lookup token", "error", err) - return false - } - - // Ensure the token is valid - if te == nil { - d.core.logger.Error("entry not found for given token") - return false - } - - policies := make(map[string][]string) - // Add token policies - policies[te.NamespaceID] = append(policies[te.NamespaceID], te.Policies...) - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, d.core) - if err != nil { - d.core.logger.Error("failed to lookup token namespace", "error", err) - return false - } - if tokenNS == nil { - d.core.logger.Error("failed to lookup token namespace", "error", namespace.ErrNoNamespace) - return false - } - - // Add identity policies from all the namespaces - entity, identityPolicies, err := d.core.fetchEntityAndDerivedPolicies(ctx, tokenNS, te.EntityID) - if err != nil { - d.core.logger.Error("failed to fetch identity policies", "error", err) - return false - } - for nsID, nsPolicies := range identityPolicies { - policies[nsID] = append(policies[nsID], nsPolicies...) - } - - tokenCtx := namespace.ContextWithNamespace(ctx, tokenNS) - - // Construct the corresponding ACL object. Derive and use a new context that - // uses the req.ClientToken's namespace - acl, err := d.core.policyStore.ACL(tokenCtx, entity, policies) - if err != nil { - d.core.logger.Error("failed to retrieve ACL for token's policies", "token_policies", te.Policies, "error", err) - return false - } - - // The operation type isn't important here as this is run from a path the - // user has already been given access to; we only care about whether they - // have sudo - req := new(logical.Request) - req.Operation = logical.ReadOperation - req.Path = path - authResults := acl.AllowOperation(ctx, req, true) - return authResults.RootPrivs -} - -// TTLsByPath returns the default and max TTLs corresponding to a particular -// mount point, or the system default -func (d dynamicSystemView) fetchTTLs() (def, max time.Duration) { - def = d.core.defaultLeaseTTL - max = d.core.maxLeaseTTL - - if d.mountEntry != nil { - if d.mountEntry.Config.DefaultLeaseTTL != 0 { - def = d.mountEntry.Config.DefaultLeaseTTL - } - if d.mountEntry.Config.MaxLeaseTTL != 0 { - max = d.mountEntry.Config.MaxLeaseTTL - } - } - - return -} - -// Tainted indicates that the mount is in the process of being removed -func (d dynamicSystemView) Tainted() bool { - return d.mountEntry.Tainted -} - -// CachingDisabled indicates whether to use caching behavior -func (d dynamicSystemView) CachingDisabled() bool { - return d.core.cachingDisabled || (d.mountEntry != nil && d.mountEntry.Config.ForceNoCache) -} - -func (d dynamicSystemView) LocalMount() bool { - return d.mountEntry != nil && d.mountEntry.Local -} - -// Checks if this is a primary Vault instance. Caller should hold the stateLock -// in read mode. -func (d dynamicSystemView) ReplicationState() consts.ReplicationState { - state := d.core.ReplicationState() - if d.core.perfStandby { - state |= consts.ReplicationPerformanceStandby - } - return state -} - -func (d dynamicSystemView) HasFeature(feature license.Features) bool { - return d.core.HasFeature(feature) -} - -// ResponseWrapData wraps the given data in a cubbyhole and returns the -// token used to unwrap. -func (d dynamicSystemView) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - req := &logical.Request{ - Operation: logical.CreateOperation, - Path: "sys/wrapping/wrap", - } - - resp := &logical.Response{ - WrapInfo: &wrapping.ResponseWrapInfo{ - TTL: ttl, - }, - Data: data, - } - - if jwt { - resp.WrapInfo.Format = "jwt" - } - - _, err := d.core.wrapInCubbyhole(ctx, req, resp, nil) - if err != nil { - return nil, err - } - - return resp.WrapInfo, nil -} - -// LookupPlugin looks for a plugin with the given name in the plugin catalog. It -// returns a PluginRunner or an error if no plugin was found. -func (d dynamicSystemView) LookupPlugin(ctx context.Context, name string, pluginType consts.PluginType) (*pluginutil.PluginRunner, error) { - if d.core == nil { - return nil, fmt.Errorf("system view core is nil") - } - if d.core.pluginCatalog == nil { - return nil, fmt.Errorf("system view core plugin catalog is nil") - } - r, err := d.core.pluginCatalog.Get(ctx, name, pluginType) - if err != nil { - return nil, err - } - if r == nil { - return nil, errwrap.Wrapf(fmt.Sprintf("{{err}}: %s", name), ErrPluginNotFound) - } - - return r, nil -} - -// MlockEnabled returns the configuration setting for enabling mlock on plugins. -func (d dynamicSystemView) MlockEnabled() bool { - return d.core.enableMlock -} - -func (d dynamicSystemView) EntityInfo(entityID string) (*logical.Entity, error) { - // Requests from token created from the token backend will not have entity information. - // Return missing entity instead of error when requesting from MemDB. - if entityID == "" { - return nil, nil - } - - if d.core == nil { - return nil, fmt.Errorf("system view core is nil") - } - if d.core.identityStore == nil { - return nil, fmt.Errorf("system view identity store is nil") - } - - // Retrieve the entity from MemDB - entity, err := d.core.identityStore.MemDBEntityByID(entityID, false) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - // Return a subset of the data - ret := &logical.Entity{ - ID: entity.ID, - Name: entity.Name, - } - - if entity.Metadata != nil { - ret.Metadata = make(map[string]string, len(entity.Metadata)) - for k, v := range entity.Metadata { - ret.Metadata[k] = v - } - } - - aliases := make([]*logical.Alias, len(entity.Aliases)) - for i, a := range entity.Aliases { - alias := &logical.Alias{ - MountAccessor: a.MountAccessor, - Name: a.Name, - } - // MountType is not stored with the entity and must be looked up - if mount := d.core.router.validateMountByAccessor(a.MountAccessor); mount != nil { - alias.MountType = mount.MountType - } - - if a.Metadata != nil { - alias.Metadata = make(map[string]string, len(a.Metadata)) - for k, v := range a.Metadata { - alias.Metadata[k] = v - } - } - - aliases[i] = alias - } - ret.Aliases = aliases - - return ret, nil -} - -func (d dynamicSystemView) PluginEnv(_ context.Context) (*logical.PluginEnvironment, error) { - return &logical.PluginEnvironment{ - VaultVersion: version.GetVersion().Version, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/expiration.go b/vendor/github.com/hashicorp/vault/vault/expiration.go deleted file mode 100644 index 54bc98f2..00000000 --- a/vendor/github.com/hashicorp/vault/vault/expiration.go +++ /dev/null @@ -1,1802 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "path" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/base62" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // expirationSubPath is the sub-path used for the expiration manager - // view. This is nested under the system view. - expirationSubPath = "expire/" - - // leaseViewPrefix is the prefix used for the ID based lookup of leases. - leaseViewPrefix = "id/" - - // tokenViewPrefix is the prefix used for the token based lookup of leases. - tokenViewPrefix = "token/" - - // maxRevokeAttempts limits how many revoke attempts are made - maxRevokeAttempts = 6 - - // revokeRetryBase is a baseline retry time - revokeRetryBase = 10 * time.Second - - // maxLeaseDuration is the default maximum lease duration - maxLeaseTTL = 32 * 24 * time.Hour - - // defaultLeaseDuration is the default lease duration used when no lease is specified - defaultLeaseTTL = maxLeaseTTL - - //maxLeaseThreshold is the maximum lease count before generating log warning - maxLeaseThreshold = 256000 -) - -type pendingInfo struct { - exportLeaseTimes *leaseEntry - timer *time.Timer -} - -// ExpirationManager is used by the Core to manage leases. Secrets -// can provide a lease, meaning that they can be renewed or revoked. -// If a secret is not renewed in timely manner, it may be expired, and -// the ExpirationManager will handle doing automatic revocation. -type ExpirationManager struct { - core *Core - router *Router - idView *BarrierView - tokenView *BarrierView - tokenStore *TokenStore - logger log.Logger - - pending map[string]pendingInfo - pendingLock sync.RWMutex - - tidyLock *int32 - - restoreMode *int32 - restoreModeLock sync.RWMutex - restoreRequestLock sync.RWMutex - restoreLocks []*locksutil.LockEntry - restoreLoaded sync.Map - quitCh chan struct{} - - coreStateLock *sync.RWMutex - quitContext context.Context - leaseCheckCounter *uint32 - - logLeaseExpirations bool - expireFunc ExpireLeaseStrategy -} - -type ExpireLeaseStrategy func(context.Context, *ExpirationManager, *leaseEntry) - -// revokeIDFunc is invoked when a given ID is expired -func expireLeaseStrategyRevoke(ctx context.Context, m *ExpirationManager, le *leaseEntry) { - for attempt := uint(0); attempt < maxRevokeAttempts; attempt++ { - revokeCtx, cancel := context.WithTimeout(ctx, DefaultMaxRequestDuration) - revokeCtx = namespace.ContextWithNamespace(revokeCtx, le.namespace) - - go func() { - select { - case <-ctx.Done(): - case <-m.quitCh: - cancel() - case <-revokeCtx.Done(): - } - }() - - select { - case <-m.quitCh: - m.logger.Error("shutting down, not attempting further revocation of lease", "lease_id", le.LeaseID) - cancel() - return - case <-m.quitContext.Done(): - m.logger.Error("core context canceled, not attempting further revocation of lease", "lease_id", le.LeaseID) - cancel() - return - default: - } - - m.coreStateLock.RLock() - err := m.Revoke(revokeCtx, le.LeaseID) - m.coreStateLock.RUnlock() - cancel() - if err == nil { - return - } - - m.logger.Error("failed to revoke lease", "lease_id", le.LeaseID, "error", err) - time.Sleep((1 << attempt) * revokeRetryBase) - } - m.logger.Error("maximum revoke attempts reached", "lease_id", le.LeaseID) -} - -// NewExpirationManager creates a new ExpirationManager that is backed -// using a given view, and uses the provided router for revocation. -func NewExpirationManager(c *Core, view *BarrierView, e ExpireLeaseStrategy, logger log.Logger) *ExpirationManager { - exp := &ExpirationManager{ - core: c, - router: c.router, - idView: view.SubView(leaseViewPrefix), - tokenView: view.SubView(tokenViewPrefix), - tokenStore: c.tokenStore, - logger: logger, - pending: make(map[string]pendingInfo), - tidyLock: new(int32), - - // new instances of the expiration manager will go immediately into - // restore mode - restoreMode: new(int32), - restoreLocks: locksutil.CreateLocks(), - quitCh: make(chan struct{}), - - coreStateLock: &c.stateLock, - quitContext: c.activeContext, - leaseCheckCounter: new(uint32), - - logLeaseExpirations: os.Getenv("VAULT_SKIP_LOGGING_LEASE_EXPIRATIONS") == "", - expireFunc: e, - } - *exp.restoreMode = 1 - - if exp.logger == nil { - opts := log.LoggerOptions{Name: "expiration_manager"} - exp.logger = log.New(&opts) - } - - return exp -} - -// setupExpiration is invoked after we've loaded the mount table to -// initialize the expiration manager -func (c *Core) setupExpiration(e ExpireLeaseStrategy) error { - c.metricsMutex.Lock() - defer c.metricsMutex.Unlock() - // Create a sub-view - view := c.systemBarrierView.SubView(expirationSubPath) - - // Create the manager - expLogger := c.baseLogger.Named("expiration") - c.AddLogger(expLogger) - mgr := NewExpirationManager(c, view, e, expLogger) - c.expiration = mgr - - // Link the token store to this - c.tokenStore.SetExpirationManager(mgr) - - // Restore the existing state - c.logger.Info("restoring leases") - errorFunc := func() { - c.logger.Error("shutting down") - if err := c.Shutdown(); err != nil { - c.logger.Error("error shutting down core", "error", err) - } - } - go c.expiration.Restore(errorFunc) - - return nil -} - -// stopExpiration is used to stop the expiration manager before -// sealing the Vault. -func (c *Core) stopExpiration() error { - if c.expiration != nil { - if err := c.expiration.Stop(); err != nil { - return err - } - c.metricsMutex.Lock() - defer c.metricsMutex.Unlock() - c.expiration = nil - } - return nil -} - -// lockLease takes out a lock for a given lease ID -func (m *ExpirationManager) lockLease(leaseID string) { - locksutil.LockForKey(m.restoreLocks, leaseID).Lock() -} - -// unlockLease unlocks a given lease ID -func (m *ExpirationManager) unlockLease(leaseID string) { - locksutil.LockForKey(m.restoreLocks, leaseID).Unlock() -} - -// inRestoreMode returns if we are currently in restore mode -func (m *ExpirationManager) inRestoreMode() bool { - return atomic.LoadInt32(m.restoreMode) == 1 -} - -func (m *ExpirationManager) invalidate(key string) { - - switch { - case strings.HasPrefix(key, leaseViewPrefix): - // Clear from the pending expiration - leaseID := strings.TrimPrefix(key, leaseViewPrefix) - m.pendingLock.Lock() - if pending, ok := m.pending[leaseID]; ok { - pending.timer.Stop() - delete(m.pending, leaseID) - } - m.pendingLock.Unlock() - } -} - -// Tidy cleans up the dangling storage entries for leases. It scans the storage -// view to find all the available leases, checks if the token embedded in it is -// either empty or invalid and in both the cases, it revokes them. It also uses -// a token cache to avoid multiple lookups of the same token ID. It is normally -// not required to use the API that invokes this. This is only intended to -// clean up the corrupt storage due to bugs. -func (m *ExpirationManager) Tidy(ctx context.Context) error { - if m.inRestoreMode() { - return errors.New("cannot run tidy while restoring leases") - } - - var tidyErrors *multierror.Error - - logger := m.logger.Named("tidy") - m.core.AddLogger(logger) - - if !atomic.CompareAndSwapInt32(m.tidyLock, 0, 1) { - logger.Warn("tidy operation on leases is already in progress") - return nil - } - - defer atomic.CompareAndSwapInt32(m.tidyLock, 1, 0) - - logger.Info("beginning tidy operation on leases") - defer logger.Info("finished tidy operation on leases") - - // Create a cache to keep track of looked up tokens - tokenCache := make(map[string]bool) - var countLease, revokedCount, deletedCountInvalidToken, deletedCountEmptyToken int64 - - tidyFunc := func(leaseID string) { - countLease++ - if countLease%500 == 0 { - logger.Info("tidying leases", "progress", countLease) - } - - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to load the lease ID %q: {{err}}", leaseID), err)) - return - } - - if le == nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("nil entry for lease ID %q: {{err}}", leaseID), err)) - return - } - - var isValid, ok bool - revokeLease := false - if le.ClientToken == "" { - logger.Debug("revoking lease which has an empty token", "lease_id", leaseID) - revokeLease = true - deletedCountEmptyToken++ - goto REVOKE_CHECK - } - - isValid, ok = tokenCache[le.ClientToken] - if !ok { - lock := locksutil.LockForKey(m.tokenStore.tokenLocks, le.ClientToken) - lock.RLock() - te, err := m.tokenStore.lookupInternal(ctx, le.ClientToken, false, true) - lock.RUnlock() - - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup token: {{err}}", err)) - return - } - - if te == nil { - logger.Debug("revoking lease which holds an invalid token", "lease_id", leaseID) - revokeLease = true - deletedCountInvalidToken++ - tokenCache[le.ClientToken] = false - } else { - tokenCache[le.ClientToken] = true - } - goto REVOKE_CHECK - } else { - if isValid { - return - } - - logger.Debug("revoking lease which contains an invalid token", "lease_id", leaseID) - revokeLease = true - deletedCountInvalidToken++ - goto REVOKE_CHECK - } - - REVOKE_CHECK: - if revokeLease { - // Force the revocation and skip going through the token store - // again - err = m.revokeCommon(ctx, leaseID, true, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to revoke an invalid lease with ID %q: {{err}}", leaseID), err)) - return - } - revokedCount++ - } - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - leaseView := m.leaseView(ns) - if err := logical.ScanView(m.quitContext, leaseView, tidyFunc); err != nil { - return err - } - - logger.Info("number of leases scanned", "count", countLease) - logger.Info("number of leases which had empty tokens", "count", deletedCountEmptyToken) - logger.Info("number of leases which had invalid tokens", "count", deletedCountInvalidToken) - logger.Info("number of leases successfully revoked", "count", revokedCount) - - return tidyErrors.ErrorOrNil() -} - -// Restore is used to recover the lease states when starting. -// This is used after starting the vault. -func (m *ExpirationManager) Restore(errorFunc func()) (retErr error) { - defer func() { - // Turn off restore mode. We can do this safely without the lock because - // if restore mode finished successfully, restore mode was already - // disabled with the lock. In an error state, this will allow the - // Stop() function to shut everything down. - atomic.StoreInt32(m.restoreMode, 0) - - switch { - case retErr == nil: - case strings.Contains(retErr.Error(), context.Canceled.Error()): - // Don't run error func because we lost leadership - m.logger.Warn("context cancled while restoring leases, stopping lease loading") - retErr = nil - case errwrap.Contains(retErr, ErrBarrierSealed.Error()): - // Don't run error func because we're likely already shutting down - m.logger.Warn("barrier sealed while restoring leases, stopping lease loading") - retErr = nil - default: - m.logger.Error("error restoring leases", "error", retErr) - if errorFunc != nil { - errorFunc() - } - } - }() - - // Accumulate existing leases - m.logger.Debug("collecting leases") - existing, leaseCount, err := m.collectLeases() - if err != nil { - return err - } - m.logger.Debug("leases collected", "num_existing", leaseCount) - - // Make the channels used for the worker pool - type lease struct { - namespace *namespace.Namespace - id string - } - broker := make(chan *lease) - quit := make(chan bool) - // Buffer these channels to prevent deadlocks - errs := make(chan error, len(existing)) - result := make(chan struct{}, len(existing)) - - // Use a wait group - wg := &sync.WaitGroup{} - - // Create 64 workers to distribute work to - for i := 0; i < consts.ExpirationRestoreWorkerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() - - for { - select { - case lease, ok := <-broker: - // broker has been closed, we are done - if !ok { - return - } - - ctx := namespace.ContextWithNamespace(m.quitContext, lease.namespace) - err := m.processRestore(ctx, lease.id) - if err != nil { - errs <- err - continue - } - - // Send message that lease is done - result <- struct{}{} - - // quit early - case <-quit: - return - - case <-m.quitCh: - return - } - } - }() - } - - // Distribute the collected keys to the workers in a go routine - wg.Add(1) - go func() { - defer wg.Done() - i := 0 - for ns := range existing { - for _, leaseID := range existing[ns] { - i++ - if i%500 == 0 { - m.logger.Debug("leases loading", "progress", i) - } - - select { - case <-quit: - return - - case <-m.quitCh: - return - - default: - broker <- &lease{ - namespace: ns, - id: leaseID, - } - } - } - } - - // Close the broker, causing worker routines to exit - close(broker) - }() - - // Ensure all keys on the chan are processed - for i := 0; i < leaseCount; i++ { - select { - case err := <-errs: - // Close all go routines - close(quit) - return err - - case <-m.quitCh: - close(quit) - return nil - - case <-result: - } - } - - // Let all go routines finish - wg.Wait() - - m.restoreModeLock.Lock() - atomic.StoreInt32(m.restoreMode, 0) - m.restoreLoaded.Range(func(k, v interface{}) bool { - m.restoreLoaded.Delete(k) - return true - }) - m.restoreLocks = nil - m.restoreModeLock.Unlock() - - m.logger.Info("lease restore complete") - return nil -} - -// processRestore takes a lease and restores it in the expiration manager if it has -// not already been seen -func (m *ExpirationManager) processRestore(ctx context.Context, leaseID string) error { - m.restoreRequestLock.RLock() - defer m.restoreRequestLock.RUnlock() - - // Check if the lease has been seen - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return nil - } - - m.lockLease(leaseID) - defer m.unlockLease(leaseID) - - // Check again with the lease locked - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return nil - } - - // Load lease and restore expiration timer - _, err := m.loadEntryInternal(ctx, leaseID, true, false) - if err != nil { - return err - } - return nil -} - -// Stop is used to prevent further automatic revocations. -// This must be called before sealing the view. -func (m *ExpirationManager) Stop() error { - // Stop all the pending expiration timers - m.logger.Debug("stop triggered") - defer m.logger.Debug("finished stopping") - - // Do this before stopping pending timers to avoid potential races with - // expiring timers - close(m.quitCh) - - m.pendingLock.Lock() - for _, pending := range m.pending { - pending.timer.Stop() - } - m.pending = make(map[string]pendingInfo) - m.pendingLock.Unlock() - - if m.inRestoreMode() { - for { - if !m.inRestoreMode() { - break - } - time.Sleep(10 * time.Millisecond) - } - } - - return nil -} - -// Revoke is used to revoke a secret named by the given LeaseID -func (m *ExpirationManager) Revoke(ctx context.Context, leaseID string) error { - defer metrics.MeasureSince([]string{"expire", "revoke"}, time.Now()) - - return m.revokeCommon(ctx, leaseID, false, false) -} - -// LazyRevoke is used to queue revocation for a secret named by the given -// LeaseID. If the lease was not found it returns nil; if the lease was found -// it triggers a return of a 202. -func (m *ExpirationManager) LazyRevoke(ctx context.Context, leaseID string) error { - defer metrics.MeasureSince([]string{"expire", "lazy-revoke"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there is no entry, nothing to revoke - if le == nil { - return nil - } - - le.ExpireTime = time.Now() - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return err - } - - m.updatePendingInternal(le, 0) - m.pendingLock.Unlock() - } - - return nil -} - -// revokeCommon does the heavy lifting. If force is true, we ignore a problem -// during revocation and still remove entries/index/lease timers -func (m *ExpirationManager) revokeCommon(ctx context.Context, leaseID string, force, skipToken bool) error { - defer metrics.MeasureSince([]string{"expire", "revoke-common"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there is no entry, nothing to revoke - if le == nil { - return nil - } - - // Revoke the entry - if !skipToken || le.Auth == nil { - if err := m.revokeEntry(ctx, le); err != nil { - if !force { - return err - } - - if m.logger.IsWarn() { - m.logger.Warn("revocation from the backend failed, but in force mode so ignoring", "error", err) - } - } - } - - // Delete the entry - if err := m.deleteEntry(ctx, le); err != nil { - return err - } - - // Delete the secondary index, but only if it's a leased secret (not auth) - if le.Secret != nil { - if err := m.removeIndexByToken(ctx, le); err != nil { - return err - } - } - - // Clear the expiration handler - m.pendingLock.Lock() - if pending, ok := m.pending[leaseID]; ok { - pending.timer.Stop() - delete(m.pending, leaseID) - } - m.pendingLock.Unlock() - - if m.logger.IsInfo() && !skipToken && m.logLeaseExpirations { - m.logger.Info("revoked lease", "lease_id", leaseID) - } - - return nil -} - -// RevokeForce works similarly to RevokePrefix but continues in the case of a -// revocation error; this is mostly meant for recovery operations -func (m *ExpirationManager) RevokeForce(ctx context.Context, prefix string) error { - defer metrics.MeasureSince([]string{"expire", "revoke-force"}, time.Now()) - - return m.revokePrefixCommon(ctx, prefix, true, true) -} - -// RevokePrefix is used to revoke all secrets with a given prefix. -// The prefix maps to that of the mount table to make this simpler -// to reason about. -func (m *ExpirationManager) RevokePrefix(ctx context.Context, prefix string, sync bool) error { - defer metrics.MeasureSince([]string{"expire", "revoke-prefix"}, time.Now()) - - return m.revokePrefixCommon(ctx, prefix, false, sync) -} - -// RevokeByToken is used to revoke all the secrets issued with a given token. -// This is done by using the secondary index. It also removes the lease entry -// for the token itself. As a result it should *ONLY* ever be called from the -// token store's revokeSalted function. -func (m *ExpirationManager) RevokeByToken(ctx context.Context, te *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"expire", "revoke-by-token"}, time.Now()) - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - tokenCtx := namespace.ContextWithNamespace(ctx, tokenNS) - // Lookup the leases - existing, err := m.lookupLeasesByToken(tokenCtx, te) - if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - - // Revoke all the keys - for _, leaseID := range existing { - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there's a lease, set expiration to now, persist, and call - // updatePending to hand off revocation to the expiration manager's pending - // timer map - if le != nil { - le.ExpireTime = time.Now() - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return err - } - - m.updatePendingInternal(le, 0) - m.pendingLock.Unlock() - } - } - } - - // te.Path should never be empty, but we check just in case - if te.Path != "" { - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := m.tokenStore.SaltID(saltCtx, te.ID) - if err != nil { - return err - } - tokenLeaseID := path.Join(te.Path, saltedID) - - if tokenNS.ID != namespace.RootNamespaceID { - tokenLeaseID = fmt.Sprintf("%s.%s", tokenLeaseID, tokenNS.ID) - } - - // We want to skip the revokeEntry call as that will call back into - // revocation logic in the token store, which is what is running this - // function in the first place -- it'd be a deadlock loop. Since the only - // place that this function is called is revokeSalted in the token store, - // we're already revoking the token, so we just want to clean up the lease. - // This avoids spurious revocations later in the log when the timer runs - // out, and eases up resource usage. - return m.revokeCommon(ctx, tokenLeaseID, false, true) - } - - return nil -} - -func (m *ExpirationManager) revokePrefixCommon(ctx context.Context, prefix string, force, sync bool) error { - if m.inRestoreMode() { - m.restoreRequestLock.Lock() - defer m.restoreRequestLock.Unlock() - } - - // Ensure there is a trailing slash; or, if there is no slash, see if there - // is a matching specific ID - if !strings.HasSuffix(prefix, "/") { - le, err := m.loadEntry(ctx, prefix) - if err == nil && le != nil { - if sync { - if err := m.revokeCommon(ctx, prefix, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q: {{err}}", prefix), err) - } - return nil - } - return m.LazyRevoke(ctx, prefix) - } - prefix = prefix + "/" - } - - // Accumulate existing leases - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - view := m.leaseView(ns) - sub := view.SubView(prefix) - existing, err := logical.CollectKeys(ctx, sub) - if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - - // Revoke all the keys - for idx, suffix := range existing { - leaseID := prefix + suffix - switch { - case sync: - if err := m.revokeCommon(ctx, leaseID, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) - } - default: - if err := m.LazyRevoke(ctx, leaseID); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) - } - } - } - - return nil -} - -// Renew is used to renew a secret using the given leaseID -// and a renew interval. The increment may be ignored. -func (m *ExpirationManager) Renew(ctx context.Context, leaseID string, increment time.Duration) (*logical.Response, error) { - defer metrics.MeasureSince([]string{"expire", "renew"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return nil, err - } - - // Check if the lease is renewable - if _, err := le.renewable(); err != nil { - return nil, err - } - - if le.Secret == nil { - if le.Auth != nil { - return logical.ErrorResponse("tokens cannot be renewed through this endpoint"), logical.ErrPermissionDenied - } - return logical.ErrorResponse("lease does not correspond to a secret"), nil - } - - reqNS, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if reqNS.ID != le.namespace.ID { - return nil, errors.New("cannot renew a lease across namespaces") - } - - sysViewCtx := namespace.ContextWithNamespace(ctx, le.namespace) - sysView := m.router.MatchingSystemView(sysViewCtx, le.Path) - if sysView == nil { - return nil, fmt.Errorf("unable to retrieve system view from router") - } - - // Attempt to renew the entry - resp, err := m.renewEntry(ctx, le, increment) - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - if resp.IsError() { - return &logical.Response{ - Data: resp.Data, - }, nil - } - if resp.Secret == nil { - return nil, nil - } - - ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Secret.TTL, 0, resp.Secret.MaxTTL, 0, le.IssueTime) - if err != nil { - return nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - resp.Secret.TTL = ttl - - // Attach the LeaseID - resp.Secret.LeaseID = leaseID - - // Update the lease entry - le.Data = resp.Data - le.Secret = resp.Secret - le.ExpireTime = resp.Secret.ExpirationTime() - le.LastRenewalTime = time.Now() - - // If the token it's associated with is a batch token, constrain lease - // times - if le.ClientTokenType == logical.TokenTypeBatch { - te, err := m.tokenStore.Lookup(ctx, le.ClientToken) - if err != nil { - return nil, err - } - if te == nil { - return nil, errors.New("cannot renew lease, no valid associated token") - } - tokenLeaseTimes, err := m.FetchLeaseTimesByToken(ctx, te) - if err != nil { - return nil, err - } - if le.ExpireTime.After(tokenLeaseTimes.ExpireTime) { - resp.Secret.TTL = tokenLeaseTimes.ExpireTime.Sub(le.LastRenewalTime) - le.ExpireTime = tokenLeaseTimes.ExpireTime - } - } - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return nil, err - } - - // Update the expiration time - m.updatePendingInternal(le, resp.Secret.LeaseTotal()) - m.pendingLock.Unlock() - } - - // Return the response - return resp, nil -} - -// RenewToken is used to renew a token which does not need to -// invoke a logical backend. -func (m *ExpirationManager) RenewToken(ctx context.Context, req *logical.Request, te *logical.TokenEntry, - increment time.Duration) (*logical.Response, error) { - defer metrics.MeasureSince([]string{"expire", "renew-token"}, time.Now()) - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != tokenNS.ID { - return nil, errors.New("cannot renew a token across namespaces") - } - - // Compute the Lease ID - saltedID, err := m.tokenStore.SaltID(ctx, te.ID) - if err != nil { - return nil, err - } - - leaseID := path.Join(te.Path, saltedID) - - if ns.ID != namespace.RootNamespaceID { - leaseID = fmt.Sprintf("%s.%s", leaseID, ns.ID) - } - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return nil, err - } - if le == nil { - return logical.ErrorResponse("invalid lease ID"), logical.ErrInvalidRequest - } - - // Check if the lease is renewable. Note that this also checks for a nil - // lease and errors in that case as well. - if _, err := le.renewable(); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - // Attempt to renew the auth entry - resp, err := m.renewAuthEntry(ctx, req, le, increment) - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - if resp.IsError() { - return &logical.Response{ - Data: resp.Data, - }, nil - } - if resp.Auth == nil { - return nil, nil - } - - sysViewCtx := namespace.ContextWithNamespace(ctx, le.namespace) - sysView := m.router.MatchingSystemView(sysViewCtx, le.Path) - if sysView == nil { - return nil, fmt.Errorf("unable to retrieve system view from router") - } - - ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Auth.TTL, resp.Auth.Period, resp.Auth.MaxTTL, resp.Auth.ExplicitMaxTTL, le.IssueTime) - if err != nil { - return nil, err - } - retResp := &logical.Response{} - for _, warning := range warnings { - retResp.AddWarning(warning) - } - resp.Auth.TTL = ttl - - // Attach the ClientToken - resp.Auth.ClientToken = te.ID - - // Refresh groups - if resp.Auth.EntityID != "" && - resp.Auth.GroupAliases != nil && - m.core.identityStore != nil { - validAliases, err := m.core.identityStore.refreshExternalGroupMembershipsByEntityID(resp.Auth.EntityID, resp.Auth.GroupAliases) - if err != nil { - return nil, err - } - resp.Auth.GroupAliases = validAliases - } - - // Update the lease entry - le.Auth = resp.Auth - le.ExpireTime = resp.Auth.ExpirationTime() - le.LastRenewalTime = time.Now() - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return nil, err - } - - // Update the expiration time - m.updatePendingInternal(le, resp.Auth.LeaseTotal()) - m.pendingLock.Unlock() - } - - retResp.Auth = resp.Auth - return retResp, nil -} - -// Register is used to take a request and response with an associated -// lease. The secret gets assigned a LeaseID and the management of -// of lease is assumed by the expiration manager. -func (m *ExpirationManager) Register(ctx context.Context, req *logical.Request, resp *logical.Response) (id string, retErr error) { - defer metrics.MeasureSince([]string{"expire", "register"}, time.Now()) - - te := req.TokenEntry() - if te == nil { - return "", fmt.Errorf("cannot register a lease with an empty client token") - } - - // Ignore if there is no leased secret - if resp == nil || resp.Secret == nil { - return "", nil - } - - // Validate the secret - if err := resp.Secret.Validate(); err != nil { - return "", err - } - - // Create a lease entry - leaseRand, err := base62.Random(TokenLength, true) - if err != nil { - return "", err - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return "", err - } - - leaseID := path.Join(req.Path, leaseRand) - - if ns.ID != namespace.RootNamespaceID { - leaseID = fmt.Sprintf("%s.%s", leaseID, ns.ID) - } - - le := &leaseEntry{ - LeaseID: leaseID, - ClientToken: req.ClientToken, - ClientTokenType: te.Type, - Path: req.Path, - Data: resp.Data, - Secret: resp.Secret, - IssueTime: time.Now(), - ExpireTime: resp.Secret.ExpirationTime(), - namespace: ns, - } - - defer func() { - // If there is an error we want to rollback as much as possible (note - // that errors here are ignored to do as much cleanup as we can). We - // want to revoke a generated secret (since an error means we may not - // be successfully tracking it), remove indexes, and delete the entry. - if retErr != nil { - revokeCtx := namespace.ContextWithNamespace(m.quitContext, ns) - revResp, err := m.router.Route(revokeCtx, logical.RevokeRequest(req.Path, resp.Secret, resp.Data)) - if err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional internal error was encountered revoking the newly-generated secret: {{err}}", err)) - } else if revResp != nil && revResp.IsError() { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered revoking the newly-generated secret: {{err}}", revResp.Error())) - } - - if err := m.deleteEntry(ctx, le); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered deleting any lease associated with the newly-generated secret: {{err}}", err)) - } - - if err := m.removeIndexByToken(ctx, le); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered removing lease indexes associated with the newly-generated secret: {{err}}", err)) - } - } - }() - - // If the token is a batch token, we want to constrain the maximum lifetime - // by the token's lifetime - if te.Type == logical.TokenTypeBatch { - tokenLeaseTimes, err := m.FetchLeaseTimesByToken(ctx, te) - if err != nil { - return "", err - } - if le.ExpireTime.After(tokenLeaseTimes.ExpireTime) { - le.ExpireTime = tokenLeaseTimes.ExpireTime - } - } - - // Encode the entry - if err := m.persistEntry(ctx, le); err != nil { - return "", err - } - - // Maintain secondary index by token, except for orphan batch tokens - switch { - case te.Type != logical.TokenTypeBatch: - if err := m.createIndexByToken(ctx, le, le.ClientToken); err != nil { - return "", err - } - case te.Parent != "": - // If it's a non-orphan batch token, assign the secondary index to its - // parent - if err := m.createIndexByToken(ctx, le, te.Parent); err != nil { - return "", err - } - } - - // Setup revocation timer if there is a lease - m.updatePending(le, resp.Secret.LeaseTotal()) - - // Done - return le.LeaseID, nil -} - -// RegisterAuth is used to take an Auth response with an associated lease. -// The token does not get a LeaseID, but the lease management is handled by -// the expiration manager. -func (m *ExpirationManager) RegisterAuth(ctx context.Context, te *logical.TokenEntry, auth *logical.Auth) error { - defer metrics.MeasureSince([]string{"expire", "register-auth"}, time.Now()) - - if te.Type == logical.TokenTypeBatch { - return errors.New("cannot register a lease for a batch token") - } - - if auth.ClientToken == "" { - return errors.New("cannot register an auth lease with an empty token") - } - - if strings.Contains(te.Path, "..") { - return consts.ErrPathContainsParentReferences - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := m.tokenStore.SaltID(saltCtx, auth.ClientToken) - if err != nil { - return err - } - - leaseID := path.Join(te.Path, saltedID) - if tokenNS.ID != namespace.RootNamespaceID { - leaseID = fmt.Sprintf("%s.%s", leaseID, tokenNS.ID) - } - - // Create a lease entry - le := leaseEntry{ - LeaseID: leaseID, - ClientToken: auth.ClientToken, - Auth: auth, - Path: te.Path, - IssueTime: time.Now(), - ExpireTime: auth.ExpirationTime(), - namespace: tokenNS, - } - - // Encode the entry - if err := m.persistEntry(ctx, &le); err != nil { - return err - } - - // Setup revocation timer - m.updatePending(&le, auth.LeaseTotal()) - - return nil -} - -// FetchLeaseTimesByToken is a helper function to use token values to compute -// the leaseID, rather than pushing that logic back into the token store. -// As a special case, for a batch token it simply returns the information -// encoded on it. -func (m *ExpirationManager) FetchLeaseTimesByToken(ctx context.Context, te *logical.TokenEntry) (*leaseEntry, error) { - defer metrics.MeasureSince([]string{"expire", "fetch-lease-times-by-token"}, time.Now()) - - if te == nil { - return nil, errors.New("cannot fetch lease times for nil token") - } - - if te.Type == logical.TokenTypeBatch { - issueTime := time.Unix(te.CreationTime, 0) - return &leaseEntry{ - IssueTime: issueTime, - ExpireTime: issueTime.Add(te.TTL), - ClientTokenType: logical.TokenTypeBatch, - }, nil - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := m.tokenStore.SaltID(saltCtx, te.ID) - if err != nil { - return nil, err - } - - leaseID := path.Join(te.Path, saltedID) - - if tokenNS.ID != namespace.RootNamespaceID { - leaseID = fmt.Sprintf("%s.%s", leaseID, tokenNS.ID) - } - - return m.FetchLeaseTimes(ctx, leaseID) -} - -// FetchLeaseTimes is used to fetch the issue time, expiration time, and last -// renewed time of a lease entry. It returns a leaseEntry itself, but with only -// those values copied over. -func (m *ExpirationManager) FetchLeaseTimes(ctx context.Context, leaseID string) (*leaseEntry, error) { - defer metrics.MeasureSince([]string{"expire", "fetch-lease-times"}, time.Now()) - - m.pendingLock.RLock() - val := m.pending[leaseID] - m.pendingLock.RUnlock() - - if val.exportLeaseTimes != nil { - return val.exportLeaseTimes, nil - } - - // Load the entry - le, err := m.loadEntryInternal(ctx, leaseID, true, false) - if err != nil { - return nil, err - } - if le == nil { - return nil, nil - } - - return m.leaseTimesForExport(le), nil -} - -// Returns lease times for outside callers based on the full leaseEntry passed in -func (m *ExpirationManager) leaseTimesForExport(le *leaseEntry) *leaseEntry { - ret := &leaseEntry{ - IssueTime: le.IssueTime, - ExpireTime: le.ExpireTime, - LastRenewalTime: le.LastRenewalTime, - } - if le.Secret != nil { - ret.Secret = &logical.Secret{} - ret.Secret.Renewable = le.Secret.Renewable - ret.Secret.TTL = le.Secret.TTL - } - if le.Auth != nil { - ret.Auth = &logical.Auth{} - ret.Auth.Renewable = le.Auth.Renewable - ret.Auth.TTL = le.Auth.TTL - } - - return ret -} - -// updatePending is used to update a pending invocation for a lease -func (m *ExpirationManager) updatePending(le *leaseEntry, leaseTotal time.Duration) { - m.pendingLock.Lock() - defer m.pendingLock.Unlock() - - m.updatePendingInternal(le, leaseTotal) -} - -// updatePendingInternal is the locked version of updatePending; do not call -// this without a write lock on m.pending -func (m *ExpirationManager) updatePendingInternal(le *leaseEntry, leaseTotal time.Duration) { - // Check for an existing timer - pending, ok := m.pending[le.LeaseID] - - // If there is no expiry time, don't do anything - if le.ExpireTime.IsZero() { - // if the timer happened to exist, stop the time and delete it from the - // pending timers. - if ok { - pending.timer.Stop() - delete(m.pending, le.LeaseID) - } - return - } - - // Create entry if it does not exist or reset if it does - if ok { - pending.timer.Reset(leaseTotal) - } else { - timer := time.AfterFunc(leaseTotal, func() { - m.expireFunc(m.quitContext, m, le) - }) - pending = pendingInfo{ - timer: timer, - } - } - - // Extend the timer by the lease total - pending.exportLeaseTimes = m.leaseTimesForExport(le) - - m.pending[le.LeaseID] = pending -} - -// revokeEntry is used to attempt revocation of an internal entry -func (m *ExpirationManager) revokeEntry(ctx context.Context, le *leaseEntry) error { - // Revocation of login tokens is special since we can by-pass the - // backend and directly interact with the token store - if le.Auth != nil { - if le.ClientTokenType == logical.TokenTypeBatch { - return errors.New("batch tokens cannot be revoked") - } - - if err := m.tokenStore.revokeTree(ctx, le); err != nil { - return errwrap.Wrapf("failed to revoke token: {{err}}", err) - } - - return nil - } - - if le.Secret != nil { - // not sure if this is really valid to have a leaseEntry with a nil Secret - // (if there's a nil Secret, what are you really leasing?), but the tests - // create one, and good to be defensive - le.Secret.IssueTime = le.IssueTime - } - - // Make sure we're operating in the right namespace - nsCtx := namespace.ContextWithNamespace(ctx, le.namespace) - - // Handle standard revocation via backends - resp, err := m.router.Route(nsCtx, logical.RevokeRequest(le.Path, le.Secret, le.Data)) - if err != nil || (resp != nil && resp.IsError()) { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke entry: resp: %#v err: {{err}}", resp), err) - } - return nil -} - -// renewEntry is used to attempt renew of an internal entry -func (m *ExpirationManager) renewEntry(ctx context.Context, le *leaseEntry, increment time.Duration) (*logical.Response, error) { - secret := *le.Secret - secret.IssueTime = le.IssueTime - secret.Increment = increment - secret.LeaseID = "" - - // Make sure we're operating in the right namespace - nsCtx := namespace.ContextWithNamespace(ctx, le.namespace) - - req := logical.RenewRequest(le.Path, &secret, le.Data) - resp, err := m.router.Route(nsCtx, req) - if err != nil || (resp != nil && resp.IsError()) { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to renew entry: resp: %#v err: {{err}}", resp), err) - } - return resp, nil -} - -// renewAuthEntry is used to attempt renew of an auth entry. Only the token -// store should get the actual token ID intact. -func (m *ExpirationManager) renewAuthEntry(ctx context.Context, req *logical.Request, le *leaseEntry, increment time.Duration) (*logical.Response, error) { - if le.ClientTokenType == logical.TokenTypeBatch { - return logical.ErrorResponse("batch tokens cannot be renewed"), nil - } - - auth := *le.Auth - auth.IssueTime = le.IssueTime - auth.Increment = increment - if strings.HasPrefix(le.Path, "auth/token/") { - auth.ClientToken = le.ClientToken - } else { - auth.ClientToken = "" - } - - // Make sure we're operating in the right namespace - nsCtx := namespace.ContextWithNamespace(ctx, le.namespace) - - authReq := logical.RenewAuthRequest(le.Path, &auth, nil) - authReq.Connection = req.Connection - resp, err := m.router.Route(nsCtx, authReq) - if err != nil { - return nil, errwrap.Wrapf("failed to renew entry: {{err}}", err) - } - return resp, nil -} - -// loadEntry is used to read a lease entry -func (m *ExpirationManager) loadEntry(ctx context.Context, leaseID string) (*leaseEntry, error) { - // Take out the lease locks after we ensure we are in restore mode - restoreMode := m.inRestoreMode() - if restoreMode { - m.restoreModeLock.RLock() - defer m.restoreModeLock.RUnlock() - - restoreMode = m.inRestoreMode() - if restoreMode { - m.lockLease(leaseID) - defer m.unlockLease(leaseID) - } - } - - _, nsID := namespace.SplitIDFromString(leaseID) - if nsID != "" { - leaseNS, err := NamespaceByID(ctx, nsID, m.core) - if err != nil { - return nil, err - } - if leaseNS != nil { - ctx = namespace.ContextWithNamespace(ctx, leaseNS) - } - } else { - ctx = namespace.ContextWithNamespace(ctx, namespace.RootNamespace) - } - return m.loadEntryInternal(ctx, leaseID, restoreMode, true) -} - -// loadEntryInternal is used when you need to load an entry but also need to -// control the lifecycle of the restoreLock -func (m *ExpirationManager) loadEntryInternal(ctx context.Context, leaseID string, restoreMode bool, checkRestored bool) (*leaseEntry, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - view := m.leaseView(ns) - out, err := view.Get(ctx, leaseID) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read lease entry %s: {{err}}", leaseID), err) - } - if out == nil { - return nil, nil - } - le, err := decodeLeaseEntry(out.Value) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode lease entry %s: {{err}}", leaseID), err) - } - le.namespace = ns - - if restoreMode { - if checkRestored { - // If we have already loaded this lease, we don't need to update on - // load. In the case of renewal and revocation, updatePending will be - // done after making the appropriate modifications to the lease. - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return le, nil - } - } - - // Update the cache of restored leases, either synchronously or through - // the lazy loaded restore process - m.restoreLoaded.Store(le.LeaseID, struct{}{}) - - // Setup revocation timer - m.updatePending(le, le.ExpireTime.Sub(time.Now())) - } - return le, nil -} - -// persistEntry is used to persist a lease entry -func (m *ExpirationManager) persistEntry(ctx context.Context, le *leaseEntry) error { - // Encode the entry - buf, err := le.encode() - if err != nil { - return errwrap.Wrapf("failed to encode lease entry: {{err}}", err) - } - - // Write out to the view - ent := logical.StorageEntry{ - Key: le.LeaseID, - Value: buf, - } - if le.Auth != nil && len(le.Auth.Policies) == 1 && le.Auth.Policies[0] == "root" { - ent.SealWrap = true - } - - view := m.leaseView(le.namespace) - if err := view.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease entry: {{err}}", err) - } - return nil -} - -// deleteEntry is used to delete a lease entry -func (m *ExpirationManager) deleteEntry(ctx context.Context, le *leaseEntry) error { - view := m.leaseView(le.namespace) - if err := view.Delete(ctx, le.LeaseID); err != nil { - return errwrap.Wrapf("failed to delete lease entry: {{err}}", err) - } - return nil -} - -// createIndexByToken creates a secondary index from the token to a lease entry -func (m *ExpirationManager) createIndexByToken(ctx context.Context, le *leaseEntry, token string) error { - tokenNS := namespace.RootNamespace - saltCtx := namespace.ContextWithNamespace(ctx, namespace.RootNamespace) - _, nsID := namespace.SplitIDFromString(token) - if nsID != "" { - tokenNS, err := NamespaceByID(ctx, nsID, m.core) - if err != nil { - return err - } - if tokenNS != nil { - saltCtx = namespace.ContextWithNamespace(ctx, tokenNS) - } - } - - saltedID, err := m.tokenStore.SaltID(saltCtx, token) - if err != nil { - return err - } - - leaseSaltedID, err := m.tokenStore.SaltID(saltCtx, le.LeaseID) - if err != nil { - return err - } - - ent := logical.StorageEntry{ - Key: saltedID + "/" + leaseSaltedID, - Value: []byte(le.LeaseID), - } - tokenView := m.tokenIndexView(tokenNS) - if err := tokenView.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease index entry: {{err}}", err) - } - return nil -} - -// indexByToken looks up the secondary index from the token to a lease entry -func (m *ExpirationManager) indexByToken(ctx context.Context, le *leaseEntry) (*logical.StorageEntry, error) { - tokenNS := namespace.RootNamespace - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - _, nsID := namespace.SplitIDFromString(le.ClientToken) - if nsID != "" { - tokenNS, err := NamespaceByID(ctx, nsID, m.core) - if err != nil { - return nil, err - } - if tokenNS != nil { - saltCtx = namespace.ContextWithNamespace(ctx, tokenNS) - } - } - - saltedID, err := m.tokenStore.SaltID(saltCtx, le.ClientToken) - if err != nil { - return nil, err - } - - leaseSaltedID, err := m.tokenStore.SaltID(saltCtx, le.LeaseID) - if err != nil { - return nil, err - } - - key := saltedID + "/" + leaseSaltedID - tokenView := m.tokenIndexView(tokenNS) - entry, err := tokenView.Get(ctx, key) - if err != nil { - return nil, fmt.Errorf("failed to look up secondary index entry") - } - return entry, nil -} - -// removeIndexByToken removes the secondary index from the token to a lease entry -func (m *ExpirationManager) removeIndexByToken(ctx context.Context, le *leaseEntry) error { - tokenNS := namespace.RootNamespace - saltCtx := namespace.ContextWithNamespace(ctx, namespace.RootNamespace) - _, nsID := namespace.SplitIDFromString(le.ClientToken) - if nsID != "" { - tokenNS, err := NamespaceByID(ctx, nsID, m.core) - if err != nil { - return err - } - if tokenNS != nil { - saltCtx = namespace.ContextWithNamespace(ctx, tokenNS) - } - } - - saltedID, err := m.tokenStore.SaltID(saltCtx, le.ClientToken) - if err != nil { - return err - } - - leaseSaltedID, err := m.tokenStore.SaltID(saltCtx, le.LeaseID) - if err != nil { - return err - } - - key := saltedID + "/" + leaseSaltedID - tokenView := m.tokenIndexView(tokenNS) - if err := tokenView.Delete(ctx, key); err != nil { - return errwrap.Wrapf("failed to delete lease index entry: {{err}}", err) - } - return nil -} - -// CreateOrFetchRevocationLeaseByToken is used to create or fetch the matching -// leaseID for a particular token. The lease is set to expire immediately after -// it's created. -func (m *ExpirationManager) CreateOrFetchRevocationLeaseByToken(ctx context.Context, te *logical.TokenEntry) (string, error) { - // Fetch the saltedID of the token and construct the leaseID - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return "", err - } - if tokenNS == nil { - return "", namespace.ErrNoNamespace - } - - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := m.tokenStore.SaltID(saltCtx, te.ID) - if err != nil { - return "", err - } - leaseID := path.Join(te.Path, saltedID) - - if tokenNS.ID != namespace.RootNamespaceID { - leaseID = fmt.Sprintf("%s.%s", leaseID, tokenNS.ID) - } - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return "", err - } - - // If there's no associated leaseEntry for the token, we create one - if le == nil { - auth := &logical.Auth{ - ClientToken: te.ID, - LeaseOptions: logical.LeaseOptions{ - TTL: time.Nanosecond, - }, - } - - if strings.Contains(te.Path, "..") { - return "", consts.ErrPathContainsParentReferences - } - - // Create a lease entry - now := time.Now() - le = &leaseEntry{ - LeaseID: leaseID, - ClientToken: auth.ClientToken, - Auth: auth, - Path: te.Path, - IssueTime: now, - ExpireTime: now.Add(time.Nanosecond), - namespace: tokenNS, - } - - // Encode the entry - if err := m.persistEntry(ctx, le); err != nil { - return "", err - } - } - - return le.LeaseID, nil -} - -// lookupLeasesByToken is used to lookup all the leaseID's via the tokenID -func (m *ExpirationManager) lookupLeasesByToken(ctx context.Context, te *logical.TokenEntry) ([]string, error) { - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := m.tokenStore.SaltID(saltCtx, te.ID) - if err != nil { - return nil, err - } - - tokenView := m.tokenIndexView(tokenNS) - - // Scan via the index for sub-leases - prefix := saltedID + "/" - subKeys, err := tokenView.List(ctx, prefix) - if err != nil { - return nil, errwrap.Wrapf("failed to list leases: {{err}}", err) - } - - // Read each index entry - leaseIDs := make([]string, 0, len(subKeys)) - for _, sub := range subKeys { - out, err := tokenView.Get(ctx, prefix+sub) - if err != nil { - return nil, errwrap.Wrapf("failed to read lease index: {{err}}", err) - } - if out == nil { - continue - } - leaseIDs = append(leaseIDs, string(out.Value)) - } - return leaseIDs, nil -} - -// emitMetrics is invoked periodically to emit statistics -func (m *ExpirationManager) emitMetrics() { - m.pendingLock.RLock() - num := len(m.pending) - m.pendingLock.RUnlock() - metrics.SetGauge([]string{"expire", "num_leases"}, float32(num)) - // Check if lease count is greater than the threshold - if num > maxLeaseThreshold { - if atomic.LoadUint32(m.leaseCheckCounter) > 59 { - m.logger.Warn("lease count exceeds warning lease threshold") - atomic.StoreUint32(m.leaseCheckCounter, 0) - } else { - atomic.AddUint32(m.leaseCheckCounter, 1) - } - } -} - -// leaseEntry is used to structure the values the expiration -// manager stores. This is used to handle renew and revocation. -type leaseEntry struct { - LeaseID string `json:"lease_id"` - ClientToken string `json:"client_token"` - ClientTokenType logical.TokenType `json:"token_type"` - Path string `json:"path"` - Data map[string]interface{} `json:"data"` - Secret *logical.Secret `json:"secret"` - Auth *logical.Auth `json:"auth"` - IssueTime time.Time `json:"issue_time"` - ExpireTime time.Time `json:"expire_time"` - LastRenewalTime time.Time `json:"last_renewal_time"` - - namespace *namespace.Namespace -} - -// encode is used to JSON encode the lease entry -func (le *leaseEntry) encode() ([]byte, error) { - return json.Marshal(le) -} - -func (le *leaseEntry) renewable() (bool, error) { - switch { - // If there is no entry, cannot review to renew - case le == nil: - return false, fmt.Errorf("lease not found") - - case le.ExpireTime.IsZero(): - return false, fmt.Errorf("lease is not renewable") - - case le.ClientTokenType == logical.TokenTypeBatch: - return false, nil - - // Determine if the lease is expired - case le.ExpireTime.Before(time.Now()): - return false, fmt.Errorf("lease expired") - - // Determine if the lease is renewable - case le.Secret != nil && !le.Secret.Renewable: - return false, fmt.Errorf("lease is not renewable") - - case le.Auth != nil && !le.Auth.Renewable: - return false, fmt.Errorf("lease is not renewable") - } - - return true, nil -} - -func (le *leaseEntry) ttl() int64 { - return int64(le.ExpireTime.Sub(time.Now().Round(time.Second)).Seconds()) -} - -// decodeLeaseEntry is used to reverse encode and return a new entry -func decodeLeaseEntry(buf []byte) (*leaseEntry, error) { - out := new(leaseEntry) - return out, jsonutil.DecodeJSON(buf, out) -} diff --git a/vendor/github.com/hashicorp/vault/vault/expiration_util.go b/vendor/github.com/hashicorp/vault/vault/expiration_util.go deleted file mode 100644 index ab1454a2..00000000 --- a/vendor/github.com/hashicorp/vault/vault/expiration_util.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -func (m *ExpirationManager) leaseView(*namespace.Namespace) *BarrierView { - return m.idView -} - -func (m *ExpirationManager) tokenIndexView(*namespace.Namespace) *BarrierView { - return m.tokenView -} - -func (m *ExpirationManager) collectLeases() (map[*namespace.Namespace][]string, int, error) { - leaseCount := 0 - existing := make(map[*namespace.Namespace][]string) - keys, err := logical.CollectKeys(m.quitContext, m.leaseView(namespace.RootNamespace)) - if err != nil { - return nil, 0, errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - existing[namespace.RootNamespace] = keys - leaseCount += len(keys) - return existing, leaseCount, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/generate_root.go b/vendor/github.com/hashicorp/vault/vault/generate_root.go deleted file mode 100644 index 43443424..00000000 --- a/vendor/github.com/hashicorp/vault/vault/generate_root.go +++ /dev/null @@ -1,369 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/helper/xor" - "github.com/hashicorp/vault/shamir" -) - -const coreDROperationTokenPath = "core/dr-operation-token" - -var ( - // GenerateStandardRootTokenStrategy is the strategy used to generate a - // typical root token - GenerateStandardRootTokenStrategy GenerateRootStrategy = generateStandardRootToken{} - - // GenerateDROperationTokenStrategy is the strategy used to generate a - // DR operational token - GenerateDROperationTokenStrategy GenerateRootStrategy = generateStandardRootToken{} -) - -// GenerateRootStrategy allows us to swap out the strategy we want to use to -// create a token upon completion of the generate root process. -type GenerateRootStrategy interface { - generate(context.Context, *Core) (string, func(), error) -} - -// generateStandardRootToken implements the GenerateRootStrategy and is in -// charge of creating standard root tokens. -type generateStandardRootToken struct{} - -func (g generateStandardRootToken) generate(ctx context.Context, c *Core) (string, func(), error) { - te, err := c.tokenStore.rootToken(ctx) - if err != nil { - c.logger.Error("root token generation failed", "error", err) - return "", nil, err - } - if te == nil { - c.logger.Error("got nil token entry back from root generation") - return "", nil, fmt.Errorf("got nil token entry back from root generation") - } - - cleanupFunc := func() { - c.tokenStore.revokeOrphan(ctx, te.ID) - } - - return te.ID, cleanupFunc, nil -} - -// GenerateRootConfig holds the configuration for a root generation -// command. -type GenerateRootConfig struct { - Nonce string - PGPKey string - PGPFingerprint string - OTP string - Strategy GenerateRootStrategy -} - -// GenerateRootResult holds the result of a root generation update -// command -type GenerateRootResult struct { - Progress int - Required int - EncodedToken string - PGPFingerprint string -} - -// GenerateRootProgress is used to return the root generation progress (num shares) -func (c *Core) GenerateRootProgress() (int, error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return 0, consts.ErrSealed - } - if c.standby { - return 0, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - return len(c.generateRootProgress), nil -} - -// GenerateRootConfiguration is used to read the root generation configuration -// It stubbornly refuses to return the OTP if one is there. -func (c *Core) GenerateRootConfiguration() (*GenerateRootConfig, error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby { - return nil, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Copy the config if any - var conf *GenerateRootConfig - if c.generateRootConfig != nil { - conf = new(GenerateRootConfig) - *conf = *c.generateRootConfig - conf.OTP = "" - conf.Strategy = nil - } - return conf, nil -} - -// GenerateRootInit is used to initialize the root generation settings -func (c *Core) GenerateRootInit(otp, pgpKey string, strategy GenerateRootStrategy) error { - var fingerprint string - switch { - case len(otp) > 0: - if len(otp) != TokenLength+2 { - return fmt.Errorf("OTP string is wrong length") - } - - case len(pgpKey) > 0: - fingerprints, err := pgpkeys.GetFingerprints([]string{pgpKey}, nil) - if err != nil { - return errwrap.Wrapf("error parsing PGP key: {{err}}", err) - } - if len(fingerprints) != 1 || fingerprints[0] == "" { - return fmt.Errorf("could not acquire PGP key entity") - } - fingerprint = fingerprints[0] - - default: - return fmt.Errorf("otp or pgp_key parameter must be provided") - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return consts.ErrSealed - } - if c.standby { - return consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Prevent multiple concurrent root generations - if c.generateRootConfig != nil { - return fmt.Errorf("root generation already in progress") - } - - // Copy the configuration - generationNonce, err := uuid.GenerateUUID() - if err != nil { - return err - } - - c.generateRootConfig = &GenerateRootConfig{ - Nonce: generationNonce, - OTP: otp, - PGPKey: pgpKey, - PGPFingerprint: fingerprint, - Strategy: strategy, - } - - if c.logger.IsInfo() { - switch strategy.(type) { - case generateStandardRootToken: - c.logger.Info("root generation initialized", "nonce", c.generateRootConfig.Nonce) - default: - c.logger.Info("dr operation token generation initialized", "nonce", c.generateRootConfig.Nonce) - } - } - - return nil -} - -// GenerateRootUpdate is used to provide a new key part -func (c *Core) GenerateRootUpdate(ctx context.Context, key []byte, nonce string, strategy GenerateRootStrategy) (*GenerateRootResult, error) { - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, &ErrInvalidKey{fmt.Sprintf("key is shorter than minimum %d bytes", min)} - } - if len(key) > max { - return nil, &ErrInvalidKey{fmt.Sprintf("key is longer than maximum %d bytes", max)} - } - - // Get the seal configuration - var config *SealConfig - var err error - if c.seal.RecoveryKeySupported() { - config, err = c.seal.RecoveryConfig(ctx) - if err != nil { - return nil, err - } - } else { - config, err = c.seal.BarrierConfig(ctx) - if err != nil { - return nil, err - } - } - - // Ensure the barrier is initialized - if config == nil { - return nil, ErrNotInit - } - - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby { - return nil, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Ensure a generateRoot is in progress - if c.generateRootConfig == nil { - return nil, fmt.Errorf("no root generation in progress") - } - - if nonce != c.generateRootConfig.Nonce { - return nil, fmt.Errorf("incorrect nonce supplied; nonce for this root generation operation is %q", c.generateRootConfig.Nonce) - } - - if strategy != c.generateRootConfig.Strategy { - return nil, fmt.Errorf("incorrect strategy supplied; a generate root operation of another type is already in progress") - } - - // Check if we already have this piece - for _, existing := range c.generateRootProgress { - if bytes.Equal(existing, key) { - return nil, fmt.Errorf("given key has already been provided during this generation operation") - } - } - - // Store this key - c.generateRootProgress = append(c.generateRootProgress, key) - progress := len(c.generateRootProgress) - - // Check if we don't have enough keys to unlock - if len(c.generateRootProgress) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot generate root, not enough keys", "keys", progress, "threshold", config.SecretThreshold) - } - return &GenerateRootResult{ - Progress: progress, - Required: config.SecretThreshold, - PGPFingerprint: c.generateRootConfig.PGPFingerprint, - }, nil - } - - // Recover the master key - var masterKey []byte - if config.SecretThreshold == 1 { - masterKey = c.generateRootProgress[0] - c.generateRootProgress = nil - } else { - masterKey, err = shamir.Combine(c.generateRootProgress) - c.generateRootProgress = nil - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - - // Verify the master key - if c.seal.RecoveryKeySupported() { - if err := c.seal.VerifyRecoveryKey(ctx, masterKey); err != nil { - c.logger.Error("root generation aborted, recovery key verification failed", "error", err) - return nil, err - } - } else { - if err := c.barrier.VerifyMaster(masterKey); err != nil { - c.logger.Error("root generation aborted, master key verification failed", "error", err) - return nil, err - } - } - - // Run the generate strategy - token, cleanupFunc, err := strategy.generate(ctx, c) - if err != nil { - return nil, err - } - - var tokenBytes []byte - - // Get the encoded value first so that if there is an error we don't create - // the root token. - switch { - case len(c.generateRootConfig.OTP) > 0: - // This function performs decoding checks so rather than decode the OTP, - // just encode the value we're passing in. - tokenBytes, err = xor.XORBytes([]byte(c.generateRootConfig.OTP), []byte(token)) - if err != nil { - cleanupFunc() - c.logger.Error("xor of root token failed", "error", err) - return nil, err - } - token = base64.RawStdEncoding.EncodeToString(tokenBytes) - - case len(c.generateRootConfig.PGPKey) > 0: - _, tokenBytesArr, err := pgpkeys.EncryptShares([][]byte{[]byte(token)}, []string{c.generateRootConfig.PGPKey}) - if err != nil { - cleanupFunc() - c.logger.Error("error encrypting new root token", "error", err) - return nil, err - } - token = base64.StdEncoding.EncodeToString(tokenBytesArr[0]) - - default: - cleanupFunc() - return nil, fmt.Errorf("unreachable condition") - } - - results := &GenerateRootResult{ - Progress: progress, - Required: config.SecretThreshold, - EncodedToken: token, - PGPFingerprint: c.generateRootConfig.PGPFingerprint, - } - - switch strategy.(type) { - case generateStandardRootToken: - if c.logger.IsInfo() { - c.logger.Info("root generation finished", "nonce", c.generateRootConfig.Nonce) - } - default: - if c.logger.IsInfo() { - c.logger.Info("dr operation token generation finished", "nonce", c.generateRootConfig.Nonce) - } - } - - c.generateRootProgress = nil - c.generateRootConfig = nil - return results, nil -} - -// GenerateRootCancel is used to cancel an in-progress root generation -func (c *Core) GenerateRootCancel() error { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return consts.ErrSealed - } - if c.standby { - return consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Clear any progress or config - c.generateRootConfig = nil - c.generateRootProgress = nil - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/ha.go b/vendor/github.com/hashicorp/vault/vault/ha.go deleted file mode 100644 index cd0d1467..00000000 --- a/vendor/github.com/hashicorp/vault/vault/ha.go +++ /dev/null @@ -1,875 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/x509" - "errors" - "fmt" - "sync/atomic" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/oklog/run" -) - -const ( - // lockRetryInterval is the interval we re-attempt to acquire the - // HA lock if an error is encountered - lockRetryInterval = 10 * time.Second - - // leaderCheckInterval is how often a standby checks for a new leader - leaderCheckInterval = 2500 * time.Millisecond - - // keyRotateCheckInterval is how often a standby checks for a key - // rotation taking place. - keyRotateCheckInterval = 10 * time.Second - - // keyRotateGracePeriod is how long we allow an upgrade path - // for standby instances before we delete the upgrade keys - keyRotateGracePeriod = 2 * time.Minute - - // leaderPrefixCleanDelay is how long to wait between deletions - // of orphaned leader keys, to prevent slamming the backend. - leaderPrefixCleanDelay = 200 * time.Millisecond -) - -var ( - addEnterpriseHaActors func(*Core, *run.Group) chan func() = addEnterpriseHaActorsNoop - interruptPerfStandby func(chan func(), chan struct{}) chan struct{} = interruptPerfStandbyNoop -) - -func addEnterpriseHaActorsNoop(*Core, *run.Group) chan func() { return nil } -func interruptPerfStandbyNoop(chan func(), chan struct{}) chan struct{} { - return make(chan struct{}) -} - -// Standby checks if the Vault is in standby mode -func (c *Core) Standby() (bool, error) { - c.stateLock.RLock() - standby := c.standby - c.stateLock.RUnlock() - return standby, nil -} - -// PerfStandby checks if the vault is a performance standby -func (c *Core) PerfStandby() bool { - c.stateLock.RLock() - perfStandby := c.perfStandby - c.stateLock.RUnlock() - return perfStandby -} - -// Leader is used to get the current active leader -func (c *Core) Leader() (isLeader bool, leaderAddr, clusterAddr string, err error) { - // Check if HA enabled. We don't need the lock for this check as it's set - // on startup and never modified - if c.ha == nil { - return false, "", "", ErrHANotEnabled - } - - // Check if sealed - if c.Sealed() { - return false, "", "", consts.ErrSealed - } - - c.stateLock.RLock() - - // Check if we are the leader - if !c.standby { - c.stateLock.RUnlock() - return true, c.redirectAddr, c.clusterAddr, nil - } - - // Initialize a lock - lock, err := c.ha.LockWith(CoreLockPath, "read") - if err != nil { - c.stateLock.RUnlock() - return false, "", "", err - } - - // Read the value - held, leaderUUID, err := lock.Value() - if err != nil { - c.stateLock.RUnlock() - return false, "", "", err - } - if !held { - c.stateLock.RUnlock() - return false, "", "", nil - } - - c.clusterLeaderParamsLock.RLock() - localLeaderUUID := c.clusterLeaderUUID - localRedirAddr := c.clusterLeaderRedirectAddr - localClusterAddr := c.clusterLeaderClusterAddr - c.clusterLeaderParamsLock.RUnlock() - - // If the leader hasn't changed, return the cached value; nothing changes - // mid-leadership, and the barrier caches anyways - if leaderUUID == localLeaderUUID && localRedirAddr != "" { - c.stateLock.RUnlock() - return false, localRedirAddr, localClusterAddr, nil - } - - c.logger.Trace("found new active node information, refreshing") - - defer c.stateLock.RUnlock() - c.clusterLeaderParamsLock.Lock() - defer c.clusterLeaderParamsLock.Unlock() - - // Validate base conditions again - if leaderUUID == c.clusterLeaderUUID && c.clusterLeaderRedirectAddr != "" { - return false, localRedirAddr, localClusterAddr, nil - } - - key := coreLeaderPrefix + leaderUUID - // Use background because postUnseal isn't run on standby - entry, err := c.barrier.Get(context.Background(), key) - if err != nil { - return false, "", "", err - } - if entry == nil { - return false, "", "", nil - } - - var oldAdv bool - - var adv activeAdvertisement - err = jsonutil.DecodeJSON(entry.Value, &adv) - if err != nil { - // Fall back to pre-struct handling - adv.RedirectAddr = string(entry.Value) - c.logger.Debug("parsed redirect addr for new active node", "redirect_addr", adv.RedirectAddr) - oldAdv = true - } - - if !oldAdv { - c.logger.Debug("parsing information for new active node", "active_cluster_addr", adv.ClusterAddr, "active_redirect_addr", adv.RedirectAddr) - - // Ensure we are using current values - err = c.loadLocalClusterTLS(adv) - if err != nil { - return false, "", "", err - } - - // This will ensure that we both have a connection at the ready and that - // the address is the current known value - // Since this is standby, we don't use the active context. Later we may - // use a process-scoped context - err = c.refreshRequestForwardingConnection(context.Background(), adv.ClusterAddr) - if err != nil { - return false, "", "", err - } - } - - // Don't set these until everything has been parsed successfully or we'll - // never try again - c.clusterLeaderRedirectAddr = adv.RedirectAddr - c.clusterLeaderClusterAddr = adv.ClusterAddr - c.clusterLeaderUUID = leaderUUID - - return false, adv.RedirectAddr, adv.ClusterAddr, nil -} - -// StepDown is used to step down from leadership -func (c *Core) StepDown(httpCtx context.Context, req *logical.Request) (retErr error) { - defer metrics.MeasureSince([]string{"core", "step_down"}, time.Now()) - - if req == nil { - retErr = multierror.Append(retErr, errors.New("nil request to step-down")) - return retErr - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil - } - if c.ha == nil || c.standby { - return nil - } - - ctx, cancel := context.WithCancel(namespace.RootContext(nil)) - defer cancel() - - go func() { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }() - - acl, te, entity, identityPolicies, err := c.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - retErr = multierror.Append(retErr, err) - return retErr - } - - // Audit-log the request before going any further - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Accessor: req.ClientTokenAccessor, - } - if te != nil { - auth.IdentityPolicies = identityPolicies[te.NamespaceID] - delete(identityPolicies, te.NamespaceID) - auth.ExternalNamespacePolicies = identityPolicies - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies[te.NamespaceID]...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - auth.TokenType = te.Type - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, errors.New("failed to audit request, cannot continue")) - return retErr - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - // Attempt to use the token (decrement num_uses) - if te != nil { - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return retErr - } - if te == nil { - // Token has been revoked - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - return retErr - } - } - - // Verify that this operation is allowed - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - RootPrivsRequired: true, - }) - if !authResults.Allowed { - retErr = multierror.Append(retErr, authResults.Error) - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return retErr - } - - if te != nil && te.NumUses == tokenRevocationPending { - // Token needs to be revoked. We do this immediately here because - // we won't have a token store after sealing. - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(c.activeContext, te) - if err == nil { - err = c.expiration.Revoke(c.activeContext, leaseID) - } - if err != nil { - c.logger.Error("token needed revocation before step-down but failed to revoke", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - } - } - - select { - case c.manualStepDownCh <- struct{}{}: - default: - c.logger.Warn("manual step-down operation already queued") - } - - return retErr -} - -// runStandby is a long running process that manages a number of the HA -// subsystems. -func (c *Core) runStandby(doneCh, manualStepDownCh, stopCh chan struct{}) { - defer close(doneCh) - defer close(manualStepDownCh) - c.logger.Info("entering standby mode") - - var g run.Group - newLeaderCh := addEnterpriseHaActors(c, &g) - { - // This will cause all the other actors to close when the stop channel - // is closed. - g.Add(func() error { - <-stopCh - return nil - }, func(error) {}) - } - { - // Monitor for key rotation - keyRotateStop := make(chan struct{}) - - g.Add(func() error { - c.periodicCheckKeyUpgrade(context.Background(), keyRotateStop) - return nil - }, func(error) { - close(keyRotateStop) - c.logger.Debug("shutting down periodic key rotation checker") - }) - } - { - // Monitor for new leadership - checkLeaderStop := make(chan struct{}) - - g.Add(func() error { - c.periodicLeaderRefresh(newLeaderCh, checkLeaderStop) - return nil - }, func(error) { - close(checkLeaderStop) - c.logger.Debug("shutting down periodic leader refresh") - }) - } - { - // Wait for leadership - leaderStopCh := make(chan struct{}) - - g.Add(func() error { - c.waitForLeadership(newLeaderCh, manualStepDownCh, leaderStopCh) - return nil - }, func(error) { - close(leaderStopCh) - c.logger.Debug("shutting down leader elections") - }) - } - - // Start all the actors - g.Run() -} - -// waitForLeadership is a long running routine that is used when an HA backend -// is enabled. It waits until we are leader and switches this Vault to -// active. -func (c *Core) waitForLeadership(newLeaderCh chan func(), manualStepDownCh, stopCh chan struct{}) { - var manualStepDown bool - for { - // Check for a shutdown - select { - case <-stopCh: - c.logger.Debug("stop channel triggered in runStandby") - return - default: - // If we've just down, we could instantly grab the lock again. Give - // the other nodes a chance. - if manualStepDown { - time.Sleep(manualStepDownSleepPeriod) - manualStepDown = false - } - } - - // Create a lock - uuid, err := uuid.GenerateUUID() - if err != nil { - c.logger.Error("failed to generate uuid", "error", err) - return - } - lock, err := c.ha.LockWith(CoreLockPath, uuid) - if err != nil { - c.logger.Error("failed to create lock", "error", err) - return - } - - // Attempt the acquisition - leaderLostCh := c.acquireLock(lock, stopCh) - - // Bail if we are being shutdown - if leaderLostCh == nil { - return - } - c.logger.Info("acquired lock, enabling active operation") - - // This is used later to log a metrics event; this can be helpful to - // detect flapping - activeTime := time.Now() - - continueCh := interruptPerfStandby(newLeaderCh, stopCh) - // Grab the statelock or stop - if stopped := grabLockOrStop(c.stateLock.Lock, c.stateLock.Unlock, stopCh); stopped { - lock.Unlock() - close(continueCh) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - - if c.Sealed() { - c.logger.Warn("grabbed HA lock but already sealed, exiting") - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - - // Store the lock so that we can manually clear it later if needed - c.heldHALock = lock - - // Create the active context - activeCtx, activeCtxCancel := context.WithCancel(namespace.RootContext(nil)) - c.activeContext = activeCtx - c.activeContextCancelFunc.Store(activeCtxCancel) - - // This block is used to wipe barrier/seal state and verify that - // everything is sane. If we have no sanity in the barrier, we actually - // seal, as there's little we can do. - { - c.seal.SetBarrierConfig(activeCtx, nil) - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(activeCtx, nil) - } - - if err := c.performKeyUpgrades(activeCtx); err != nil { - // We call this in a goroutine so that we can give up the - // statelock and have this shut us down; sealInternal has a - // workflow where it watches for the stopCh to close so we want - // to return from here - c.logger.Error("error performing key upgrades", "error", err) - go c.Shutdown() - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - } - - { - // Clear previous local cluster cert info so we generate new. Since the - // UUID will have changed, standbys will know to look for new info - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - if err := c.setupCluster(activeCtx); err != nil { - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - c.logger.Error("cluster setup failed", "error", err) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - - } - // Advertise as leader - if err := c.advertiseLeader(activeCtx, uuid, leaderLostCh); err != nil { - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - c.logger.Error("leader advertisement setup failed", "error", err) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - - // Attempt the post-unseal process - err = c.postUnseal(activeCtx, activeCtxCancel, standardUnsealStrategy{}) - if err == nil { - c.standby = false - } - - close(continueCh) - c.stateLock.Unlock() - - // Handle a failure to unseal - if err != nil { - c.logger.Error("post-unseal setup failed", "error", err) - lock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - - // Monitor a loss of leadership - select { - case <-leaderLostCh: - c.logger.Warn("leadership lost, stopping active operation") - case <-stopCh: - case <-manualStepDownCh: - manualStepDown = true - c.logger.Warn("stepping down from active operation to standby") - } - - // Stop Active Duty - { - // Spawn this in a go routine so we can cancel the context and - // unblock any inflight requests that are holding the statelock. - go func() { - select { - case <-activeCtx.Done(): - // Attempt to drain any inflight requests - case <-time.After(DefaultMaxRequestDuration): - activeCtxCancel() - } - }() - - // Grab lock if we are not stopped - stopped := grabLockOrStop(c.stateLock.Lock, c.stateLock.Unlock, stopCh) - - // Cancel the context incase the above go routine hasn't done it - // yet - activeCtxCancel() - metrics.MeasureSince([]string{"core", "leadership_lost"}, activeTime) - - // Mark as standby - c.standby = true - - // Seal - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - } - - // If we are not meant to keep the HA lock, clear it - if atomic.LoadUint32(c.keepHALockOnStepDown) == 0 { - if err := c.clearLeader(uuid); err != nil { - c.logger.Error("clearing leader advertisement failed", "error", err) - } - - c.heldHALock.Unlock() - c.heldHALock = nil - } - - // If we are stopped return, otherwise unlock the statelock - if stopped { - return - } - c.stateLock.Unlock() - } - } -} - -func grabLockOrStop(lockFunc, unlockFunc func(), stopCh chan struct{}) (stopped bool) { - // Grab the lock as we need it for cluster setup, which needs to happen - // before advertising; - lockGrabbedCh := make(chan struct{}) - go func() { - // Grab the lock - lockFunc() - // If stopCh has been closed, which only happens while the - // stateLock is held, we have actually terminated, so we just - // instantly give up the lock, otherwise we notify that it's ready - // for consumption - select { - case <-stopCh: - unlockFunc() - default: - close(lockGrabbedCh) - } - }() - - select { - case <-stopCh: - return true - case <-lockGrabbedCh: - // We now have the lock and can use it - } - - return false -} - -// This checks the leader periodically to ensure that we switch RPC to a new -// leader pretty quickly. There is logic in Leader() already to not make this -// onerous and avoid more traffic than needed, so we just call that and ignore -// the result. -func (c *Core) periodicLeaderRefresh(newLeaderCh chan func(), stopCh chan struct{}) { - opCount := new(int32) - - clusterAddr := "" - for { - select { - case <-time.After(leaderCheckInterval): - count := atomic.AddInt32(opCount, 1) - if count > 1 { - atomic.AddInt32(opCount, -1) - continue - } - // We do this in a goroutine because otherwise if this refresh is - // called while we're shutting down the call to Leader() can - // deadlock, which then means stopCh can never been seen and we can - // block shutdown - go func() { - // Bind locally, as the race detector is tripping here - lopCount := opCount - isLeader, _, newClusterAddr, _ := c.Leader() - - if !isLeader && newClusterAddr != clusterAddr && newLeaderCh != nil { - select { - case newLeaderCh <- nil: - c.logger.Debug("new leader found, triggering new leader channel") - clusterAddr = newClusterAddr - default: - c.logger.Debug("new leader found, but still processing previous leader change") - } - - } - atomic.AddInt32(lopCount, -1) - }() - case <-stopCh: - return - } - } -} - -// periodicCheckKeyUpgrade is used to watch for key rotation events as a standby -func (c *Core) periodicCheckKeyUpgrade(ctx context.Context, stopCh chan struct{}) { - opCount := new(int32) - for { - select { - case <-time.After(keyRotateCheckInterval): - count := atomic.AddInt32(opCount, 1) - if count > 1 { - atomic.AddInt32(opCount, -1) - continue - } - - go func() { - // Bind locally, as the race detector is tripping here - lopCount := opCount - - // Only check if we are a standby - c.stateLock.RLock() - standby := c.standby - c.stateLock.RUnlock() - if !standby { - atomic.AddInt32(lopCount, -1) - return - } - - // Check for a poison pill. If we can read it, it means we have stale - // keys (e.g. from replication being activated) and we need to seal to - // be unsealed again. - entry, _ := c.barrier.Get(ctx, poisonPillPath) - if entry != nil && len(entry.Value) > 0 { - c.logger.Warn("encryption keys have changed out from underneath us (possibly due to replication enabling), must be unsealed again") - go c.Shutdown() - atomic.AddInt32(lopCount, -1) - return - } - - if err := c.checkKeyUpgrades(ctx); err != nil { - c.logger.Error("key rotation periodic upgrade check failed", "error", err) - } - - atomic.AddInt32(lopCount, -1) - return - }() - case <-stopCh: - return - } - } -} - -// checkKeyUpgrades is used to check if there have been any key rotations -// and if there is a chain of upgrades available -func (c *Core) checkKeyUpgrades(ctx context.Context) error { - for { - // Check for an upgrade - didUpgrade, newTerm, err := c.barrier.CheckUpgrade(ctx) - if err != nil { - return err - } - - // Nothing to do if no upgrade - if !didUpgrade { - break - } - if c.logger.IsInfo() { - c.logger.Info("upgraded to new key term", "term", newTerm) - } - } - return nil -} - -func (c *Core) performKeyUpgrades(ctx context.Context) error { - if err := c.checkKeyUpgrades(ctx); err != nil { - return errwrap.Wrapf("error checking for key upgrades: {{err}}", err) - } - - if err := c.barrier.ReloadMasterKey(ctx); err != nil { - return errwrap.Wrapf("error reloading master key: {{err}}", err) - } - - if err := c.barrier.ReloadKeyring(ctx); err != nil { - return errwrap.Wrapf("error reloading keyring: {{err}}", err) - } - - if err := c.scheduleUpgradeCleanup(ctx); err != nil { - return errwrap.Wrapf("error scheduling upgrade cleanup: {{err}}", err) - } - - return nil -} - -// scheduleUpgradeCleanup is used to ensure that all the upgrade paths -// are cleaned up in a timely manner if a leader failover takes place -func (c *Core) scheduleUpgradeCleanup(ctx context.Context) error { - // List the upgrades - upgrades, err := c.barrier.List(ctx, keyringUpgradePrefix) - if err != nil { - return errwrap.Wrapf("failed to list upgrades: {{err}}", err) - } - - // Nothing to do if no upgrades - if len(upgrades) == 0 { - return nil - } - - // Schedule cleanup for all of them - time.AfterFunc(keyRotateGracePeriod, func() { - sealed, err := c.barrier.Sealed() - if err != nil { - c.logger.Warn("failed to check barrier status at upgrade cleanup time") - return - } - if sealed { - c.logger.Warn("barrier sealed at upgrade cleanup time") - return - } - for _, upgrade := range upgrades { - path := fmt.Sprintf("%s%s", keyringUpgradePrefix, upgrade) - if err := c.barrier.Delete(ctx, path); err != nil { - c.logger.Error("failed to cleanup upgrade", "path", path, "error", err) - } - } - }) - return nil -} - -// acquireLock blocks until the lock is acquired, returning the leaderLostCh -func (c *Core) acquireLock(lock physical.Lock, stopCh <-chan struct{}) <-chan struct{} { - for { - // Attempt lock acquisition - leaderLostCh, err := lock.Lock(stopCh) - if err == nil { - return leaderLostCh - } - - // Retry the acquisition - c.logger.Error("failed to acquire lock", "error", err) - select { - case <-time.After(lockRetryInterval): - case <-stopCh: - return nil - } - } -} - -// advertiseLeader is used to advertise the current node as leader -func (c *Core) advertiseLeader(ctx context.Context, uuid string, leaderLostCh <-chan struct{}) error { - go c.cleanLeaderPrefix(ctx, uuid, leaderLostCh) - - var key *ecdsa.PrivateKey - switch c.localClusterPrivateKey.Load().(type) { - case *ecdsa.PrivateKey: - key = c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey) - default: - c.logger.Error("unknown cluster private key type", "key_type", fmt.Sprintf("%T", c.localClusterPrivateKey.Load())) - return fmt.Errorf("unknown cluster private key type %T", c.localClusterPrivateKey.Load()) - } - - keyParams := &clusterKeyParams{ - Type: corePrivateKeyTypeP521, - X: key.X, - Y: key.Y, - D: key.D, - } - - locCert := c.localClusterCert.Load().([]byte) - localCert := make([]byte, len(locCert)) - copy(localCert, locCert) - adv := &activeAdvertisement{ - RedirectAddr: c.redirectAddr, - ClusterAddr: c.clusterAddr, - ClusterCert: localCert, - ClusterKeyParams: keyParams, - } - val, err := jsonutil.EncodeJSON(adv) - if err != nil { - return err - } - ent := &Entry{ - Key: coreLeaderPrefix + uuid, - Value: val, - } - err = c.barrier.Put(ctx, ent) - if err != nil { - return err - } - - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifyActiveStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify active status", "error", err) - } - } - } - return nil -} - -func (c *Core) cleanLeaderPrefix(ctx context.Context, uuid string, leaderLostCh <-chan struct{}) { - keys, err := c.barrier.List(ctx, coreLeaderPrefix) - if err != nil { - c.logger.Error("failed to list entries in core/leader", "error", err) - return - } - for len(keys) > 0 { - select { - case <-time.After(leaderPrefixCleanDelay): - if keys[0] != uuid { - c.barrier.Delete(ctx, coreLeaderPrefix+keys[0]) - } - keys = keys[1:] - case <-leaderLostCh: - return - } - } -} - -// clearLeader is used to clear our leadership entry -func (c *Core) clearLeader(uuid string) error { - key := coreLeaderPrefix + uuid - err := c.barrier.Delete(context.Background(), key) - - // Advertise ourselves as a standby - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifyActiveStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify standby status", "error", err) - } - } - } - - return err -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_lookup.go b/vendor/github.com/hashicorp/vault/vault/identity_lookup.go deleted file mode 100644 index 4a4b0eb0..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_lookup.go +++ /dev/null @@ -1,329 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func lookupPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "lookup/entity$", - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the entity.", - }, - "id": { - Type: framework.TypeString, - Description: "ID of the entity.", - }, - "alias_id": { - Type: framework.TypeString, - Description: "ID of the alias.", - }, - "alias_name": { - Type: framework.TypeString, - Description: "Name of the alias. This should be supplied in conjunction with 'alias_mount_accessor'.", - }, - "alias_mount_accessor": { - Type: framework.TypeString, - Description: "Accessor of the mount to which the alias belongs to. This should be supplied in conjunction with 'alias_name'.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathLookupEntityUpdate(), - }, - - HelpSynopsis: strings.TrimSpace(lookupHelp["lookup-entity"][0]), - HelpDescription: strings.TrimSpace(lookupHelp["lookup-entity"][1]), - }, - { - Pattern: "lookup/group$", - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the group.", - }, - "id": { - Type: framework.TypeString, - Description: "ID of the group.", - }, - "alias_id": { - Type: framework.TypeString, - Description: "ID of the alias.", - }, - "alias_name": { - Type: framework.TypeString, - Description: "Name of the alias. This should be supplied in conjunction with 'alias_mount_accessor'.", - }, - "alias_mount_accessor": { - Type: framework.TypeString, - Description: "Accessor of the mount to which the alias belongs to. This should be supplied in conjunction with 'alias_name'.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathLookupGroupUpdate(), - }, - - HelpSynopsis: strings.TrimSpace(lookupHelp["lookup-group"][0]), - HelpDescription: strings.TrimSpace(lookupHelp["lookup-group"][1]), - }, - } -} - -func (i *IdentityStore) pathLookupEntityUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var entity *identity.Entity - var err error - - inputCount := 0 - - id := "" - idRaw, ok := d.GetOk("id") - if ok { - inputCount++ - id = idRaw.(string) - } - - name := "" - nameRaw, ok := d.GetOk("name") - if ok { - inputCount++ - name = nameRaw.(string) - } - - aliasID := "" - aliasIDRaw, ok := d.GetOk("alias_id") - if ok { - inputCount++ - aliasID = aliasIDRaw.(string) - } - - aliasName := "" - aliasNameRaw, ok := d.GetOk("alias_name") - if ok { - inputCount++ - aliasName = aliasNameRaw.(string) - } - - aliasMountAccessor := "" - aliasMountAccessorRaw, ok := d.GetOk("alias_mount_accessor") - if ok { - inputCount++ - aliasMountAccessor = aliasMountAccessorRaw.(string) - } - - switch { - case inputCount == 0: - return logical.ErrorResponse(fmt.Sprintf("query parameter not supplied")), nil - - case inputCount != 1: - switch { - case inputCount == 2 && aliasName != "" && aliasMountAccessor != "": - default: - return logical.ErrorResponse(fmt.Sprintf("query parameter conflict; please supply distinct set of query parameters")), nil - } - - case inputCount == 1: - switch { - case aliasName != "" || aliasMountAccessor != "": - return logical.ErrorResponse(fmt.Sprintf("both 'alias_name' and 'alias_mount_accessor' needs to be set")), nil - } - } - - switch { - case id != "": - entity, err = i.MemDBEntityByID(id, false) - if err != nil { - return nil, err - } - - case name != "": - entity, err = i.MemDBEntityByName(ctx, name, false) - if err != nil { - return nil, err - } - - case aliasID != "": - alias, err := i.MemDBAliasByID(aliasID, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - entity, err = i.MemDBEntityByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - - case aliasName != "" && aliasMountAccessor != "": - alias, err := i.MemDBAliasByFactors(aliasMountAccessor, aliasName, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - entity, err = i.MemDBEntityByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - } - - if entity == nil { - return nil, nil - } - - return i.handleEntityReadCommon(ctx, entity) - } -} - -func (i *IdentityStore) pathLookupGroupUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var group *identity.Group - var err error - - inputCount := 0 - - id := "" - idRaw, ok := d.GetOk("id") - if ok { - inputCount++ - id = idRaw.(string) - } - - name := "" - nameRaw, ok := d.GetOk("name") - if ok { - inputCount++ - name = nameRaw.(string) - } - - aliasID := "" - aliasIDRaw, ok := d.GetOk("alias_id") - if ok { - inputCount++ - aliasID = aliasIDRaw.(string) - } - - aliasName := "" - aliasNameRaw, ok := d.GetOk("alias_name") - if ok { - inputCount++ - aliasName = aliasNameRaw.(string) - } - - aliasMountAccessor := "" - aliasMountAccessorRaw, ok := d.GetOk("alias_mount_accessor") - if ok { - inputCount++ - aliasMountAccessor = aliasMountAccessorRaw.(string) - } - - switch { - case inputCount == 0: - return logical.ErrorResponse(fmt.Sprintf("query parameter not supplied")), nil - - case inputCount != 1: - switch { - case inputCount == 2 && aliasName != "" && aliasMountAccessor != "": - default: - return logical.ErrorResponse(fmt.Sprintf("query parameter conflict; please supply distinct set of query parameters")), nil - } - - case inputCount == 1: - switch { - case aliasName != "" || aliasMountAccessor != "": - return logical.ErrorResponse(fmt.Sprintf("both 'alias_name' and 'alias_mount_accessor' needs to be set")), nil - } - } - - switch { - case id != "": - group, err = i.MemDBGroupByID(id, false) - if err != nil { - return nil, err - } - case name != "": - group, err = i.MemDBGroupByName(ctx, name, false) - if err != nil { - return nil, err - } - case aliasID != "": - alias, err := i.MemDBAliasByID(aliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - group, err = i.MemDBGroupByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - - case aliasName != "" && aliasMountAccessor != "": - alias, err := i.MemDBAliasByFactors(aliasMountAccessor, aliasName, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - group, err = i.MemDBGroupByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - } - - if group == nil { - return nil, nil - } - - return i.handleGroupReadCommon(ctx, group) - } -} - -var lookupHelp = map[string][2]string{ - "lookup-entity": { - "Query entities based on various properties.", - `Distinct query parameters to be set: - - 'id' - To query the entity by its ID. - - 'name' - To query the entity by its name. - - 'alias_id' - To query the entity by the ID of any of its aliases. - - 'alias_name' and 'alias_mount_accessor' - To query the entity by the unique factors that represent an alias; the name and the mount accessor. - `, - }, - "lookup-group": { - "Query groups based on various properties.", - `Distinct query parameters to be set: - - 'id' - To query the group by its ID. - - 'name' - To query the group by its name. - - 'alias_id' - To query the group by the ID of any of its aliases. - - 'alias_name' and 'alias_mount_accessor' - To query the group by the unique factors that represent an alias; the name and the mount accessor. - `, - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store.go b/vendor/github.com/hashicorp/vault/vault/identity_store.go deleted file mode 100644 index c2976ce6..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store.go +++ /dev/null @@ -1,493 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - groupBucketsPrefix = "packer/group/buckets/" -) - -var ( - sendGroupUpgrade = func(*IdentityStore, *identity.Group) (bool, error) { return false, nil } - parseExtraEntityFromBucket = func(context.Context, *IdentityStore, *identity.Entity) (bool, error) { return false, nil } - addExtraEntityDataToResponse = func(*identity.Entity, map[string]interface{}) {} -) - -func (c *Core) IdentityStore() *IdentityStore { - return c.identityStore -} - -func (i *IdentityStore) resetDB(ctx context.Context) error { - var err error - - i.db, err = memdb.NewMemDB(identityStoreSchema(!i.disableLowerCasedNames)) - if err != nil { - return err - } - - return nil -} - -func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendConfig, logger log.Logger) (*IdentityStore, error) { - iStore := &IdentityStore{ - view: config.StorageView, - logger: logger, - core: core, - } - - // Create a memdb instance, which by default, operates on lower cased - // identity names - err := iStore.resetDB(ctx) - if err != nil { - return nil, err - } - - entitiesPackerLogger := iStore.logger.Named("storagepacker").Named("entities") - core.AddLogger(entitiesPackerLogger) - groupsPackerLogger := iStore.logger.Named("storagepacker").Named("groups") - core.AddLogger(groupsPackerLogger) - iStore.entityPacker, err = storagepacker.NewStoragePacker(iStore.view, entitiesPackerLogger, "") - if err != nil { - return nil, errwrap.Wrapf("failed to create entity packer: {{err}}", err) - } - - iStore.groupPacker, err = storagepacker.NewStoragePacker(iStore.view, groupsPackerLogger, groupBucketsPrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to create group packer: {{err}}", err) - } - - iStore.Backend = &framework.Backend{ - BackendType: logical.TypeLogical, - Paths: iStore.paths(), - Invalidate: iStore.Invalidate, - } - - err = iStore.Setup(ctx, config) - if err != nil { - return nil, err - } - - return iStore, nil -} - -func (i *IdentityStore) paths() []*framework.Path { - return framework.PathAppend( - entityPaths(i), - aliasPaths(i), - groupAliasPaths(i), - groupPaths(i), - lookupPaths(i), - upgradePaths(i), - ) -} - -// Invalidate is a callback wherein the backend is informed that the value at -// the given key is updated. In identity store's case, it would be the entity -// storage entries that get updated. The value needs to be read and MemDB needs -// to be updated accordingly. -func (i *IdentityStore) Invalidate(ctx context.Context, key string) { - i.logger.Debug("invalidate notification received", "key", key) - - i.lock.Lock() - defer i.lock.Unlock() - - switch { - // Check if the key is a storage entry key for an entity bucket - case strings.HasPrefix(key, storagepacker.StoragePackerBucketsPrefix): - // Get the hash value of the storage bucket entry key - bucketKeyHash := i.entityPacker.BucketKeyHashByKey(key) - if len(bucketKeyHash) == 0 { - i.logger.Error("failed to get the bucket entry key hash") - return - } - - // Create a MemDB transaction - txn := i.db.Txn(true) - defer txn.Abort() - - // Each entity object in MemDB holds the MD5 hash of the storage - // entry key of the entity bucket. Fetch all the entities that - // belong to this bucket using the hash value. Remove these entities - // from MemDB along with all the aliases of each entity. - entitiesFetched, err := i.MemDBEntitiesByBucketEntryKeyHashInTxn(txn, string(bucketKeyHash)) - if err != nil { - i.logger.Error("failed to fetch entities using the bucket entry key hash", "bucket_entry_key_hash", bucketKeyHash) - return - } - - for _, entity := range entitiesFetched { - // Delete all the aliases in the entity. This function will also remove - // the corresponding alias indexes too. - err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases) - if err != nil { - i.logger.Error("failed to delete aliases in entity", "entity_id", entity.ID, "error", err) - return - } - - // Delete the entity using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID) - if err != nil { - i.logger.Error("failed to delete entity from MemDB", "entity_id", entity.ID, "error", err) - return - } - } - - // Get the storage bucket entry - bucket, err := i.entityPacker.GetBucket(key) - if err != nil { - i.logger.Error("failed to refresh entities", "key", key, "error", err) - return - } - - // If the underlying entry is nil, it means that this invalidation - // notification is for the deletion of the underlying storage entry. At - // this point, since all the entities belonging to this bucket are - // already removed, there is nothing else to be done. But, if the - // storage entry is non-nil, its an indication of an update. In this - // case, entities in the updated bucket needs to be reinserted into - // MemDB. - if bucket != nil { - for _, item := range bucket.Items { - entity, err := i.parseEntityFromBucketItem(ctx, item) - if err != nil { - i.logger.Error("failed to parse entity from bucket entry item", "error", err) - return - } - - // Only update MemDB and don't touch the storage - err = i.upsertEntityInTxn(ctx, txn, entity, nil, false) - if err != nil { - i.logger.Error("failed to update entity in MemDB", "error", err) - return - } - } - } - - txn.Commit() - return - - // Check if the key is a storage entry key for an group bucket - case strings.HasPrefix(key, groupBucketsPrefix): - // Get the hash value of the storage bucket entry key - bucketKeyHash := i.groupPacker.BucketKeyHashByKey(key) - if len(bucketKeyHash) == 0 { - i.logger.Error("failed to get the bucket entry key hash") - return - } - - // Create a MemDB transaction - txn := i.db.Txn(true) - defer txn.Abort() - - groupsFetched, err := i.MemDBGroupsByBucketEntryKeyHashInTxn(txn, string(bucketKeyHash)) - if err != nil { - i.logger.Error("failed to fetch groups using the bucket entry key hash", "bucket_entry_key_hash", bucketKeyHash) - return - } - - for _, group := range groupsFetched { - // Delete the group using the same transaction - err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID) - if err != nil { - i.logger.Error("failed to delete group from MemDB", "group_id", group.ID, "error", err) - return - } - } - - // Get the storage bucket entry - bucket, err := i.groupPacker.GetBucket(key) - if err != nil { - i.logger.Error("failed to refresh group", "key", key, "error", err) - return - } - - if bucket != nil { - for _, item := range bucket.Items { - group, err := i.parseGroupFromBucketItem(item) - if err != nil { - i.logger.Error("failed to parse group from bucket entry item", "error", err) - return - } - - // Before updating the group, check if the group exists. If it - // does, then delete the group alias from memdb, for the - // invalidation would have sent an update. - groupFetched, err := i.MemDBGroupByIDInTxn(txn, group.ID, true) - if err != nil { - i.logger.Error("failed to fetch group from MemDB", "error", err) - return - } - - // If the group has an alias remove it from memdb - if groupFetched != nil && groupFetched.Alias != nil { - err := i.MemDBDeleteAliasByIDInTxn(txn, groupFetched.Alias.ID, true) - if err != nil { - i.logger.Error("failed to delete old group alias from MemDB", "error", err) - return - } - } - - // Only update MemDB and don't touch the storage - err = i.UpsertGroupInTxn(txn, group, false) - if err != nil { - i.logger.Error("failed to update group in MemDB", "error", err) - return - } - } - } - - txn.Commit() - return - } -} - -func (i *IdentityStore) parseEntityFromBucketItem(ctx context.Context, item *storagepacker.Item) (*identity.Entity, error) { - if item == nil { - return nil, fmt.Errorf("nil item") - } - - persistNeeded := false - - var entity identity.Entity - err := ptypes.UnmarshalAny(item.Message, &entity) - if err != nil { - // If we encounter an error, it would mean that the format of the - // entity is an older one. Try decoding using the older format and if - // successful, upgrage the storage with the newer format. - var oldEntity identity.EntityStorageEntry - oldEntityErr := ptypes.UnmarshalAny(item.Message, &oldEntity) - if oldEntityErr != nil { - return nil, errwrap.Wrapf("failed to decode entity from storage bucket item: {{err}}", err) - } - - i.logger.Debug("upgrading the entity using patch introduced with vault 0.8.2.1", "entity_id", oldEntity.ID) - - // Successfully decoded entity using older format. Entity is stored - // with older format. Upgrade it. - entity.ID = oldEntity.ID - entity.Name = oldEntity.Name - entity.Metadata = oldEntity.Metadata - entity.CreationTime = oldEntity.CreationTime - entity.LastUpdateTime = oldEntity.LastUpdateTime - entity.MergedEntityIDs = oldEntity.MergedEntityIDs - entity.Policies = oldEntity.Policies - entity.BucketKeyHash = oldEntity.BucketKeyHash - entity.MFASecrets = oldEntity.MFASecrets - // Copy each alias individually since the format of aliases were - // also different - for _, oldAlias := range oldEntity.Personas { - var newAlias identity.Alias - newAlias.ID = oldAlias.ID - newAlias.Name = oldAlias.Name - newAlias.CanonicalID = oldAlias.EntityID - newAlias.MountType = oldAlias.MountType - newAlias.MountAccessor = oldAlias.MountAccessor - newAlias.MountPath = oldAlias.MountPath - newAlias.Metadata = oldAlias.Metadata - newAlias.CreationTime = oldAlias.CreationTime - newAlias.LastUpdateTime = oldAlias.LastUpdateTime - newAlias.MergedFromCanonicalIDs = oldAlias.MergedFromEntityIDs - entity.Aliases = append(entity.Aliases, &newAlias) - } - - persistNeeded = true - } - - pN, err := parseExtraEntityFromBucket(ctx, i, &entity) - if err != nil { - return nil, err - } - if pN { - persistNeeded = true - } - - if persistNeeded && !i.core.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - entityAsAny, err := ptypes.MarshalAny(&entity) - if err != nil { - return nil, err - } - - item := &storagepacker.Item{ - ID: entity.ID, - Message: entityAsAny, - } - - // Store the entity with new format - err = i.entityPacker.PutItem(item) - if err != nil { - return nil, err - } - } - - if entity.NamespaceID == "" { - entity.NamespaceID = namespace.RootNamespaceID - } - - return &entity, nil -} - -func (i *IdentityStore) parseGroupFromBucketItem(item *storagepacker.Item) (*identity.Group, error) { - if item == nil { - return nil, fmt.Errorf("nil item") - } - - var group identity.Group - err := ptypes.UnmarshalAny(item.Message, &group) - if err != nil { - return nil, errwrap.Wrapf("failed to decode group from storage bucket item: {{err}}", err) - } - - if group.NamespaceID == "" { - group.NamespaceID = namespace.RootNamespaceID - } - - return &group, nil -} - -// entityByAliasFactors fetches the entity based on factors of alias, i.e mount -// accessor and the alias name. -func (i *IdentityStore) entityByAliasFactors(mountAccessor, aliasName string, clone bool) (*identity.Entity, error) { - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - txn := i.db.Txn(false) - - return i.entityByAliasFactorsInTxn(txn, mountAccessor, aliasName, clone) -} - -// entityByAlaisFactorsInTxn fetches the entity based on factors of alias, i.e -// mount accessor and the alias name. -func (i *IdentityStore) entityByAliasFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool) (*identity.Entity, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - alias, err := i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBEntityByAliasIDInTxn(txn, alias.ID, clone) -} - -// CreateOrFetchEntity creates a new entity. This is used by core to -// associate each login attempt by an alias to a unified entity in Vault. -func (i *IdentityStore) CreateOrFetchEntity(ctx context.Context, alias *logical.Alias) (*identity.Entity, error) { - var entity *identity.Entity - var err error - - if alias == nil { - return nil, fmt.Errorf("alias is nil") - } - - if alias.Name == "" { - return nil, fmt.Errorf("empty alias name") - } - - mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor) - if mountValidationResp == nil { - return nil, fmt.Errorf("invalid mount accessor %q", alias.MountAccessor) - } - - if mountValidationResp.MountLocal { - return nil, fmt.Errorf("mount_accessor %q is of a local mount", alias.MountAccessor) - } - - if mountValidationResp.MountType != alias.MountType { - return nil, fmt.Errorf("mount accessor %q is not a mount of type %q", alias.MountAccessor, alias.MountType) - } - - // Check if an entity already exists for the given alais - entity, err = i.entityByAliasFactors(alias.MountAccessor, alias.Name, false) - if err != nil { - return nil, err - } - if entity != nil { - return entity, nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to update both alias and entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Check if an entity was created before acquiring the lock - entity, err = i.entityByAliasFactorsInTxn(txn, alias.MountAccessor, alias.Name, false) - if err != nil { - return nil, err - } - if entity != nil { - return entity, nil - } - - entity = new(identity.Entity) - err = i.sanitizeEntity(ctx, entity) - if err != nil { - return nil, err - } - - // Create a new alias - newAlias := &identity.Alias{ - CanonicalID: entity.ID, - Name: alias.Name, - MountAccessor: alias.MountAccessor, - Metadata: alias.Metadata, - MountPath: mountValidationResp.MountPath, - MountType: mountValidationResp.MountType, - } - - err = i.sanitizeAlias(ctx, newAlias) - if err != nil { - return nil, err - } - - i.logger.Debug("creating a new entity", "alias", newAlias) - - // Append the new alias to the new entity - entity.Aliases = []*identity.Alias{ - newAlias, - } - - // Update MemDB and persist entity object - err = i.upsertEntityInTxn(ctx, txn, entity, nil, true) - if err != nil { - return nil, err - } - - txn.Commit() - - return entity, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go b/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go deleted file mode 100644 index 88259240..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go +++ /dev/null @@ -1,443 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// aliasPaths returns the API endpoints to operate on aliases. -// Following are the paths supported: -// entity-alias - To register/modify an alias -// entity-alias/id - To read, modify, delete and list aliases based on their ID -func aliasPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "entity-alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the entity alias. If set, updates the corresponding entity alias.", - }, - // entity_id is deprecated in favor of canonical_id - "entity_id": { - Type: framework.TypeString, - Description: `Entity ID to which this alias belongs. -This field is deprecated, use canonical_id.`, - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to; unused for a modify", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias; unused for a modify", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - { - Pattern: "entity-alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - // entity_id is deprecated - "entity_id": { - Type: framework.TypeString, - Description: `Entity ID to which this alias belongs to. -This field is deprecated, use canonical_id.`, - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "(Unused)", - }, - "name": { - Type: framework.TypeString, - Description: "(Unused)", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "entity-alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - } -} - -// handleAliasUpdateCommon is used to update an alias -func (i *IdentityStore) handleAliasUpdateCommon() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var err error - var alias *identity.Alias - var entity *identity.Entity - var previousEntity *identity.Entity - - i.lock.Lock() - defer i.lock.Unlock() - - // Check for update or create - aliasID := d.Get("id").(string) - if aliasID != "" { - alias, err = i.MemDBAliasByID(aliasID, true, false) - if err != nil { - return nil, err - } - if alias == nil { - return logical.ErrorResponse("invalid alias id"), nil - } - } else { - alias = &identity.Alias{} - } - - // Get entity id - canonicalID := d.Get("canonical_id").(string) - if canonicalID == "" { - // For backwards compatibility - canonicalID = d.Get("entity_id").(string) - } - - // Get alias name - if aliasName := d.Get("name").(string); aliasName == "" { - if alias.Name == "" { - return logical.ErrorResponse("missing alias name"), nil - } - } else { - alias.Name = aliasName - } - - // Get mount accessor - if mountAccessor := d.Get("mount_accessor").(string); mountAccessor == "" { - if alias.MountAccessor == "" { - return logical.ErrorResponse("missing mount_accessor"), nil - } - } else { - alias.MountAccessor = mountAccessor - } - - mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor) - if mountValidationResp == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid mount accessor %q", alias.MountAccessor)), nil - } - if mountValidationResp.MountLocal { - return logical.ErrorResponse(fmt.Sprintf("mount_accessor %q is of a local mount", alias.MountAccessor)), nil - } - - // Verify that the combination of alias name and mount is not - // already tied to a different alias - aliasByFactors, err := i.MemDBAliasByFactors(mountValidationResp.MountAccessor, alias.Name, false, false) - if err != nil { - return nil, err - } - if aliasByFactors != nil { - // If it's a create we won't have an alias ID so this will correctly - // bail. If it's an update alias will be the same as aliasbyfactors so - // we don't need to transfer any info over - if aliasByFactors.ID != alias.ID { - return logical.ErrorResponse("combination of mount and alias name is already in use"), nil - } - - // Fetch the entity to which the alias is tied. We don't need to append - // here, so the only further checking is whether the canonical ID is - // different - entity, err = i.MemDBEntityByAliasID(alias.ID, true) - if err != nil { - return nil, err - } - if entity == nil { - return nil, fmt.Errorf("existing alias is not associated with an entity") - } - } else if alias.ID != "" { - // This is an update, not a create; if we have an associated entity - // already, load it - entity, err = i.MemDBEntityByAliasID(alias.ID, true) - if err != nil { - return nil, err - } - } - - resp := &logical.Response{} - - // If we found an existing alias we won't hit this condition because - // canonicalID being empty will result in nil being returned in the block - // above, so in this case we know that creating a new entity is the right - // thing. - if canonicalID == "" { - entity = &identity.Entity{ - Aliases: []*identity.Alias{ - alias, - }, - } - } else { - // If we can look up by the given canonical ID, see if this is a - // transfer; otherwise if we found no previous entity but we find one - // here, use it. - canonicalEntity, err := i.MemDBEntityByID(canonicalID, true) - if err != nil { - return nil, err - } - if canonicalEntity == nil { - return logical.ErrorResponse("invalid canonical ID"), nil - } - if entity == nil { - // If entity is nil, we didn't find a previous alias from factors, - // so append to this entity - entity = canonicalEntity - entity.Aliases = append(entity.Aliases, alias) - } else if entity.ID != canonicalEntity.ID { - // In this case we found an entity from alias factors or given - // alias ID but it's not the same, so it's a migration - previousEntity = entity - entity = canonicalEntity - - for aliasIndex, item := range previousEntity.Aliases { - if item.ID == alias.ID { - previousEntity.Aliases = append(previousEntity.Aliases[:aliasIndex], previousEntity.Aliases[aliasIndex+1:]...) - break - } - } - - entity.Aliases = append(entity.Aliases, alias) - resp.AddWarning(fmt.Sprintf("alias is being transferred from entity %q to %q", previousEntity.ID, entity.ID)) - } - } - - // ID creation and other validations; This is more useful for new entities - // and may not perform anything for the existing entities. Placing the - // check here to make the flow common for both new and existing entities. - err = i.sanitizeEntity(ctx, entity) - if err != nil { - return nil, err - } - - // Explicitly set to empty as in the past we incorrectly saved it - alias.MountPath = "" - alias.MountType = "" - - // Set the canonical ID in the alias index. This should be done after - // sanitizing entity. - alias.CanonicalID = entity.ID - - // ID creation and other validations - err = i.sanitizeAlias(ctx, alias) - if err != nil { - return nil, err - } - - for index, item := range entity.Aliases { - if item.ID == alias.ID { - entity.Aliases[index] = alias - } - } - - // Index entity and its aliases in MemDB and persist entity along with - // aliases in storage. If the alias is being transferred over from - // one entity to another, previous entity needs to get refreshed in MemDB - // and persisted in storage as well. - if err := i.upsertEntity(ctx, entity, previousEntity, true); err != nil { - return nil, err - } - - // Return ID of both alias and entity - resp.Data = map[string]interface{}{ - "id": alias.ID, - "canonical_id": entity.ID, - } - - return resp, nil - } -} - -// pathAliasIDRead returns the properties of an alias for a given -// alias ID -func (i *IdentityStore) pathAliasIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - aliasID := d.Get("id").(string) - if aliasID == "" { - return logical.ErrorResponse("missing alias id"), nil - } - - alias, err := i.MemDBAliasByID(aliasID, false, false) - if err != nil { - return nil, err - } - - return i.handleAliasReadCommon(ctx, alias) - } -} - -func (i *IdentityStore) handleAliasReadCommon(ctx context.Context, alias *identity.Alias) (*logical.Response, error) { - if alias == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != alias.NamespaceID { - return nil, nil - } - - respData := map[string]interface{}{} - respData["id"] = alias.ID - respData["canonical_id"] = alias.CanonicalID - respData["mount_accessor"] = alias.MountAccessor - respData["metadata"] = alias.Metadata - respData["name"] = alias.Name - respData["merged_from_canonical_ids"] = alias.MergedFromCanonicalIDs - - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - respData["mount_path"] = mountValidationResp.MountPath - respData["mount_type"] = mountValidationResp.MountType - } - - // Convert protobuf timestamp into RFC3339 format - respData["creation_time"] = ptypes.TimestampString(alias.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(alias.LastUpdateTime) - - return &logical.Response{ - Data: respData, - }, nil -} - -// pathAliasIDDelete deletes the alias for a given alias ID -func (i *IdentityStore) pathAliasIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - aliasID := d.Get("id").(string) - if aliasID == "" { - return logical.ErrorResponse("missing alias ID"), nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to delete entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Fetch the alias - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, false) - if err != nil { - return nil, err - } - - // If there is no alias for the ID, do nothing - if alias == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != alias.NamespaceID { - return nil, logical.ErrUnsupportedPath - } - - // Fetch the associated entity - entity, err := i.MemDBEntityByAliasIDInTxn(txn, alias.ID, true) - if err != nil { - return nil, err - } - - // If there is no entity tied to a valid alias, something is wrong - if entity == nil { - return nil, fmt.Errorf("alias not associated to an entity") - } - - aliases := []*identity.Alias{ - alias, - } - - // Delete alias from the entity object - err = i.deleteAliasesInEntityInTxn(txn, entity, aliases) - if err != nil { - return nil, err - } - - // Update the entity index in the entities table - err = i.MemDBUpsertEntityInTxn(txn, entity) - if err != nil { - return nil, err - } - - // Persist the entity object - entityAsAny, err := ptypes.MarshalAny(entity) - if err != nil { - return nil, err - } - item := &storagepacker.Item{ - ID: entity.ID, - Message: entityAsAny, - } - - err = i.entityPacker.PutItem(item) - if err != nil { - return nil, err - } - - // Committing the transaction *after* successfully updating entity in - // storage - txn.Commit() - - return nil, nil - } -} - -// pathAliasIDList lists the IDs of all the valid aliases in the identity -// store -func (i *IdentityStore) pathAliasIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handleAliasListCommon(ctx, false) - } -} - -var aliasHelp = map[string][2]string{ - "alias": { - "Create a new alias.", - "", - }, - "alias-id": { - "Update, read or delete an alias ID.", - "", - }, - "alias-id-list": { - "List all the alias IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go b/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go deleted file mode 100644 index 4cfadb68..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go +++ /dev/null @@ -1,763 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func entityPathFields() map[string]*framework.FieldSchema { - return map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the entity. If set, updates the corresponding existing entity.", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the entity", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the entity. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the entity.", - }, - "disabled": { - Type: framework.TypeBool, - Description: "If set true, tokens tied to this identity will not be able to be used (but will not be revoked).", - }, - } -} - -// entityPaths returns the API endpoints supported to operate on entities. -// Following are the paths supported: -// entity - To register a new entity -// entity/id - To lookup, modify, delete and list entities based on ID -// entity/merge - To merge entities based on ID -func entityPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "entity$", - Fields: entityPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity"][1]), - }, - { - Pattern: "entity/name/" + framework.GenericNameRegex("name"), - Fields: entityPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - logical.ReadOperation: i.pathEntityNameRead(), - logical.DeleteOperation: i.pathEntityNameDelete(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-name"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-name"][1]), - }, - { - Pattern: "entity/id/" + framework.GenericNameRegex("id"), - Fields: entityPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - logical.ReadOperation: i.pathEntityIDRead(), - logical.DeleteOperation: i.pathEntityIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-id"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-id"][1]), - }, - { - Pattern: "entity/name/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathEntityNameList(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-name-list"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-name-list"][1]), - }, - { - Pattern: "entity/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathEntityIDList(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-id-list"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-id-list"][1]), - }, - { - Pattern: "entity/merge/?$", - Fields: map[string]*framework.FieldSchema{ - "from_entity_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Entity IDs which needs to get merged", - }, - "to_entity_id": { - Type: framework.TypeString, - Description: "Entity ID into which all the other entities need to get merged", - }, - "force": { - Type: framework.TypeBool, - Description: "Setting this will follow the 'mine' strategy for merging MFA secrets. If there are secrets of the same type both in entities that are merged from and in entity into which all others are getting merged, secrets in the destination will be unaltered. If not set, this API will throw an error containing all the conflicts.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathEntityMergeID(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-merge-id"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-merge-id"][1]), - }, - } -} - -// pathEntityMergeID merges two or more entities into a single entity -func (i *IdentityStore) pathEntityMergeID() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - toEntityID := d.Get("to_entity_id").(string) - if toEntityID == "" { - return logical.ErrorResponse("missing entity id to merge to"), nil - } - - fromEntityIDs := d.Get("from_entity_ids").([]string) - if len(fromEntityIDs) == 0 { - return logical.ErrorResponse("missing entity ids to merge from"), nil - } - - force := d.Get("force").(bool) - - // Create a MemDB transaction to merge entities - txn := i.db.Txn(true) - defer txn.Abort() - - toEntity, err := i.MemDBEntityByID(toEntityID, true) - if err != nil { - return nil, err - } - - userErr, intErr := i.mergeEntity(ctx, txn, toEntity, fromEntityIDs, force, true, false) - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), nil - } - if intErr != nil { - return nil, intErr - } - - // Committing the transaction *after* successfully performing storage - // persistence - txn.Commit() - - return nil, nil - } -} - -// handleEntityUpdateCommon is used to update an entity -func (i *IdentityStore) handleEntityUpdateCommon() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - i.lock.Lock() - defer i.lock.Unlock() - - entity := new(identity.Entity) - var err error - - entityID := d.Get("id").(string) - if entityID != "" { - entity, err = i.MemDBEntityByID(entityID, true) - if err != nil { - return nil, err - } - if entity == nil { - return logical.ErrorResponse("entity not found from id"), nil - } - } - - // Get the name - entityName := d.Get("name").(string) - if entityName != "" { - entityByName, err := i.MemDBEntityByName(ctx, entityName, false) - if err != nil { - return nil, err - } - switch { - case entityByName == nil: - // Not found, safe to use this name with an existing or new entity - case entity.ID == "": - // Entity by ID was not found, but and entity for the supplied - // name was found. Continue updating the entity. - entity = entityByName - case entity.ID == entityByName.ID: - // Same exact entity, carry on (this is basically a noop then) - default: - return logical.ErrorResponse("entity name is already in use"), nil - } - } - - if entityName != "" { - entity.Name = entityName - } - - // Update the policies if supplied - entityPoliciesRaw, ok := d.GetOk("policies") - if ok { - entity.Policies = entityPoliciesRaw.([]string) - } - - if strutil.StrListContains(entity.Policies, "root") { - return logical.ErrorResponse("policies cannot contain root"), nil - } - - disabledRaw, ok := d.GetOk("disabled") - if ok { - entity.Disabled = disabledRaw.(bool) - } - - // Get entity metadata - metadata, ok, err := d.GetOkErr("metadata") - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil - } - if ok { - entity.Metadata = metadata.(map[string]string) - } - - // At this point, if entity.ID is empty, it indicates that a new entity - // is being created. Using this to respond data in the response. - newEntity := entity.ID == "" - - // ID creation and some validations - err = i.sanitizeEntity(ctx, entity) - if err != nil { - return nil, err - } - - if err := i.upsertEntity(ctx, entity, nil, true); err != nil { - return nil, err - } - - // If this operation was an update to an existing entity, return 204 - if !newEntity { - return nil, nil - } - - // Prepare the response - respData := map[string]interface{}{ - "id": entity.ID, - } - - var aliasIDs []string - for _, alias := range entity.Aliases { - aliasIDs = append(aliasIDs, alias.ID) - } - - respData["aliases"] = aliasIDs - - // Return ID of the entity that was either created or updated along with - // its aliases - return &logical.Response{ - Data: respData, - }, nil - } -} - -// pathEntityNameRead returns the properties of an entity for a given entity ID -func (i *IdentityStore) pathEntityNameRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityName := d.Get("name").(string) - if entityName == "" { - return logical.ErrorResponse("missing entity name"), nil - } - - entity, err := i.MemDBEntityByName(ctx, entityName, false) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - return i.handleEntityReadCommon(ctx, entity) - } -} - -// pathEntityIDRead returns the properties of an entity for a given entity ID -func (i *IdentityStore) pathEntityIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityID := d.Get("id").(string) - if entityID == "" { - return logical.ErrorResponse("missing entity id"), nil - } - - entity, err := i.MemDBEntityByID(entityID, false) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - return i.handleEntityReadCommon(ctx, entity) - } -} - -func (i *IdentityStore) handleEntityReadCommon(ctx context.Context, entity *identity.Entity) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != entity.NamespaceID { - return nil, nil - } - - respData := map[string]interface{}{} - respData["id"] = entity.ID - respData["name"] = entity.Name - respData["metadata"] = entity.Metadata - respData["merged_entity_ids"] = entity.MergedEntityIDs - respData["policies"] = entity.Policies - respData["disabled"] = entity.Disabled - - // Convert protobuf timestamp into RFC3339 format - respData["creation_time"] = ptypes.TimestampString(entity.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(entity.LastUpdateTime) - - // Convert each alias into a map and replace the time format in each - aliasesToReturn := make([]interface{}, len(entity.Aliases)) - for aliasIdx, alias := range entity.Aliases { - aliasMap := map[string]interface{}{} - aliasMap["id"] = alias.ID - aliasMap["canonical_id"] = alias.CanonicalID - aliasMap["mount_accessor"] = alias.MountAccessor - aliasMap["metadata"] = alias.Metadata - aliasMap["name"] = alias.Name - aliasMap["merged_from_canonical_ids"] = alias.MergedFromCanonicalIDs - aliasMap["creation_time"] = ptypes.TimestampString(alias.CreationTime) - aliasMap["last_update_time"] = ptypes.TimestampString(alias.LastUpdateTime) - - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - aliasMap["mount_type"] = mountValidationResp.MountType - aliasMap["mount_path"] = mountValidationResp.MountPath - } - - aliasesToReturn[aliasIdx] = aliasMap - } - - // Add the aliases information to the response which has the correct time - // formats - respData["aliases"] = aliasesToReturn - - addExtraEntityDataToResponse(entity, respData) - - // Fetch the groups this entity belongs to and return their identifiers - groups, inheritedGroups, err := i.groupsByEntityID(entity.ID) - if err != nil { - return nil, err - } - - groupIDs := make([]string, len(groups)) - for i, group := range groups { - groupIDs[i] = group.ID - } - respData["direct_group_ids"] = groupIDs - - inheritedGroupIDs := make([]string, len(inheritedGroups)) - for i, group := range inheritedGroups { - inheritedGroupIDs[i] = group.ID - } - respData["inherited_group_ids"] = inheritedGroupIDs - - respData["group_ids"] = append(groupIDs, inheritedGroupIDs...) - - return &logical.Response{ - Data: respData, - }, nil -} - -// pathEntityIDDelete deletes the entity for a given entity ID -func (i *IdentityStore) pathEntityIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityID := d.Get("id").(string) - if entityID == "" { - return logical.ErrorResponse("missing entity id"), nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to delete entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Fetch the entity using its ID - entity, err := i.MemDBEntityByIDInTxn(txn, entityID, true) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - err = i.handleEntityDeleteCommon(ctx, txn, entity) - if err != nil { - return nil, err - } - - txn.Commit() - - return nil, nil - } -} - -// pathEntityNameDelete deletes the entity for a given entity ID -func (i *IdentityStore) pathEntityNameDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityName := d.Get("name").(string) - if entityName == "" { - return logical.ErrorResponse("missing entity name"), nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to delete entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Fetch the entity using its name - entity, err := i.MemDBEntityByNameInTxn(ctx, txn, entityName, true) - if err != nil { - return nil, err - } - // If there is no entity for the ID, do nothing - if entity == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if entity.NamespaceID != ns.ID { - return nil, nil - } - - err = i.handleEntityDeleteCommon(ctx, txn, entity) - if err != nil { - return nil, err - } - - txn.Commit() - - return nil, nil - } -} - -func (i *IdentityStore) handleEntityDeleteCommon(ctx context.Context, txn *memdb.Txn, entity *identity.Entity) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - if entity.NamespaceID != ns.ID { - return nil - } - - // Remove entity ID as a member from all the groups it belongs, both - // internal and external - groups, err := i.MemDBGroupsByMemberEntityIDInTxn(txn, entity.ID, true, false) - if err != nil { - return nil - } - - for _, group := range groups { - group.MemberEntityIDs = strutil.StrListDelete(group.MemberEntityIDs, entity.ID) - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return err - } - } - - // Delete all the aliases in the entity and the respective indexes - err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases) - if err != nil { - return err - } - - // Delete the entity using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID) - if err != nil { - return err - } - - // Delete the entity from storage - err = i.entityPacker.DeleteItem(entity.ID) - if err != nil { - return err - } - - return nil -} - -func (i *IdentityStore) pathEntityIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handlePathEntityListCommon(ctx, req, d, true) - } -} - -func (i *IdentityStore) pathEntityNameList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handlePathEntityListCommon(ctx, req, d, false) - } -} - -// handlePathEntityListCommon lists the IDs or names of all the valid entities -// in the identity store -func (i *IdentityStore) handlePathEntityListCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, byID bool) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - ws := memdb.NewWatchSet() - - txn := i.db.Txn(false) - - iter, err := txn.Get(entitiesTable, "namespace_id", ns.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for entities in memdb: {{err}}", err) - } - - ws.Add(iter.WatchCh()) - - var keys []string - entityInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - entity := raw.(*identity.Entity) - if byID { - keys = append(keys, entity.ID) - } else { - keys = append(keys, entity.Name) - } - entityInfoEntry := map[string]interface{}{ - "name": entity.Name, - } - if len(entity.Aliases) > 0 { - aliasList := make([]interface{}, 0, len(entity.Aliases)) - for _, alias := range entity.Aliases { - entry := map[string]interface{}{ - "id": alias.ID, - "name": alias.Name, - "mount_accessor": alias.MountAccessor, - } - - mi, ok := mountAccessorMap[alias.MountAccessor] - if ok { - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } - mountAccessorMap[alias.MountAccessor] = mi - } - - aliasList = append(aliasList, entry) - } - entityInfoEntry["aliases"] = aliasList - } - entityInfo[entity.ID] = entityInfoEntry - } - - return logical.ListResponseWithInfo(keys, entityInfo), nil -} - -func (i *IdentityStore) mergeEntity(ctx context.Context, txn *memdb.Txn, toEntity *identity.Entity, fromEntityIDs []string, force, grabLock, mergePolicies bool) (error, error) { - if grabLock { - i.lock.Lock() - defer i.lock.Unlock() - } - - if toEntity == nil { - return errors.New("entity id to merge to is invalid"), nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if toEntity.NamespaceID != ns.ID { - return errors.New("entity id to merge into does not belong to the request's namespace"), nil - } - - // Merge the MFA secrets - for _, fromEntityID := range fromEntityIDs { - if fromEntityID == toEntity.ID { - return errors.New("to_entity_id should not be present in from_entity_ids"), nil - } - - fromEntity, err := i.MemDBEntityByID(fromEntityID, false) - if err != nil { - return nil, err - } - - if fromEntity == nil { - return errors.New("entity id to merge from is invalid"), nil - } - - if fromEntity.NamespaceID != toEntity.NamespaceID { - return errors.New("entity id to merge from does not belong to this namespace"), nil - } - - for configID, configSecret := range fromEntity.MFASecrets { - _, ok := toEntity.MFASecrets[configID] - if ok && !force { - return nil, fmt.Errorf("conflicting MFA config ID %q in entity ID %q", configID, fromEntity.ID) - } else { - toEntity.MFASecrets[configID] = configSecret - } - } - } - - for _, fromEntityID := range fromEntityIDs { - if fromEntityID == toEntity.ID { - return errors.New("to_entity_id should not be present in from_entity_ids"), nil - } - - fromEntity, err := i.MemDBEntityByID(fromEntityID, false) - if err != nil { - return nil, err - } - - if fromEntity == nil { - return errors.New("entity id to merge from is invalid"), nil - } - - if fromEntity.NamespaceID != toEntity.NamespaceID { - return errors.New("entity id to merge from does not belong to this namespace"), nil - } - - for _, alias := range fromEntity.Aliases { - // Set the desired canonical ID - alias.CanonicalID = toEntity.ID - - alias.MergedFromCanonicalIDs = append(alias.MergedFromCanonicalIDs, fromEntity.ID) - - err = i.MemDBUpsertAliasInTxn(txn, alias, false) - if err != nil { - return nil, errwrap.Wrapf("failed to update alias during merge: {{err}}", err) - } - - // Add the alias to the desired entity - toEntity.Aliases = append(toEntity.Aliases, alias) - } - - // If told to, merge policies - if mergePolicies { - toEntity.Policies = strutil.MergeSlices(toEntity.Policies, fromEntity.Policies) - } - - // If the entity from which we are merging from was already a merged - // entity, transfer over the Merged set to the entity we are - // merging into. - toEntity.MergedEntityIDs = append(toEntity.MergedEntityIDs, fromEntity.MergedEntityIDs...) - - // Add the entity from which we are merging from to the list of entities - // the entity we are merging into is composed of. - toEntity.MergedEntityIDs = append(toEntity.MergedEntityIDs, fromEntity.ID) - - // Delete the entity which we are merging from in MemDB using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, fromEntity.ID) - if err != nil { - return nil, err - } - - // Delete the entity which we are merging from in storage - err = i.entityPacker.DeleteItem(fromEntity.ID) - if err != nil { - return nil, err - } - } - - // Update MemDB with changes to the entity we are merging to - err = i.MemDBUpsertEntityInTxn(txn, toEntity) - if err != nil { - return nil, err - } - - // Persist the entity which we are merging to - toEntityAsAny, err := ptypes.MarshalAny(toEntity) - if err != nil { - return nil, err - } - item := &storagepacker.Item{ - ID: toEntity.ID, - Message: toEntityAsAny, - } - - err = i.entityPacker.PutItem(item) - if err != nil { - return nil, err - } - - return nil, nil -} - -var entityHelp = map[string][2]string{ - "entity": { - "Create a new entity", - "", - }, - "entity-id": { - "Update, read or delete an entity using entity ID", - "", - }, - "entity-name": { - "Update, read or delete an entity using entity name", - "", - }, - "entity-id-list": { - "List all the entity IDs", - "", - }, - "entity-name-list": { - "List all the entity names", - "", - }, - "entity-merge-id": { - "Merge two or more entities together", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go b/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go deleted file mode 100644 index 4a57b0aa..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go +++ /dev/null @@ -1,329 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func groupAliasPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "group-alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group alias.", - }, - "name": { - Type: framework.TypeString, - Description: "Alias of the group.", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "ID of the group to which this is an alias.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupAliasRegister(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias"][1]), - }, - { - Pattern: "group-alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group alias.", - }, - "name": { - Type: framework.TypeString, - Description: "Alias of the group.", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "ID of the group to which this is an alias.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupAliasIDUpdate(), - logical.ReadOperation: i.pathGroupAliasIDRead(), - logical.DeleteOperation: i.pathGroupAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias-by-id"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias-by-id"][1]), - }, - { - Pattern: "group-alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathGroupAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias-id-list"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias-id-list"][1]), - }, - } -} - -func (i *IdentityStore) pathGroupAliasRegister() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - _, ok := d.GetOk("id") - if ok { - return i.pathGroupAliasIDUpdate()(ctx, req, d) - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - return i.handleGroupAliasUpdateCommon(ctx, req, d, nil) - } -} - -func (i *IdentityStore) pathGroupAliasIDUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("empty group alias ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - groupAlias, err := i.MemDBAliasByID(groupAliasID, true, true) - if err != nil { - return nil, err - } - if groupAlias == nil { - return logical.ErrorResponse("invalid group alias ID"), nil - } - - return i.handleGroupAliasUpdateCommon(ctx, req, d, groupAlias) - } -} - -func (i *IdentityStore) handleGroupAliasUpdateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, groupAlias *identity.Alias) (*logical.Response, error) { - var newGroupAlias bool - var group *identity.Group - var err error - - if groupAlias == nil { - groupAlias = &identity.Alias{} - newGroupAlias = true - } - - groupID := d.Get("canonical_id").(string) - if groupID != "" { - group, err = i.MemDBGroupByID(groupID, true) - if err != nil { - return nil, err - } - if group == nil { - return logical.ErrorResponse("invalid group ID"), nil - } - if group.Type != groupTypeExternal { - return logical.ErrorResponse("alias can't be set on an internal group"), nil - } - } - - // Get group alias name - groupAliasName := d.Get("name").(string) - if groupAliasName == "" { - return logical.ErrorResponse("missing alias name"), nil - } - - mountAccessor := d.Get("mount_accessor").(string) - if mountAccessor == "" { - return logical.ErrorResponse("missing mount_accessor"), nil - } - - mountValidationResp := i.core.router.validateMountByAccessor(mountAccessor) - if mountValidationResp == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid mount accessor %q", mountAccessor)), nil - } - - if mountValidationResp.MountLocal { - return logical.ErrorResponse(fmt.Sprintf("mount_accessor %q is of a local mount", mountAccessor)), nil - } - - groupAliasByFactors, err := i.MemDBAliasByFactors(mountValidationResp.MountAccessor, groupAliasName, false, true) - if err != nil { - return nil, err - } - - resp := &logical.Response{} - - if newGroupAlias { - if groupAliasByFactors != nil { - return logical.ErrorResponse("combination of mount and group alias name is already in use"), nil - } - - // If this is an alias being tied to a non-existent group, create - // a new group for it. - if group == nil { - group = &identity.Group{ - Type: groupTypeExternal, - Alias: groupAlias, - } - } else { - group.Alias = groupAlias - } - } else { - // Verify that the combination of group alias name and mount is not - // already tied to a different alias - if groupAliasByFactors != nil && groupAliasByFactors.ID != groupAlias.ID { - return logical.ErrorResponse("combination of mount and group alias name is already in use"), nil - } - - // Fetch the group to which the alias is tied to - existingGroup, err := i.MemDBGroupByAliasID(groupAlias.ID, true) - if err != nil { - return nil, err - } - - if existingGroup == nil { - return nil, fmt.Errorf("group alias is not associated with a group") - } - - if group != nil && group.ID != existingGroup.ID { - return logical.ErrorResponse("alias is already tied to a different group"), nil - } - - group = existingGroup - group.Alias = groupAlias - } - - group.Alias.Name = groupAliasName - group.Alias.MountAccessor = mountValidationResp.MountAccessor - // Explicitly correct for previous versions that persisted this - group.Alias.MountType = "" - - err = i.sanitizeAndUpsertGroup(ctx, group, nil) - if err != nil { - return nil, err - } - - resp.Data = map[string]interface{}{ - "id": groupAlias.ID, - "canonical_id": group.ID, - } - - return resp, nil -} - -// pathGroupAliasIDRead returns the properties of an alias for a given -// alias ID -func (i *IdentityStore) pathGroupAliasIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("empty group alias id"), nil - } - - groupAlias, err := i.MemDBAliasByID(groupAliasID, false, true) - if err != nil { - return nil, err - } - - return i.handleAliasReadCommon(ctx, groupAlias) - } -} - -// pathGroupAliasIDDelete deletes the group's alias for a given group alias ID -func (i *IdentityStore) pathGroupAliasIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("missing group alias ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - txn := i.db.Txn(true) - defer txn.Abort() - - alias, err := i.MemDBAliasByIDInTxn(txn, groupAliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != alias.NamespaceID { - return nil, logical.ErrUnsupportedOperation - } - - group, err := i.MemDBGroupByAliasIDInTxn(txn, alias.ID, true) - if err != nil { - return nil, err - } - - // If there is no group tied to a valid alias, something is wrong - if group == nil { - return nil, fmt.Errorf("alias not associated to a group") - } - - // Delete group alias in memdb - err = i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true) - if err != nil { - return nil, err - } - - // Delete the alias - group.Alias = nil - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - - txn.Commit() - - return nil, nil - } -} - -// pathGroupAliasIDList lists the IDs of all the valid group aliases in the -// identity store -func (i *IdentityStore) pathGroupAliasIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handleAliasListCommon(ctx, true) - } -} - -var groupAliasHelp = map[string][2]string{ - "group-alias": { - "Creates a new group alias, or updates an existing one.", - "", - }, - "group-alias-id": { - "Update, read or delete a group alias using ID.", - "", - }, - "group-alias-id-list": { - "List all the group alias IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go b/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go deleted file mode 100644 index d8c3280b..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go +++ /dev/null @@ -1,550 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - groupTypeInternal = "internal" - groupTypeExternal = "external" -) - -func groupPathFields() map[string]*framework.FieldSchema { - return map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group. If set, updates the corresponding existing group.", - }, - "type": { - Type: framework.TypeString, - Description: "Type of the group, 'internal' or 'external'. Defaults to 'internal'", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the group.", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the group. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the group.", - }, - "member_group_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Group IDs to be assigned as group members.", - }, - "member_entity_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Entity IDs to be assigned as group members.", - }, - } -} - -func groupPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "group$", - Fields: groupPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupRegister(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["register"][0]), - HelpDescription: strings.TrimSpace(groupHelp["register"][1]), - }, - { - Pattern: "group/id/" + framework.GenericNameRegex("id"), - Fields: groupPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupIDUpdate(), - logical.ReadOperation: i.pathGroupIDRead(), - logical.DeleteOperation: i.pathGroupIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-by-id"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-by-id"][1]), - }, - { - Pattern: "group/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathGroupIDList(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-id-list"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-id-list"][1]), - }, - { - Pattern: "group/name/" + framework.GenericNameRegex("name"), - Fields: groupPathFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupNameUpdate(), - logical.ReadOperation: i.pathGroupNameRead(), - logical.DeleteOperation: i.pathGroupNameDelete(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-by-name"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-by-name"][1]), - }, - { - Pattern: "group/name/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathGroupNameList(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-name-list"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-name-list"][1]), - }, - } -} - -func (i *IdentityStore) pathGroupRegister() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - _, ok := d.GetOk("id") - if ok { - return i.pathGroupIDUpdate()(ctx, req, d) - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - return i.handleGroupUpdateCommon(ctx, req, d, nil) - } -} - -func (i *IdentityStore) pathGroupIDUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - group, err := i.MemDBGroupByID(groupID, true) - if err != nil { - return nil, err - } - if group == nil { - return logical.ErrorResponse("invalid group ID"), nil - } - - return i.handleGroupUpdateCommon(ctx, req, d, group) - } -} - -func (i *IdentityStore) pathGroupNameUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupName := d.Get("name").(string) - if groupName == "" { - return logical.ErrorResponse("empty group name"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - group, err := i.MemDBGroupByName(ctx, groupName, true) - if err != nil { - return nil, err - } - return i.handleGroupUpdateCommon(ctx, req, d, group) - } -} - -func (i *IdentityStore) handleGroupUpdateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, group *identity.Group) (*logical.Response, error) { - var newGroup bool - if group == nil { - group = new(identity.Group) - newGroup = true - } - - // Update the policies if supplied - policiesRaw, ok := d.GetOk("policies") - if ok { - group.Policies = policiesRaw.([]string) - } - - if strutil.StrListContains(group.Policies, "root") { - return logical.ErrorResponse("policies cannot contain root"), nil - } - - groupTypeRaw, ok := d.GetOk("type") - if ok { - groupType := groupTypeRaw.(string) - if group.Type != "" && groupType != group.Type { - return logical.ErrorResponse(fmt.Sprintf("group type cannot be changed")), nil - } - - group.Type = groupType - } - - // If group type is not set, default to internal type - if group.Type == "" { - group.Type = groupTypeInternal - } - - if group.Type != groupTypeInternal && group.Type != groupTypeExternal { - return logical.ErrorResponse(fmt.Sprintf("invalid group type %q", group.Type)), nil - } - - // Get the name - groupName := d.Get("name").(string) - if groupName != "" { - // Check if there is a group already existing for the given name - groupByName, err := i.MemDBGroupByName(ctx, groupName, false) - if err != nil { - return nil, err - } - - // If this is a new group and if there already exists a group by this - // name, error out. If the name of an existing group is about to be - // modified into something which is already tied to a different group, - // error out. - switch { - case groupByName == nil: - // Allowed - case group.ID == "": - group = groupByName - case group.ID != "" && groupByName.ID != group.ID: - return logical.ErrorResponse("group name is already in use"), nil - } - group.Name = groupName - } - - metadata, ok, err := d.GetOkErr("metadata") - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil - } - if ok { - group.Metadata = metadata.(map[string]string) - } - - memberEntityIDsRaw, ok := d.GetOk("member_entity_ids") - if ok { - if group.Type == groupTypeExternal { - return logical.ErrorResponse("member entities can't be set manually for external groups"), nil - } - group.MemberEntityIDs = memberEntityIDsRaw.([]string) - if len(group.MemberEntityIDs) > 512 { - return logical.ErrorResponse("member entity IDs exceeding the limit of 512"), nil - } - } - - memberGroupIDsRaw, ok := d.GetOk("member_group_ids") - var memberGroupIDs []string - if ok { - if group.Type == groupTypeExternal { - return logical.ErrorResponse("member groups can't be set for external groups"), nil - } - memberGroupIDs = memberGroupIDsRaw.([]string) - } - - err = i.sanitizeAndUpsertGroup(ctx, group, memberGroupIDs) - if err != nil { - return nil, err - } - - if !newGroup { - return nil, nil - } - - respData := map[string]interface{}{ - "id": group.ID, - "name": group.Name, - } - return &logical.Response{ - Data: respData, - }, nil -} - -func (i *IdentityStore) pathGroupIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group id"), nil - } - - group, err := i.MemDBGroupByID(groupID, false) - if err != nil { - return nil, err - } - if group == nil { - return nil, nil - } - - return i.handleGroupReadCommon(ctx, group) - } -} - -func (i *IdentityStore) pathGroupNameRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupName := d.Get("name").(string) - if groupName == "" { - return logical.ErrorResponse("empty group name"), nil - } - - group, err := i.MemDBGroupByName(ctx, groupName, false) - if err != nil { - return nil, err - } - if group == nil { - return nil, nil - } - - return i.handleGroupReadCommon(ctx, group) - } -} - -func (i *IdentityStore) handleGroupReadCommon(ctx context.Context, group *identity.Group) (*logical.Response, error) { - if group == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != group.NamespaceID { - return nil, nil - } - - respData := map[string]interface{}{} - respData["id"] = group.ID - respData["name"] = group.Name - respData["policies"] = group.Policies - respData["member_entity_ids"] = group.MemberEntityIDs - respData["parent_group_ids"] = group.ParentGroupIDs - respData["metadata"] = group.Metadata - respData["creation_time"] = ptypes.TimestampString(group.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(group.LastUpdateTime) - respData["modify_index"] = group.ModifyIndex - respData["type"] = group.Type - - aliasMap := map[string]interface{}{} - if group.Alias != nil { - aliasMap["id"] = group.Alias.ID - aliasMap["canonical_id"] = group.Alias.CanonicalID - aliasMap["mount_accessor"] = group.Alias.MountAccessor - aliasMap["metadata"] = group.Alias.Metadata - aliasMap["name"] = group.Alias.Name - aliasMap["merged_from_canonical_ids"] = group.Alias.MergedFromCanonicalIDs - aliasMap["creation_time"] = ptypes.TimestampString(group.Alias.CreationTime) - aliasMap["last_update_time"] = ptypes.TimestampString(group.Alias.LastUpdateTime) - - if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil { - aliasMap["mount_path"] = mountValidationResp.MountPath - aliasMap["mount_type"] = mountValidationResp.MountType - } - } - - respData["alias"] = aliasMap - - var memberGroupIDs []string - memberGroups, err := i.MemDBGroupsByParentGroupID(group.ID, false) - if err != nil { - return nil, err - } - for _, memberGroup := range memberGroups { - memberGroupIDs = append(memberGroupIDs, memberGroup.ID) - } - - respData["member_group_ids"] = memberGroupIDs - - return &logical.Response{ - Data: respData, - }, nil -} - -func (i *IdentityStore) pathGroupIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group ID"), nil - } - - return i.handleGroupDeleteCommon(ctx, groupID, true) - } -} - -func (i *IdentityStore) pathGroupNameDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupName := d.Get("name").(string) - if groupName == "" { - return logical.ErrorResponse("empty group name"), nil - } - - return i.handleGroupDeleteCommon(ctx, groupName, false) - } -} - -func (i *IdentityStore) handleGroupDeleteCommon(ctx context.Context, key string, byID bool) (*logical.Response, error) { - // Acquire the lock to modify the group storage entry - i.groupLock.Lock() - defer i.groupLock.Unlock() - - // Create a MemDB transaction to delete group - txn := i.db.Txn(true) - defer txn.Abort() - - var group *identity.Group - var err error - switch byID { - case true: - group, err = i.MemDBGroupByIDInTxn(txn, key, false) - if err != nil { - return nil, err - } - default: - group, err = i.MemDBGroupByNameInTxn(ctx, txn, key, false) - if err != nil { - return nil, err - } - } - if group == nil { - return nil, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if group.NamespaceID != ns.ID { - return nil, nil - } - - // Delete group alias from memdb - if group.Type == groupTypeExternal && group.Alias != nil { - err = i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true) - if err != nil { - return nil, err - } - } - - // Delete the group using the same transaction - err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID) - if err != nil { - return nil, err - } - - // Delete the group from storage - err = i.groupPacker.DeleteItem(group.ID) - if err != nil { - return nil, err - } - - // Committing the transaction *after* successfully deleting group - txn.Commit() - - return nil, nil -} - -// pathGroupIDList lists the IDs of all the groups in the identity store -func (i *IdentityStore) pathGroupIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handleGroupListCommon(ctx, true) - } -} - -// pathGroupNameList lists the names of all the groups in the identity store -func (i *IdentityStore) pathGroupNameList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return i.handleGroupListCommon(ctx, false) - } -} - -func (i *IdentityStore) handleGroupListCommon(ctx context.Context, byID bool) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - txn := i.db.Txn(false) - - iter, err := txn.Get(groupsTable, "namespace_id", ns.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using namespace ID: {{err}}", err) - } - - var keys []string - groupInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for entry := iter.Next(); entry != nil; entry = iter.Next() { - group := entry.(*identity.Group) - - if byID { - keys = append(keys, group.ID) - } else { - keys = append(keys, group.Name) - } - - groupInfoEntry := map[string]interface{}{ - "name": group.Name, - "num_member_entities": len(group.MemberEntityIDs), - "num_parent_groups": len(group.ParentGroupIDs), - } - if group.Alias != nil { - entry := map[string]interface{}{ - "id": group.Alias.ID, - "name": group.Alias.Name, - "mount_accessor": group.Alias.MountAccessor, - } - - mi, ok := mountAccessorMap[group.Alias.MountAccessor] - if ok { - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } - mountAccessorMap[group.Alias.MountAccessor] = mi - } - - groupInfoEntry["alias"] = entry - } - groupInfo[group.ID] = groupInfoEntry - } - - return logical.ListResponseWithInfo(keys, groupInfo), nil -} - -var groupHelp = map[string][2]string{ - "register": { - "Create a new group.", - "", - }, - "group-by-id": { - "Update or delete an existing group using its ID.", - "", - }, - "group-id-list": { - "List all the group IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go b/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go deleted file mode 100644 index 5989c4f1..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go +++ /dev/null @@ -1,215 +0,0 @@ -package vault - -import ( - "fmt" - - memdb "github.com/hashicorp/go-memdb" -) - -const ( - entitiesTable = "entities" - entityAliasesTable = "entity_aliases" - groupsTable = "groups" - groupAliasesTable = "group_aliases" -) - -func identityStoreSchema(lowerCaseName bool) *memdb.DBSchema { - iStoreSchema := &memdb.DBSchema{ - Tables: make(map[string]*memdb.TableSchema), - } - - schemas := []func(bool) *memdb.TableSchema{ - entitiesTableSchema, - aliasesTableSchema, - groupsTableSchema, - groupAliasesTableSchema, - } - - for _, schemaFunc := range schemas { - schema := schemaFunc(lowerCaseName) - if _, ok := iStoreSchema.Tables[schema.Name]; ok { - panic(fmt.Sprintf("duplicate table name: %s", schema.Name)) - } - iStoreSchema.Tables[schema.Name] = schema - } - - return iStoreSchema -} - -func aliasesTableSchema(lowerCaseName bool) *memdb.TableSchema { - return &memdb.TableSchema{ - Name: entityAliasesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "factors": &memdb.IndexSchema{ - Name: "factors", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "MountAccessor", - }, - &memdb.StringFieldIndex{ - Field: "Name", - Lowercase: lowerCaseName, - }, - }, - }, - }, - "namespace_id": &memdb.IndexSchema{ - Name: "namespace_id", - Indexer: &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - }, - }, - } -} - -func entitiesTableSchema(lowerCaseName bool) *memdb.TableSchema { - return &memdb.TableSchema{ - Name: entitiesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "name": &memdb.IndexSchema{ - Name: "name", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - &memdb.StringFieldIndex{ - Field: "Name", - Lowercase: lowerCaseName, - }, - }, - }, - }, - "merged_entity_ids": &memdb.IndexSchema{ - Name: "merged_entity_ids", - Unique: true, - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "MergedEntityIDs", - }, - }, - "bucket_key_hash": &memdb.IndexSchema{ - Name: "bucket_key_hash", - Indexer: &memdb.StringFieldIndex{ - Field: "BucketKeyHash", - }, - }, - "namespace_id": &memdb.IndexSchema{ - Name: "namespace_id", - Indexer: &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - }, - }, - } -} - -func groupsTableSchema(lowerCaseName bool) *memdb.TableSchema { - return &memdb.TableSchema{ - Name: groupsTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": { - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "name": { - Name: "name", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - &memdb.StringFieldIndex{ - Field: "Name", - Lowercase: lowerCaseName, - }, - }, - }, - }, - "member_entity_ids": { - Name: "member_entity_ids", - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "MemberEntityIDs", - }, - }, - "parent_group_ids": { - Name: "parent_group_ids", - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "ParentGroupIDs", - }, - }, - "bucket_key_hash": &memdb.IndexSchema{ - Name: "bucket_key_hash", - Indexer: &memdb.StringFieldIndex{ - Field: "BucketKeyHash", - }, - }, - "namespace_id": &memdb.IndexSchema{ - Name: "namespace_id", - Indexer: &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - }, - }, - } -} - -func groupAliasesTableSchema(lowerCaseName bool) *memdb.TableSchema { - return &memdb.TableSchema{ - Name: groupAliasesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "factors": &memdb.IndexSchema{ - Name: "factors", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "MountAccessor", - }, - &memdb.StringFieldIndex{ - Field: "Name", - Lowercase: lowerCaseName, - }, - }, - }, - }, - "namespace_id": &memdb.IndexSchema{ - Name: "namespace_id", - Indexer: &memdb.StringFieldIndex{ - Field: "NamespaceID", - }, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go b/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go deleted file mode 100644 index c8e8026c..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go +++ /dev/null @@ -1,83 +0,0 @@ -package vault - -import ( - "regexp" - "sync" - - log "github.com/hashicorp/go-hclog" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // Storage prefixes - entityPrefix = "entity/" -) - -var ( - // metaKeyFormatRegEx checks if a metadata key string is valid - metaKeyFormatRegEx = regexp.MustCompile(`^[a-zA-Z0-9=/+_-]+$`).MatchString -) - -const ( - // The meta key prefix reserved for Vault's internal use - metaKeyReservedPrefix = "vault-" - - // The maximum number of metadata key pairs allowed to be registered - metaMaxKeyPairs = 64 - - // The maximum allowed length of a metadata key - metaKeyMaxLength = 128 - - // The maximum allowed length of a metadata value - metaValueMaxLength = 512 -) - -// IdentityStore is composed of its own storage view and a MemDB which -// maintains active in-memory replicas of the storage contents indexed by -// multiple fields. -type IdentityStore struct { - // IdentityStore is a secret backend in Vault - *framework.Backend - - // view is the storage sub-view where all the artifacts of identity store - // gets persisted - view logical.Storage - - // db is the in-memory database where the storage artifacts gets replicated - // to enable richer queries based on multiple indexes. - db *memdb.MemDB - - // A lock to make sure things are consistent - lock sync.RWMutex - - // groupLock is used to protect modifications to group entries - groupLock sync.RWMutex - - // logger is the server logger copied over from core - logger log.Logger - - // entityPacker is used to pack multiple entity storage entries into 256 - // buckets - entityPacker *storagepacker.StoragePacker - - // groupPacker is used to pack multiple group storage entries into 256 - // buckets - groupPacker *storagepacker.StoragePacker - - // core is the pointer to Vault's core - core *Core - - // disableLowerCaseNames indicates whether or not identity artifacts are - // operated case insensitively - disableLowerCasedNames bool -} - -type groupDiff struct { - New []*identity.Group - Deleted []*identity.Group - Unmodified []*identity.Group -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go b/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go deleted file mode 100644 index ebf3e558..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go +++ /dev/null @@ -1,168 +0,0 @@ -package vault - -import ( - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func upgradePaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "persona$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the persona", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this persona belongs to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this persona belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the persona", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the persona. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 -`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - { - Pattern: "persona/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the persona", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this persona should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this persona belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the persona", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the persona. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 -`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "persona/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - { - Pattern: "alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs to. This field is deprecated in favor of 'canonical_id'.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - - { - Pattern: "alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to. This field is deprecated in favor of 'canonical_id'.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_util.go b/vendor/github.com/hashicorp/vault/vault/identity_store_util.go deleted file mode 100644 index f186b36f..00000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_util.go +++ /dev/null @@ -1,1979 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - "sync" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/identity/mfa" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -var ( - errDuplicateIdentityName = errors.New("duplicate identity name") -) - -func (c *Core) loadIdentityStoreArtifacts(ctx context.Context) error { - if c.identityStore == nil { - c.logger.Warn("identity store is not setup, skipping loading") - return nil - } - - loadFunc := func(context.Context) error { - err := c.identityStore.loadEntities(ctx) - if err != nil { - return err - } - return c.identityStore.loadGroups(ctx) - } - - // Load everything when memdb is set to operate on lower cased names - err := loadFunc(ctx) - switch { - case err == nil: - // If it succeeds, all is well - return nil - case err != nil && !errwrap.Contains(err, errDuplicateIdentityName.Error()): - return err - } - - c.identityStore.logger.Warn("enabling case sensitive identity names") - - // Set identity store to operate on case sensitive identity names - c.identityStore.disableLowerCasedNames = true - - // Swap the memdb instance by the one which operates on case sensitive - // names, hence obviating the need to unload anything that's already - // loaded. - err = c.identityStore.resetDB(ctx) - if err != nil { - return err - } - - // Attempt to load identity artifacts once more after memdb is reset to - // accept case sensitive names - return loadFunc(ctx) -} - -func (i *IdentityStore) sanitizeName(name string) string { - if i.disableLowerCasedNames { - return name - } - return strings.ToLower(name) -} - -func (i *IdentityStore) loadGroups(ctx context.Context) error { - i.logger.Debug("identity loading groups") - existing, err := i.groupPacker.View().List(ctx, groupBucketsPrefix) - if err != nil { - return errwrap.Wrapf("failed to scan for groups: {{err}}", err) - } - i.logger.Debug("groups collected", "num_existing", len(existing)) - - for _, key := range existing { - bucket, err := i.groupPacker.GetBucket(i.groupPacker.BucketPath(key)) - if err != nil { - return err - } - - if bucket == nil { - continue - } - - for _, item := range bucket.Items { - group, err := i.parseGroupFromBucketItem(item) - if err != nil { - return err - } - if group == nil { - continue - } - - // Ensure that there are no groups with duplicate names - groupByName, err := i.MemDBGroupByName(ctx, group.Name, false) - if err != nil { - return err - } - if groupByName != nil { - i.logger.Warn(errDuplicateIdentityName.Error(), "group_name", group.Name, "conflicting_group_name", groupByName.Name, "action", "merge the contents of duplicated groups into one and delete the other") - if !i.disableLowerCasedNames { - return errDuplicateIdentityName - } - } - - if i.logger.IsDebug() { - i.logger.Debug("loading group", "name", group.Name, "id", group.ID) - } - - txn := i.db.Txn(true) - - // Before pull#5786, entity memberships in groups were not getting - // updated when respective entities were deleted. This is here to - // check that the entity IDs in the group are indeed valid, and if - // not remove them. - persist := false - for _, memberEntityID := range group.MemberEntityIDs { - entity, err := i.MemDBEntityByID(memberEntityID, false) - if err != nil { - return err - } - if entity == nil { - persist = true - group.MemberEntityIDs = strutil.StrListDelete(group.MemberEntityIDs, memberEntityID) - } - } - - err = i.UpsertGroupInTxn(txn, group, persist) - if err != nil { - txn.Abort() - return errwrap.Wrapf("failed to update group in memdb: {{err}}", err) - } - - txn.Commit() - } - } - - if i.logger.IsInfo() { - i.logger.Info("groups restored") - } - - return nil -} - -func (i *IdentityStore) loadEntities(ctx context.Context) error { - // Accumulate existing entities - i.logger.Debug("loading entities") - existing, err := i.entityPacker.View().List(ctx, storagepacker.StoragePackerBucketsPrefix) - if err != nil { - return errwrap.Wrapf("failed to scan for entities: {{err}}", err) - } - i.logger.Debug("entities collected", "num_existing", len(existing)) - - // Make the channels used for the worker pool - broker := make(chan string) - quit := make(chan bool) - - // Buffer these channels to prevent deadlocks - errs := make(chan error, len(existing)) - result := make(chan *storagepacker.Bucket, len(existing)) - - // Use a wait group - wg := &sync.WaitGroup{} - - // Create 64 workers to distribute work to - for j := 0; j < consts.ExpirationRestoreWorkerCount; j++ { - wg.Add(1) - go func() { - defer wg.Done() - - for { - select { - case bucketKey, ok := <-broker: - // broker has been closed, we are done - if !ok { - return - } - - bucket, err := i.entityPacker.GetBucket(i.entityPacker.BucketPath(bucketKey)) - if err != nil { - errs <- err - continue - } - - // Write results out to the result channel - result <- bucket - - // quit early - case <-quit: - return - } - } - }() - } - - // Distribute the collected keys to the workers in a go routine - wg.Add(1) - go func() { - defer wg.Done() - for j, bucketKey := range existing { - if j%500 == 0 { - i.logger.Debug("entities loading", "progress", j) - } - - select { - case <-quit: - return - - default: - broker <- bucketKey - } - } - - // Close the broker, causing worker routines to exit - close(broker) - }() - - // Restore each key by pulling from the result chan - for j := 0; j < len(existing); j++ { - select { - case err := <-errs: - // Close all go routines - close(quit) - - return err - - case bucket := <-result: - // If there is no entry, nothing to restore - if bucket == nil { - continue - } - - for _, item := range bucket.Items { - entity, err := i.parseEntityFromBucketItem(ctx, item) - if err != nil { - return err - } - - if entity == nil { - continue - } - - // Ensure that there are no entities with duplicate names - entityByName, err := i.MemDBEntityByName(ctx, entity.Name, false) - if err != nil { - return nil - } - if entityByName != nil { - i.logger.Warn(errDuplicateIdentityName.Error(), "entity_name", entity.Name, "conflicting_entity_name", entityByName.Name, "action", "merge the duplicate entities into one") - if !i.disableLowerCasedNames { - return errDuplicateIdentityName - } - } - - // Only update MemDB and don't hit the storage again - err = i.upsertEntity(ctx, entity, nil, false) - if err != nil { - return errwrap.Wrapf("failed to update entity in MemDB: {{err}}", err) - } - } - } - } - - // Let all go routines finish - wg.Wait() - - if i.logger.IsInfo() { - i.logger.Info("entities restored") - } - - return nil -} - -// upsertEntityInTxn either creates or updates an existing entity. The -// operations will be updated in both MemDB and storage. If 'persist' is set to -// false, then storage will not be updated. When an alias is transferred from -// one entity to another, both the source and destination entities should get -// updated, in which case, callers should send in both entity and -// previousEntity. -func (i *IdentityStore) upsertEntityInTxn(ctx context.Context, txn *memdb.Txn, entity *identity.Entity, previousEntity *identity.Entity, persist bool) error { - var err error - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - aliasFactors := make([]string, len(entity.Aliases)) - - for index, alias := range entity.Aliases { - // Verify that alias is not associated to a different one already - aliasByFactors, err := i.MemDBAliasByFactors(alias.MountAccessor, alias.Name, false, false) - if err != nil { - return err - } - - switch { - case aliasByFactors == nil: - // Not found, no merging needed - case aliasByFactors.CanonicalID == entity.ID: - // Lookup found the same entity, so it's already attached to the - // right place - case previousEntity != nil && aliasByFactors.CanonicalID == previousEntity.ID: - // previousEntity isn't upserted yet so may still contain the old - // alias reference in memdb if it was just changed; validate - // whether or not it's _actually_ still tied to the entity - var found bool - for _, prevEntAlias := range previousEntity.Aliases { - if prevEntAlias.ID == alias.ID { - found = true - break - } - } - // If we didn't find the alias still tied to previousEntity, we - // shouldn't use the merging logic and should bail - if !found { - break - } - - // Otherwise it's still tied to previousEntity and fall through - // into merging - fallthrough - default: - i.logger.Warn("alias is already tied to a different entity; these entities are being merged", "alias_id", alias.ID, "other_entity_id", aliasByFactors.CanonicalID, "entity_aliases", entity.Aliases, "alias_by_factors", aliasByFactors) - respErr, intErr := i.mergeEntity(ctx, txn, entity, []string{aliasByFactors.CanonicalID}, true, false, true) - switch { - case respErr != nil: - return respErr - case intErr != nil: - return intErr - } - // The entity and aliases will be loaded into memdb and persisted - // as a result of the merge so we are done here - return nil - } - - if strutil.StrListContains(aliasFactors, i.sanitizeName(alias.Name)+alias.MountAccessor) { - i.logger.Warn(errDuplicateIdentityName.Error(), "alias_name", alias.Name, "mount_accessor", alias.MountAccessor, "entity_name", entity.Name, "action", "delete one of the duplicate aliases") - if !i.disableLowerCasedNames { - return errDuplicateIdentityName - } - } - - // Insert or update alias in MemDB using the transaction created above - err = i.MemDBUpsertAliasInTxn(txn, alias, false) - if err != nil { - return err - } - - aliasFactors[index] = i.sanitizeName(alias.Name) + alias.MountAccessor - } - - // If previous entity is set, update it in MemDB and persist it - if previousEntity != nil && persist { - err = i.MemDBUpsertEntityInTxn(txn, previousEntity) - if err != nil { - return err - } - - // Persist the previous entity object - marshaledPreviousEntity, err := ptypes.MarshalAny(previousEntity) - if err != nil { - return err - } - err = i.entityPacker.PutItem(&storagepacker.Item{ - ID: previousEntity.ID, - Message: marshaledPreviousEntity, - }) - if err != nil { - return err - } - } - - // Insert or update entity in MemDB using the transaction created above - err = i.MemDBUpsertEntityInTxn(txn, entity) - if err != nil { - return err - } - - if persist { - entityAsAny, err := ptypes.MarshalAny(entity) - if err != nil { - return err - } - item := &storagepacker.Item{ - ID: entity.ID, - Message: entityAsAny, - } - - // Persist the entity object - err = i.entityPacker.PutItem(item) - if err != nil { - return err - } - } - - return nil -} - -// upsertEntity either creates or updates an existing entity. The operations -// will be updated in both MemDB and storage. If 'persist' is set to false, -// then storage will not be updated. When an alias is transferred from one -// entity to another, both the source and destination entities should get -// updated, in which case, callers should send in both entity and -// previousEntity. -func (i *IdentityStore) upsertEntity(ctx context.Context, entity *identity.Entity, previousEntity *identity.Entity, persist bool) error { - - // Create a MemDB transaction to update both alias and entity - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.upsertEntityInTxn(ctx, txn, entity, previousEntity, persist) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) MemDBUpsertAliasInTxn(txn *memdb.Txn, alias *identity.Alias, groupAlias bool) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if alias == nil { - return fmt.Errorf("alias is nil") - } - - if alias.NamespaceID == "" { - alias.NamespaceID = namespace.RootNamespaceID - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "id", alias.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup alias from memdb using alias ID: {{err}}", err) - } - - if aliasRaw != nil { - err = txn.Delete(tableName, aliasRaw) - if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) - } - } - - if err := txn.Insert(tableName, alias); err != nil { - return errwrap.Wrapf("failed to update alias into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBAliasByIDInTxn(txn *memdb.Txn, aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "id", aliasID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using alias ID: {{err}}", err) - } - - if aliasRaw == nil { - return nil, nil - } - - alias, ok := aliasRaw.(*identity.Alias) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched alias") - } - - if clone { - return alias.Clone() - } - - return alias, nil -} - -func (i *IdentityStore) MemDBAliasByID(aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBAliasByIDInTxn(txn, aliasID, clone, groupAlias) -} - -func (i *IdentityStore) MemDBAliasByFactors(mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - txn := i.db.Txn(false) - - return i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, clone, groupAlias) -} - -func (i *IdentityStore) MemDBAliasByFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "factors", mountAccessor, aliasName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using factors: {{err}}", err) - } - - if aliasRaw == nil { - return nil, nil - } - - alias, ok := aliasRaw.(*identity.Alias) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched alias") - } - - if clone { - return alias.Clone() - } - - return alias, nil -} - -func (i *IdentityStore) MemDBDeleteAliasByIDInTxn(txn *memdb.Txn, aliasID string, groupAlias bool) error { - if aliasID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, groupAlias) - if err != nil { - return err - } - - if alias == nil { - return nil - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - err = txn.Delete(tableName, alias) - if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBAliases(ws memdb.WatchSet, groupAlias bool) (memdb.ResultIterator, error) { - txn := i.db.Txn(false) - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - iter, err := txn.Get(tableName, "id") - if err != nil { - return nil, err - } - - ws.Add(iter.WatchCh()) - - return iter, nil -} - -func (i *IdentityStore) MemDBUpsertEntityInTxn(txn *memdb.Txn, entity *identity.Entity) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - if entity.NamespaceID == "" { - entity.NamespaceID = namespace.RootNamespaceID - } - - entityRaw, err := txn.First(entitiesTable, "id", entity.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup entity from memdb using entity id: {{err}}", err) - } - - if entityRaw != nil { - err = txn.Delete(entitiesTable, entityRaw) - if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) - } - } - - if err := txn.Insert(entitiesTable, entity); err != nil { - return errwrap.Wrapf("failed to update entity into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBEntityByIDInTxn(txn *memdb.Txn, entityID string, clone bool) (*identity.Entity, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity id") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - entityRaw, err := txn.First(entitiesTable, "id", entityID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity id: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntityByID(entityID string, clone bool) (*identity.Entity, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity id") - } - - txn := i.db.Txn(false) - - return i.MemDBEntityByIDInTxn(txn, entityID, clone) -} - -func (i *IdentityStore) MemDBEntityByName(ctx context.Context, entityName string, clone bool) (*identity.Entity, error) { - if entityName == "" { - return nil, fmt.Errorf("missing entity name") - } - - txn := i.db.Txn(false) - - return i.MemDBEntityByNameInTxn(ctx, txn, entityName, clone) -} - -func (i *IdentityStore) MemDBEntityByNameInTxn(ctx context.Context, txn *memdb.Txn, entityName string, clone bool) (*identity.Entity, error) { - if entityName == "" { - return nil, fmt.Errorf("missing entity name") - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - entityRaw, err := txn.First(entitiesTable, "name", ns.ID, entityName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity name: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntitiesByBucketEntryKeyHashInTxn(txn *memdb.Txn, hashValue string) ([]*identity.Entity, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if hashValue == "" { - return nil, fmt.Errorf("empty hash value") - } - - entitiesIter, err := txn.Get(entitiesTable, "bucket_key_hash", hashValue) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup entities using bucket entry key hash: {{err}}", err) - } - - var entities []*identity.Entity - for entity := entitiesIter.Next(); entity != nil; entity = entitiesIter.Next() { - entities = append(entities, entity.(*identity.Entity)) - } - - return entities, nil -} - -func (i *IdentityStore) MemDBEntityByMergedEntityID(mergedEntityID string, clone bool) (*identity.Entity, error) { - if mergedEntityID == "" { - return nil, fmt.Errorf("missing merged entity id") - } - - txn := i.db.Txn(false) - - entityRaw, err := txn.First(entitiesTable, "merged_entity_ids", mergedEntityID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using merged entity id: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntityByAliasIDInTxn(txn *memdb.Txn, aliasID string, clone bool) (*identity.Entity, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBEntityByIDInTxn(txn, alias.CanonicalID, clone) -} - -func (i *IdentityStore) MemDBEntityByAliasID(aliasID string, clone bool) (*identity.Entity, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBEntityByAliasIDInTxn(txn, aliasID, clone) -} - -func (i *IdentityStore) MemDBDeleteEntityByID(entityID string) error { - if entityID == "" { - return nil - } - - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.MemDBDeleteEntityByIDInTxn(txn, entityID) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) MemDBDeleteEntityByIDInTxn(txn *memdb.Txn, entityID string) error { - if entityID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - entity, err := i.MemDBEntityByIDInTxn(txn, entityID, false) - if err != nil { - return err - } - - if entity == nil { - return nil - } - - err = txn.Delete(entitiesTable, entity) - if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) sanitizeAlias(ctx context.Context, alias *identity.Alias) error { - var err error - - if alias == nil { - return fmt.Errorf("alias is nil") - } - - // Alias must always be tied to a canonical object - if alias.CanonicalID == "" { - return fmt.Errorf("missing canonical ID") - } - - // Alias must have a name - if alias.Name == "" { - return fmt.Errorf("missing alias name %q", alias.Name) - } - - // Alias metadata should always be map[string]string - err = validateMetadata(alias.Metadata) - if err != nil { - return errwrap.Wrapf("invalid alias metadata: {{err}}", err) - } - - // Create an ID if there isn't one already - if alias.ID == "" { - alias.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate alias ID") - } - } - - if alias.NamespaceID == "" { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - alias.NamespaceID = ns.ID - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - if ns.ID != alias.NamespaceID { - return fmt.Errorf("alias belongs to a different namespace") - } - - // Set the creation and last update times - if alias.CreationTime == nil { - alias.CreationTime = ptypes.TimestampNow() - alias.LastUpdateTime = alias.CreationTime - } else { - alias.LastUpdateTime = ptypes.TimestampNow() - } - - return nil -} - -func (i *IdentityStore) sanitizeEntity(ctx context.Context, entity *identity.Entity) error { - var err error - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - // Create an ID if there isn't one already - if entity.ID == "" { - entity.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate entity id") - } - - // Set the hash value of the storage bucket key in entity - entity.BucketKeyHash = i.entityPacker.BucketKeyHashByItemID(entity.ID) - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - if entity.NamespaceID == "" { - entity.NamespaceID = ns.ID - } - if ns.ID != entity.NamespaceID { - return fmt.Errorf("entity does not belong to this namespace") - } - - // Create a name if there isn't one already - if entity.Name == "" { - entity.Name, err = i.generateName(ctx, "entity") - if err != nil { - return fmt.Errorf("failed to generate entity name") - } - } - - // Entity metadata should always be map[string]string - err = validateMetadata(entity.Metadata) - if err != nil { - return errwrap.Wrapf("invalid entity metadata: {{err}}", err) - } - - // Set the creation and last update times - if entity.CreationTime == nil { - entity.CreationTime = ptypes.TimestampNow() - entity.LastUpdateTime = entity.CreationTime - } else { - entity.LastUpdateTime = ptypes.TimestampNow() - } - - // Ensure that MFASecrets is non-nil at any time. This is useful when MFA - // secret generation procedures try to append MFA info to entity. - if entity.MFASecrets == nil { - entity.MFASecrets = make(map[string]*mfa.Secret) - } - - return nil -} - -func (i *IdentityStore) sanitizeAndUpsertGroup(ctx context.Context, group *identity.Group, memberGroupIDs []string) error { - var err error - - if group == nil { - return fmt.Errorf("group is nil") - } - - // Create an ID if there isn't one already - if group.ID == "" { - group.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate group id") - } - - // Set the hash value of the storage bucket key in group - group.BucketKeyHash = i.groupPacker.BucketKeyHashByItemID(group.ID) - } - - if group.NamespaceID == "" { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - group.NamespaceID = ns.ID - } - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - if ns.ID != group.NamespaceID { - return fmt.Errorf("group does not belong to this namespace") - } - - // Create a name if there isn't one already - if group.Name == "" { - group.Name, err = i.generateName(ctx, "group") - if err != nil { - return fmt.Errorf("failed to generate group name") - } - } - - // Entity metadata should always be map[string]string - err = validateMetadata(group.Metadata) - if err != nil { - return errwrap.Wrapf("invalid group metadata: {{err}}", err) - } - - // Set the creation and last update times - if group.CreationTime == nil { - group.CreationTime = ptypes.TimestampNow() - group.LastUpdateTime = group.CreationTime - } else { - group.LastUpdateTime = ptypes.TimestampNow() - } - - // Remove duplicate entity IDs and check if all IDs are valid - group.MemberEntityIDs = strutil.RemoveDuplicates(group.MemberEntityIDs, false) - for _, entityID := range group.MemberEntityIDs { - entity, err := i.MemDBEntityByID(entityID, false) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to validate entity ID %q: {{err}}", entityID), err) - } - if entity == nil { - return fmt.Errorf("invalid entity ID %q", entityID) - } - } - - txn := i.db.Txn(true) - defer txn.Abort() - - memberGroupIDs = strutil.RemoveDuplicates(memberGroupIDs, false) - - // For those group member IDs that are removed from the list, remove current - // group ID as their respective ParentGroupID. - - // Get the current MemberGroups IDs for this group - var currentMemberGroupIDs []string - currentMemberGroups, err := i.MemDBGroupsByParentGroupID(group.ID, false) - if err != nil { - return err - } - for _, currentMemberGroup := range currentMemberGroups { - currentMemberGroupIDs = append(currentMemberGroupIDs, currentMemberGroup.ID) - } - - // Update parent group IDs in the removed members - for _, currentMemberGroupID := range currentMemberGroupIDs { - if strutil.StrListContains(memberGroupIDs, currentMemberGroupID) { - continue - } - - currentMemberGroup, err := i.MemDBGroupByID(currentMemberGroupID, true) - if err != nil { - return err - } - if currentMemberGroup == nil { - return fmt.Errorf("invalid member group ID %q", currentMemberGroupID) - } - - // Remove group ID from the parent group IDs - currentMemberGroup.ParentGroupIDs = strutil.StrListDelete(currentMemberGroup.ParentGroupIDs, group.ID) - - err = i.UpsertGroupInTxn(txn, currentMemberGroup, true) - if err != nil { - return err - } - } - - // After the group lock is held, make membership updates to all the - // relevant groups - for _, memberGroupID := range memberGroupIDs { - memberGroup, err := i.MemDBGroupByID(memberGroupID, true) - if err != nil { - return err - } - if memberGroup == nil { - return fmt.Errorf("invalid member group ID %q", memberGroupID) - } - - // Skip if memberGroupID is already a member of group.ID - if strutil.StrListContains(memberGroup.ParentGroupIDs, group.ID) { - continue - } - - // Ensure that adding memberGroupID does not lead to cyclic - // relationships - // Detect self loop - if group.ID == memberGroupID { - return fmt.Errorf("member group ID %q is same as the ID of the group", group.ID) - } - - groupByID, err := i.MemDBGroupByID(group.ID, true) - if err != nil { - return err - } - - // If group is nil, that means that a group doesn't already exist and its - // okay to add any group as its member group. - if groupByID != nil { - // If adding the memberGroupID to groupID creates a cycle, then groupID must - // be a hop in that loop. Start a DFS traversal from memberGroupID and see if - // it reaches back to groupID. If it does, then it's a loop. - - // Created a visited set - visited := make(map[string]bool) - cycleDetected, err := i.detectCycleDFS(visited, groupByID.ID, memberGroupID) - if err != nil { - return fmt.Errorf("failed to perform cyclic relationship detection for member group ID %q", memberGroupID) - } - if cycleDetected { - return fmt.Errorf("cyclic relationship detected for member group ID %q", memberGroupID) - } - } - - memberGroup.ParentGroupIDs = append(memberGroup.ParentGroupIDs, group.ID) - - // This technically is not upsert. It is only update, only the method - // name is upsert here. - err = i.UpsertGroupInTxn(txn, memberGroup, true) - if err != nil { - // Ideally we would want to revert the whole operation in case of - // errors while persisting in member groups. But there is no - // storage transaction support yet. When we do have it, this will need - // an update. - return err - } - } - - // Sanitize the group alias - if group.Alias != nil { - group.Alias.CanonicalID = group.ID - err = i.sanitizeAlias(ctx, group.Alias) - if err != nil { - return err - } - } - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) deleteAliasesInEntityInTxn(txn *memdb.Txn, entity *identity.Entity, aliases []*identity.Alias) error { - if entity == nil { - return fmt.Errorf("entity is nil") - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - var remainList []*identity.Alias - var removeList []*identity.Alias - - for _, item := range aliases { - for _, alias := range entity.Aliases { - if alias.ID == item.ID { - removeList = append(removeList, alias) - } else { - remainList = append(remainList, alias) - } - } - } - - // Remove identity indices from aliases table for those that needs to - // be removed - for _, alias := range removeList { - err := i.MemDBDeleteAliasByIDInTxn(txn, alias.ID, false) - if err != nil { - return err - } - } - - // Update the entity with remaining items - entity.Aliases = remainList - - return nil -} - -// validateMeta validates a set of key/value pairs from the agent config -func validateMetadata(meta map[string]string) error { - if len(meta) > metaMaxKeyPairs { - return fmt.Errorf("metadata cannot contain more than %d key/value pairs", metaMaxKeyPairs) - } - - for key, value := range meta { - if err := validateMetaPair(key, value); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to load metadata pair (%q, %q): {{err}}", key, value), err) - } - } - - return nil -} - -// validateMetaPair checks that the given key/value pair is in a valid format -func validateMetaPair(key, value string) error { - if key == "" { - return fmt.Errorf("key cannot be blank") - } - if !metaKeyFormatRegEx(key) { - return fmt.Errorf("key contains invalid characters") - } - if len(key) > metaKeyMaxLength { - return fmt.Errorf("key is too long (limit: %d characters)", metaKeyMaxLength) - } - if strings.HasPrefix(key, metaKeyReservedPrefix) { - return fmt.Errorf("key prefix %q is reserved for internal use", metaKeyReservedPrefix) - } - if len(value) > metaValueMaxLength { - return fmt.Errorf("value is too long (limit: %d characters)", metaValueMaxLength) - } - return nil -} - -func (i *IdentityStore) MemDBGroupByNameInTxn(ctx context.Context, txn *memdb.Txn, groupName string, clone bool) (*identity.Group, error) { - if groupName == "" { - return nil, fmt.Errorf("missing group name") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - groupRaw, err := txn.First(groupsTable, "name", ns.ID, groupName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group name: {{err}}", err) - } - - if groupRaw == nil { - return nil, nil - } - - group, ok := groupRaw.(*identity.Group) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched group") - } - - if clone { - return group.Clone() - } - - return group, nil -} - -func (i *IdentityStore) MemDBGroupByName(ctx context.Context, groupName string, clone bool) (*identity.Group, error) { - if groupName == "" { - return nil, fmt.Errorf("missing group name") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByNameInTxn(ctx, txn, groupName, clone) -} - -func (i *IdentityStore) UpsertGroup(group *identity.Group, persist bool) error { - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) UpsertGroupInTxn(txn *memdb.Txn, group *identity.Group, persist bool) error { - var err error - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - if group == nil { - return fmt.Errorf("group is nil") - } - - // Increment the modify index of the group - group.ModifyIndex++ - - // Clear the old alias from memdb - groupClone, err := i.MemDBGroupByID(group.ID, true) - if err != nil { - return err - } - if groupClone != nil && groupClone.Alias != nil { - err = i.MemDBDeleteAliasByIDInTxn(txn, groupClone.Alias.ID, true) - if err != nil { - return err - } - } - - // Add the new alias to memdb - if group.Alias != nil { - err = i.MemDBUpsertAliasInTxn(txn, group.Alias, true) - if err != nil { - return err - } - } - - // Insert or update group in MemDB using the transaction created above - err = i.MemDBUpsertGroupInTxn(txn, group) - if err != nil { - return err - } - - if persist { - groupAsAny, err := ptypes.MarshalAny(group) - if err != nil { - return err - } - - item := &storagepacker.Item{ - ID: group.ID, - Message: groupAsAny, - } - - sent, err := sendGroupUpgrade(i, group) - if err != nil { - return err - } - if !sent { - if err := i.groupPacker.PutItem(item); err != nil { - return err - } - } - } - - return nil -} - -func (i *IdentityStore) MemDBUpsertGroupInTxn(txn *memdb.Txn, group *identity.Group) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if group == nil { - return fmt.Errorf("group is nil") - } - - if group.NamespaceID == "" { - group.NamespaceID = namespace.RootNamespaceID - } - - groupRaw, err := txn.First(groupsTable, "id", group.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup group from memdb using group id: {{err}}", err) - } - - if groupRaw != nil { - err = txn.Delete(groupsTable, groupRaw) - if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) - } - } - - if err := txn.Insert(groupsTable, group); err != nil { - return errwrap.Wrapf("failed to update group into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBDeleteGroupByIDInTxn(txn *memdb.Txn, groupID string) error { - if groupID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - group, err := i.MemDBGroupByIDInTxn(txn, groupID, false) - if err != nil { - return err - } - - if group == nil { - return nil - } - - err = txn.Delete("groups", group) - if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBGroupByIDInTxn(txn *memdb.Txn, groupID string, clone bool) (*identity.Group, error) { - if groupID == "" { - return nil, fmt.Errorf("missing group ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - groupRaw, err := txn.First(groupsTable, "id", groupID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group ID: {{err}}", err) - } - - if groupRaw == nil { - return nil, nil - } - - group, ok := groupRaw.(*identity.Group) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched group") - } - - if clone { - return group.Clone() - } - - return group, nil -} - -func (i *IdentityStore) MemDBGroupByID(groupID string, clone bool) (*identity.Group, error) { - if groupID == "" { - return nil, fmt.Errorf("missing group ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByIDInTxn(txn, groupID, clone) -} - -func (i *IdentityStore) MemDBGroupsByParentGroupIDInTxn(txn *memdb.Txn, memberGroupID string, clone bool) ([]*identity.Group, error) { - if memberGroupID == "" { - return nil, fmt.Errorf("missing member group ID") - } - - groupsIter, err := txn.Get(groupsTable, "parent_group_ids", memberGroupID) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using member group ID: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - entry := group.(*identity.Group) - if clone { - entry, err = entry.Clone() - if err != nil { - return nil, err - } - } - groups = append(groups, entry) - } - - return groups, nil -} - -func (i *IdentityStore) MemDBGroupsByParentGroupID(memberGroupID string, clone bool) ([]*identity.Group, error) { - if memberGroupID == "" { - return nil, fmt.Errorf("missing member group ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupsByParentGroupIDInTxn(txn, memberGroupID, clone) -} - -func (i *IdentityStore) MemDBGroupsByMemberEntityID(entityID string, clone bool, externalOnly bool) ([]*identity.Group, error) { - txn := i.db.Txn(false) - defer txn.Abort() - - return i.MemDBGroupsByMemberEntityIDInTxn(txn, entityID, clone, externalOnly) -} - -func (i *IdentityStore) MemDBGroupsByMemberEntityIDInTxn(txn *memdb.Txn, entityID string, clone bool, externalOnly bool) ([]*identity.Group, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity ID") - } - - groupsIter, err := txn.Get(groupsTable, "member_entity_ids", entityID) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using entity ID: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - entry := group.(*identity.Group) - if externalOnly && entry.Type == groupTypeInternal { - continue - } - if clone { - entry, err = entry.Clone() - if err != nil { - return nil, err - } - } - groups = append(groups, entry) - } - - return groups, nil -} - -func (i *IdentityStore) groupPoliciesByEntityID(entityID string) (map[string][]string, error) { - if entityID == "" { - return nil, fmt.Errorf("empty entity ID") - } - - groups, err := i.MemDBGroupsByMemberEntityID(entityID, false, false) - if err != nil { - return nil, err - } - - visited := make(map[string]bool) - policies := make(map[string][]string) - for _, group := range groups { - err := i.collectPoliciesReverseDFS(group, visited, policies) - if err != nil { - return nil, err - } - } - - return policies, nil -} - -func (i *IdentityStore) groupsByEntityID(entityID string) ([]*identity.Group, []*identity.Group, error) { - if entityID == "" { - return nil, nil, fmt.Errorf("empty entity ID") - } - - groups, err := i.MemDBGroupsByMemberEntityID(entityID, true, false) - if err != nil { - return nil, nil, err - } - - visited := make(map[string]bool) - var tGroups []*identity.Group - for _, group := range groups { - gGroups, err := i.collectGroupsReverseDFS(group, visited, nil) - if err != nil { - return nil, nil, err - } - tGroups = append(tGroups, gGroups...) - } - - // Remove duplicates - groupMap := make(map[string]*identity.Group) - for _, group := range tGroups { - groupMap[group.ID] = group - } - - tGroups = make([]*identity.Group, 0, len(groupMap)) - for _, group := range groupMap { - tGroups = append(tGroups, group) - } - - diff := diffGroups(groups, tGroups) - - // For sanity - // There should not be any group that gets deleted - if len(diff.Deleted) != 0 { - return nil, nil, fmt.Errorf("failed to diff group memberships") - } - - return diff.Unmodified, diff.New, nil -} - -func (i *IdentityStore) collectGroupsReverseDFS(group *identity.Group, visited map[string]bool, groups []*identity.Group) ([]*identity.Group, error) { - if group == nil { - return nil, fmt.Errorf("nil group") - } - - // If traversal for a groupID is performed before, skip it - if visited[group.ID] { - return groups, nil - } - visited[group.ID] = true - - groups = append(groups, group) - - // Traverse all the parent groups - for _, parentGroupID := range group.ParentGroupIDs { - parentGroup, err := i.MemDBGroupByID(parentGroupID, false) - if err != nil { - return nil, err - } - if parentGroup == nil { - continue - } - groups, err = i.collectGroupsReverseDFS(parentGroup, visited, groups) - if err != nil { - return nil, fmt.Errorf("failed to collect group at parent group ID %q", parentGroup.ID) - } - } - - return groups, nil -} - -func (i *IdentityStore) collectPoliciesReverseDFS(group *identity.Group, visited map[string]bool, policies map[string][]string) error { - if group == nil { - return fmt.Errorf("nil group") - } - - // If traversal for a groupID is performed before, skip it - if visited[group.ID] { - return nil - } - visited[group.ID] = true - - policies[group.NamespaceID] = append(policies[group.NamespaceID], group.Policies...) - - // Traverse all the parent groups - for _, parentGroupID := range group.ParentGroupIDs { - parentGroup, err := i.MemDBGroupByID(parentGroupID, false) - if err != nil { - return err - } - if parentGroup == nil { - continue - } - err = i.collectPoliciesReverseDFS(parentGroup, visited, policies) - if err != nil { - return fmt.Errorf("failed to collect policies at parent group ID %q", parentGroup.ID) - } - } - - return nil -} - -func (i *IdentityStore) detectCycleDFS(visited map[string]bool, startingGroupID, groupID string) (bool, error) { - // If the traversal reaches the startingGroupID, a loop is detected - if startingGroupID == groupID { - return true, nil - } - - // If traversal for a groupID is performed before, skip it - if visited[groupID] { - return false, nil - } - visited[groupID] = true - - group, err := i.MemDBGroupByID(groupID, true) - if err != nil { - return false, err - } - if group == nil { - return false, nil - } - - // Fetch all groups in which groupID is present as a ParentGroupID. In - // other words, find all the subgroups of groupID. - memberGroups, err := i.MemDBGroupsByParentGroupID(groupID, false) - if err != nil { - return false, err - } - - // DFS traverse the member groups - for _, memberGroup := range memberGroups { - cycleDetected, err := i.detectCycleDFS(visited, startingGroupID, memberGroup.ID) - if err != nil { - return false, fmt.Errorf("failed to perform cycle detection at member group ID %q", memberGroup.ID) - } - if cycleDetected { - return true, fmt.Errorf("cycle detected at member group ID %q", memberGroup.ID) - } - } - - return false, nil -} - -func (i *IdentityStore) memberGroupIDsByID(groupID string) ([]string, error) { - var memberGroupIDs []string - memberGroups, err := i.MemDBGroupsByParentGroupID(groupID, false) - if err != nil { - return nil, err - } - for _, memberGroup := range memberGroups { - memberGroupIDs = append(memberGroupIDs, memberGroup.ID) - } - return memberGroupIDs, nil -} - -func (i *IdentityStore) generateName(ctx context.Context, entryType string) (string, error) { - var name string -OUTER: - for { - randBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - return "", err - } - name = fmt.Sprintf("%s_%s", entryType, fmt.Sprintf("%08x", randBytes[0:4])) - - switch entryType { - case "entity": - entity, err := i.MemDBEntityByName(ctx, name, false) - if err != nil { - return "", err - } - if entity == nil { - break OUTER - } - case "group": - group, err := i.MemDBGroupByName(ctx, name, false) - if err != nil { - return "", err - } - if group == nil { - break OUTER - } - default: - return "", fmt.Errorf("unrecognized type %q", entryType) - } - } - - return name, nil -} - -func (i *IdentityStore) MemDBGroupsByBucketEntryKeyHashInTxn(txn *memdb.Txn, hashValue string) ([]*identity.Group, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if hashValue == "" { - return nil, fmt.Errorf("empty hash value") - } - - groupsIter, err := txn.Get(groupsTable, "bucket_key_hash", hashValue) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using bucket entry key hash: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - groups = append(groups, group.(*identity.Group)) - } - - return groups, nil -} - -func (i *IdentityStore) MemDBGroupByAliasIDInTxn(txn *memdb.Txn, aliasID string, clone bool) (*identity.Group, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBGroupByIDInTxn(txn, alias.CanonicalID, clone) -} - -func (i *IdentityStore) MemDBGroupByAliasID(aliasID string, clone bool) (*identity.Group, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByAliasIDInTxn(txn, aliasID, clone) -} - -func (i *IdentityStore) refreshExternalGroupMembershipsByEntityID(entityID string, groupAliases []*logical.Alias) ([]*logical.Alias, error) { - i.logger.Debug("refreshing external group memberships", "entity_id", entityID, "group_aliases", groupAliases) - if entityID == "" { - return nil, fmt.Errorf("empty entity ID") - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - txn := i.db.Txn(true) - defer txn.Abort() - - oldGroups, err := i.MemDBGroupsByMemberEntityIDInTxn(txn, entityID, true, true) - if err != nil { - return nil, err - } - - mountAccessor := "" - if len(groupAliases) != 0 { - mountAccessor = groupAliases[0].MountAccessor - } - - var newGroups []*identity.Group - var validAliases []*logical.Alias - for _, alias := range groupAliases { - aliasByFactors, err := i.MemDBAliasByFactors(alias.MountAccessor, alias.Name, true, true) - if err != nil { - return nil, err - } - if aliasByFactors == nil { - continue - } - mappingGroup, err := i.MemDBGroupByAliasID(aliasByFactors.ID, true) - if err != nil { - return nil, err - } - if mappingGroup == nil { - return nil, fmt.Errorf("group unavailable for a valid alias ID %q", aliasByFactors.ID) - } - - newGroups = append(newGroups, mappingGroup) - validAliases = append(validAliases, alias) - } - - diff := diffGroups(oldGroups, newGroups) - - // Add the entity ID to all the new groups - for _, group := range diff.New { - if group.Type != groupTypeExternal { - continue - } - - i.logger.Debug("adding member entity ID to external group", "member_entity_id", entityID, "group_id", group.ID) - - group.MemberEntityIDs = append(group.MemberEntityIDs, entityID) - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - } - - // Remove the entity ID from all the deleted groups - for _, group := range diff.Deleted { - if group.Type != groupTypeExternal { - continue - } - - // If the external group is from a different mount, don't remove the - // entity ID from it. - if mountAccessor != "" && group.Alias.MountAccessor != mountAccessor { - continue - } - - i.logger.Debug("removing member entity ID from external group", "member_entity_id", entityID, "group_id", group.ID) - - group.MemberEntityIDs = strutil.StrListDelete(group.MemberEntityIDs, entityID) - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - } - - txn.Commit() - - return validAliases, nil -} - -// diffGroups is used to diff two sets of groups -func diffGroups(old, new []*identity.Group) *groupDiff { - diff := &groupDiff{} - - existing := make(map[string]*identity.Group) - for _, group := range old { - existing[group.ID] = group - } - - for _, group := range new { - // Check if the entry in new is present in the old - _, ok := existing[group.ID] - - // If its not present, then its a new entry - if !ok { - diff.New = append(diff.New, group) - continue - } - - // If its present, it means that its unmodified - diff.Unmodified = append(diff.Unmodified, group) - - // By deleting the unmodified from the old set, we could determine the - // ones that are stale by looking at the remaining ones. - delete(existing, group.ID) - } - - // Any remaining entries must have been deleted - for _, me := range existing { - diff.Deleted = append(diff.Deleted, me) - } - - return diff -} - -func (i *IdentityStore) handleAliasListCommon(ctx context.Context, groupAlias bool) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - ws := memdb.NewWatchSet() - - txn := i.db.Txn(false) - - iter, err := txn.Get(tableName, "namespace_id", ns.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for aliases in memdb: {{err}}", err) - } - - ws.Add(iter.WatchCh()) - - var aliasIDs []string - aliasInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - alias := raw.(*identity.Alias) - aliasIDs = append(aliasIDs, alias.ID) - aliasInfoEntry := map[string]interface{}{ - "name": alias.Name, - "canonical_id": alias.CanonicalID, - "mount_accessor": alias.MountAccessor, - } - - mi, ok := mountAccessorMap[alias.MountAccessor] - if ok { - aliasInfoEntry["mount_type"] = mi.MountType - aliasInfoEntry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - aliasInfoEntry["mount_type"] = mi.MountType - aliasInfoEntry["mount_path"] = mi.MountPath - } - mountAccessorMap[alias.MountAccessor] = mi - } - - aliasInfo[alias.ID] = aliasInfoEntry - } - - return logical.ListResponseWithInfo(aliasIDs, aliasInfo), nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/init.go b/vendor/github.com/hashicorp/vault/vault/init.go deleted file mode 100644 index 426cc62a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/init.go +++ /dev/null @@ -1,323 +0,0 @@ -package vault - -import ( - "context" - "encoding/base64" - "encoding/hex" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/shamir" -) - -// InitParams keeps the init function from being littered with too many -// params, that's it! -type InitParams struct { - BarrierConfig *SealConfig - RecoveryConfig *SealConfig - RootTokenPGPKey string -} - -// InitResult is used to provide the key parts back after -// they are generated as part of the initialization. -type InitResult struct { - SecretShares [][]byte - RecoveryShares [][]byte - RootToken string -} - -var ( - initPTFunc = func(c *Core) func() { return nil } -) - -// Initialized checks if the Vault is already initialized -func (c *Core) Initialized(ctx context.Context) (bool, error) { - // Check the barrier first - init, err := c.barrier.Initialized(ctx) - if err != nil { - c.logger.Error("barrier init check failed", "error", err) - return false, err - } - if !init { - c.logger.Info("security barrier not initialized") - return false, nil - } - - // Verify the seal configuration - sealConf, err := c.seal.BarrierConfig(ctx) - if err != nil { - return false, err - } - if sealConf == nil { - return false, fmt.Errorf("core: barrier reports initialized but no seal configuration found") - } - - return true, nil -} - -func (c *Core) generateShares(sc *SealConfig) ([]byte, [][]byte, error) { - // Generate a master key - masterKey, err := c.barrier.GenerateKey() - if err != nil { - return nil, nil, errwrap.Wrapf("key generation failed: {{err}}", err) - } - - // Return the master key if only a single key part is used - var unsealKeys [][]byte - if sc.SecretShares == 1 { - unsealKeys = append(unsealKeys, masterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(masterKey, sc.SecretShares, sc.SecretThreshold) - if err != nil { - return nil, nil, errwrap.Wrapf("failed to generate barrier shares: {{err}}", err) - } - unsealKeys = shares - } - - // If we have PGP keys, perform the encryption - if len(sc.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(unsealKeys)) - for i, _ := range unsealKeys { - hexEncodedShares[i] = []byte(hex.EncodeToString(unsealKeys[i])) - } - _, encryptedShares, err := pgpkeys.EncryptShares(hexEncodedShares, sc.PGPKeys) - if err != nil { - return nil, nil, err - } - unsealKeys = encryptedShares - } - - return masterKey, unsealKeys, nil -} - -// Initialize is used to initialize the Vault with the given -// configurations. -func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitResult, error) { - barrierConfig := initParams.BarrierConfig - recoveryConfig := initParams.RecoveryConfig - - if c.seal.RecoveryKeySupported() { - if recoveryConfig == nil { - return nil, fmt.Errorf("recovery configuration must be supplied") - } - - if recoveryConfig.SecretShares < 1 { - return nil, fmt.Errorf("recovery configuration must specify a positive number of shares") - } - - // Check if the seal configuration is valid - if err := recoveryConfig.Validate(); err != nil { - c.logger.Error("invalid recovery configuration", "error", err) - return nil, errwrap.Wrapf("invalid recovery configuration: {{err}}", err) - } - } - - // Check if the seal configuration is valid - if err := barrierConfig.Validate(); err != nil { - c.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("invalid seal configuration: {{err}}", err) - } - - // Avoid an initialization race - c.stateLock.Lock() - defer c.stateLock.Unlock() - - // Check if we are initialized - init, err := c.Initialized(ctx) - if err != nil { - return nil, err - } - if init { - return nil, ErrAlreadyInit - } - - err = c.seal.Init(ctx) - if err != nil { - c.logger.Error("failed to initialize seal", "error", err) - return nil, errwrap.Wrapf("error initializing seal: {{err}}", err) - } - - barrierKey, barrierUnsealKeys, err := c.generateShares(barrierConfig) - if err != nil { - c.logger.Error("error generating shares", "error", err) - return nil, err - } - - initPTCleanup := initPTFunc(c) - if initPTCleanup != nil { - defer initPTCleanup() - } - - // Initialize the barrier - if err := c.barrier.Initialize(ctx, barrierKey); err != nil { - c.logger.Error("failed to initialize barrier", "error", err) - return nil, errwrap.Wrapf("failed to initialize barrier: {{err}}", err) - } - if c.logger.IsInfo() { - c.logger.Info("security barrier initialized", "shares", barrierConfig.SecretShares, "threshold", barrierConfig.SecretThreshold) - } - - // Unseal the barrier - if err := c.barrier.Unseal(ctx, barrierKey); err != nil { - c.logger.Error("failed to unseal barrier", "error", err) - return nil, errwrap.Wrapf("failed to unseal barrier: {{err}}", err) - } - - // Ensure the barrier is re-sealed - defer func() { - // Defers are LIFO so we need to run this here too to ensure the stop - // happens before sealing. preSeal also stops, so we just make the - // stopping safe against multiple calls. - if err := c.barrier.Seal(); err != nil { - c.logger.Error("failed to seal barrier", "error", err) - } - }() - - err = c.seal.SetBarrierConfig(ctx, barrierConfig) - if err != nil { - c.logger.Error("failed to save barrier configuration", "error", err) - return nil, errwrap.Wrapf("barrier configuration saving failed: {{err}}", err) - } - - // If we are storing shares, pop them out of the returned results and push - // them through the seal - if barrierConfig.StoredShares > 0 { - var keysToStore [][]byte - for i := 0; i < barrierConfig.StoredShares; i++ { - keysToStore = append(keysToStore, barrierUnsealKeys[0]) - barrierUnsealKeys = barrierUnsealKeys[1:] - } - if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { - c.logger.Error("failed to store keys", "error", err) - return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) - } - } - - results := &InitResult{ - SecretShares: barrierUnsealKeys, - } - - // Perform initial setup - if err := c.setupCluster(ctx); err != nil { - c.logger.Error("cluster setup failed during init", "error", err) - return nil, err - } - - // Start tracking - if initPTCleanup != nil { - initPTCleanup() - } - - activeCtx, ctxCancel := context.WithCancel(namespace.RootContext(nil)) - if err := c.postUnseal(activeCtx, ctxCancel, standardUnsealStrategy{}); err != nil { - c.logger.Error("post-unseal setup failed during init", "error", err) - return nil, err - } - - // Save the configuration regardless, but only generate a key if it's not - // disabled. When using recovery keys they are stored in the barrier, so - // this must happen post-unseal. - if c.seal.RecoveryKeySupported() { - err = c.seal.SetRecoveryConfig(ctx, recoveryConfig) - if err != nil { - c.logger.Error("failed to save recovery configuration", "error", err) - return nil, errwrap.Wrapf("recovery configuration saving failed: {{err}}", err) - } - - if recoveryConfig.SecretShares > 0 { - recoveryKey, recoveryUnsealKeys, err := c.generateShares(recoveryConfig) - if err != nil { - c.logger.Error("failed to generate recovery shares", "error", err) - return nil, err - } - - err = c.seal.SetRecoveryKey(ctx, recoveryKey) - if err != nil { - return nil, err - } - - results.RecoveryShares = recoveryUnsealKeys - } - } - - // Generate a new root token - rootToken, err := c.tokenStore.rootToken(ctx) - if err != nil { - c.logger.Error("root token generation failed", "error", err) - return nil, err - } - results.RootToken = rootToken.ID - c.logger.Info("root token generated") - - if initParams.RootTokenPGPKey != "" { - _, encryptedVals, err := pgpkeys.EncryptShares([][]byte{[]byte(results.RootToken)}, []string{initParams.RootTokenPGPKey}) - if err != nil { - c.logger.Error("root token encryption failed", "error", err) - return nil, err - } - results.RootToken = base64.StdEncoding.EncodeToString(encryptedVals[0]) - } - - // Prepare to re-seal - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - return nil, err - } - - return results, nil -} - -// UnsealWithStoredKeys performs auto-unseal using stored keys. -func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { - if !c.seal.StoredKeysSupported() { - return nil - } - - // Disallow auto-unsealing when migrating - if c.IsInSealMigration() { - return nil - } - - sealed := c.Sealed() - if !sealed { - return nil - } - - c.logger.Info("stored unseal keys supported, attempting fetch") - keys, err := c.seal.GetStoredKeys(ctx) - if err != nil { - c.logger.Error("fetching stored unseal keys failed", "error", err) - return &NonFatalError{Err: errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err)} - } - if len(keys) == 0 { - c.logger.Warn("stored unseal key(s) supported but none found") - } else { - unsealed := false - keysUsed := 0 - for _, key := range keys { - unsealed, err = c.Unseal(key) - if err != nil { - c.logger.Error("unseal with stored unseal key failed", "error", err) - return &NonFatalError{Err: errwrap.Wrapf("unseal with stored key failed: {{err}}", err)} - } - keysUsed += 1 - if unsealed { - break - } - } - if !unsealed { - if c.logger.IsWarn() { - c.logger.Warn("stored unseal key(s) used but Vault not unsealed yet", "stored_keys_used", keysUsed) - } - } else { - if c.logger.IsInfo() { - c.logger.Info("successfully unsealed with stored key(s)", "stored_keys_used", keysUsed) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/keyring.go b/vendor/github.com/hashicorp/vault/vault/keyring.go deleted file mode 100644 index fd656479..00000000 --- a/vendor/github.com/hashicorp/vault/vault/keyring.go +++ /dev/null @@ -1,203 +0,0 @@ -package vault - -import ( - "bytes" - "encoding/json" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" -) - -// Keyring is used to manage multiple encryption keys used by -// the barrier. New keys can be installed and each has a sequential term. -// The term used to encrypt a key is prefixed to the key written out. -// All data is encrypted with the latest key, but storing the old keys -// allows for decryption of keys written previously. Along with the encryption -// keys, the keyring also tracks the master key. This is necessary so that -// when a new key is added to the keyring, we can encrypt with the master key -// and write out the new keyring. -type Keyring struct { - masterKey []byte - keys map[uint32]*Key - activeTerm uint32 -} - -// EncodedKeyring is used for serialization of the keyring -type EncodedKeyring struct { - MasterKey []byte - Keys []*Key -} - -// Key represents a single term, along with the key used. -type Key struct { - Term uint32 - Version int - Value []byte - InstallTime time.Time -} - -// Serialize is used to create a byte encoded key -func (k *Key) Serialize() ([]byte, error) { - return json.Marshal(k) -} - -// DeserializeKey is used to deserialize and return a new key -func DeserializeKey(buf []byte) (*Key, error) { - k := new(Key) - if err := jsonutil.DecodeJSON(buf, k); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) - } - return k, nil -} - -// NewKeyring creates a new keyring -func NewKeyring() *Keyring { - k := &Keyring{ - keys: make(map[uint32]*Key), - activeTerm: 0, - } - return k -} - -// Clone returns a new copy of the keyring -func (k *Keyring) Clone() *Keyring { - clone := &Keyring{ - masterKey: k.masterKey, - keys: make(map[uint32]*Key, len(k.keys)), - activeTerm: k.activeTerm, - } - for idx, key := range k.keys { - clone.keys[idx] = key - } - return clone -} - -// AddKey adds a new key to the keyring -func (k *Keyring) AddKey(key *Key) (*Keyring, error) { - // Ensure there is no conflict - if exist, ok := k.keys[key.Term]; ok { - if !bytes.Equal(key.Value, exist.Value) { - return nil, fmt.Errorf("conflicting key for term %d already installed", key.Term) - } - return k, nil - } - - // Add a time if none - if key.InstallTime.IsZero() { - key.InstallTime = time.Now() - } - - // Make a new keyring - clone := k.Clone() - - // Install the new key - clone.keys[key.Term] = key - - // Update the active term if newer - if key.Term > clone.activeTerm { - clone.activeTerm = key.Term - } - return clone, nil -} - -// RemoveKey removes a key from the keyring -func (k *Keyring) RemoveKey(term uint32) (*Keyring, error) { - // Ensure this is not the active key - if term == k.activeTerm { - return nil, fmt.Errorf("cannot remove active key") - } - - // Check if this term does not exist - if _, ok := k.keys[term]; !ok { - return k, nil - } - - // Delete the key - clone := k.Clone() - delete(clone.keys, term) - return clone, nil -} - -// ActiveTerm returns the currently active term -func (k *Keyring) ActiveTerm() uint32 { - return k.activeTerm -} - -// ActiveKey returns the active encryption key, or nil -func (k *Keyring) ActiveKey() *Key { - return k.keys[k.activeTerm] -} - -// TermKey returns the key for the given term, or nil -func (k *Keyring) TermKey(term uint32) *Key { - return k.keys[term] -} - -// SetMasterKey is used to update the master key -func (k *Keyring) SetMasterKey(val []byte) *Keyring { - valCopy := make([]byte, len(val)) - copy(valCopy, val) - clone := k.Clone() - clone.masterKey = valCopy - return clone -} - -// MasterKey returns the master key -func (k *Keyring) MasterKey() []byte { - return k.masterKey -} - -// Serialize is used to create a byte encoded keyring -func (k *Keyring) Serialize() ([]byte, error) { - // Create the encoded entry - enc := EncodedKeyring{ - MasterKey: k.masterKey, - } - for _, key := range k.keys { - enc.Keys = append(enc.Keys, key) - } - - // JSON encode the keyring - buf, err := json.Marshal(enc) - return buf, err -} - -// DeserializeKeyring is used to deserialize and return a new keyring -func DeserializeKeyring(buf []byte) (*Keyring, error) { - // Deserialize the keyring - var enc EncodedKeyring - if err := jsonutil.DecodeJSON(buf, &enc); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) - } - - // Create a new keyring - k := NewKeyring() - k.masterKey = enc.MasterKey - for _, key := range enc.Keys { - k.keys[key.Term] = key - if key.Term > k.activeTerm { - k.activeTerm = key.Term - } - } - return k, nil -} - -// N.B.: -// Since Go 1.5 these are not reliable; see the documentation around the memzero -// function. These are best-effort. -func (k *Keyring) Zeroize(keysToo bool) { - if k == nil { - return - } - if k.masterKey != nil { - memzero(k.masterKey) - } - if !keysToo || k.keys == nil { - return - } - for _, key := range k.keys { - memzero(key.Value) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go b/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go deleted file mode 100644 index 5f45d9e5..00000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go +++ /dev/null @@ -1,240 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// CubbyholeBackendFactory constructs a new cubbyhole backend -func CubbyholeBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := &CubbyholeBackend{} - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(cubbyholeHelp), - } - - b.Backend.Paths = append(b.Backend.Paths, b.paths()...) - - if conf == nil { - return nil, fmt.Errorf("configuration passed into backend is nil") - } - b.Backend.Setup(ctx, conf) - - return b, nil -} - -// CubbyholeBackend is used for storing secrets directly into the physical -// backend. The secrets are encrypted in the durable storage. -// This differs from kv in that every token has its own private -// storage view. The view is removed when the token expires. -type CubbyholeBackend struct { - *framework.Backend - - saltUUID string - storageView logical.Storage -} - -func (b *CubbyholeBackend) paths() []*framework.Path { - return []*framework.Path{ - { - Pattern: framework.MatchAllRegex("path"), - - Fields: map[string]*framework.FieldSchema{ - "path": { - Type: framework.TypeString, - Description: "Specifies the path of the secret.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleRead, - Summary: "Retrieve the secret at the specified location.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleWrite, - Summary: "Store a secret at the specified location.", - }, - logical.CreateOperation: &framework.PathOperation{ - Callback: b.handleWrite, - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleDelete, - Summary: "Deletes the secret at the specified location.", - }, - logical.ListOperation: &framework.PathOperation{ - Callback: b.handleList, - Summary: "List secret entries at the specified location.", - Description: "Folders are suffixed with /. The input must be a folder; list on a file will not return a value. The values themselves are not accessible via this command.", - }, - }, - - ExistenceCheck: b.handleExistenceCheck, - - HelpSynopsis: strings.TrimSpace(cubbyholeHelpSynopsis), - HelpDescription: strings.TrimSpace(cubbyholeHelpDescription), - }, - } -} - -func (b *CubbyholeBackend) revoke(ctx context.Context, saltedToken string) error { - if saltedToken == "" { - return fmt.Errorf("client token empty during revocation") - } - - if err := logical.ClearView(ctx, b.storageView.(*BarrierView).SubView(saltedToken+"/")); err != nil { - return err - } - - return nil -} - -func (b *CubbyholeBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - out, err := req.Storage.Get(ctx, req.ClientToken+"/"+req.Path) - if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) - } - - return out != nil, nil -} - -func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - path := data.Get("path").(string) - - // Read the path - out, err := req.Storage.Get(ctx, req.ClientToken+"/"+path) - if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) - } - - // Fast-path the no data case - if out == nil { - return nil, nil - } - - // Decode the data - var rawData map[string]interface{} - if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) - } - - // Generate the response - resp := &logical.Response{ - Data: rawData, - } - - return resp, nil -} - -func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - // Check that some fields are given - if len(req.Data) == 0 { - return nil, fmt.Errorf("missing data fields") - } - - path := data.Get("path").(string) - - // JSON encode the data - buf, err := json.Marshal(req.Data) - if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) - } - - // Write out a new key - entry := &logical.StorageEntry{ - Key: req.ClientToken + "/" + path, - Value: buf, - } - if req.WrapInfo != nil && req.WrapInfo.SealWrap { - entry.SealWrap = true - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) - } - - return nil, nil -} - -func (b *CubbyholeBackend) handleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - path := data.Get("path").(string) - - // Delete the key at the request path - if err := req.Storage.Delete(ctx, req.ClientToken+"/"+path); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *CubbyholeBackend) handleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - // Right now we only handle directories, so ensure it ends with / We also - // check if it's empty so we don't end up doing a listing on '//' - path := data.Get("path").(string) - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // List the keys at the prefix given by the request - keys, err := req.Storage.List(ctx, req.ClientToken+"/"+path) - if err != nil { - return nil, err - } - - // Strip the token - strippedKeys := make([]string, len(keys)) - for i, key := range keys { - strippedKeys[i] = strings.TrimPrefix(key, req.ClientToken+"/") - } - - // Generate the response - return logical.ListResponse(strippedKeys), nil -} - -const cubbyholeHelp = ` -The cubbyhole backend reads and writes arbitrary secrets to the backend. -The secrets are encrypted/decrypted by Vault: they are never stored -unencrypted in the backend and the backend never has an opportunity to -see the unencrypted value. - -This backend differs from the 'kv' backend in that it is namespaced -per-token. Tokens can only read and write their own values, with no -sharing possible (per-token cubbyholes). This can be useful for implementing -certain authentication workflows, as well as "scratch" areas for individual -clients. When the token is revoked, the entire set of stored values for that -token is also removed. -` - -const cubbyholeHelpSynopsis = ` -Pass-through secret storage to a token-specific cubbyhole in the storage -backend, allowing you to read/write arbitrary data into secret storage. -` - -const cubbyholeHelpDescription = ` -The cubbyhole backend reads and writes arbitrary data into secret storage, -encrypting it along the way. - -The view into the cubbyhole storage space is different for each token; it is -a per-token cubbyhole. When the token is revoked all values are removed. -` diff --git a/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go b/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go deleted file mode 100644 index 6c10cc7b..00000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go +++ /dev/null @@ -1,252 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// PassthroughBackendFactory returns a PassthroughBackend -// with leases switched off -func PassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, false) -} - -// LeasedPassthroughBackendFactory returns a PassthroughBackend -// with leases switched on -func LeasedPassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, true) -} - -// LeaseSwitchedPassthroughBackend returns a PassthroughBackend -// with leases switched on or off -func LeaseSwitchedPassthroughBackend(ctx context.Context, conf *logical.BackendConfig, leases bool) (logical.Backend, error) { - var b PassthroughBackend - b.generateLeases = leases - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(passthroughHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "*", - }, - }, - - Paths: []*framework.Path{ - { - Pattern: ".*", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRead, - logical.CreateOperation: b.handleWrite, - logical.UpdateOperation: b.handleWrite, - logical.DeleteOperation: b.handleDelete, - logical.ListOperation: b.handleList, - }, - - ExistenceCheck: b.handleExistenceCheck, - - HelpSynopsis: strings.TrimSpace(passthroughHelpSynopsis), - HelpDescription: strings.TrimSpace(passthroughHelpDescription), - }, - }, - BackendType: logical.TypeLogical, - } - - b.Backend.Secrets = []*framework.Secret{ - &framework.Secret{ - Type: "kv", - - Renew: b.handleRead, - Revoke: b.handleRevoke, - }, - } - - if conf == nil { - return nil, fmt.Errorf("configuration passed into backend is nil") - } - b.Backend.Setup(ctx, conf) - - return &b, nil -} - -// PassthroughBackend is used storing secrets directly into the physical -// backend. The secrets are encrypted in the durable storage and custom TTL -// information can be specified, but otherwise this backend doesn't do anything -// fancy. -type PassthroughBackend struct { - *framework.Backend - generateLeases bool -} - -func (b *PassthroughBackend) handleRevoke(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // This is a no-op - return nil, nil -} - -func (b *PassthroughBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) - } - - return out != nil, nil -} - -func (b *PassthroughBackend) handleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Read the path - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) - } - - // Fast-path the no data case - if out == nil { - return nil, nil - } - - // Decode the data - var rawData map[string]interface{} - - if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) - } - - var resp *logical.Response - if b.generateLeases { - // Generate the response - resp = b.Secret("kv").Response(rawData, nil) - resp.Secret.Renewable = false - } else { - resp = &logical.Response{ - Secret: &logical.Secret{}, - Data: rawData, - } - } - - // Ensure seal wrapping is carried through if the response is - // response-wrapped - if out.SealWrap { - if resp.WrapInfo == nil { - resp.WrapInfo = &wrapping.ResponseWrapInfo{} - } - resp.WrapInfo.SealWrap = out.SealWrap - } - - // Check if there is a ttl key - ttlDuration := b.System().DefaultLeaseTTL() - ttlRaw, ok := rawData["ttl"] - if !ok { - ttlRaw, ok = rawData["lease"] - } - if ok { - dur, err := parseutil.ParseDurationSecond(ttlRaw) - if err == nil { - ttlDuration = dur - } - - if b.generateLeases { - resp.Secret.Renewable = true - } - } - - resp.Secret.TTL = ttlDuration - - return resp, nil -} - -func (b *PassthroughBackend) GeneratesLeases() bool { - return b.generateLeases -} - -func (b *PassthroughBackend) handleWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.Path == "" { - return logical.ErrorResponse("missing path"), nil - } - - // Check that some fields are given - if len(req.Data) == 0 { - return logical.ErrorResponse("missing data fields"), nil - } - - // JSON encode the data - buf, err := json.Marshal(req.Data) - if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) - } - - // Write out a new key - entry := &logical.StorageEntry{ - Key: req.Path, - Value: buf, - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) - } - - return nil, nil -} - -func (b *PassthroughBackend) handleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Delete the key at the request path - if err := req.Storage.Delete(ctx, req.Path); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *PassthroughBackend) handleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Right now we only handle directories, so ensure it ends with /; however, - // some physical backends may not handle the "/" case properly, so only add - // it if we're not listing the root - path := req.Path - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // List the keys at the prefix given by the request - keys, err := req.Storage.List(ctx, path) - if err != nil { - return nil, err - } - - // Generate the response - return logical.ListResponse(keys), nil -} - -const passthroughHelp = ` -The kv backend reads and writes arbitrary secrets to the backend. -The secrets are encrypted/decrypted by Vault: they are never stored -unencrypted in the backend and the backend never has an opportunity to -see the unencrypted value. - -TTLs can be set on a per-secret basis. These TTLs will be sent down -when that secret is read, and it is assumed that some outside process will -revoke and/or replace the secret at that path. -` - -const passthroughHelpSynopsis = ` -Pass-through secret storage to the storage backend, allowing you to -read/write arbitrary data into secret storage. -` - -const passthroughHelpDescription = ` -The pass-through backend reads and writes arbitrary data into secret storage, -encrypting it along the way. - -A TTL can be specified when writing with the "ttl" field. If given, the -duration of leases returned by this backend will be set to this value. This -can be used as a hint from the writer of a secret to the consumer of a secret -that the consumer should re-read the value before the TTL has expired. -However, any revocation must be handled by the user of this backend; the lease -duration does not affect the provided data in any way. -` diff --git a/vendor/github.com/hashicorp/vault/vault/logical_system.go b/vendor/github.com/hashicorp/vault/vault/logical_system.go deleted file mode 100644 index 20942bb8..00000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_system.go +++ /dev/null @@ -1,3845 +0,0 @@ -package vault - -import ( - "context" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "net/http" - "path/filepath" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-memdb" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -var ( - // protectedPaths cannot be accessed via the raw APIs. - // This is both for security and to prevent disrupting Vault. - protectedPaths = []string{ - keyringPath, - // Changing the cluster info path can change the cluster ID which can be disruptive - coreLocalClusterInfoPath, - } -) - -func systemBackendMemDBSchema() *memdb.DBSchema { - systemSchema := &memdb.DBSchema{ - Tables: make(map[string]*memdb.TableSchema), - } - - schemas := getSystemSchemas() - - for _, schemaFunc := range schemas { - schema := schemaFunc() - if _, ok := systemSchema.Tables[schema.Name]; ok { - panic(fmt.Sprintf("duplicate table name: %s", schema.Name)) - } - systemSchema.Tables[schema.Name] = schema - } - - return systemSchema -} - -func NewSystemBackend(core *Core, logger log.Logger) *SystemBackend { - db, _ := memdb.NewMemDB(systemBackendMemDBSchema()) - - b := &SystemBackend{ - Core: core, - db: db, - logger: logger, - mfaLogger: core.baseLogger.Named("mfa"), - mfaLock: &sync.RWMutex{}, - } - - core.AddLogger(b.mfaLogger) - - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(sysHelpRoot), - - PathsSpecial: &logical.Paths{ - Root: []string{ - "auth/*", - "remount", - "audit", - "audit/*", - "raw", - "raw/*", - "replication/primary/secondary-token", - "replication/performance/primary/secondary-token", - "replication/dr/primary/secondary-token", - "replication/reindex", - "replication/dr/reindex", - "replication/performance/reindex", - "rotate", - "config/cors", - "config/auditing/*", - "config/ui/headers/*", - "plugins/catalog/*", - "revoke-prefix/*", - "revoke-force/*", - "leases/revoke-prefix/*", - "leases/revoke-force/*", - "leases/lookup/*", - }, - - Unauthenticated: []string{ - "wrapping/lookup", - "wrapping/pubkey", - "replication/status", - "internal/specs/openapi", - "internal/ui/mounts", - "internal/ui/mounts/*", - "internal/ui/namespaces", - "replication/performance/status", - "replication/dr/status", - "replication/dr/secondary/promote", - "replication/dr/secondary/update-primary", - "replication/dr/secondary/operation-token/delete", - "replication/dr/secondary/license", - "replication/dr/secondary/reindex", - }, - - LocalStorage: []string{ - expirationSubPath, - }, - }, - } - - b.Backend.Paths = append(b.Backend.Paths, entPaths(b)...) - b.Backend.Paths = append(b.Backend.Paths, b.configPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.rekeyPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.sealPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.pluginsCatalogListPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.pluginsCatalogCRUDPath()) - b.Backend.Paths = append(b.Backend.Paths, b.pluginsReloadPath()) - b.Backend.Paths = append(b.Backend.Paths, b.auditPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.mountPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.authPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.leasePaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.policyPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.wrappingPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.toolsPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.capabilitiesPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.internalPaths()...) - b.Backend.Paths = append(b.Backend.Paths, b.remountPath()) - - if core.rawEnabled { - b.Backend.Paths = append(b.Backend.Paths, &framework.Path{ - Pattern: "(raw/?$|raw/(?P.+))", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - }, - "value": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleRawRead, - Summary: "Read the value of the key at the given path.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleRawWrite, - Summary: "Update the value of the key at the given path.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleRawDelete, - Summary: "Delete the key with given path.", - }, - logical.ListOperation: &framework.PathOperation{ - Callback: b.handleRawList, - Summary: "Return a list keys for a given path prefix.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["raw"][0]), - HelpDescription: strings.TrimSpace(sysHelp["raw"][1]), - }) - } - - b.Backend.Invalidate = sysInvalidate(b) - return b -} - -// SystemBackend implements logical.Backend and is used to interact with -// the core of the system. This backend is hardcoded to exist at the "sys" -// prefix. Conceptually it is similar to procfs on Linux. -type SystemBackend struct { - *framework.Backend - Core *Core - db *memdb.MemDB - mfaLock *sync.RWMutex - mfaLogger log.Logger - logger log.Logger -} - -// handleCORSRead returns the current CORS configuration -func (b *SystemBackend) handleCORSRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - corsConf := b.Core.corsConfig - - enabled := corsConf.IsEnabled() - - resp := &logical.Response{ - Data: map[string]interface{}{ - "enabled": enabled, - }, - } - - if enabled { - corsConf.RLock() - resp.Data["allowed_origins"] = corsConf.AllowedOrigins - resp.Data["allowed_headers"] = corsConf.AllowedHeaders - corsConf.RUnlock() - } - - return resp, nil -} - -// handleCORSUpdate sets the list of origins that are allowed to make -// cross-origin requests and sets the CORS enabled flag to true -func (b *SystemBackend) handleCORSUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - origins := d.Get("allowed_origins").([]string) - headers := d.Get("allowed_headers").([]string) - - return nil, b.Core.corsConfig.Enable(ctx, origins, headers) -} - -// handleCORSDelete sets the CORS enabled flag to false and clears the list of -// allowed origins & headers. -func (b *SystemBackend) handleCORSDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return nil, b.Core.corsConfig.Disable(ctx) -} - -func (b *SystemBackend) handleTidyLeases(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - go func() { - tidyCtx := namespace.ContextWithNamespace(b.Core.activeContext, ns) - err := b.Core.expiration.Tidy(tidyCtx) - if err != nil { - b.Backend.Logger().Error("failed to tidy leases", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -func (b *SystemBackend) handlePluginCatalogTypedList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginType, err := consts.ParsePluginType(d.Get("type").(string)) - if err != nil { - return nil, err - } - - plugins, err := b.Core.pluginCatalog.List(ctx, pluginType) - if err != nil { - return nil, err - } - return logical.ListResponse(plugins), nil -} - -func (b *SystemBackend) handlePluginCatalogUntypedList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginsByType := make(map[string]interface{}) - for _, pluginType := range consts.PluginTypes { - plugins, err := b.Core.pluginCatalog.List(ctx, pluginType) - if err != nil { - return nil, err - } - if len(plugins) > 0 { - sort.Strings(plugins) - pluginsByType[pluginType.String()] = plugins - } - } - return &logical.Response{ - Data: pluginsByType, - }, nil -} - -func (b *SystemBackend) handlePluginCatalogUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - - pluginTypeStr := d.Get("type").(string) - if pluginTypeStr == "" { - // If the plugin type is not provided, list it as unknown so that we - // add it to the catalog and UpdatePlugins later will sort it. - pluginTypeStr = "unknown" - } - pluginType, err := consts.ParsePluginType(pluginTypeStr) - if err != nil { - return nil, err - } - - sha256 := d.Get("sha256").(string) - if sha256 == "" { - sha256 = d.Get("sha_256").(string) - if sha256 == "" { - return logical.ErrorResponse("missing SHA-256 value"), nil - } - } - - command := d.Get("command").(string) - if command == "" { - return logical.ErrorResponse("missing command value"), nil - } - - // For backwards compatibility, also accept args as part of command. Don't - // accepts args in both command and args. - args := d.Get("args").([]string) - parts := strings.Split(command, " ") - if len(parts) <= 0 { - return logical.ErrorResponse("missing command value"), nil - } else if len(parts) > 1 && len(args) > 0 { - return logical.ErrorResponse("must not specify args in command and args field"), nil - } else if len(parts) > 1 { - args = parts[1:] - } - - env := d.Get("env").([]string) - - sha256Bytes, err := hex.DecodeString(sha256) - if err != nil { - return logical.ErrorResponse("Could not decode SHA-256 value from Hex"), err - } - - err = b.Core.pluginCatalog.Set(ctx, pluginName, pluginType, parts[0], args, env, sha256Bytes) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *SystemBackend) handlePluginCatalogRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - - pluginTypeStr := d.Get("type").(string) - if pluginTypeStr == "" { - // If the plugin type is not provided (i.e. the old - // sys/plugins/catalog/:name endpoint is being requested) short-circuit here - // and return a warning - resp := &logical.Response{} - resp.AddWarning(fmt.Sprintf("Deprecated API endpoint, cannot read plugin information from catalog for %q", pluginName)) - return resp, nil - } - - pluginType, err := consts.ParsePluginType(pluginTypeStr) - if err != nil { - return nil, err - } - - plugin, err := b.Core.pluginCatalog.Get(ctx, pluginName, pluginType) - if err != nil { - return nil, err - } - if plugin == nil { - return nil, nil - } - - command := "" - if !plugin.Builtin { - command, err = filepath.Rel(b.Core.pluginCatalog.directory, plugin.Command) - if err != nil { - return nil, err - } - } - - data := map[string]interface{}{ - "name": plugin.Name, - "args": plugin.Args, - "command": command, - "sha256": hex.EncodeToString(plugin.Sha256), - "builtin": plugin.Builtin, - } - - return &logical.Response{ - Data: data, - }, nil -} - -func (b *SystemBackend) handlePluginCatalogDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - - var resp *logical.Response - pluginTypeStr := d.Get("type").(string) - if pluginTypeStr == "" { - // If the plugin type is not provided (i.e. the old - // sys/plugins/catalog/:name endpoint is being requested), set type to - // unknown and let pluginCatalog.Delete proceed. It should handle - // deregistering out of the old storage path (root of core/plugin-catalog) - resp = new(logical.Response) - resp.AddWarning(fmt.Sprintf("Deprecated API endpoint, cannot deregister plugin from catalog for %q", pluginName)) - pluginTypeStr = "unknown" - } - - pluginType, err := consts.ParsePluginType(pluginTypeStr) - if err != nil { - return nil, err - } - if err := b.Core.pluginCatalog.Delete(ctx, pluginName, pluginType); err != nil { - return nil, err - } - - return resp, nil -} - -func (b *SystemBackend) handlePluginReloadUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("plugin").(string) - pluginMounts := d.Get("mounts").([]string) - - if pluginName != "" && len(pluginMounts) > 0 { - return logical.ErrorResponse("plugin and mounts cannot be set at the same time"), nil - } - if pluginName == "" && len(pluginMounts) == 0 { - return logical.ErrorResponse("plugin or mounts must be provided"), nil - } - - if pluginName != "" { - err := b.Core.reloadMatchingPlugin(ctx, pluginName) - if err != nil { - return nil, err - } - } else if len(pluginMounts) > 0 { - err := b.Core.reloadMatchingPluginMounts(ctx, pluginMounts) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -// handleAuditedHeaderUpdate creates or overwrites a header entry -func (b *SystemBackend) handleAuditedHeaderUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - hmac := d.Get("hmac").(bool) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - err := headerConfig.add(ctx, header, hmac) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleAuditedHeaderDelete deletes the header with the given name -func (b *SystemBackend) handleAuditedHeaderDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - err := headerConfig.remove(ctx, header) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleAuditedHeaderRead returns the header configuration for the given header name -func (b *SystemBackend) handleAuditedHeaderRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - settings, ok := headerConfig.Headers[strings.ToLower(header)] - if !ok { - return logical.ErrorResponse("Could not find header in config"), nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - header: settings, - }, - }, nil -} - -// handleAuditedHeadersRead returns the whole audited headers config -func (b *SystemBackend) handleAuditedHeadersRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - headerConfig := b.Core.AuditedHeadersConfig() - - return &logical.Response{ - Data: map[string]interface{}{ - "headers": headerConfig.Headers, - }, - }, nil -} - -// handleCapabilitiesAccessor returns the ACL capabilities of the -// token associated with the given accessor for a given path. -func (b *SystemBackend) handleCapabilitiesAccessor(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - accessor := d.Get("accessor").(string) - if accessor == "" { - return logical.ErrorResponse("missing accessor"), nil - } - - aEntry, err := b.Core.tokenStore.lookupByAccessor(ctx, accessor, false, false) - if err != nil { - return nil, err - } - - d.Raw["token"] = aEntry.TokenID - return b.handleCapabilities(ctx, req, d) -} - -// handleCapabilities returns the ACL capabilities of the token for a given path -func (b *SystemBackend) handleCapabilities(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var token string - if strings.HasSuffix(req.Path, "capabilities-self") { - token = req.ClientToken - } else { - tokenRaw, ok := d.Raw["token"] - if ok { - token, _ = tokenRaw.(string) - } - } - if token == "" { - return nil, fmt.Errorf("no token found") - } - - ret := &logical.Response{ - Data: map[string]interface{}{}, - } - - paths := d.Get("paths").([]string) - if len(paths) == 0 { - // Read from the deprecated field - paths = d.Get("path").([]string) - } - - if len(paths) == 0 { - return logical.ErrorResponse("paths must be supplied"), nil - } - - for _, path := range paths { - pathCap, err := b.Core.Capabilities(ctx, token, path) - if err != nil { - if !strings.HasSuffix(req.Path, "capabilities-self") && errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - return nil, &logical.StatusBadRequest{Err: "invalid token"} - } - return nil, err - } - ret.Data[path] = pathCap - } - - // This is only here for backwards compatibility - if len(paths) == 1 { - ret.Data["capabilities"] = ret.Data[paths[0]] - } - - return ret, nil -} - -// handleRekeyRetrieve returns backed-up, PGP-encrypted unseal keys from a -// rekey operation -func (b *SystemBackend) handleRekeyRetrieve( - ctx context.Context, - req *logical.Request, - data *framework.FieldData, - recovery bool) (*logical.Response, error) { - backup, err := b.Core.RekeyRetrieveBackup(ctx, recovery) - if err != nil { - return nil, errwrap.Wrapf("unable to look up backed-up keys: {{err}}", err) - } - if backup == nil { - return logical.ErrorResponse("no backed-up keys found"), nil - } - - keysB64 := map[string][]string{} - for k, v := range backup.Keys { - for _, j := range v { - currB64Keys := keysB64[k] - if currB64Keys == nil { - currB64Keys = []string{} - } - key, err := hex.DecodeString(j) - if err != nil { - return nil, errwrap.Wrapf("error decoding hex-encoded backup key: {{err}}", err) - } - currB64Keys = append(currB64Keys, base64.StdEncoding.EncodeToString(key)) - keysB64[k] = currB64Keys - } - } - - // Format the status - resp := &logical.Response{ - Data: map[string]interface{}{ - "nonce": backup.Nonce, - "keys": backup.Keys, - "keys_base64": keysB64, - }, - } - - return resp, nil -} - -func (b *SystemBackend) handleRekeyRetrieveBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyRetrieve(ctx, req, data, false) -} - -func (b *SystemBackend) handleRekeyRetrieveRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyRetrieve(ctx, req, data, true) -} - -// handleRekeyDelete deletes backed-up, PGP-encrypted unseal keys from a rekey -// operation -func (b *SystemBackend) handleRekeyDelete( - ctx context.Context, - req *logical.Request, - data *framework.FieldData, - recovery bool) (*logical.Response, error) { - err := b.Core.RekeyDeleteBackup(ctx, recovery) - if err != nil { - return nil, errwrap.Wrapf("error during deletion of backed-up keys: {{err}}", err) - } - - return nil, nil -} - -func (b *SystemBackend) handleRekeyDeleteBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyDelete(ctx, req, data, false) -} - -func (b *SystemBackend) handleRekeyDeleteRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyDelete(ctx, req, data, true) -} - -func mountInfo(entry *MountEntry) map[string]interface{} { - info := map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "accessor": entry.Accessor, - "local": entry.Local, - "seal_wrap": entry.SealWrap, - "options": entry.Options, - } - entryConfig := map[string]interface{}{ - "default_lease_ttl": int64(entry.Config.DefaultLeaseTTL.Seconds()), - "max_lease_ttl": int64(entry.Config.MaxLeaseTTL.Seconds()), - "force_no_cache": entry.Config.ForceNoCache, - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - entryConfig["audit_non_hmac_request_keys"] = rawVal.([]string) - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - entryConfig["audit_non_hmac_response_keys"] = rawVal.([]string) - } - // Even though empty value is valid for ListingVisibility, we can ignore - // this case during mount since there's nothing to unset/hide. - if len(entry.Config.ListingVisibility) > 0 { - entryConfig["listing_visibility"] = entry.Config.ListingVisibility - } - if rawVal, ok := entry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - entryConfig["passthrough_request_headers"] = rawVal.([]string) - } - if entry.Table == credentialTableType { - entryConfig["token_type"] = entry.Config.TokenType.String() - } - - info["config"] = entryConfig - - return info -} - -// handleMountTable handles the "mounts" endpoint to provide the mount table -func (b *SystemBackend) handleMountTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - b.Core.mountsLock.RLock() - defer b.Core.mountsLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - - for _, entry := range b.Core.mounts.Entries { - // Only show entries for current namespace - if entry.Namespace().Path != ns.Path { - continue - } - - cont, err := b.Core.checkReplicatedFiltering(ctx, entry, "") - if err != nil { - return nil, err - } - if cont { - continue - } - - // Populate mount info - info := mountInfo(entry) - resp.Data[entry.Path] = info - } - - return resp, nil -} - -// handleMount is used to mount a new path -func (b *SystemBackend) handleMount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - logicalType := data.Get("type").(string) - description := data.Get("description").(string) - pluginName := data.Get("plugin_name").(string) - sealWrap := data.Get("seal_wrap").(bool) - options := data.Get("options").(map[string]string) - - var config MountConfig - var apiConfig APIMountConfig - - configMap := data.Get("config").(map[string]interface{}) - if configMap != nil && len(configMap) != 0 { - err := mapstructure.Decode(configMap, &apiConfig) - if err != nil { - return logical.ErrorResponse( - "unable to convert given mount config information"), - logical.ErrInvalidRequest - } - } - - switch apiConfig.DefaultLeaseTTL { - case "": - case "system": - default: - tmpDef, err := parseutil.ParseDurationSecond(apiConfig.DefaultLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse default TTL of %s: %s", apiConfig.DefaultLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.DefaultLeaseTTL = tmpDef - } - - switch apiConfig.MaxLeaseTTL { - case "": - case "system": - default: - tmpMax, err := parseutil.ParseDurationSecond(apiConfig.MaxLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse max TTL of %s: %s", apiConfig.MaxLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.MaxLeaseTTL = tmpMax - } - - if config.MaxLeaseTTL != 0 && config.DefaultLeaseTTL > config.MaxLeaseTTL { - return logical.ErrorResponse( - "given default lease TTL greater than given max lease TTL"), - logical.ErrInvalidRequest - } - - if config.DefaultLeaseTTL > b.Core.maxLeaseTTL && config.MaxLeaseTTL == 0 { - return logical.ErrorResponse(fmt.Sprintf( - "given default lease TTL greater than system max lease TTL of %d", int(b.Core.maxLeaseTTL.Seconds()))), - logical.ErrInvalidRequest - } - - switch logicalType { - case "": - return logical.ErrorResponse( - "backend type must be specified as a string"), - logical.ErrInvalidRequest - case "plugin": - // Only set plugin-name if mount is of type plugin, with apiConfig.PluginName - // option taking precedence. - switch { - case apiConfig.PluginName != "": - logicalType = apiConfig.PluginName - case pluginName != "": - logicalType = pluginName - default: - return logical.ErrorResponse( - "plugin_name must be provided for plugin backend"), - logical.ErrInvalidRequest - } - } - - switch logicalType { - case "kv": - case "kv-v1": - // Alias KV v1 - logicalType = "kv" - if options == nil { - options = map[string]string{} - } - options["version"] = "1" - - case "kv-v2": - // Alias KV v2 - logicalType = "kv" - if options == nil { - options = map[string]string{} - } - options["version"] = "2" - - default: - if options != nil && options["version"] != "" { - return logical.ErrorResponse(fmt.Sprintf( - "secrets engine %q does not allow setting a version", logicalType)), - logical.ErrInvalidRequest - } - } - - // Copy over the force no cache if set - if apiConfig.ForceNoCache { - config.ForceNoCache = true - } - - if err := checkListingVisibility(apiConfig.ListingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", apiConfig.ListingVisibility)), nil - } - config.ListingVisibility = apiConfig.ListingVisibility - - if len(apiConfig.AuditNonHMACRequestKeys) > 0 { - config.AuditNonHMACRequestKeys = apiConfig.AuditNonHMACRequestKeys - } - if len(apiConfig.AuditNonHMACResponseKeys) > 0 { - config.AuditNonHMACResponseKeys = apiConfig.AuditNonHMACResponseKeys - } - if len(apiConfig.PassthroughRequestHeaders) > 0 { - config.PassthroughRequestHeaders = apiConfig.PassthroughRequestHeaders - } - - // Create the mount entry - me := &MountEntry{ - Table: mountTableType, - Path: path, - Type: logicalType, - Description: description, - Config: config, - Local: local, - SealWrap: sealWrap, - Options: options, - } - - // Attempt mount - if err := b.Core.mount(ctx, me); err != nil { - b.Backend.Logger().Error("mount failed", "path", me.Path, "error", err) - return handleError(err) - } - - return nil, nil -} - -// used to intercept an HTTPCodedError so it goes back to callee -func handleError( - err error) (*logical.Response, error) { - if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return logical.ErrorResponse(err.Error()), err - } - switch err.(type) { - case logical.HTTPCodedError: - return logical.ErrorResponse(err.Error()), err - default: - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } -} - -// Performs a similar function to handleError, but upon seeing a ReadOnlyError -// will actually strip it out to prevent forwarding -func handleErrorNoReadOnlyForward( - err error) (*logical.Response, error) { - if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return nil, fmt.Errorf("operation could not be completed as storage is read-only") - } - switch err.(type) { - case logical.HTTPCodedError: - return logical.ErrorResponse(err.Error()), err - default: - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } -} - -// handleUnmount is used to unmount a path -func (b *SystemBackend) handleUnmount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - repState := b.Core.ReplicationState() - entry := b.Core.router.MatchingMountEntry(ctx, path) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot unmount a non-local mount on a replication secondary"), nil - } - - // We return success when the mount does not exists to not expose if the - // mount existed or not - match := b.Core.router.MatchingMount(ctx, path) - if match == "" || ns.Path+path != match { - return nil, nil - } - - prefix, found := b.Core.router.MatchingStoragePrefixByAPIPath(ctx, path) - if !found { - b.Backend.Logger().Error("unable to find storage for path", "path", path) - return handleError(fmt.Errorf("unable to find storage for path: %q", path)) - } - - // Attempt unmount - if err := b.Core.unmount(ctx, path); err != nil { - b.Backend.Logger().Error("unmount failed", "path", path, "error", err) - return handleError(err) - } - - // Remove from filtered mounts - if err := b.Core.removePrefixFromFilteredPaths(ctx, prefix); err != nil { - b.Backend.Logger().Error("filtered path removal failed", path, "error", err) - return handleError(err) - } - - return nil, nil -} - -// handleRemount is used to remount a path -func (b *SystemBackend) handleRemount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - // Get the paths - fromPath := data.Get("from").(string) - toPath := data.Get("to").(string) - if fromPath == "" || toPath == "" { - return logical.ErrorResponse( - "both 'from' and 'to' path must be specified as a string"), - logical.ErrInvalidRequest - } - - entry := b.Core.router.MatchingMountEntry(ctx, fromPath) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot remount a non-local mount on a replication secondary"), nil - } - - // Attempt remount - if err := b.Core.remount(ctx, fromPath, toPath); err != nil { - b.Backend.Logger().Error("remount failed", "from_path", fromPath, "to_path", toPath, "error", err) - return handleError(err) - } - - return nil, nil -} - -// handleAuthTuneRead is used to get config settings on a auth path -func (b *SystemBackend) handleAuthTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse( - "path must be specified as a string"), - logical.ErrInvalidRequest - } - return b.handleTuneReadCommon(ctx, "auth/"+path) -} - -// handleMountTuneRead is used to get config settings on a backend -func (b *SystemBackend) handleMountTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse( - "path must be specified as a string"), - logical.ErrInvalidRequest - } - - // This call will read both logical backend's configuration as well as auth methods'. - // Retaining this behavior for backward compatibility. If this behavior is not desired, - // an error can be returned if path has a prefix of "auth/". - return b.handleTuneReadCommon(ctx, path) -} - -// handleTuneReadCommon returns the config settings of a path -func (b *SystemBackend) handleTuneReadCommon(ctx context.Context, path string) (*logical.Response, error) { - path = sanitizeMountPath(path) - - sysView := b.Core.router.MatchingSystemView(ctx, path) - if sysView == nil { - b.Backend.Logger().Error("cannot fetch sysview", "path", path) - return handleError(fmt.Errorf("cannot fetch sysview for path %q", path)) - } - - mountEntry := b.Core.router.MatchingMountEntry(ctx, path) - if mountEntry == nil { - b.Backend.Logger().Error("cannot fetch mount entry", "path", path) - return handleError(fmt.Errorf("cannot fetch mount entry for path %q", path)) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "default_lease_ttl": int(sysView.DefaultLeaseTTL().Seconds()), - "max_lease_ttl": int(sysView.MaxLeaseTTL().Seconds()), - "force_no_cache": mountEntry.Config.ForceNoCache, - }, - } - - if mountEntry.Table == credentialTableType { - resp.Data["token_type"] = mountEntry.Config.TokenType.String() - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - resp.Data["audit_non_hmac_request_keys"] = rawVal.([]string) - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - resp.Data["audit_non_hmac_response_keys"] = rawVal.([]string) - } - - if len(mountEntry.Config.ListingVisibility) > 0 { - resp.Data["listing_visibility"] = mountEntry.Config.ListingVisibility - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - resp.Data["passthrough_request_headers"] = rawVal.([]string) - } - - if len(mountEntry.Options) > 0 { - resp.Data["options"] = mountEntry.Options - } - - return resp, nil -} - -// handleAuthTuneWrite is used to set config settings on an auth path -func (b *SystemBackend) handleAuthTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse("missing path"), nil - } - - return b.handleTuneWriteCommon(ctx, "auth/"+path, data) -} - -// handleMountTuneWrite is used to set config settings on a backend -func (b *SystemBackend) handleMountTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse("missing path"), nil - } - - // This call will write both logical backend's configuration as well as auth methods'. - // Retaining this behavior for backward compatibility. If this behavior is not desired, - // an error can be returned if path has a prefix of "auth/". - return b.handleTuneWriteCommon(ctx, path, data) -} - -// handleTuneWriteCommon is used to set config settings on a path -func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - path = sanitizeMountPath(path) - - // Prevent protected paths from being changed - for _, p := range untunableMounts { - if strings.HasPrefix(path, p) { - b.Backend.Logger().Error("cannot tune this mount", "path", path) - return handleError(fmt.Errorf("cannot tune %q", path)) - } - } - - mountEntry := b.Core.router.MatchingMountEntry(ctx, path) - if mountEntry == nil { - b.Backend.Logger().Error("tune failed", "error", "no mount entry found", "path", path) - return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) - } - if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil - } - - var lock *sync.RWMutex - switch { - case strings.HasPrefix(path, credentialRoutePrefix): - lock = &b.Core.authLock - default: - lock = &b.Core.mountsLock - } - - lock.Lock() - defer lock.Unlock() - - // Check again after grabbing the lock - mountEntry = b.Core.router.MatchingMountEntry(ctx, path) - if mountEntry == nil { - b.Backend.Logger().Error("tune failed", "error", "no mount entry found", "path", path) - return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) - } - if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil - } - - // Timing configuration parameters - { - var newDefault, newMax time.Duration - defTTL := data.Get("default_lease_ttl").(string) - switch defTTL { - case "": - newDefault = mountEntry.Config.DefaultLeaseTTL - case "system": - newDefault = time.Duration(0) - default: - tmpDef, err := parseutil.ParseDurationSecond(defTTL) - if err != nil { - return handleError(err) - } - newDefault = tmpDef - } - - maxTTL := data.Get("max_lease_ttl").(string) - switch maxTTL { - case "": - newMax = mountEntry.Config.MaxLeaseTTL - case "system": - newMax = time.Duration(0) - default: - tmpMax, err := parseutil.ParseDurationSecond(maxTTL) - if err != nil { - return handleError(err) - } - newMax = tmpMax - } - - if newDefault != mountEntry.Config.DefaultLeaseTTL || - newMax != mountEntry.Config.MaxLeaseTTL { - - if err := b.tuneMountTTLs(ctx, path, mountEntry, newDefault, newMax); err != nil { - b.Backend.Logger().Error("tuning failed", "path", path, "error", err) - return handleError(err) - } - } - } - - if rawVal, ok := data.GetOk("description"); ok { - description := rawVal.(string) - - oldDesc := mountEntry.Description - mountEntry.Description = description - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Description = oldDesc - return handleError(err) - } - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of description successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("audit_non_hmac_request_keys"); ok { - auditNonHMACRequestKeys := rawVal.([]string) - - oldVal := mountEntry.Config.AuditNonHMACRequestKeys - mountEntry.Config.AuditNonHMACRequestKeys = auditNonHMACRequestKeys - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.AuditNonHMACRequestKeys = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of audit_non_hmac_request_keys successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("audit_non_hmac_response_keys"); ok { - auditNonHMACResponseKeys := rawVal.([]string) - - oldVal := mountEntry.Config.AuditNonHMACResponseKeys - mountEntry.Config.AuditNonHMACResponseKeys = auditNonHMACResponseKeys - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.AuditNonHMACResponseKeys = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of audit_non_hmac_response_keys successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("listing_visibility"); ok { - lvString := rawVal.(string) - listingVisibility := ListingVisibilityType(lvString) - - if err := checkListingVisibility(listingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", listingVisibility)), nil - } - - oldVal := mountEntry.Config.ListingVisibility - mountEntry.Config.ListingVisibility = listingVisibility - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.ListingVisibility = oldVal - return handleError(err) - } - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of listing_visibility successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("token_type"); ok { - if !strings.HasPrefix(path, "auth/") { - return logical.ErrorResponse(fmt.Sprintf("'token_type' can only be modified on auth mounts")), logical.ErrInvalidRequest - } - if mountEntry.Type == "token" || mountEntry.Type == "ns_token" { - return logical.ErrorResponse(fmt.Sprintf("'token_type' cannot be set for 'token' or 'ns_token' auth mounts")), logical.ErrInvalidRequest - } - - tokenType := logical.TokenTypeDefaultService - ttString := rawVal.(string) - - switch ttString { - case "", "default-service": - case "default-batch": - tokenType = logical.TokenTypeDefaultBatch - case "service": - tokenType = logical.TokenTypeService - case "batch": - tokenType = logical.TokenTypeBatch - default: - return logical.ErrorResponse(fmt.Sprintf( - "invalid value for 'token_type'")), logical.ErrInvalidRequest - } - - oldVal := mountEntry.Config.TokenType - mountEntry.Config.TokenType = tokenType - - // Update the mount table - if err := b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local); err != nil { - mountEntry.Config.TokenType = oldVal - return handleError(err) - } - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of token_type successful", "path", path, "token_type", ttString) - } - } - - if rawVal, ok := data.GetOk("passthrough_request_headers"); ok { - headers := rawVal.([]string) - - oldVal := mountEntry.Config.PassthroughRequestHeaders - mountEntry.Config.PassthroughRequestHeaders = headers - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.PassthroughRequestHeaders = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of passthrough_request_headers successful", "path", path) - } - } - - var err error - var resp *logical.Response - var options map[string]string - if optionsRaw, ok := data.GetOk("options"); ok { - options = optionsRaw.(map[string]string) - } - - if len(options) > 0 { - b.Core.logger.Info("mount tuning of options", "path", path, "options", options) - newOptions := make(map[string]string) - var kvUpgraded bool - - // The version options should only apply to the KV mount, check that first - if v, ok := options["version"]; ok { - // Special case to make sure we can not disable versioning once it's - // enabled. If the vkv backend suports downgrading this can be removed. - meVersion, err := parseutil.ParseInt(mountEntry.Options["version"]) - if err != nil { - return nil, errwrap.Wrapf("unable to parse mount entry: {{err}}", err) - } - optVersion, err := parseutil.ParseInt(v) - if err != nil { - return handleError(errwrap.Wrapf("unable to parse options: {{err}}", err)) - } - - // Only accept valid versions - switch optVersion { - case 1: - case 2: - default: - return logical.ErrorResponse(fmt.Sprintf("invalid version provided: %d", optVersion)), logical.ErrInvalidRequest - } - - if meVersion > optVersion { - // Return early if version option asks for a downgrade - return logical.ErrorResponse(fmt.Sprintf("cannot downgrade mount from version %d", meVersion)), logical.ErrInvalidRequest - } - if meVersion < optVersion { - kvUpgraded = true - resp = &logical.Response{} - resp.AddWarning(fmt.Sprintf("Upgrading mount from version %d to version %d. This mount will be unavailable for a brief period and will resume service shortly.", meVersion, optVersion)) - } - } - - // Upsert options value to a copy of the existing mountEntry's options - for k, v := range mountEntry.Options { - newOptions[k] = v - } - for k, v := range options { - // If the value of the provided option is empty, delete the key We - // special-case the version value here to guard against KV downgrades, but - // this piece could potentially be refactored in the future to be non-KV - // specific. - if len(v) == 0 && k != "version" { - delete(newOptions, k) - } else { - newOptions[k] = v - } - } - - // Update the mount table - oldVal := mountEntry.Options - mountEntry.Options = newOptions - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Options = oldVal - return handleError(err) - } - - // Reload the backend to kick off the upgrade process. It should only apply to KV backend so we - // trigger based on the version logic above. - if kvUpgraded { - b.Core.reloadBackendCommon(ctx, mountEntry, strings.HasPrefix(path, credentialRoutePrefix)) - } - } - - return resp, nil -} - -// handleLease is use to view the metadata for a given LeaseID -func (b *SystemBackend) handleLeaseLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - - leaseTimes, err := b.Core.expiration.FetchLeaseTimes(ctx, leaseID) - if err != nil { - b.Backend.Logger().Error("error retrieving lease", "lease_id", leaseID, "error", err) - return handleError(err) - } - if leaseTimes == nil { - return logical.ErrorResponse("invalid lease"), logical.ErrInvalidRequest - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "id": leaseID, - "issue_time": leaseTimes.IssueTime, - "expire_time": nil, - "last_renewal": nil, - "ttl": int64(0), - }, - } - renewable, _ := leaseTimes.renewable() - resp.Data["renewable"] = renewable - - if !leaseTimes.LastRenewalTime.IsZero() { - resp.Data["last_renewal"] = leaseTimes.LastRenewalTime - } - if !leaseTimes.ExpireTime.IsZero() { - resp.Data["expire_time"] = leaseTimes.ExpireTime - resp.Data["ttl"] = leaseTimes.ttl() - } - return resp, nil -} - -func (b *SystemBackend) handleLeaseLookupList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - prefix := data.Get("prefix").(string) - if prefix != "" && !strings.HasSuffix(prefix, "/") { - prefix = prefix + "/" - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - view := b.Core.expiration.leaseView(ns) - keys, err := view.List(ctx, prefix) - if err != nil { - b.Backend.Logger().Error("error listing leases", "prefix", prefix, "error", err) - return handleErrorNoReadOnlyForward(err) - } - return logical.ListResponse(keys), nil -} - -// handleRenew is used to renew a lease with a given LeaseID -func (b *SystemBackend) handleRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get all the options - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - leaseID = data.Get("url_lease_id").(string) - } - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - incrementRaw := data.Get("increment").(int) - - // Convert the increment - increment := time.Duration(incrementRaw) * time.Second - - // Invoke the expiration manager directly - resp, err := b.Core.expiration.Renew(ctx, leaseID, increment) - if err != nil { - b.Backend.Logger().Error("lease renewal failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - return resp, err -} - -// handleRevoke is used to revoke a given LeaseID -func (b *SystemBackend) handleRevoke(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get all the options - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - leaseID = data.Get("url_lease_id").(string) - } - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - revokeCtx := namespace.ContextWithNamespace(b.Core.activeContext, ns) - if data.Get("sync").(bool) { - // Invoke the expiration manager directly - if err := b.Core.expiration.Revoke(revokeCtx, leaseID); err != nil { - b.Backend.Logger().Error("lease revocation failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - return nil, nil - } - - if err := b.Core.expiration.LazyRevoke(revokeCtx, leaseID); err != nil { - b.Backend.Logger().Error("lease revocation failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - return logical.RespondWithStatusCode(nil, nil, http.StatusAccepted) -} - -// handleRevokePrefix is used to revoke a prefix with many LeaseIDs -func (b *SystemBackend) handleRevokePrefix(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRevokePrefixCommon(ctx, req, data, false, data.Get("sync").(bool)) -} - -// handleRevokeForce is used to revoke a prefix with many LeaseIDs, ignoring errors -func (b *SystemBackend) handleRevokeForce(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRevokePrefixCommon(ctx, req, data, true, true) -} - -// handleRevokePrefixCommon is used to revoke a prefix with many LeaseIDs -func (b *SystemBackend) handleRevokePrefixCommon(ctx context.Context, - req *logical.Request, data *framework.FieldData, force, sync bool) (*logical.Response, error) { - // Get all the options - prefix := data.Get("prefix").(string) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - // Invoke the expiration manager directly - revokeCtx := namespace.ContextWithNamespace(b.Core.activeContext, ns) - if force { - err = b.Core.expiration.RevokeForce(revokeCtx, prefix) - } else { - err = b.Core.expiration.RevokePrefix(revokeCtx, prefix, sync) - } - if err != nil { - b.Backend.Logger().Error("revoke prefix failed", "prefix", prefix, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - if sync { - return nil, nil - } - - return logical.RespondWithStatusCode(nil, nil, http.StatusAccepted) -} - -// handleAuthTable handles the "auth" endpoint to provide the auth table -func (b *SystemBackend) handleAuthTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - b.Core.authLock.RLock() - defer b.Core.authLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - - for _, entry := range b.Core.auth.Entries { - // Only show entries for current namespace - if entry.Namespace().Path != ns.Path { - continue - } - - cont, err := b.Core.checkReplicatedFiltering(ctx, entry, credentialRoutePrefix) - if err != nil { - return nil, err - } - if cont { - continue - } - - info := mountInfo(entry) - resp.Data[entry.Path] = info - } - - return resp, nil -} - -// handleEnableAuth is used to enable a new credential backend -func (b *SystemBackend) handleEnableAuth(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - path = sanitizeMountPath(path) - logicalType := data.Get("type").(string) - description := data.Get("description").(string) - pluginName := data.Get("plugin_name").(string) - sealWrap := data.Get("seal_wrap").(bool) - options := data.Get("options").(map[string]string) - - var config MountConfig - var apiConfig APIMountConfig - - configMap := data.Get("config").(map[string]interface{}) - if configMap != nil && len(configMap) != 0 { - err := mapstructure.Decode(configMap, &apiConfig) - if err != nil { - return logical.ErrorResponse( - "unable to convert given auth config information"), - logical.ErrInvalidRequest - } - } - - switch apiConfig.DefaultLeaseTTL { - case "": - case "system": - default: - tmpDef, err := parseutil.ParseDurationSecond(apiConfig.DefaultLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse default TTL of %s: %s", apiConfig.DefaultLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.DefaultLeaseTTL = tmpDef - } - - switch apiConfig.MaxLeaseTTL { - case "": - case "system": - default: - tmpMax, err := parseutil.ParseDurationSecond(apiConfig.MaxLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse max TTL of %s: %s", apiConfig.MaxLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.MaxLeaseTTL = tmpMax - } - - if config.MaxLeaseTTL != 0 && config.DefaultLeaseTTL > config.MaxLeaseTTL { - return logical.ErrorResponse( - "given default lease TTL greater than given max lease TTL"), - logical.ErrInvalidRequest - } - - if config.DefaultLeaseTTL > b.Core.maxLeaseTTL && config.MaxLeaseTTL == 0 { - return logical.ErrorResponse(fmt.Sprintf( - "given default lease TTL greater than system max lease TTL of %d", int(b.Core.maxLeaseTTL.Seconds()))), - logical.ErrInvalidRequest - } - - switch apiConfig.TokenType { - case "", "default-service": - config.TokenType = logical.TokenTypeDefaultService - case "default-batch": - config.TokenType = logical.TokenTypeDefaultBatch - case "service": - config.TokenType = logical.TokenTypeService - case "batch": - config.TokenType = logical.TokenTypeBatch - default: - return logical.ErrorResponse(fmt.Sprintf( - "invalid value for 'token_type'")), logical.ErrInvalidRequest - } - - switch logicalType { - case "": - return logical.ErrorResponse( - "backend type must be specified as a string"), - logical.ErrInvalidRequest - case "plugin": - // Only set plugin name if mount is of type plugin, with apiConfig.PluginName - // option taking precedence. - switch { - case apiConfig.PluginName != "": - logicalType = apiConfig.PluginName - case pluginName != "": - logicalType = pluginName - default: - return logical.ErrorResponse( - "plugin_name must be provided for plugin backend"), - logical.ErrInvalidRequest - } - } - - if options != nil && options["version"] != "" { - return logical.ErrorResponse(fmt.Sprintf( - "auth method %q does not allow setting a version", logicalType)), - logical.ErrInvalidRequest - } - - if err := checkListingVisibility(apiConfig.ListingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", apiConfig.ListingVisibility)), nil - } - config.ListingVisibility = apiConfig.ListingVisibility - - if len(apiConfig.AuditNonHMACRequestKeys) > 0 { - config.AuditNonHMACRequestKeys = apiConfig.AuditNonHMACRequestKeys - } - if len(apiConfig.AuditNonHMACResponseKeys) > 0 { - config.AuditNonHMACResponseKeys = apiConfig.AuditNonHMACResponseKeys - } - if len(apiConfig.PassthroughRequestHeaders) > 0 { - config.PassthroughRequestHeaders = apiConfig.PassthroughRequestHeaders - } - - // Create the mount entry - me := &MountEntry{ - Table: credentialTableType, - Path: path, - Type: logicalType, - Description: description, - Config: config, - Local: local, - SealWrap: sealWrap, - Options: options, - } - - // Attempt enabling - if err := b.Core.enableCredential(ctx, me); err != nil { - b.Backend.Logger().Error("enable auth mount failed", "path", me.Path, "error", err) - return handleError(err) - } - return nil, nil -} - -// handleDisableAuth is used to disable a credential backend -func (b *SystemBackend) handleDisableAuth(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - fullPath := credentialRoutePrefix + path - - repState := b.Core.ReplicationState() - entry := b.Core.router.MatchingMountEntry(ctx, fullPath) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot unmount a non-local mount on a replication secondary"), nil - } - - // We return success when the mount does not exists to not expose if the - // mount existed or not - match := b.Core.router.MatchingMount(ctx, fullPath) - if match == "" || ns.Path+fullPath != match { - return nil, nil - } - - prefix, found := b.Core.router.MatchingStoragePrefixByAPIPath(ctx, fullPath) - if !found { - b.Backend.Logger().Error("unable to find storage for path", "path", fullPath) - return handleError(fmt.Errorf("unable to find storage for path: %q", fullPath)) - } - - // Attempt disable - if err := b.Core.disableCredential(ctx, path); err != nil { - b.Backend.Logger().Error("disable auth mount failed", "path", path, "error", err) - return handleError(err) - } - - // Remove from filtered mounts - if err := b.Core.removePrefixFromFilteredPaths(ctx, prefix); err != nil { - b.Backend.Logger().Error("filtered path removal failed", path, "error", err) - return handleError(err) - } - - return nil, nil -} - -// handlePoliciesList handles /sys/policy/ and /sys/policies/ endpoints to provide the enabled policies -func (b *SystemBackend) handlePoliciesList(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - policies, err := b.Core.policyStore.ListPolicies(ctx, policyType) - if err != nil { - return nil, err - } - - switch policyType { - case PolicyTypeACL: - // Add the special "root" policy if not egp and we are at the root namespace - if ns.ID == namespace.RootNamespaceID { - policies = append(policies, "root") - } - resp := logical.ListResponse(policies) - - // If the request is from sys/policy/ we handle backwards compatibility - if strings.HasPrefix(req.Path, "policy") { - resp.Data["policies"] = resp.Data["keys"] - } - return resp, nil - - case PolicyTypeRGP: - return logical.ListResponse(policies), nil - - case PolicyTypeEGP: - nsScopedKeyInfo := getEGPListResponseKeyInfo(b, ns) - return &logical.Response{ - Data: map[string]interface{}{ - "keys": policies, - "key_info": nsScopedKeyInfo, - }, - }, nil - } - - return logical.ErrorResponse("unknown policy type"), nil - } -} - -// handlePoliciesRead handles the "/sys/policy/" and "/sys/policies//" endpoints to read a policy -func (b *SystemBackend) handlePoliciesRead(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - policy, err := b.Core.policyStore.GetPolicy(ctx, name, policyType) - if err != nil { - return handleError(err) - } - - if policy == nil { - return nil, nil - } - - // If the request is from sys/policy/ we handle backwards compatibility - var respDataPolicyName string - if policyType == PolicyTypeACL && strings.HasPrefix(req.Path, "policy") { - respDataPolicyName = "rules" - } else { - respDataPolicyName = "policy" - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "name": policy.Name, - respDataPolicyName: policy.Raw, - }, - } - - switch policy.Type { - case PolicyTypeRGP, PolicyTypeEGP: - addSentinelPolicyData(resp.Data, policy) - } - - return resp, nil - } -} - -// handlePoliciesSet handles the "/sys/policy/" and "/sys/policies//" endpoints to set a policy -func (b *SystemBackend) handlePoliciesSet(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var resp *logical.Response - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - policy := &Policy{ - Name: strings.ToLower(data.Get("name").(string)), - Type: policyType, - namespace: ns, - } - if policy.Name == "" { - return logical.ErrorResponse("policy name must be provided in the URL"), nil - } - - policy.Raw = data.Get("policy").(string) - if policy.Raw == "" && policyType == PolicyTypeACL && strings.HasPrefix(req.Path, "policy") { - policy.Raw = data.Get("rules").(string) - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning("'rules' is deprecated, please use 'policy' instead") - } - if policy.Raw == "" { - return logical.ErrorResponse("'policy' parameter not supplied or empty"), nil - } - - if polBytes, err := base64.StdEncoding.DecodeString(policy.Raw); err == nil { - policy.Raw = string(polBytes) - } - - switch policyType { - case PolicyTypeACL: - p, err := ParseACLPolicy(ns, policy.Raw) - if err != nil { - return handleError(err) - } - policy.Paths = p.Paths - policy.Templated = p.Templated - - case PolicyTypeRGP, PolicyTypeEGP: - - default: - return logical.ErrorResponse("unknown policy type"), nil - } - - if policy.Type == PolicyTypeRGP || policy.Type == PolicyTypeEGP { - if errResp := inputSentinelPolicyData(data, policy); errResp != nil { - return errResp, nil - } - } - - // Update the policy - if err := b.Core.policyStore.SetPolicy(ctx, policy); err != nil { - return handleError(err) - } - return resp, nil - } -} - -func (b *SystemBackend) handlePoliciesDelete(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - if err := b.Core.policyStore.DeletePolicy(ctx, name, policyType); err != nil { - return handleError(err) - } - return nil, nil - } -} - -// handleAuditTable handles the "audit" endpoint to provide the audit table -func (b *SystemBackend) handleAuditTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.Core.auditLock.RLock() - defer b.Core.auditLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - for _, entry := range b.Core.audit.Entries { - info := map[string]interface{}{ - "path": entry.Path, - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - "local": entry.Local, - } - resp.Data[entry.Path] = info - } - return resp, nil -} - -// handleAuditHash is used to fetch the hash of the given input data with the -// specified audit backend's salt -func (b *SystemBackend) handleAuditHash(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - input := data.Get("input").(string) - if input == "" { - return logical.ErrorResponse("the \"input\" parameter is empty"), nil - } - - path = sanitizeMountPath(path) - - hash, err := b.Core.auditBroker.GetHash(ctx, path, input) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "hash": hash, - }, - }, nil -} - -// handleEnableAudit is used to enable a new audit backend -func (b *SystemBackend) handleEnableAudit(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - backendType := data.Get("type").(string) - description := data.Get("description").(string) - options := data.Get("options").(map[string]string) - - // Create the mount entry - me := &MountEntry{ - Table: auditTableType, - Path: path, - Type: backendType, - Description: description, - Options: options, - Local: local, - } - - // Attempt enabling - if err := b.Core.enableAudit(ctx, me, true); err != nil { - b.Backend.Logger().Error("enable audit mount failed", "path", me.Path, "error", err) - return handleError(err) - } - return nil, nil -} - -// handleDisableAudit is used to disable an audit backend -func (b *SystemBackend) handleDisableAudit(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Attempt disable - if existed, err := b.Core.disableAudit(ctx, path, true); existed && err != nil { - b.Backend.Logger().Error("disable audit mount failed", "path", path, "error", err) - return handleError(err) - } - return nil, nil -} - -func (b *SystemBackend) handleConfigUIHeadersRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - - value, err := b.Core.uiConfig.GetHeader(ctx, header) - if err != nil { - return nil, err - } - if value == "" { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "value": value, - }, - }, nil -} - -func (b *SystemBackend) handleConfigUIHeadersList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - headers, err := b.Core.uiConfig.HeaderKeys(ctx) - if err != nil { - return nil, err - } - if len(headers) == 0 { - return nil, nil - } - - return logical.ListResponse(headers), nil -} - -func (b *SystemBackend) handleConfigUIHeadersUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - values := data.Get("values").([]string) - if header == "" || len(values) == 0 { - return logical.ErrorResponse("header and values must be specified"), logical.ErrInvalidRequest - } - - lowerHeader := strings.ToLower(header) - if strings.HasPrefix(lowerHeader, "x-vault-") { - return logical.ErrorResponse("X-Vault headers cannot be set"), logical.ErrInvalidRequest - } - - // Translate the list of values to the valid header string - value := http.Header{} - for _, v := range values { - value.Add(header, v) - } - err := b.Core.uiConfig.SetHeader(ctx, header, value.Get(header)) - if err != nil { - return nil, err - } - - // Warn when overriding the CSP - resp := &logical.Response{} - if lowerHeader == "content-security-policy" { - resp.AddWarning("overriding default Content-Security-Policy which is secure by default, proceed with caution") - } - - return resp, nil -} - -func (b *SystemBackend) handleConfigUIHeadersDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - err := b.Core.uiConfig.DeleteHeader(ctx, header) - if err != nil { - return nil, err - } - return nil, nil -} - -// handleRawRead is used to read directly from the barrier -func (b *SystemBackend) handleRawRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot read '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - entry, err := b.Core.barrier.Get(ctx, path) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - if entry == nil { - return nil, nil - } - - // Run this through the decompression helper to see if it's been compressed. - // If the input contained the compression canary, `outputBytes` will hold - // the decompressed data. If the input was not compressed, then `outputBytes` - // will be nil. - outputBytes, _, err := compressutil.Decompress(entry.Value) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - - // `outputBytes` is nil if the input is uncompressed. In that case set it to the original input. - if outputBytes == nil { - outputBytes = entry.Value - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "value": string(outputBytes), - }, - } - return resp, nil -} - -// handleRawWrite is used to write directly to the barrier -func (b *SystemBackend) handleRawWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot write '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - value := data.Get("value").(string) - entry := &Entry{ - Key: path, - Value: []byte(value), - } - if err := b.Core.barrier.Put(ctx, entry); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - return nil, nil -} - -// handleRawDelete is used to delete directly from the barrier -func (b *SystemBackend) handleRawDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot delete '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - if err := b.Core.barrier.Delete(ctx, path); err != nil { - return handleErrorNoReadOnlyForward(err) - } - return nil, nil -} - -// handleRawList is used to list directly from the barrier -func (b *SystemBackend) handleRawList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot list '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - keys, err := b.Core.barrier.List(ctx, path) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - return logical.ListResponse(keys), nil -} - -// handleKeyStatus returns status information about the backend key -func (b *SystemBackend) handleKeyStatus(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get the key info - info, err := b.Core.barrier.ActiveKeyInfo() - if err != nil { - return nil, err - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "term": info.Term, - "install_time": info.InstallTime.Format(time.RFC3339Nano), - }, - } - return resp, nil -} - -// handleRotate is used to trigger a key rotation -func (b *SystemBackend) handleRotate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot rotate on a replication secondary"), nil - } - - // Rotate to the new term - newTerm, err := b.Core.barrier.Rotate(ctx) - if err != nil { - b.Backend.Logger().Error("failed to create new encryption key", "error", err) - return handleError(err) - } - b.Backend.Logger().Info("installed new encryption key") - - // In HA mode, we need to an upgrade path for the standby instances - if b.Core.ha != nil { - // Create the upgrade path to the new term - if err := b.Core.barrier.CreateUpgrade(ctx, newTerm); err != nil { - b.Backend.Logger().Error("failed to create new upgrade", "term", newTerm, "error", err) - } - - // Schedule the destroy of the upgrade path - time.AfterFunc(keyRotateGracePeriod, func() { - if err := b.Core.barrier.DestroyUpgrade(ctx, newTerm); err != nil { - b.Backend.Logger().Error("failed to destroy upgrade", "term", newTerm, "error", err) - } - }) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := b.Core.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(fmt.Sprintf("new-rotation-term-%d", newTerm)), - }); err != nil { - b.Core.logger.Error("error saving keyring canary", "error", err) - return nil, errwrap.Wrapf("failed to save keyring canary: {{err}}", err) - } - - return nil, nil -} - -func (b *SystemBackend) handleWrappingPubkey(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - x, _ := b.Core.wrappingJWTKey.X.MarshalText() - y, _ := b.Core.wrappingJWTKey.Y.MarshalText() - return &logical.Response{ - Data: map[string]interface{}{ - "jwt_x": string(x), - "jwt_y": string(y), - "jwt_curve": corePrivateKeyTypeP521, - }, - }, nil -} - -func (b *SystemBackend) handleWrappingWrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.WrapInfo == nil || req.WrapInfo.TTL == 0 { - return logical.ErrorResponse("endpoint requires response wrapping to be used"), logical.ErrInvalidRequest - } - - // N.B.: Do *NOT* allow JWT wrapping tokens to be created through this - // endpoint. JWTs are signed so if we don't allow users to create wrapping - // tokens using them we can ensure that an operator can't spoof a legit JWT - // wrapped token, which makes certain init/rekey/generate-root cases have - // better properties. - req.WrapInfo.Format = "uuid" - - return &logical.Response{ - Data: data.Raw, - }, nil -} - -// handleWrappingUnwrap will unwrap a response wrapping token or complete a -// request that required a control group. -func (b *SystemBackend) handleWrappingUnwrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // If a third party is unwrapping (rather than the calling token being the - // wrapping token) we detect this so that we can revoke the original - // wrapping token after reading it - var thirdParty bool - - token := data.Get("token").(string) - if token != "" { - thirdParty = true - } else { - token = req.ClientToken - } - - // Get the policies so we can determine if this is a normal response - // wrapping request or a control group token. - // - // We use lookupTainted here because the token might have already been used - // by handleRequest(), this happens when it's a normal response wrapping - // request and the token was provided "first party". We want to inspect the - // token policies but will not use this token entry for anything else. - te, err := b.Core.tokenStore.lookupTainted(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, nil - } - if len(te.Policies) != 1 { - return nil, errors.New("token is not a valid unwrap token") - } - - unwrapNS, err := NamespaceByID(ctx, te.NamespaceID, b.Core) - if err != nil { - return nil, err - } - unwrapCtx := namespace.ContextWithNamespace(ctx, unwrapNS) - - var response string - switch te.Policies[0] { - case controlGroupPolicyName: - response, err = controlGroupUnwrap(unwrapCtx, b, token, thirdParty) - case responseWrappingPolicyName: - response, err = b.responseWrappingUnwrap(unwrapCtx, te, thirdParty) - } - if err != nil { - var respErr *logical.Response - if len(response) > 0 { - respErr = logical.ErrorResponse(response) - } - - return respErr, err - } - - resp := &logical.Response{ - Data: map[string]interface{}{}, - } - - // Most of the time we want to just send over the marshalled HTTP bytes. - // However there is a sad separate case: if the original response was using - // bare values we need to use those or else what comes back is garbled. - httpResp := &logical.HTTPResponse{} - err = jsonutil.DecodeJSON([]byte(response), httpResp) - if err != nil { - return nil, errwrap.Wrapf("error decoding wrapped response: {{err}}", err) - } - if httpResp.Data != nil && - (httpResp.Data[logical.HTTPStatusCode] != nil || - httpResp.Data[logical.HTTPRawBody] != nil || - httpResp.Data[logical.HTTPContentType] != nil) { - if httpResp.Data[logical.HTTPStatusCode] != nil { - resp.Data[logical.HTTPStatusCode] = httpResp.Data[logical.HTTPStatusCode] - } - if httpResp.Data[logical.HTTPContentType] != nil { - resp.Data[logical.HTTPContentType] = httpResp.Data[logical.HTTPContentType] - } - - rawBody := httpResp.Data[logical.HTTPRawBody] - if rawBody != nil { - // Decode here so that we can audit properly - switch rawBody.(type) { - case string: - // Best effort decoding; if this works, the original value was - // probably a []byte instead of a string, but was marshaled - // when the value was saved, so this restores it as it was - decBytes, err := base64.StdEncoding.DecodeString(rawBody.(string)) - if err == nil { - // We end up with []byte, will not be HMAC'd - resp.Data[logical.HTTPRawBody] = decBytes - } else { - // We end up with string, will be HMAC'd - resp.Data[logical.HTTPRawBody] = rawBody - } - default: - b.Core.Logger().Error("unexpected type of raw body when decoding wrapped token", "type", fmt.Sprintf("%T", rawBody)) - } - - resp.Data[logical.HTTPRawBodyAlreadyJSONDecoded] = true - } - - return resp, nil - } - - if len(response) == 0 { - resp.Data[logical.HTTPStatusCode] = 204 - } else { - resp.Data[logical.HTTPStatusCode] = 200 - resp.Data[logical.HTTPRawBody] = []byte(response) - resp.Data[logical.HTTPContentType] = "application/json" - } - - return resp, nil -} - -// responseWrappingUnwrap will read the stored response in the cubbyhole and -// return the raw HTTP response. -func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, te *logical.TokenEntry, thirdParty bool) (string, error) { - tokenID := te.ID - if thirdParty { - // Use the token to decrement the use count to avoid a second operation on the token. - _, err := b.Core.tokenStore.UseTokenByID(ctx, tokenID) - if err != nil { - return "", errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) - } - - defer b.Core.tokenStore.revokeOrphan(ctx, tokenID) - } - - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/response", - ClientToken: tokenID, - } - cubbyReq.SetTokenEntry(te) - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return "", errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return "no information found; wrapping token may be from a previous Vault version", ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp.Error().Error(), nil - } - if cubbyResp.Data == nil { - return "wrapping information was nil; wrapping token may be from a previous Vault version", ErrInternalError - } - - responseRaw := cubbyResp.Data["response"] - if responseRaw == nil { - return "", fmt.Errorf("no response found inside the cubbyhole") - } - response, ok := responseRaw.(string) - if !ok { - return "", fmt.Errorf("could not decode response inside the cubbyhole") - } - - return response, nil -} - -func (b *SystemBackend) handleWrappingLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // This ordering of lookups has been validated already in the wrapping - // validation func, we're just doing this for a safety check - token := data.Get("token").(string) - if token == "" { - token = req.ClientToken - if token == "" { - return logical.ErrorResponse("missing \"token\" value in input"), logical.ErrInvalidRequest - } - } - - te, err := b.Core.tokenStore.lookupTainted(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, nil - } - if len(te.Policies) != 1 { - return nil, errors.New("token is not a valid unwrap token") - } - - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/wrapinfo", - ClientToken: token, - } - cubbyReq.SetTokenEntry(te) - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - creationTTLRaw := cubbyResp.Data["creation_ttl"] - creationTime := cubbyResp.Data["creation_time"] - creationPath := cubbyResp.Data["creation_path"] - - resp := &logical.Response{ - Data: map[string]interface{}{}, - } - if creationTTLRaw != nil { - creationTTL, err := creationTTLRaw.(json.Number).Int64() - if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) - } - resp.Data["creation_ttl"] = time.Duration(creationTTL).Seconds() - } - if creationTime != nil { - // This was JSON marshaled so it's already a string in RFC3339 format - resp.Data["creation_time"] = cubbyResp.Data["creation_time"] - } - if creationPath != nil { - resp.Data["creation_path"] = cubbyResp.Data["creation_path"] - } - - return resp, nil -} - -func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // If a third party is rewrapping (rather than the calling token being the - // wrapping token) we detect this so that we can revoke the original - // wrapping token after reading it. Right now wrapped tokens can't unwrap - // themselves, but in case we change it, this will be ready to do the right - // thing. - var thirdParty bool - - token := data.Get("token").(string) - if token != "" { - thirdParty = true - } else { - token = req.ClientToken - } - - te, err := b.Core.tokenStore.lookupTainted(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, nil - } - if len(te.Policies) != 1 { - return nil, errors.New("token is not a valid unwrap token") - } - - if thirdParty { - // Use the token to decrement the use count to avoid a second operation on the token. - _, err := b.Core.tokenStore.UseTokenByID(ctx, token) - if err != nil { - return nil, errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) - } - defer b.Core.tokenStore.revokeOrphan(ctx, token) - } - - // Fetch the original TTL - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/wrapinfo", - ClientToken: token, - } - cubbyReq.SetTokenEntry(te) - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - // Set the creation TTL on the request - creationTTLRaw := cubbyResp.Data["creation_ttl"] - if creationTTLRaw == nil { - return nil, fmt.Errorf("creation_ttl value in wrapping information was nil") - } - creationTTL, err := cubbyResp.Data["creation_ttl"].(json.Number).Int64() - if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) - } - - // Get creation_path to return as the response later - creationPathRaw := cubbyResp.Data["creation_path"] - if creationPathRaw == nil { - return nil, fmt.Errorf("creation_path value in wrapping information was nil") - } - creationPath := creationPathRaw.(string) - - // Fetch the original response and return it as the data for the new response - cubbyReq = &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/response", - ClientToken: token, - } - cubbyReq.SetTokenEntry(te) - cubbyResp, err = b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up response: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - response := cubbyResp.Data["response"] - if response == nil { - return nil, fmt.Errorf("no response found inside the cubbyhole") - } - - // Return response in "response"; wrapping code will detect the rewrap and - // slot in instead of nesting - return &logical.Response{ - Data: map[string]interface{}{ - "response": response, - }, - WrapInfo: &wrapping.ResponseWrapInfo{ - TTL: time.Duration(creationTTL), - CreationPath: creationPath, - }, - }, nil -} - -func (b *SystemBackend) pathHashWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - inputB64 := d.Get("input").(string) - format := d.Get("format").(string) - algorithm := d.Get("urlalgorithm").(string) - if algorithm == "" { - algorithm = d.Get("algorithm").(string) - } - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - var hf hash.Hash - switch algorithm { - case "sha2-224": - hf = sha256.New224() - case "sha2-256": - hf = sha256.New() - case "sha2-384": - hf = sha512.New384() - case "sha2-512": - hf = sha512.New() - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil - } - hf.Write(input) - retBytes := hf.Sum(nil) - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(retBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(retBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "sum": retStr, - }, - } - return resp, nil -} - -func (b *SystemBackend) pathRandomWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - bytes := 0 - var err error - strBytes := d.Get("urlbytes").(string) - if strBytes != "" { - bytes, err = strconv.Atoi(strBytes) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error parsing url-set byte count: %s", err)), nil - } - } else { - bytes = d.Get("bytes").(int) - } - format := d.Get("format").(string) - - if bytes < 1 { - return logical.ErrorResponse(`"bytes" cannot be less than 1`), nil - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - randBytes, err := uuid.GenerateRandomBytes(bytes) - if err != nil { - return nil, err - } - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(randBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(randBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "random_bytes": retStr, - }, - } - return resp, nil -} - -func hasMountAccess(ctx context.Context, acl *ACL, path string) bool { - ns, err := namespace.FromContext(ctx) - if err != nil { - return false - } - - // If an earlier policy is giving us access to the mount path then we can do - // a fast return. - capabilities := acl.Capabilities(ctx, ns.TrimmedPath(path)) - if !strutil.StrListContains(capabilities, DenyCapability) { - return true - } - - var aclCapabilitiesGiven bool - walkFn := func(s string, v interface{}) bool { - if v == nil { - return false - } - - perms := v.(*ACLPermissions) - - switch { - case perms.CapabilitiesBitmap&DenyCapabilityInt > 0: - return false - - case perms.CapabilitiesBitmap&CreateCapabilityInt > 0, - perms.CapabilitiesBitmap&DeleteCapabilityInt > 0, - perms.CapabilitiesBitmap&ListCapabilityInt > 0, - perms.CapabilitiesBitmap&ReadCapabilityInt > 0, - perms.CapabilitiesBitmap&SudoCapabilityInt > 0, - perms.CapabilitiesBitmap&UpdateCapabilityInt > 0: - - aclCapabilitiesGiven = true - return true - } - - return false - } - - acl.exactRules.WalkPrefix(path, walkFn) - if !aclCapabilitiesGiven { - acl.globRules.WalkPrefix(path, walkFn) - } - - return aclCapabilitiesGiven -} - -func (b *SystemBackend) pathInternalUIMountsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - - secretMounts := make(map[string]interface{}) - authMounts := make(map[string]interface{}) - resp.Data["secret"] = secretMounts - resp.Data["auth"] = authMounts - - var acl *ACL - var isAuthed bool - if req.ClientToken != "" { - isAuthed = true - - var entity *identity.Entity - var te *logical.TokenEntry - // Load the ACL policies so we can walk the prefix for this mount - acl, te, entity, _, err = b.Core.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return nil, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - } - - hasAccess := func(ctx context.Context, me *MountEntry) bool { - if me.Config.ListingVisibility == ListingVisibilityUnauth { - return true - } - - if isAuthed { - return hasMountAccess(ctx, acl, ns.Path+me.Path) - } - - return false - } - - b.Core.mountsLock.RLock() - for _, entry := range b.Core.mounts.Entries { - if hasAccess(ctx, entry) && ns.ID == entry.NamespaceID { - if isAuthed { - // If this is an authed request return all the mount info - secretMounts[entry.Path] = mountInfo(entry) - } else { - secretMounts[entry.Path] = map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - } - } - } - } - b.Core.mountsLock.RUnlock() - - b.Core.authLock.RLock() - for _, entry := range b.Core.auth.Entries { - if hasAccess(ctx, entry) && ns.ID == entry.NamespaceID { - if isAuthed { - // If this is an authed request return all the mount info - authMounts[entry.Path] = mountInfo(entry) - } else { - authMounts[entry.Path] = map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - } - } - } - } - b.Core.authLock.RUnlock() - - return resp, nil -} - -func (b *SystemBackend) pathInternalUIMountRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - path := d.Get("path").(string) - if path == "" { - return logical.ErrorResponse("path not set"), logical.ErrInvalidRequest - } - path = sanitizeMountPath(path) - - errResp := logical.ErrorResponse(fmt.Sprintf("preflight capability check returned 403, please ensure client's policies grant access to path %q", path)) - - me := b.Core.router.MatchingMountEntry(ctx, path) - if me == nil { - // Return a permission denied error here so this path cannot be used to - // brute force a list of mounts. - return errResp, logical.ErrPermissionDenied - } - - resp := &logical.Response{ - Data: mountInfo(me), - } - resp.Data["path"] = me.Path - - // Load the ACL policies so we can walk the prefix for this mount - acl, te, entity, _, err := b.Core.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return errResp, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - if !hasMountAccess(ctx, acl, ns.Path+me.Path) { - return errResp, logical.ErrPermissionDenied - } - - return resp, nil -} - -func (b *SystemBackend) pathInternalUIResultantACL(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - // 204 -- no ACL - return nil, nil - } - - acl, te, entity, _, err := b.Core.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return logical.ErrorResponse(logical.ErrPermissionDenied.Error()), nil - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return logical.ErrorResponse(logical.ErrPermissionDenied.Error()), nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "root": false, - }, - } - - if acl.root { - resp.Data["root"] = true - return resp, nil - } - - exact := map[string]interface{}{} - glob := map[string]interface{}{} - - walkFn := func(pt map[string]interface{}, s string, v interface{}) { - if v == nil { - return - } - - perms := v.(*ACLPermissions) - capabilities := []string{} - - if perms.CapabilitiesBitmap&CreateCapabilityInt > 0 { - capabilities = append(capabilities, CreateCapability) - } - if perms.CapabilitiesBitmap&DeleteCapabilityInt > 0 { - capabilities = append(capabilities, DeleteCapability) - } - if perms.CapabilitiesBitmap&ListCapabilityInt > 0 { - capabilities = append(capabilities, ListCapability) - } - if perms.CapabilitiesBitmap&ReadCapabilityInt > 0 { - capabilities = append(capabilities, ReadCapability) - } - if perms.CapabilitiesBitmap&SudoCapabilityInt > 0 { - capabilities = append(capabilities, SudoCapability) - } - if perms.CapabilitiesBitmap&UpdateCapabilityInt > 0 { - capabilities = append(capabilities, UpdateCapability) - } - - // If "deny" is explicitly set or if the path has no capabilities at all, - // set the path capabilities to "deny" - if perms.CapabilitiesBitmap&DenyCapabilityInt > 0 || len(capabilities) == 0 { - capabilities = []string{DenyCapability} - } - - res := map[string]interface{}{} - if len(capabilities) > 0 { - res["capabilities"] = capabilities - } - if perms.MinWrappingTTL != 0 { - res["min_wrapping_ttl"] = int64(perms.MinWrappingTTL.Seconds()) - } - if perms.MaxWrappingTTL != 0 { - res["max_wrapping_ttl"] = int64(perms.MaxWrappingTTL.Seconds()) - } - if len(perms.AllowedParameters) > 0 { - res["allowed_parameters"] = perms.AllowedParameters - } - if len(perms.DeniedParameters) > 0 { - res["denied_parameters"] = perms.DeniedParameters - } - if len(perms.RequiredParameters) > 0 { - res["required_parameters"] = perms.RequiredParameters - } - - pt[s] = res - } - - exactWalkFn := func(s string, v interface{}) bool { - walkFn(exact, s, v) - return false - } - - globWalkFn := func(s string, v interface{}) bool { - walkFn(glob, s, v) - return false - } - - acl.exactRules.Walk(exactWalkFn) - acl.globRules.Walk(globWalkFn) - - resp.Data["exact_paths"] = exact - resp.Data["glob_paths"] = glob - - return resp, nil -} - -func (b *SystemBackend) pathInternalOpenAPI(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - - // Limit output to authorized paths - resp, err := b.pathInternalUIMountsRead(ctx, req, d) - if err != nil { - return nil, err - } - - // Set up target document and convert to map[string]interface{} which is what will - // be received from plugin backends. - doc := framework.NewOASDocument() - - procMountGroup := func(group, mountPrefix string) error { - for mount := range resp.Data[group].(map[string]interface{}) { - backend := b.Core.router.MatchingBackend(ctx, mountPrefix+mount) - - if backend == nil { - continue - } - - req := &logical.Request{ - Operation: logical.HelpOperation, - } - - resp, err := backend.HandleRequest(ctx, req) - if err != nil { - return err - } - - var backendDoc *framework.OASDocument - - // Normalize response type, which will be different if received - // from an external plugin. - switch v := resp.Data["openapi"].(type) { - case *framework.OASDocument: - backendDoc = v - case map[string]interface{}: - backendDoc, err = framework.NewOASDocumentFromMap(v) - if err != nil { - return err - } - default: - continue - } - - // Prepare to add tags to default builtins that are - // type "unknown" and won't already be tagged. - var tag string - switch mountPrefix + mount { - case "cubbyhole/", "secret/": - tag = "secrets" - case "sys/": - tag = "system" - case "auth/token/": - tag = "auth" - case "identity/": - tag = "identity" - } - - // Merge backend paths with existing document - for path, obj := range backendDoc.Paths { - path := strings.TrimPrefix(path, "/") - - // Add tags to all of the operations if necessary - if tag != "" { - for _, op := range []*framework.OASOperation{obj.Get, obj.Post, obj.Delete} { - // TODO: a special override for identity is used used here because the backend - // is currently categorized as "secret", which will likely change. Also of interest - // is removing all tag handling here and providing the mount information to OpenAPI. - if op != nil && (len(op.Tags) == 0 || tag == "identity") { - op.Tags = []string{tag} - } - } - } - - doc.Paths["/"+mountPrefix+mount+path] = obj - } - } - return nil - } - - if err := procMountGroup("secret", ""); err != nil { - return nil, err - } - if err := procMountGroup("auth", "auth/"); err != nil { - return nil, err - } - - buf, err := json.Marshal(doc) - if err != nil { - return nil, err - } - - resp = &logical.Response{ - Data: map[string]interface{}{ - logical.HTTPStatusCode: 200, - logical.HTTPRawBody: buf, - logical.HTTPContentType: "application/json", - }, - } - - return resp, nil -} - -func sanitizeMountPath(path string) string { - if !strings.HasSuffix(path, "/") { - path += "/" - } - - if strings.HasPrefix(path, "/") { - path = path[1:] - } - - return path -} - -func checkListingVisibility(visibility ListingVisibilityType) error { - switch visibility { - case ListingVisibilityDefault: - case ListingVisibilityHidden: - case ListingVisibilityUnauth: - default: - return fmt.Errorf("invalid listing visilibity type") - } - - return nil -} - -const sysHelpRoot = ` -The system backend is built-in to Vault and cannot be remounted or -unmounted. It contains the paths that are used to configure Vault itself -as well as perform core operations. -` - -// sysHelp is all the help text for the sys backend. -var sysHelp = map[string][2]string{ - "license": { - "Sets the license of the server.", - ` -The path responds to the following HTTP methods. - - GET / - Returns information on the installed license - - POST - Sets the license for the server - `, - }, - "config/cors": { - "Configures or returns the current configuration of CORS settings.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the configuration of the CORS setting. - - POST / - Sets the comma-separated list of origins that can make cross-origin requests. - - DELETE / - Clears the CORS configuration and disables acceptance of CORS requests. - `, - }, - "config/ui/headers": { - "Configures response headers that should be returned from the UI.", - ` -This path responds to the following HTTP methods. - GET /
- Returns the header value. - POST /
- Sets the header value for the UI. - DELETE /
- Clears the header value for UI. - - LIST / - List the headers configured for the UI. - `, - }, - "init": { - "Initializes or returns the initialization status of the Vault.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the initialization status of the Vault. - - POST / - Initializes a new vault. - `, - }, - "generate-root": { - "Reads, generates, or deletes a root token regeneration process.", - ` -This path responds to multiple HTTP methods which change the behavior. Those -HTTP methods are listed below. - - GET /attempt - Reads the configuration and progress of the current root generation - attempt. - - POST /attempt - Initializes a new root generation attempt. Only a single root generation - attempt can take place at a time. One (and only one) of otp or pgp_key - are required. - - DELETE /attempt - Cancels any in-progress root generation attempt. This clears any - progress made. This must be called to change the OTP or PGP key being - used. - `, - }, - "seal-status": { - "Returns the seal status of the Vault.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the seal status of the Vault. This is an unauthenticated - endpoint. - `, - }, - "seal": { - "Seals the Vault.", - ` -This path responds to the following HTTP methods. - - PUT / - Seals the Vault. - `, - }, - "unseal": { - "Unseals the Vault.", - ` -This path responds to the following HTTP methods. - - PUT / - Unseals the Vault. - `, - }, - "mounts": { - "List the currently mounted backends.", - ` -This path responds to the following HTTP methods. - - GET / - Lists all the mounted secret backends. - - GET / - Get information about the mount at the specified path. - - POST / - Mount a new secret backend to the mount point in the URL. - - POST //tune - Tune configuration parameters for the given mount point. - - DELETE / - Unmount the specified mount point. - `, - }, - - "mount": { - `Mount a new backend at a new path.`, - ` -Mount a backend at a new path. A backend can be mounted multiple times at -multiple paths in order to configure multiple separately configured backends. -Example: you might have an AWS backend for the east coast, and one for the -west coast. - `, - }, - - "mount_path": { - `The path to mount to. Example: "aws/east"`, - "", - }, - - "mount_type": { - `The type of the backend. Example: "passthrough"`, - "", - }, - - "mount_desc": { - `User-friendly description for this mount.`, - "", - }, - - "mount_config": { - `Configuration for this mount, such as default_lease_ttl -and max_lease_ttl.`, - }, - - "mount_local": { - `Mark the mount as a local mount, which is not replicated -and is unaffected by replication.`, - }, - - "mount_plugin_name": { - `Name of the plugin to mount based from the name registered -in the plugin catalog.`, - }, - - "mount_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "seal_wrap": { - `Whether to turn on seal wrapping for the mount.`, - }, - - "tune_default_lease_ttl": { - `The default lease TTL for this mount.`, - }, - - "tune_max_lease_ttl": { - `The max lease TTL for this mount.`, - }, - - "tune_audit_non_hmac_request_keys": { - `The list of keys in the request data object that will not be HMAC'ed by audit devices.`, - }, - - "tune_audit_non_hmac_response_keys": { - `The list of keys in the response data object that will not be HMAC'ed by audit devices.`, - }, - - "tune_mount_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "remount": { - "Move the mount point of an already-mounted backend.", - ` -This path responds to the following HTTP methods. - - POST /sys/remount - Changes the mount point of an already-mounted backend. - `, - }, - - "auth_tune": { - "Tune the configuration parameters for an auth path.", - `Read and write the 'default-lease-ttl' and 'max-lease-ttl' values of -the auth path.`, - }, - - "mount_tune": { - "Tune backend configuration parameters for this mount.", - `Read and write the 'default-lease-ttl' and 'max-lease-ttl' values of -the mount.`, - }, - - "renew": { - "Renew a lease on a secret", - ` -When a secret is read, it may optionally include a lease interval -and a boolean indicating if renew is possible. For secrets that support -lease renewal, this endpoint is used to extend the validity of the -lease and to prevent an automatic revocation. - `, - }, - - "lease_id": { - "The lease identifier to renew. This is included with a lease.", - "", - }, - - "increment": { - "The desired increment in seconds to the lease", - "", - }, - - "revoke": { - "Revoke a leased secret immediately", - ` -When a secret is generated with a lease, it is automatically revoked -at the end of the lease period if not renewed. However, in some cases -you may want to force an immediate revocation. This endpoint can be -used to revoke the secret with the given Lease ID. - `, - }, - - "revoke-sync": { - "Whether or not to perform the revocation synchronously", - ` -If false, the call will return immediately and revocation will be queued; if it -fails, Vault will keep trying. If true, if the revocation fails, Vault will not -automatically try again and will return an error. For revoke-prefix, this -setting will apply to all leases being revoked. For revoke-force, since errors -are ignored, this setting is not supported. -`, - }, - - "revoke-prefix": { - "Revoke all secrets generated in a given prefix", - ` -Revokes all the secrets generated under a given mount prefix. As -an example, "prod/aws/" might be the AWS logical backend, and due to -a change in the "ops" policy, we may want to invalidate all the secrets -generated. We can do a revoke prefix at "prod/aws/ops" to revoke all -the ops secrets. This does a prefix match on the Lease IDs and revokes -all matching leases. - `, - }, - - "revoke-prefix-path": { - `The path to revoke keys under. Example: "prod/aws/ops"`, - "", - }, - - "revoke-force": { - "Revoke all secrets generated in a given prefix, ignoring errors.", - ` -See the path help for 'revoke-prefix'; this behaves the same, except that it -ignores errors encountered during revocation. This can be used in certain -recovery situations; for instance, when you want to unmount a backend, but it -is impossible to fix revocation errors and these errors prevent the unmount -from proceeding. This is a DANGEROUS operation as it removes Vault's oversight -of external secrets. Access to this prefix should be tightly controlled. - `, - }, - - "revoke-force-path": { - `The path to revoke keys under. Example: "prod/aws/ops"`, - "", - }, - - "auth-table": { - "List the currently enabled credential backends.", - ` -This path responds to the following HTTP methods. - - GET / - List the currently enabled credential backends: the name, the type of - the backend, and a user friendly description of the purpose for the - credential backend. - - POST / - Enable a new auth method. - - DELETE / - Disable the auth method at the given mount point. - `, - }, - - "auth": { - `Enable a new credential backend with a name.`, - ` -Enable a credential mechanism at a new path. A backend can be mounted multiple times at -multiple paths in order to configure multiple separately configured backends. -Example: you might have an OAuth backend for GitHub, and one for Google Apps. - `, - }, - - "auth_path": { - `The path to mount to. Cannot be delimited. Example: "user"`, - "", - }, - - "auth_type": { - `The type of the backend. Example: "userpass"`, - "", - }, - - "auth_desc": { - `User-friendly description for this credential backend.`, - "", - }, - - "auth_config": { - `Configuration for this mount, such as plugin_name.`, - }, - - "auth_plugin": { - `Name of the auth plugin to use based from the name in the plugin catalog.`, - "", - }, - - "auth_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "policy-list": { - `List the configured access control policies.`, - ` -This path responds to the following HTTP methods. - - GET / - List the names of the configured access control policies. - - GET / - Retrieve the rules for the named policy. - - PUT / - Add or update a policy. - - DELETE / - Delete the policy with the given name. - `, - }, - - "policy": { - `Read, Modify, or Delete an access control policy.`, - ` -Read the rules of an existing policy, create or update the rules of a policy, -or delete a policy. - `, - }, - - "policy-name": { - `The name of the policy. Example: "ops"`, - "", - }, - - "policy-rules": { - `The rules of the policy.`, - "", - }, - - "policy-paths": { - `The paths on which the policy should be applied.`, - "", - }, - - "policy-enforcement-level": { - `The enforcement level to apply to the policy.`, - "", - }, - - "audit-hash": { - "The hash of the given string via the given audit backend", - "", - }, - - "audit-table": { - "List the currently enabled audit backends.", - ` -This path responds to the following HTTP methods. - - GET / - List the currently enabled audit backends. - - PUT / - Enable an audit backend at the given path. - - DELETE / - Disable the given audit backend. - `, - }, - - "audit_path": { - `The name of the backend. Cannot be delimited. Example: "mysql"`, - "", - }, - - "audit_type": { - `The type of the backend. Example: "mysql"`, - "", - }, - - "audit_desc": { - `User-friendly description for this audit backend.`, - "", - }, - - "audit_opts": { - `Configuration options for the audit backend.`, - "", - }, - - "audit": { - `Enable or disable audit backends.`, - ` -Enable a new audit backend or disable an existing backend. - `, - }, - - "key-status": { - "Provides information about the backend encryption key.", - ` - Provides the current backend encryption key term and installation time. - `, - }, - - "rotate": { - "Rotates the backend encryption key used to persist data.", - ` - Rotate generates a new encryption key which is used to encrypt all - data going to the storage backend. The old encryption keys are kept so - that data encrypted using those keys can still be decrypted. - `, - }, - - "rekey_backup": { - "Allows fetching or deleting the backup of the rotated unseal keys.", - "", - }, - - "capabilities": { - "Fetches the capabilities of the given token on the given path.", - `Returns the capabilities of the given token on the path. - The path will be searched for a path match in all the policies associated with the token.`, - }, - - "capabilities_self": { - "Fetches the capabilities of the given token on the given path.", - `Returns the capabilities of the client token on the path. - The path will be searched for a path match in all the policies associated with the client token.`, - }, - - "capabilities_accessor": { - "Fetches the capabilities of the token associated with the given token, on the given path.", - `When there is no access to the token, token accessor can be used to fetch the token's capabilities - on a given path.`, - }, - - "tidy_leases": { - `This endpoint performs cleanup tasks that can be run if certain error -conditions have occurred.`, - `This endpoint performs cleanup tasks that can be run to clean up the -lease entries after certain error conditions. Usually running this is not -necessary, and is only required if upgrade notes or support personnel suggest -it.`, - }, - - "wrap": { - "Response-wraps an arbitrary JSON object.", - `Round trips the given input data into a response-wrapped token.`, - }, - - "wrappubkey": { - "Returns pubkeys used in some wrapping formats.", - "Returns pubkeys used in some wrapping formats.", - }, - - "unwrap": { - "Unwraps a response-wrapped token.", - `Unwraps a response-wrapped token. Unlike simply reading from cubbyhole/response, - this provides additional validation on the token, and rather than a JSON-escaped - string, the returned response is the exact same as the contained wrapped response.`, - }, - - "wraplookup": { - "Looks up the properties of a response-wrapped token.", - `Returns the creation TTL and creation time of a response-wrapped token.`, - }, - - "rewrap": { - "Rotates a response-wrapped token.", - `Rotates a response-wrapped token; the output is a new token with the same - response wrapped inside and the same creation TTL. The original token is revoked.`, - }, - "audited-headers-name": { - "Configures the headers sent to the audit logs.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the setting for the header with the given name. - - POST / - Enable auditing of the given header. - - DELETE / - Disable auditing of the given header. - `, - }, - "audited-headers": { - "Lists the headers configured to be audited.", - `Returns a list of headers that have been configured to be audited.`, - }, - "plugin-catalog-list-all": { - "Lists all the plugins known to Vault", - ` -This path responds to the following HTTP methods. - LIST / - Returns a list of names of configured plugins. - `, - }, - "plugin-catalog": { - "Configures the plugins known to Vault", - ` -This path responds to the following HTTP methods. - LIST / - Returns a list of names of configured plugins. - - GET / - Retrieve the metadata for the named plugin. - - PUT / - Add or update plugin. - - DELETE / - Delete the plugin with the given name. - `, - }, - "plugin-catalog_name": { - "The name of the plugin", - "", - }, - "plugin-catalog_type": { - "The type of the plugin, may be auth, secret, or database", - "", - }, - "plugin-catalog_sha-256": { - `The SHA256 sum of the executable used in the -command field. This should be HEX encoded.`, - "", - }, - "plugin-catalog_command": { - `The command used to start the plugin. The -executable defined in this command must exist in vault's -plugin directory.`, - "", - }, - "plugin-catalog_args": { - `The args passed to plugin command.`, - "", - }, - "plugin-catalog_env": { - `The environment variables passed to plugin command. -Each entry is of the form "key=value".`, - "", - }, - "leases": { - `View or list lease metadata.`, - ` -This path responds to the following HTTP methods. - - PUT / - Retrieve the metadata for the provided lease id. - - LIST / - Lists the leases for the named prefix. - `, - }, - - "leases-list-prefix": { - `The path to list leases under. Example: "aws/creds/deploy"`, - "", - }, - "plugin-reload": { - "Reload mounts that use a particular backend plugin.", - `Reload mounts that use a particular backend plugin. Either the plugin name - or the desired plugin backend mounts must be provided, but not both. In the - case that the plugin name is provided, all mounted paths that use that plugin - backend will be reloaded.`, - }, - "plugin-backend-reload-plugin": { - `The name of the plugin to reload, as registered in the plugin catalog.`, - "", - }, - "plugin-backend-reload-mounts": { - `The mount paths of the plugin backends to reload.`, - "", - }, - "hash": { - "Generate a hash sum for input data", - "Generates a hash sum of the given algorithm against the given input data.", - }, - "random": { - "Generate random bytes", - "This function can be used to generate high-entropy random bytes.", - }, - "listing_visibility": { - "Determines the visibility of the mount in the UI-specific listing endpoint. Accepted value are 'unauth' and ''.", - "", - }, - "passthrough_request_headers": { - "A list of headers to whitelist and pass from the request to the backend.", - "", - }, - "token_type": { - "The type of token to issue (service or batch).", - "", - }, - "raw": { - "Write, Read, and Delete data directly in the Storage backend.", - "", - }, - "internal-ui-mounts": { - "Information about mounts returned according to their tuned visibility. Internal API; its location, inputs, and outputs may change.", - "", - }, - "internal-ui-namespaces": { - "Information about visible child namespaces. Internal API; its location, inputs, and outputs may change.", - `Information about visible child namespaces returned starting from the request's - context namespace and filtered based on access from the client token. Internal API; - its location, inputs, and outputs may change.`, - }, - "internal-ui-resultant-acl": { - "Information about a token's resultant ACL. Internal API; its location, inputs, and outputs may change.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go b/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go deleted file mode 100644 index 28fae412..00000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go +++ /dev/null @@ -1,133 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -var ( - invalidateMFAConfig = func(context.Context, *SystemBackend, string) {} - - sysInvalidate = func(b *SystemBackend) func(context.Context, string) { - return nil - } - - getSystemSchemas = func() []func() *memdb.TableSchema { return nil } - - getEGPListResponseKeyInfo = func(*SystemBackend, *namespace.Namespace) map[string]interface{} { return nil } - addSentinelPolicyData = func(map[string]interface{}, *Policy) {} - inputSentinelPolicyData = func(*framework.FieldData, *Policy) *logical.Response { return nil } - - controlGroupUnwrap = func(context.Context, *SystemBackend, string, bool) (string, error) { - return "", errors.New("control groups unavailable") - } - - pathInternalUINamespacesRead = func(b *SystemBackend) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { - // Short-circuit here if there's no client token provided - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - // Load the ACL policies so we can check for access and filter namespaces - _, te, entity, _, err := b.Core.fetchACLTokenEntryAndEntity(ctx, req) - if err != nil { - return nil, err - } - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return nil, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - - return logical.ListResponse([]string{""}), nil - } - } - - pathLicenseRead = func(b *SystemBackend) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return nil, nil - } - } - - pathLicenseUpdate = func(b *SystemBackend) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return nil, nil - } - } - - entPaths = func(b *SystemBackend) []*framework.Path { - return []*framework.Path{ - { - Pattern: "replication/status", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - resp := &logical.Response{ - Data: map[string]interface{}{ - "mode": "disabled", - }, - } - return resp, nil - }, - }, - }, - } - } -) - -// tuneMount is used to set config on a mount point -func (b *SystemBackend) tuneMountTTLs(ctx context.Context, path string, me *MountEntry, newDefault, newMax time.Duration) error { - zero := time.Duration(0) - - switch { - case newDefault == zero && newMax == zero: - // No checks needed - - case newDefault == zero && newMax != zero: - // No default/max conflict, no checks needed - - case newDefault != zero && newMax == zero: - // No default/max conflict, no checks needed - - case newDefault != zero && newMax != zero: - if newMax < newDefault { - return fmt.Errorf("backend max lease TTL of %d would be less than backend default lease TTL of %d", int(newMax.Seconds()), int(newDefault.Seconds())) - } - } - - origMax := me.Config.MaxLeaseTTL - origDefault := me.Config.DefaultLeaseTTL - - me.Config.MaxLeaseTTL = newMax - me.Config.DefaultLeaseTTL = newDefault - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, credentialRoutePrefix): - err = b.Core.persistAuth(ctx, b.Core.auth, &me.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &me.Local) - } - if err != nil { - me.Config.MaxLeaseTTL = origMax - me.Config.DefaultLeaseTTL = origDefault - return fmt.Errorf("failed to update mount table, rolling back TTL changes") - } - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of leases successful", "path", path) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/logical_system_paths.go b/vendor/github.com/hashicorp/vault/vault/logical_system_paths.go deleted file mode 100644 index 366f8353..00000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_system_paths.go +++ /dev/null @@ -1,1515 +0,0 @@ -package vault - -import ( - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *SystemBackend) configPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "config/cors$", - - Fields: map[string]*framework.FieldSchema{ - "enable": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Enables or disables CORS headers on requests.", - }, - "allowed_origins": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "A comma-separated string or array of strings indicating origins that may make cross-origin requests.", - }, - "allowed_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "A comma-separated string or array of strings indicating headers that are allowed on cross-origin requests.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleCORSRead, - Summary: "Return the current CORS settings.", - Description: "", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleCORSUpdate, - Summary: "Configure the CORS settings.", - Description: "", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleCORSDelete, - Summary: "Remove any CORS settings.", - }, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/cors"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/cors"][1]), - }, - - { - Pattern: "config/ui/headers/" + framework.GenericNameRegex("header"), - - Fields: map[string]*framework.FieldSchema{ - "header": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The name of the header.", - }, - "values": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: "The values to set the header.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleConfigUIHeadersRead, - Summary: "Return the given UI header's configuration", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleConfigUIHeadersUpdate, - Summary: "Configure the values to be returned for the UI header.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleConfigUIHeadersDelete, - Summary: "Remove a UI header.", - }, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/ui/headers"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/ui/headers"][1]), - }, - - { - Pattern: "config/ui/headers/$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ListOperation: &framework.PathOperation{ - Callback: b.handleConfigUIHeadersList, - Summary: "Return a list of configured UI headers.", - }, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/ui/headers"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/ui/headers"][1]), - }, - - { - Pattern: "generate-root(/attempt)?$", - Fields: map[string]*framework.FieldSchema{ - "pgp_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a base64-encoded PGP public key.", - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Read the configuration and progress of the current root generation attempt.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Initializes a new root generation attempt.", - Description: "Only a single root generation attempt can take place at a time. One (and only one) of otp or pgp_key are required.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Summary: "Cancels any in-progress root generation attempt.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["generate-root"][0]), - HelpDescription: strings.TrimSpace(sysHelp["generate-root"][1]), - }, - { - Pattern: "generate-root/update$", - Fields: map[string]*framework.FieldSchema{ - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a single master key share.", - }, - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies the nonce of the attempt.", - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Enter a single master key share to progress the root generation attempt.", - Description: "If the threshold number of master key shares is reached, Vault will complete the root generation and issue the new token. Otherwise, this API must be called multiple times until that threshold is met. The attempt nonce must be provided with each call.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["generate-root"][0]), - HelpDescription: strings.TrimSpace(sysHelp["generate-root"][1]), - }, - { - Pattern: "health$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Returns the health status of Vault.", - Responses: map[int][]framework.Response{ - 200: {{Description: "initialized, unsealed, and active"}}, - 429: {{Description: "unsealed and standby"}}, - 472: {{Description: "data recovery mode replication secondary and active"}}, - 501: {{Description: "not initialized"}}, - 503: {{Description: "sealed"}}, - }, - }, - }, - }, - - { - Pattern: "init$", - Fields: map[string]*framework.FieldSchema{ - "pgp_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Specifies an array of PGP public keys used to encrypt the output unseal keys. Ordering is preserved. The keys must be base64-encoded from their original binary representation. The size of this array must be the same as `secret_shares`.", - }, - "root_token_pgp_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a PGP public key used to encrypt the initial root token. The key must be base64-encoded from its original binary representation.", - }, - "secret_shares": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares to split the master key into.", - }, - "secret_threshold": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares required to reconstruct the master key. This must be less than or equal secret_shares. If using Vault HSM with auto-unsealing, this value must be the same as `secret_shares`.", - }, - "stored_shares": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares that should be encrypted by the HSM and stored for auto-unsealing. Currently must be the same as `secret_shares`.", - }, - "recovery_shares": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares to split the recovery key into.", - }, - "recovery_threshold": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: " Specifies the number of shares required to reconstruct the recovery key. This must be less than or equal to `recovery_shares`.", - }, - "recovery_pgp_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Specifies an array of PGP public keys used to encrypt the output recovery keys. Ordering is preserved. The keys must be base64-encoded from their original binary representation. The size of this array must be the same as `recovery_shares`.", - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Returns the initialization status of Vault.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Initialize a new Vault.", - Description: "The Vault must not have been previously initialized. The recovery options, as well as the stored shares option, are only available when using Vault HSM.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["init"][0]), - HelpDescription: strings.TrimSpace(sysHelp["init"][1]), - }, - { - Pattern: "leader$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Returns the high availability status and current leader instance of Vault.", - }, - }, - - HelpSynopsis: "Check the high availability status and current leader of Vault", - }, - { - Pattern: "step-down$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Cause the node to give up active status.", - Description: "This endpoint forces the node to give up active status. If the node does not have active status, this endpoint does nothing. Note that the node will sleep for ten seconds before attempting to grab the active lock again, but if no standby nodes grab the active lock in the interim, the same node may become the active node again.", - Responses: map[int][]framework.Response{ - 204: {{Description: "empty body"}}, - }, - }, - }, - }, - } -} - -func (b *SystemBackend) rekeyPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "rekey/init", - - Fields: map[string]*framework.FieldSchema{ - "secret_shares": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares to split the master key into.", - }, - "secret_threshold": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Specifies the number of shares required to reconstruct the master key. This must be less than or equal secret_shares. If using Vault HSM with auto-unsealing, this value must be the same as secret_shares.", - }, - "pgp_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Specifies an array of PGP public keys used to encrypt the output unseal keys. Ordering is preserved. The keys must be base64-encoded from their original binary representation. The size of this array must be the same as secret_shares.", - }, - "backup": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Specifies if using PGP-encrypted keys, whether Vault should also store a plaintext backup of the PGP-encrypted keys.", - }, - "require_verification": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Turns on verification functionality", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Reads the configuration and progress of the current rekey attempt.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Initializes a new rekey attempt.", - Description: "Only a single rekey attempt can take place at a time, and changing the parameters of a rekey requires canceling and starting a new rekey, which will also provide a new nonce.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Summary: "Cancels any in-progress rekey.", - Description: "This clears the rekey settings as well as any progress made. This must be called to change the parameters of the rekey. Note: verification is still a part of a rekey. If rekeying is canceled during the verification flow, the current unseal keys remain valid.", - }, - }, - }, - { - Pattern: "rekey/backup$", - - Fields: map[string]*framework.FieldSchema{}, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleRekeyRetrieveBarrier, - Summary: "Return the backup copy of PGP-encrypted unseal keys.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleRekeyDeleteBarrier, - Summary: "Delete the backup copy of PGP-encrypted unseal keys.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rekey_backup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rekey_backup"][0]), - }, - - { - Pattern: "rekey/recovery-key-backup$", - - Fields: map[string]*framework.FieldSchema{}, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRekeyRetrieveRecovery, - logical.DeleteOperation: b.handleRekeyDeleteRecovery, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rekey_backup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rekey_backup"][0]), - }, - { - Pattern: "rekey/update", - - Fields: map[string]*framework.FieldSchema{ - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a single master key share.", - }, - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies the nonce of the rekey attempt.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Enter a single master key share to progress the rekey of the Vault.", - }, - }, - }, - { - Pattern: "rekey/verify", - - Fields: map[string]*framework.FieldSchema{ - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a single master share key from the new set of shares.", - }, - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies the nonce of the rekey verification operation.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Read the configuration and progress of the current rekey verification attempt.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Summary: "Cancel any in-progress rekey verification operation.", - Description: "This clears any progress made and resets the nonce. Unlike a `DELETE` against `sys/rekey/init`, this only resets the current verification operation, not the entire rekey atttempt.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Enter a single new key share to progress the rekey verification operation.", - }, - }, - }, - - { - Pattern: "seal-status$", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Summary: "Check the seal status of a Vault.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["seal-status"][0]), - HelpDescription: strings.TrimSpace(sysHelp["seal-status"][1]), - }, - - { - Pattern: "seal$", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Seal the Vault.", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["seal"][0]), - HelpDescription: strings.TrimSpace(sysHelp["seal"][1]), - }, - - { - Pattern: "unseal$", - Fields: map[string]*framework.FieldSchema{ - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Specifies a single master key share. This is required unless reset is true.", - }, - "reset": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Specifies if previously-provided unseal keys are discarded and the unseal process is reset.", - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Summary: "Unseal the Vault.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["unseal"][0]), - HelpDescription: strings.TrimSpace(sysHelp["unseal"][1]), - }, - } -} - -func (b *SystemBackend) auditPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "audit-hash/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_path"][0]), - }, - - "input": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleAuditHash, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit-hash"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit-hash"][1]), - }, - - { - Pattern: "audit$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleAuditTable, - Summary: "List the enabled audit devices.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit-table"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit-table"][1]), - }, - - { - Pattern: "audit/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_desc"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["audit_opts"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleEnableAudit, - Summary: "Enable a new audit device at the supplied path.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleDisableAudit, - Summary: "Disable the audit device at the given path.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit"][1]), - }, - - { - Pattern: "config/auditing/request-headers/(?P
.+)", - - Fields: map[string]*framework.FieldSchema{ - "header": &framework.FieldSchema{ - Type: framework.TypeString, - }, - "hmac": &framework.FieldSchema{ - Type: framework.TypeBool, - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleAuditedHeaderUpdate, - Summary: "Enable auditing of a header.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleAuditedHeaderDelete, - Summary: "Disable auditing of the given request header.", - }, - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleAuditedHeaderRead, - Summary: "List the information for the given request header.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audited-headers-name"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audited-headers-name"][1]), - }, - - { - Pattern: "config/auditing/request-headers$", - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleAuditedHeadersRead, - Summary: "List the request headers that are configured to be audited.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audited-headers"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audited-headers"][1]), - }, - } -} - -func (b *SystemBackend) sealPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "key-status$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleKeyStatus, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["key-status"][0]), - HelpDescription: strings.TrimSpace(sysHelp["key-status"][1]), - }, - - { - Pattern: "rotate$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRotate, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rotate"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rotate"][1]), - }, - } -} - -func (b *SystemBackend) pluginsCatalogCRUDPath() *framework.Path { - return &framework.Path{ - Pattern: "plugins/catalog(/(?Pauth|database|secret))?/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_name"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_type"][0]), - }, - "sha256": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_sha-256"][0]), - }, - "sha_256": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_sha-256"][0]), - }, - "command": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_command"][0]), - }, - "args": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: strings.TrimSpace(sysHelp["plugin-catalog_args"][0]), - }, - "env": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: strings.TrimSpace(sysHelp["plugin-catalog_env"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handlePluginCatalogUpdate, - Summary: "Register a new plugin, or updates an existing one with the supplied name.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handlePluginCatalogDelete, - Summary: "Remove the plugin with the given name.", - }, - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handlePluginCatalogRead, - Summary: "Return the configuration data for the plugin with the given name.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-catalog"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-catalog"][1]), - } -} - -func (b *SystemBackend) pluginsCatalogListPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "plugins/catalog/(?Pauth|database|secret)/?$", - - Fields: map[string]*framework.FieldSchema{ - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_type"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ListOperation: &framework.PathOperation{ - Callback: b.handlePluginCatalogTypedList, - Summary: "List the plugins in the catalog.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-catalog"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-catalog"][1]), - }, - { - Pattern: "plugins/catalog/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handlePluginCatalogUntypedList, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-catalog-list-all"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-catalog-list-all"][1]), - }, - } -} - -func (b *SystemBackend) pluginsReloadPath() *framework.Path { - return &framework.Path{ - Pattern: "plugins/reload/backend$", - - Fields: map[string]*framework.FieldSchema{ - "plugin": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-backend-reload-plugin"][0]), - }, - "mounts": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["plugin-backend-reload-mounts"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handlePluginReloadUpdate, - Summary: "Reload mounted plugin backends.", - Description: "Either the plugin name (`plugin`) or the desired plugin backend mounts (`mounts`) must be provided, but not both. In the case that the plugin name is provided, all mounted paths that use that plugin backend will be reloaded.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-reload"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-reload"][1]), - } -} - -func (b *SystemBackend) toolsPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "tools/hash" + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data", - }, - - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Algorithm to use (POST body parameter). Valid values are: - - * sha2-224 - * sha2-256 - * sha2-384 - * sha2-512 - - Defaults to "sha2-256".`, - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Algorithm to use (POST URL parameter)`, - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "hex", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "hex".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathHashWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["hash"][0]), - HelpDescription: strings.TrimSpace(sysHelp["hash"][1]), - }, - - { - Pattern: "tools/random" + framework.OptionalParamRegex("urlbytes"), - Fields: map[string]*framework.FieldSchema{ - "urlbytes": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The number of bytes to generate (POST URL parameter)", - }, - - "bytes": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 32, - Description: "The number of bytes to generate (POST body parameter). Defaults to 32 (256 bits).", - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "base64", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "base64".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRandomWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["random"][0]), - HelpDescription: strings.TrimSpace(sysHelp["random"][1]), - }, - } -} - -func (b *SystemBackend) internalPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "internal/specs/openapi", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathInternalOpenAPI, - }, - }, - { - Pattern: "internal/specs/openapi", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.pathInternalOpenAPI, - Summary: "Generate an OpenAPI 3 document of all mounted paths.", - }, - }, - }, - { - Pattern: "internal/ui/mounts", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.pathInternalUIMountsRead, - Summary: "Lists all enabled and visible auth and secrets mounts.", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-mounts"][1]), - }, - { - Pattern: "internal/ui/mounts/(?P.+)", - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The path of the mount.", - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.pathInternalUIMountRead, - Summary: "Return information about the given mount.", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-mounts"][1]), - }, - { - Pattern: "internal/ui/namespaces", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: pathInternalUINamespacesRead(b), - Unpublished: true, - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-namespaces"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-namespaces"][1]), - }, - { - Pattern: "internal/ui/resultant-acl", - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.pathInternalUIResultantACL, - Unpublished: true, - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-resultant-acl"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-resultant-acl"][1]), - }, - } -} - -func (b *SystemBackend) capabilitiesPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "capabilities-accessor$", - - Fields: map[string]*framework.FieldSchema{ - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - Deprecated: true, - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilitiesAccessor, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities_accessor"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities_accessor"][1]), - }, - - { - Pattern: "capabilities$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - Deprecated: true, - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilities, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities"][1]), - }, - - { - Pattern: "capabilities-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - Deprecated: true, - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilities, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities_self"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities_self"][1]), - }, - } -} - -func (b *SystemBackend) leasePaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "leases/lookup/(?P.+?)?", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["leases-list-prefix"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ListOperation: &framework.PathOperation{ - Callback: b.handleLeaseLookupList, - Summary: "Returns a list of lease ids.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["leases"][1]), - }, - - { - Pattern: "leases/lookup", - - Fields: map[string]*framework.FieldSchema{ - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleLeaseLookup, - Summary: "Retrieve lease metadata.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["leases"][1]), - }, - - { - Pattern: "(leases/)?renew" + framework.OptionalParamRegex("url_lease_id"), - - Fields: map[string]*framework.FieldSchema{ - "url_lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: strings.TrimSpace(sysHelp["increment"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleRenew, - Summary: "Renews a lease, requesting to extend the lease.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["renew"][0]), - HelpDescription: strings.TrimSpace(sysHelp["renew"][1]), - }, - - { - Pattern: "(leases/)?revoke" + framework.OptionalParamRegex("url_lease_id"), - - Fields: map[string]*framework.FieldSchema{ - "url_lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "sync": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: strings.TrimSpace(sysHelp["revoke-sync"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleRevoke, - Summary: "Revokes a lease immediately.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke"][1]), - }, - - { - Pattern: "(leases/)?revoke-force/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["revoke-force-path"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleRevokeForce, - Summary: "Revokes all secrets or tokens generated under a given prefix immediately", - Description: "Unlike `/sys/leases/revoke-prefix`, this path ignores backend errors encountered during revocation. This is potentially very dangerous and should only be used in specific emergency situations where errors in the backend or the connected backend service prevent normal revocation.\n\nBy ignoring these errors, Vault abdicates responsibility for ensuring that the issued credentials or secrets are properly revoked and/or cleaned up. Access to this endpoint should be tightly controlled.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke-force"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke-force"][1]), - }, - - { - Pattern: "(leases/)?revoke-prefix/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["revoke-prefix-path"][0]), - }, - "sync": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: strings.TrimSpace(sysHelp["revoke-sync"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleRevokePrefix, - Summary: "Revokes all secrets (via a lease ID prefix) or tokens (via the tokens' path property) generated under a given prefix immediately.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke-prefix"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke-prefix"][1]), - }, - - { - Pattern: "leases/tidy$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleTidyLeases, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["tidy_leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["tidy_leases"][1]), - }, - } -} - -func (b *SystemBackend) remountPath() *framework.Path { - return &framework.Path{ - Pattern: "remount", - - Fields: map[string]*framework.FieldSchema{ - "from": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The previous mount point.", - }, - "to": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The new mount point.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRemount, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["remount"][0]), - HelpDescription: strings.TrimSpace(sysHelp["remount"][1]), - } -} - -func (b *SystemBackend) authPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "auth$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleAuthTable, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["auth-table"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth-table"][1]), - }, - { - Pattern: "auth/(?P.+?)/tune$", - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_tune"][0]), - }, - "default_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_default_lease_ttl"][0]), - }, - "max_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_max_lease_ttl"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "audit_non_hmac_request_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_request_keys"][0]), - }, - "audit_non_hmac_response_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_response_keys"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["tune_mount_options"][0]), - }, - "listing_visibility": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["listing_visibility"][0]), - }, - "passthrough_request_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["passthrough_request_headers"][0]), - }, - "token_type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["token_type"][0]), - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleAuthTuneRead, - Summary: "Reads the given auth path's configuration.", - Description: "This endpoint requires sudo capability on the final path, but the same functionality can be achieved without sudo via `sys/mounts/auth/[auth-path]/tune`.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleAuthTuneWrite, - Summary: "Tune configuration parameters for a given auth path.", - Description: "This endpoint requires sudo capability on the final path, but the same functionality can be achieved without sudo via `sys/mounts/auth/[auth-path]/tune`.", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["auth_tune"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth_tune"][1]), - }, - { - Pattern: "auth/(?P.+)", - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "config": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: strings.TrimSpace(sysHelp["auth_config"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - "seal_wrap": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["seal_wrap"][0]), - }, - "plugin_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_plugin"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["auth_options"][0]), - }, - }, - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleEnableAuth, - Summary: "Enables a new auth method.", - Description: `After enabling, the auth method can be accessed and configured via the auth path specified as part of the URL. This auth path will be nested under the auth prefix. - -For example, enable the "foo" auth method will make it accessible at /auth/foo.`, - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleDisableAuth, - Summary: "Disable the auth method at the given auth path", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["auth"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth"][1]), - }, - } -} - -func (b *SystemBackend) policyPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "policy/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handlePoliciesList(PolicyTypeACL), - logical.ListOperation: b.handlePoliciesList(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy-list"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy-list"][1]), - }, - - { - Pattern: "policy/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-name"][0]), - }, - "rules": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - Deprecated: true, - }, - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handlePoliciesRead(PolicyTypeACL), - Summary: "Retrieve the policy body for the named policy.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handlePoliciesSet(PolicyTypeACL), - Summary: "Add a new or update an existing policy.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handlePoliciesDelete(PolicyTypeACL), - Summary: "Delete the policy with the given name.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy"][1]), - }, - - { - Pattern: "policies/acl/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.handlePoliciesList(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy-list"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy-list"][1]), - }, - - { - Pattern: "policies/acl/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-name"][0]), - }, - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handlePoliciesRead(PolicyTypeACL), - Summary: "Retrieve information about the named ACL policy.", - }, - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handlePoliciesSet(PolicyTypeACL), - Summary: "Add a new or update an existing ACL policy.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handlePoliciesDelete(PolicyTypeACL), - Summary: "Delete the ACL policy with the given name.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy"][1]), - }, - } -} - -func (b *SystemBackend) wrappingPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "wrapping/wrap$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingWrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["wrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["wrap"][1]), - }, - - { - Pattern: "wrapping/unwrap$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingUnwrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["unwrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["unwrap"][1]), - }, - - { - Pattern: "wrapping/lookup$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleWrappingLookup, - Summary: "Look up wrapping properties for the given token.", - }, - logical.ReadOperation: &framework.PathOperation{ - Callback: b.handleWrappingLookup, - Summary: "Look up wrapping properties for the requester's token.", - }, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["wraplookup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["wraplookup"][1]), - }, - - { - Pattern: "wrapping/rewrap$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingRewrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rewrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rewrap"][1]), - }, - } -} - -func (b *SystemBackend) mountPaths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "mounts/(?P.+?)/tune$", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_path"][0]), - }, - "default_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_default_lease_ttl"][0]), - }, - "max_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_max_lease_ttl"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "audit_non_hmac_request_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_request_keys"][0]), - }, - "audit_non_hmac_response_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_response_keys"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["tune_mount_options"][0]), - }, - "listing_visibility": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["listing_visibility"][0]), - }, - "passthrough_request_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["passthrough_request_headers"][0]), - }, - "token_type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["token_type"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleMountTuneRead, - logical.UpdateOperation: b.handleMountTuneWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["mount_tune"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mount_tune"][1]), - }, - - { - Pattern: "mounts/(?P.+?)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_desc"][0]), - }, - "config": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: strings.TrimSpace(sysHelp["mount_config"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - "seal_wrap": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["seal_wrap"][0]), - }, - "plugin_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_plugin_name"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["mount_options"][0]), - }, - }, - - Operations: map[logical.Operation]framework.OperationHandler{ - logical.UpdateOperation: &framework.PathOperation{ - Callback: b.handleMount, - Summary: "Enable a new secrets engine at the given path.", - }, - logical.DeleteOperation: &framework.PathOperation{ - Callback: b.handleUnmount, - Summary: "Disable the mount point specified at the given path.", - }, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["mount"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mount"][1]), - }, - - { - Pattern: "mounts$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleMountTable, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mounts"][1]), - }, - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/mount.go b/vendor/github.com/hashicorp/vault/vault/mount.go deleted file mode 100644 index fd9905e3..00000000 --- a/vendor/github.com/hashicorp/vault/vault/mount.go +++ /dev/null @@ -1,1343 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "os" - "sort" - "strings" - "sync" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/builtin/plugin" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -const ( - // coreMountConfigPath is used to store the mount configuration. - // Mounts are protected within the Vault itself, which means they - // can only be viewed or modified after an unseal. - coreMountConfigPath = "core/mounts" - - // coreLocalMountConfigPath is used to store mount configuration for local - // (non-replicated) mounts - coreLocalMountConfigPath = "core/local-mounts" - - // backendBarrierPrefix is the prefix to the UUID used in the - // barrier view for the backends. - backendBarrierPrefix = "logical/" - - // systemBarrierPrefix is the prefix used for the - // system logical backend. - systemBarrierPrefix = "sys/" - - // mountTableType is the value we expect to find for the mount table and - // corresponding entries - mountTableType = "mounts" -) - -// ListingVisibilityType represents the types for listing visibility -type ListingVisibilityType string - -const ( - // ListingVisibilityDefault is the default value for listing visibility - ListingVisibilityDefault ListingVisibilityType = "" - // ListingVisibilityHidden is the hidden type for listing visibility - ListingVisibilityHidden ListingVisibilityType = "hidden" - // ListingVisibilityUnauth is the unauth type for listing visibility - ListingVisibilityUnauth ListingVisibilityType = "unauth" - - systemMountPath = "sys/" - identityMountPath = "identity/" - cubbyholeMountPath = "cubbyhole/" - - systemMountType = "system" - identityMountType = "identity" - cubbyholeMountType = "cubbyhole" - pluginMountType = "plugin" - - MountTableUpdateStorage = true - MountTableNoUpdateStorage = false -) - -var ( - // loadMountsFailed if loadMounts encounters an error - errLoadMountsFailed = errors.New("failed to setup mount table") - - // protectedMounts cannot be remounted - protectedMounts = []string{ - "audit/", - "auth/", - systemMountPath, - cubbyholeMountPath, - identityMountPath, - } - - untunableMounts = []string{ - cubbyholeMountPath, - systemMountPath, - "audit/", - identityMountPath, - } - - // singletonMounts can only exist in one location and are - // loaded by default. These are types, not paths. - singletonMounts = []string{ - cubbyholeMountType, - systemMountType, - "token", - identityMountType, - } - - // mountAliases maps old backend names to new backend names, allowing us - // to move/rename backends but maintain backwards compatibility - mountAliases = map[string]string{"generic": "kv"} -) - -func (c *Core) generateMountAccessor(entryType string) (string, error) { - var accessor string - for { - randBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - return "", err - } - accessor = fmt.Sprintf("%s_%s", entryType, fmt.Sprintf("%08x", randBytes[0:4])) - if entry := c.router.MatchingMountByAccessor(accessor); entry == nil { - break - } - } - - return accessor, nil -} - -// MountTable is used to represent the internal mount table -type MountTable struct { - Type string `json:"type"` - Entries []*MountEntry `json:"entries"` -} - -// shallowClone returns a copy of the mount table that -// keeps the MountEntry locations, so as not to invalidate -// other locations holding pointers. Care needs to be taken -// if modifying entries rather than modifying the table itself -func (t *MountTable) shallowClone() *MountTable { - mt := &MountTable{ - Type: t.Type, - Entries: make([]*MountEntry, len(t.Entries)), - } - for i, e := range t.Entries { - mt.Entries[i] = e - } - return mt -} - -// setTaint is used to set the taint on given entry Accepts either the mount -// entry's path or namespace + path, i.e. /secret/ or /token/ -func (t *MountTable) setTaint(ctx context.Context, path string, value bool) (*MountEntry, error) { - n := len(t.Entries) - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - for i := 0; i < n; i++ { - if entry := t.Entries[i]; entry.Path == path && entry.Namespace().ID == ns.ID { - t.Entries[i].Tainted = value - return t.Entries[i], nil - } - } - return nil, nil -} - -// remove is used to remove a given path entry; returns the entry that was -// removed -func (t *MountTable) remove(ctx context.Context, path string) (*MountEntry, error) { - n := len(t.Entries) - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - for i := 0; i < n; i++ { - if entry := t.Entries[i]; entry.Path == path && entry.Namespace().ID == ns.ID { - t.Entries[i], t.Entries[n-1] = t.Entries[n-1], nil - t.Entries = t.Entries[:n-1] - return entry, nil - } - } - return nil, nil -} - -// sortEntriesByPath sorts the entries in the table by path and returns the -// table; this is useful for tests -func (t *MountTable) sortEntriesByPath() *MountTable { - sort.Slice(t.Entries, func(i, j int) bool { - return t.Entries[i].Path < t.Entries[j].Path - }) - return t -} - -// sortEntriesByPath sorts the entries in the table by path and returns the -// table; this is useful for tests -func (t *MountTable) sortEntriesByPathDepth() *MountTable { - sort.Slice(t.Entries, func(i, j int) bool { - return len(strings.Split(t.Entries[i].Namespace().Path+t.Entries[i].Path, "/")) < len(strings.Split(t.Entries[j].Namespace().Path+t.Entries[j].Path, "/")) - }) - return t -} - -// MountEntry is used to represent a mount table entry -type MountEntry struct { - Table string `json:"table"` // The table it belongs to - Path string `json:"path"` // Mount Path - Type string `json:"type"` // Logical backend Type - Description string `json:"description"` // User-provided description - UUID string `json:"uuid"` // Barrier view UUID - BackendAwareUUID string `json:"backend_aware_uuid"` // UUID that can be used by the backend as a helper when a consistent value is needed outside of storage. - Accessor string `json:"accessor"` // Unique but more human-friendly ID. Does not change, not used for any sensitive things (like as a salt, which the UUID sometimes is). - Config MountConfig `json:"config"` // Configuration related to this mount (but not backend-derived) - Options map[string]string `json:"options"` // Backend options - Local bool `json:"local"` // Local mounts are not replicated or affected by replication - SealWrap bool `json:"seal_wrap"` // Whether to wrap CSPs - Tainted bool `json:"tainted,omitempty"` // Set as a Write-Ahead flag for unmount/remount - NamespaceID string `json:"namespace_id"` - - // namespace contains the populated namespace - namespace *namespace.Namespace - - // synthesizedConfigCache is used to cache configuration values. These - // particular values are cached since we want to get them at a point-in-time - // without separately managing their locks individually. See SyncCache() for - // the specific values that are being cached. - synthesizedConfigCache sync.Map -} - -// MountConfig is used to hold settable options -type MountConfig struct { - DefaultLeaseTTL time.Duration `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` // Override for global default - MaxLeaseTTL time.Duration `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` // Override for global default - ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` // Override for global default - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"` - TokenType logical.TokenType `json:"token_type" structs:"token_type" mapstructure:"token_type"` - - // PluginName is the name of the plugin registered in the catalog. - // - // Deprecated: MountEntry.Type should be used instead for Vault 1.0.0 and beyond. - PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"` -} - -// APIMountConfig is an embedded struct of api.MountConfigInput -type APIMountConfig struct { - DefaultLeaseTTL string `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL string `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"` - TokenType string `json:"token_type" structs:"token_type" mapstructure:"token_type"` - - // PluginName is the name of the plugin registered in the catalog. - // - // Deprecated: MountEntry.Type should be used instead for Vault 1.0.0 and beyond. - PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"` -} - -// Clone returns a deep copy of the mount entry -func (e *MountEntry) Clone() (*MountEntry, error) { - cp, err := copystructure.Copy(e) - if err != nil { - return nil, err - } - return cp.(*MountEntry), nil -} - -// Namespace returns the namespace for the mount entry -func (e *MountEntry) Namespace() *namespace.Namespace { - return e.namespace -} - -// APIPath returns the full API Path for the given mount entry -func (e *MountEntry) APIPath() string { - path := e.Path - if e.Table == credentialTableType { - path = credentialRoutePrefix + path - } - return e.namespace.Path + path -} - -// SyncCache syncs tunable configuration values to the cache. In the case of -// cached values, they should be retrieved via synthesizedConfigCache.Load() -// instead of accessing them directly through MountConfig. -func (e *MountEntry) SyncCache() { - if len(e.Config.AuditNonHMACRequestKeys) == 0 { - e.synthesizedConfigCache.Delete("audit_non_hmac_request_keys") - } else { - e.synthesizedConfigCache.Store("audit_non_hmac_request_keys", e.Config.AuditNonHMACRequestKeys) - } - - if len(e.Config.AuditNonHMACResponseKeys) == 0 { - e.synthesizedConfigCache.Delete("audit_non_hmac_response_keys") - } else { - e.synthesizedConfigCache.Store("audit_non_hmac_response_keys", e.Config.AuditNonHMACResponseKeys) - } - - if len(e.Config.PassthroughRequestHeaders) == 0 { - e.synthesizedConfigCache.Delete("passthrough_request_headers") - } else { - e.synthesizedConfigCache.Store("passthrough_request_headers", e.Config.PassthroughRequestHeaders) - } -} - -func (c *Core) decodeMountTable(ctx context.Context, raw []byte) (*MountTable, error) { - // Decode into mount table - mountTable := new(MountTable) - if err := jsonutil.DecodeJSON(raw, mountTable); err != nil { - return nil, err - } - - // Populate the namespace in memory - var mountEntries []*MountEntry - for _, entry := range mountTable.Entries { - if entry.NamespaceID == "" { - entry.NamespaceID = namespace.RootNamespaceID - } - ns, err := NamespaceByID(ctx, entry.NamespaceID, c) - if err != nil { - return nil, err - } - if ns == nil { - c.logger.Error("namespace on mount entry not found", "namespace_id", entry.NamespaceID, "mount_path", entry.Path, "mount_description", entry.Description) - continue - } - - entry.namespace = ns - mountEntries = append(mountEntries, entry) - } - - return &MountTable{ - Type: mountTable.Type, - Entries: mountEntries, - }, nil -} - -// Mount is used to mount a new backend to the mount table. -func (c *Core) mount(ctx context.Context, entry *MountEntry) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Prevent protected paths from being mounted - for _, p := range protectedMounts { - if strings.HasPrefix(entry.Path, p) && entry.namespace == nil { - return logical.CodedError(403, fmt.Sprintf("cannot mount %q", entry.Path)) - } - } - - // Do not allow more than one instance of a singleton mount - for _, p := range singletonMounts { - if entry.Type == p { - return logical.CodedError(403, fmt.Sprintf("mount type of %q is not mountable", entry.Type)) - } - } - return c.mountInternal(ctx, entry, MountTableUpdateStorage) -} - -func (c *Core) mountInternal(ctx context.Context, entry *MountEntry, updateStorage bool) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - if err := verifyNamespace(c, ns, entry); err != nil { - return err - } - - entry.NamespaceID = ns.ID - entry.namespace = ns - - // Ensure the cache is populated, don't need the result - NamespaceByID(ctx, ns.ID, c) - - // Verify there are no conflicting mounts - if match := c.router.MountConflict(ctx, entry.Path); match != "" { - return logical.CodedError(409, fmt.Sprintf("existing mount at %s", match)) - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor(entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - // Sync values to the cache - entry.SyncCache() - - viewPath := entry.ViewPath() - view := NewBarrierView(c.barrier, viewPath) - - // Singleton mounts cannot be filtered on a per-secondary basis - // from replication - if strutil.StrListContains(singletonMounts, entry.Type) { - addFilterablePath(c, viewPath) - } - - nilMount, err := preprocessMount(c, entry, view) - if err != nil { - return err - } - origReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - // We defer this because we're already up and running so we don't need to - // time it for after postUnseal - defer view.setReadOnlyErr(origReadOnlyErr) - - var backend logical.Backend - sysView := c.mountEntrySysView(entry) - - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend of type %q returned from creation function", entry.Type) - } - - // Check for the correct backend type - backendType := backend.Type() - if backendType != logical.TypeLogical { - if entry.Type != "kv" && entry.Type != "system" && entry.Type != "cubbyhole" { - return fmt.Errorf(`unknown backend type: "%s"`, entry.Type) - } - } - - addPathCheckers(c, entry, backend, viewPath) - - c.setCoreBackend(entry, backend, view) - - // If the mount is filtered or we are on a DR secondary we don't want to - // keep the actual backend running, so we clean it up and set it to nil - // so the router does not have a pointer to the object. - if nilMount { - backend.Cleanup(ctx) - backend = nil - } - - newTable := c.mounts.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - if updateStorage { - if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil { - c.logger.Error("failed to update mount table", "error", err) - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - - return logical.CodedError(500, "failed to update mount table") - } - } - c.mounts = newTable - - if err := c.router.Mount(backend, entry.Path, entry, view); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("successful mount", "namespace", entry.Namespace().Path, "path", entry.Path, "type", entry.Type) - } - return nil -} - -// Unmount is used to unmount a path. The boolean indicates whether the mount -// was found. -func (c *Core) unmount(ctx context.Context, path string) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Prevent protected paths from being unmounted - for _, p := range protectedMounts { - if strings.HasPrefix(path, p) { - return fmt.Errorf("cannot unmount %q", path) - } - } - return c.unmountInternal(ctx, path, MountTableUpdateStorage) -} - -func (c *Core) unmountInternal(ctx context.Context, path string, updateStorage bool) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - // Verify exact match of the route - match := c.router.MatchingMount(ctx, path) - if match == "" || ns.Path+path != match { - return fmt.Errorf("no matching mount") - } - - // Get the view for this backend - view := c.router.MatchingStorageByAPIPath(ctx, path) - - // Get the backend/mount entry for this path, used to remove ignored - // replication prefixes - backend := c.router.MatchingBackend(ctx, path) - entry := c.router.MatchingMountEntry(ctx, path) - - // Mark the entry as tainted - if err := c.taintMountEntry(ctx, path, updateStorage); err != nil { - c.logger.Error("failed to taint mount entry for path being unmounted", "error", err, "path", path) - return err - } - - // Taint the router path to prevent routing. Note that in-flight requests - // are uncertain, right now. - if err := c.router.Taint(ctx, path); err != nil { - return err - } - - rCtx := namespace.ContextWithNamespace(c.activeContext, ns) - if backend != nil && c.rollback != nil { - // Invoke the rollback manager a final time - if err := c.rollback.Rollback(rCtx, path); err != nil { - return err - } - } - if backend != nil && c.expiration != nil && updateStorage { - // Revoke all the dynamic keys - if err := c.expiration.RevokePrefix(rCtx, path, true); err != nil { - return err - } - } - - if backend != nil { - // Call cleanup function if it exists - backend.Cleanup(ctx) - } - - // Unmount the backend entirely - if err := c.router.Unmount(ctx, path); err != nil { - return err - } - - viewPath := entry.ViewPath() - switch { - case !updateStorage: - // Don't attempt to clear data, replication will handle this - case c.IsDRSecondary(), entry.Local, !c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - // Have writable storage, remove the whole thing - if err := logical.ClearView(ctx, view); err != nil { - c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path) - return err - } - - case !entry.Local && c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - if err := clearIgnoredPaths(ctx, c, backend, viewPath); err != nil { - return err - } - } - // Remove the mount table entry - if err := c.removeMountEntry(ctx, path, updateStorage); err != nil { - c.logger.Error("failed to remove mount entry for path being unmounted", "error", err, "path", path) - return err - } - - removePathCheckers(c, entry, viewPath) - - if c.logger.IsInfo() { - c.logger.Info("successfully unmounted", "path", path, "namespace", ns.Path) - } - - return nil -} - -// removeMountEntry is used to remove an entry from the mount table -func (c *Core) removeMountEntry(ctx context.Context, path string, updateStorage bool) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // Remove the entry from the mount table - newTable := c.mounts.shallowClone() - entry, err := newTable.remove(ctx, path) - if err != nil { - return err - } - if entry == nil { - c.logger.Error("nil entry found removing entry in mounts table", "path", path) - return logical.CodedError(500, "failed to remove entry in mounts table") - } - - // When unmounting all entries the JSON code will load back up from storage - // as a nil slice, which kills tests...just set it nil explicitly - if len(newTable.Entries) == 0 { - newTable.Entries = nil - } - - if updateStorage { - // Update the mount table - if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil { - c.logger.Error("failed to remove entry from mounts table", "error", err) - return logical.CodedError(500, "failed to remove entry from mounts table") - } - } - - c.mounts = newTable - return nil -} - -// taintMountEntry is used to mark an entry in the mount table as tainted -func (c *Core) taintMountEntry(ctx context.Context, path string, updateStorage bool) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // As modifying the taint of an entry affects shallow clones, - // we simply use the original - entry, err := c.mounts.setTaint(ctx, path, true) - if err != nil { - return err - } - if entry == nil { - c.logger.Error("nil entry found tainting entry in mounts table", "path", path) - return logical.CodedError(500, "failed to taint entry in mounts table") - } - - if updateStorage { - // Update the mount table - if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil { - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - - c.logger.Error("failed to taint entry in mounts table", "error", err) - return logical.CodedError(500, "failed to taint entry in mounts table") - } - } - - return nil -} - -// remountForce takes a copy of the mount entry for the path and fully unmounts -// and remounts the backend to pick up any changes, such as filtered paths -func (c *Core) remountForce(ctx context.Context, path string) error { - me := c.router.MatchingMountEntry(ctx, path) - if me == nil { - return fmt.Errorf("cannot find mount for path %q", path) - } - - me, err := me.Clone() - if err != nil { - return err - } - - if err := c.unmount(ctx, path); err != nil { - return err - } - return c.mount(ctx, me) -} - -// Remount is used to remount a path at a new mount point. -func (c *Core) remount(ctx context.Context, src, dst string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - // Ensure we end the path in a slash - if !strings.HasSuffix(src, "/") { - src += "/" - } - if !strings.HasSuffix(dst, "/") { - dst += "/" - } - - // Prevent protected paths from being remounted - for _, p := range protectedMounts { - if strings.HasPrefix(src, p) { - return fmt.Errorf("cannot remount %q", src) - } - } - - // Verify exact match of the route - srcMatch := c.router.MatchingMountEntry(ctx, src) - if srcMatch == nil { - return fmt.Errorf("no matching mount at %q", src) - } - if srcMatch.NamespaceID != ns.ID { - return fmt.Errorf("source mount in a different namespace than request") - } - - if err := verifyNamespace(c, ns, &MountEntry{Path: dst}); err != nil { - return err - } - - if match := c.router.MatchingMount(ctx, dst); match != "" { - return fmt.Errorf("existing mount at %q", match) - } - - // Mark the entry as tainted - if err := c.taintMountEntry(ctx, src, true); err != nil { - return err - } - - // Taint the router path to prevent routing - if err := c.router.Taint(ctx, src); err != nil { - return err - } - - if !c.IsDRSecondary() { - // Invoke the rollback manager a final time - rCtx := namespace.ContextWithNamespace(c.activeContext, ns) - if err := c.rollback.Rollback(rCtx, src); err != nil { - return err - } - - entry := c.router.MatchingMountEntry(ctx, src) - if entry == nil { - return fmt.Errorf("no matching mount at %q", src) - } - - // Revoke all the dynamic keys - if err := c.expiration.RevokePrefix(rCtx, src, true); err != nil { - return err - } - } - - c.mountsLock.Lock() - var entry *MountEntry - for _, mountEntry := range c.mounts.Entries { - if mountEntry.Path == src && mountEntry.NamespaceID == ns.ID { - entry = mountEntry - entry.Path = dst - entry.Tainted = false - break - } - } - - if entry == nil { - c.mountsLock.Unlock() - c.logger.Error("failed to find entry in mounts table") - return logical.CodedError(500, "failed to find entry in mounts table") - } - - // Update the mount table - if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil { - entry.Path = src - entry.Tainted = true - c.mountsLock.Unlock() - if err == logical.ErrReadOnly && c.perfStandby { - return err - } - - c.logger.Error("failed to update mounts table", "error", err) - return logical.CodedError(500, "failed to update mounts table") - } - c.mountsLock.Unlock() - - // Remount the backend - if err := c.router.Remount(ctx, src, dst); err != nil { - return err - } - - // Un-taint the path - if err := c.router.Untaint(ctx, dst); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("successful remount", "old_path", src, "new_path", dst) - } - return nil -} - -// loadMounts is invoked as part of postUnseal to load the mount table -func (c *Core) loadMounts(ctx context.Context) error { - // Load the existing mount table - raw, err := c.barrier.Get(ctx, coreMountConfigPath) - if err != nil { - c.logger.Error("failed to read mount table", "error", err) - return errLoadMountsFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalMountConfigPath) - if err != nil { - c.logger.Error("failed to read local mount table", "error", err) - return errLoadMountsFailed - } - - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - if raw != nil { - // Check if the persisted value has canary in the beginning. If - // yes, decompress the table and then JSON decode it. If not, - // simply JSON decode it. - mountTable, err := c.decodeMountTable(ctx, raw.Value) - if err != nil { - c.logger.Error("failed to decompress and/or decode the mount table", "error", err) - return err - } - c.mounts = mountTable - } - - var needPersist bool - if c.mounts == nil { - c.logger.Info("no mounts; adding default mount table") - c.mounts = c.defaultMountTable() - needPersist = true - } - - if rawLocal != nil { - localMountTable, err := c.decodeMountTable(ctx, rawLocal.Value) - if err != nil { - c.logger.Error("failed to decompress and/or decode the local mount table", "error", err) - return err - } - if localMountTable != nil && len(localMountTable.Entries) > 0 { - c.mounts.Entries = append(c.mounts.Entries, localMountTable.Entries...) - } - } - - // Note that this is only designed to work with singletons, as it checks by - // type only. - - // Upgrade to typed mount table - if c.mounts.Type == "" { - c.mounts.Type = mountTableType - needPersist = true - } - - for _, requiredMount := range c.requiredMountTable().Entries { - foundRequired := false - for _, coreMount := range c.mounts.Entries { - if coreMount.Type == requiredMount.Type { - foundRequired = true - break - } - } - - // In a replication scenario we will let sync invalidation take - // care of creating a new required mount that doesn't exist yet. - // This should only happen in the upgrade case where a new one is - // introduced on the primary; otherwise initial bootstrapping will - // ensure this comes over. If we upgrade first, we simply don't - // create the mount, so we won't conflict when we sync. If this is - // local (e.g. cubbyhole) we do still add it. - if !foundRequired && (!c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) || requiredMount.Local) { - c.mounts.Entries = append(c.mounts.Entries, requiredMount) - needPersist = true - } - } - - // Upgrade to table-scoped entries - for _, entry := range c.mounts.Entries { - if entry.Type == cubbyholeMountType && !entry.Local { - entry.Local = true - needPersist = true - } - if entry.Table == "" { - entry.Table = c.mounts.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor(entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - needPersist = true - } - - if entry.NamespaceID == "" { - entry.NamespaceID = namespace.RootNamespaceID - needPersist = true - } - ns, err := NamespaceByID(ctx, entry.NamespaceID, c) - if err != nil { - return err - } - if ns == nil { - return namespace.ErrNoNamespace - } - entry.namespace = ns - - // Sync values to the cache - entry.SyncCache() - } - - // Done if we have restored the mount table and we don't need - // to persist - if !needPersist { - return nil - } - - // Persist both mount tables - if err := c.persistMounts(ctx, c.mounts, nil); err != nil { - c.logger.Error("failed to persist mount table", "error", err) - return errLoadMountsFailed - } - return nil -} - -// persistMounts is used to persist the mount table after modification -func (c *Core) persistMounts(ctx context.Context, table *MountTable, local *bool) error { - if table.Type != mountTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", mountTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in mount table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid mount entry found, not persisting") - } - } - - nonLocalMounts := &MountTable{ - Type: mountTableType, - } - - localMounts := &MountTable{ - Type: mountTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localMounts.Entries = append(localMounts.Entries, entry) - } else { - nonLocalMounts.Entries = append(nonLocalMounts.Entries, entry) - } - } - - writeTable := func(mt *MountTable, path string) error { - // Encode the mount table into JSON and compress it (lzw). - compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil) - if err != nil { - c.logger.Error("failed to encode or compress mount table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: path, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist mount table", "error", err) - return err - } - return nil - } - - var err error - switch { - case local == nil: - // Write non-local mounts - err := writeTable(nonLocalMounts, coreMountConfigPath) - if err != nil { - return err - } - - // Write local mounts - err = writeTable(localMounts, coreLocalMountConfigPath) - if err != nil { - return err - } - case *local: - // Write local mounts - err = writeTable(localMounts, coreLocalMountConfigPath) - default: - // Write non-local mounts - err = writeTable(nonLocalMounts, coreMountConfigPath) - } - - return err -} - -// setupMounts is invoked after we've loaded the mount table to -// initialize the logical backends and setup the router -func (c *Core) setupMounts(ctx context.Context) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - for _, entry := range c.mounts.sortEntriesByPathDepth().Entries { - // Initialize the backend, special casing for system - barrierPath := entry.ViewPath() - - // Create a barrier view using the UUID - view := NewBarrierView(c.barrier, barrierPath) - - // Singleton mounts cannot be filtered on a per-secondary basis - // from replication - if strutil.StrListContains(singletonMounts, entry.Type) { - addFilterablePath(c, barrierPath) - } - - // Determining the replicated state of the mount - nilMount, err := preprocessMount(c, entry, view) - if err != nil { - return err - } - origReadOnlyErr := view.getReadOnlyErr() - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - if strutil.StrListContains(singletonMounts, entry.Type) { - defer view.setReadOnlyErr(origReadOnlyErr) - } else { - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(origReadOnlyErr) - }) - } - - var backend logical.Backend - // Create the new backend - sysView := c.mountEntrySysView(entry) - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - if err != nil { - c.logger.Error("failed to create mount entry", "path", entry.Path, "error", err) - if !c.builtinRegistry.Contains(entry.Type, consts.PluginTypeSecrets) { - // If we encounter an error instantiating the backend due to an error, - // skip backend initialization but register the entry to the mount table - // to preserve storage and path. - c.logger.Warn("skipping plugin-based mount entry", "path", entry.Path) - goto ROUTER_MOUNT - } - return errLoadMountsFailed - } - if backend == nil { - return fmt.Errorf("created mount entry of type %q is nil", entry.Type) - } - - { - // Check for the correct backend type - backendType := backend.Type() - - if backendType != logical.TypeLogical { - if entry.Type != "kv" && entry.Type != "system" && entry.Type != "cubbyhole" { - return fmt.Errorf(`unknown backend type: "%s"`, entry.Type) - } - } - - addPathCheckers(c, entry, backend, barrierPath) - - c.setCoreBackend(entry, backend, view) - } - - // If the mount is filtered or we are on a DR secondary we don't want to - // keep the actual backend running, so we clean it up and set it to nil - // so the router does not have a pointer to the object. - if nilMount { - backend.Cleanup(ctx) - backend = nil - } - - ROUTER_MOUNT: - // Mount the backend - err = c.router.Mount(backend, entry.Path, entry, view) - if err != nil { - c.logger.Error("failed to mount entry", "path", entry.Path, "error", err) - return errLoadMountsFailed - } - - if c.logger.IsInfo() { - c.logger.Info("successfully mounted backend", "type", entry.Type, "path", entry.Path) - } - - // Ensure the path is tainted if set in the mount table - if entry.Tainted { - c.router.Taint(ctx, entry.Path) - } - - // Ensure the cache is populated, don't need the result - NamespaceByID(ctx, entry.NamespaceID, c) - } - return nil -} - -// unloadMounts is used before we seal the vault to reset the mounts to -// their unloaded state, calling Cleanup if defined. This is reversed by load and setup mounts. -func (c *Core) unloadMounts(ctx context.Context) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - if c.mounts != nil { - mountTable := c.mounts.shallowClone() - for _, e := range mountTable.Entries { - backend := c.router.MatchingBackend(namespace.ContextWithNamespace(ctx, e.namespace), e.Path) - if backend != nil { - backend.Cleanup(ctx) - } - - viewPath := e.ViewPath() - removePathCheckers(c, e, viewPath) - } - } - - c.mounts = nil - c.router = NewRouter() - c.systemBarrierView = nil - return nil -} - -// newLogicalBackend is used to create and configure a new logical backend by name -func (c *Core) newLogicalBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) { - t := entry.Type - if alias, ok := mountAliases[t]; ok { - t = alias - } - - f, ok := c.logicalBackends[t] - if !ok { - f = plugin.Factory - } - - // Set up conf to pass in plugin_name - conf := make(map[string]string, len(entry.Options)+1) - for k, v := range entry.Options { - conf[k] = v - } - - switch { - case entry.Type == "plugin": - conf["plugin_name"] = entry.Config.PluginName - default: - conf["plugin_name"] = t - } - - conf["plugin_type"] = consts.PluginTypeSecrets.String() - - backendLogger := c.baseLogger.Named(fmt.Sprintf("secrets.%s.%s", t, entry.Accessor)) - c.AddLogger(backendLogger) - config := &logical.BackendConfig{ - StorageView: view, - Logger: backendLogger, - Config: conf, - System: sysView, - BackendUUID: entry.BackendAwareUUID, - } - - b, err := f(ctx, config) - if err != nil { - return nil, err - } - if b == nil { - return nil, fmt.Errorf("nil backend of type %q returned from factory", t) - } - return b, nil -} - -// mountEntrySysView creates a logical.SystemView from global and -// mount-specific entries; because this should be called when setting -// up a mountEntry, it doesn't check to ensure that me is not nil -func (c *Core) mountEntrySysView(entry *MountEntry) logical.SystemView { - return dynamicSystemView{ - core: c, - mountEntry: entry, - } -} - -// defaultMountTable creates a default mount table -func (c *Core) defaultMountTable() *MountTable { - table := &MountTable{ - Type: mountTableType, - } - mountUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create default secret mount UUID: %v", err)) - } - mountAccessor, err := c.generateMountAccessor("kv") - if err != nil { - panic(fmt.Sprintf("could not generate default secret mount accessor: %v", err)) - } - bUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create default secret mount backend UUID: %v", err)) - } - - kvMount := &MountEntry{ - Table: mountTableType, - Path: "secret/", - Type: "kv", - Description: "key/value secret storage", - UUID: mountUUID, - Accessor: mountAccessor, - BackendAwareUUID: bUUID, - Options: map[string]string{ - "version": "1", - }, - } - if os.Getenv("VAULT_INTERACTIVE_DEMO_SERVER") != "" { - kvMount.Options["version"] = "2" - } - table.Entries = append(table.Entries, kvMount) - table.Entries = append(table.Entries, c.requiredMountTable().Entries...) - return table -} - -// requiredMountTable() creates a mount table with entries required -// to be available -func (c *Core) requiredMountTable() *MountTable { - table := &MountTable{ - Type: mountTableType, - } - cubbyholeUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create cubbyhole UUID: %v", err)) - } - cubbyholeAccessor, err := c.generateMountAccessor("cubbyhole") - if err != nil { - panic(fmt.Sprintf("could not generate cubbyhole accessor: %v", err)) - } - cubbyholeBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create cubbyhole backend UUID: %v", err)) - } - cubbyholeMount := &MountEntry{ - Table: mountTableType, - Path: cubbyholeMountPath, - Type: cubbyholeMountType, - Description: "per-token private secret storage", - UUID: cubbyholeUUID, - Accessor: cubbyholeAccessor, - Local: true, - BackendAwareUUID: cubbyholeBackendUUID, - } - - sysUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create sys UUID: %v", err)) - } - sysAccessor, err := c.generateMountAccessor("system") - if err != nil { - panic(fmt.Sprintf("could not generate sys accessor: %v", err)) - } - sysBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create sys backend UUID: %v", err)) - } - sysMount := &MountEntry{ - Table: mountTableType, - Path: "sys/", - Type: systemMountType, - Description: "system endpoints used for control, policy and debugging", - UUID: sysUUID, - Accessor: sysAccessor, - BackendAwareUUID: sysBackendUUID, - } - - identityUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity mount entry UUID: %v", err)) - } - identityAccessor, err := c.generateMountAccessor("identity") - if err != nil { - panic(fmt.Sprintf("could not generate identity accessor: %v", err)) - } - identityBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity backend UUID: %v", err)) - } - identityMount := &MountEntry{ - Table: mountTableType, - Path: "identity/", - Type: "identity", - Description: "identity store", - UUID: identityUUID, - Accessor: identityAccessor, - BackendAwareUUID: identityBackendUUID, - } - - table.Entries = append(table.Entries, cubbyholeMount) - table.Entries = append(table.Entries, sysMount) - table.Entries = append(table.Entries, identityMount) - - return table -} - -// This function returns tables that are singletons. The main usage of this is -// for replication, so we can send over mount info (especially, UUIDs of -// mounts, which are used for salts) for mounts that may not be able to be -// handled normally. After saving these values on the secondary, we let normal -// sync invalidation do its thing. Because of its use for replication, we -// exclude local mounts. -func (c *Core) singletonMountTables() (mounts, auth *MountTable) { - mounts = &MountTable{} - auth = &MountTable{} - - c.mountsLock.RLock() - for _, entry := range c.mounts.Entries { - if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local && entry.Namespace().ID == namespace.RootNamespaceID { - mounts.Entries = append(mounts.Entries, entry) - } - } - c.mountsLock.RUnlock() - - c.authLock.RLock() - for _, entry := range c.auth.Entries { - if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local && entry.Namespace().ID == namespace.RootNamespaceID { - auth.Entries = append(auth.Entries, entry) - } - } - c.authLock.RUnlock() - - return -} - -func (c *Core) setCoreBackend(entry *MountEntry, backend logical.Backend, view *BarrierView) { - switch entry.Type { - case systemMountType: - c.systemBackend = backend.(*SystemBackend) - c.systemBarrierView = view - case cubbyholeMountType: - ch := backend.(*CubbyholeBackend) - ch.saltUUID = entry.UUID - ch.storageView = view - c.cubbyholeBackend = ch - case identityMountType: - c.identityStore = backend.(*IdentityStore) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/mount_util.go b/vendor/github.com/hashicorp/vault/vault/mount_util.go deleted file mode 100644 index 66ffb98e..00000000 --- a/vendor/github.com/hashicorp/vault/vault/mount_util.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - "path" - - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -func addPathCheckers(*Core, *MountEntry, logical.Backend, string) {} -func removePathCheckers(*Core, *MountEntry, string) {} -func addAuditPathChecker(*Core, *MountEntry, *BarrierView, string) {} -func removeAuditPathChecker(*Core, *MountEntry) {} -func addFilterablePath(*Core, string) {} -func preprocessMount(*Core, *MountEntry, *BarrierView) (bool, error) { return false, nil } -func clearIgnoredPaths(context.Context, *Core, logical.Backend, string) error { return nil } - -// ViewPath returns storage prefix for the view -func (e *MountEntry) ViewPath() string { - switch e.Type { - case systemMountType: - return systemBarrierPrefix - case "token": - return path.Join(systemBarrierPrefix, tokenSubPath) + "/" - } - - switch e.Table { - case mountTableType: - return backendBarrierPrefix + e.UUID + "/" - case credentialTableType: - return credentialBarrierPrefix + e.UUID + "/" - case auditTableType: - return auditBarrierPrefix + e.UUID + "/" - } - - panic("invalid mount entry") -} - -func verifyNamespace(*Core, *namespace.Namespace, *MountEntry) error { return nil } diff --git a/vendor/github.com/hashicorp/vault/vault/namespaces.go b/vendor/github.com/hashicorp/vault/vault/namespaces.go deleted file mode 100644 index 5b9f31b9..00000000 --- a/vendor/github.com/hashicorp/vault/vault/namespaces.go +++ /dev/null @@ -1,18 +0,0 @@ -package vault - -import ( - "context" - - "github.com/hashicorp/vault/helper/namespace" -) - -var ( - NamespaceByID func(context.Context, string, *Core) (*namespace.Namespace, error) = namespaceByID -) - -func namespaceByID(ctx context.Context, nsID string, c *Core) (*namespace.Namespace, error) { - if nsID == namespace.RootNamespaceID { - return namespace.RootNamespace, nil - } - return nil, namespace.ErrNoNamespace -} diff --git a/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go b/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go deleted file mode 100644 index b81b024a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go +++ /dev/null @@ -1,368 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "path/filepath" - "sort" - "strings" - "sync" - - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - backendplugin "github.com/hashicorp/vault/logical/plugin" -) - -var ( - pluginCatalogPath = "core/plugin-catalog/" - ErrDirectoryNotConfigured = errors.New("could not set plugin, plugin directory is not configured") - ErrPluginNotFound = errors.New("plugin not found in the catalog") - ErrPluginBadType = errors.New("unable to determine plugin type") -) - -// PluginCatalog keeps a record of plugins known to vault. External plugins need -// to be registered to the catalog before they can be used in backends. Builtin -// plugins are automatically detected and included in the catalog. -type PluginCatalog struct { - builtinRegistry BuiltinRegistry - catalogView *BarrierView - directory string - - lock sync.RWMutex -} - -func (c *Core) setupPluginCatalog(ctx context.Context) error { - c.pluginCatalog = &PluginCatalog{ - builtinRegistry: c.builtinRegistry, - catalogView: NewBarrierView(c.barrier, pluginCatalogPath), - directory: c.pluginDirectory, - } - - // Run upgrade if untyped plugins exist - err := c.pluginCatalog.UpgradePlugins(ctx, c.logger) - if err != nil { - c.logger.Error("error while upgrading plugin storage", "error", err) - } - - if c.logger.IsInfo() { - c.logger.Info("successfully setup plugin catalog", "plugin-directory", c.pluginDirectory) - } - - return nil -} - -// getPluginTypeFromUnknown will attempt to run the plugin to determine the -// type. It will first attempt to run as a database plugin then a backend -// plugin. Both of these will be run in metadata mode. -func (c *PluginCatalog) getPluginTypeFromUnknown(ctx context.Context, plugin *pluginutil.PluginRunner) (consts.PluginType, error) { - { - // Attempt to run as database plugin - client, err := dbplugin.NewPluginClient(ctx, nil, plugin, log.NewNullLogger(), true) - if err == nil { - // Close the client and cleanup the plugin process - client.Close() - return consts.PluginTypeDatabase, nil - } - } - - { - // Attempt to run as backend plugin - client, err := backendplugin.NewPluginClient(ctx, nil, plugin, log.NewNullLogger(), true) - if err == nil { - err := client.Setup(ctx, &logical.BackendConfig{}) - if err != nil { - return consts.PluginTypeUnknown, err - } - - backendType := client.Type() - client.Cleanup(ctx) - - switch backendType { - case logical.TypeCredential: - return consts.PluginTypeCredential, nil - case logical.TypeLogical: - return consts.PluginTypeSecrets, nil - } - } - } - - return consts.PluginTypeUnknown, nil -} - -// UpdatePlugins will loop over all the plugins of unknown type and attempt to -// upgrade them to typed plugins -func (c *PluginCatalog) UpgradePlugins(ctx context.Context, logger log.Logger) error { - c.lock.Lock() - defer c.lock.Unlock() - - // If the directory isn't set we can skip the upgrade attempt - if c.directory == "" { - return nil - } - - // List plugins from old location - pluginsRaw, err := c.catalogView.List(ctx, "") - if err != nil { - return err - } - plugins := make([]string, 0, len(pluginsRaw)) - for _, p := range pluginsRaw { - if !strings.HasSuffix(p, "/") { - plugins = append(plugins, p) - } - } - - logger.Info("upgrading plugin information", "plugins", plugins) - - var retErr error - for _, pluginName := range plugins { - pluginRaw, err := c.catalogView.Get(ctx, pluginName) - if err != nil { - retErr = multierror.Append(errwrap.Wrapf("failed to load plugin entry: {{err}}", err)) - continue - } - - plugin := new(pluginutil.PluginRunner) - if err := jsonutil.DecodeJSON(pluginRaw.Value, plugin); err != nil { - retErr = multierror.Append(errwrap.Wrapf("failed to decode plugin entry: {{err}}", err)) - continue - } - - // prepend the plugin directory to the command - cmdOld := plugin.Command - plugin.Command = filepath.Join(c.directory, plugin.Command) - - pluginType, err := c.getPluginTypeFromUnknown(ctx, plugin) - if err != nil { - retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: %s", pluginName, err)) - continue - } - if pluginType == consts.PluginTypeUnknown { - retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: plugin of unknown type", pluginName)) - continue - } - - // Upgrade the storage - err = c.setInternal(ctx, pluginName, pluginType, cmdOld, plugin.Args, plugin.Env, plugin.Sha256) - if err != nil { - retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: %s", pluginName, err)) - continue - } - - err = c.catalogView.Delete(ctx, pluginName) - if err != nil { - logger.Error("could not remove plugin", "plugin", pluginName, "error", err) - } - - logger.Info("upgraded plugin type", "plugin", pluginName, "type", pluginType.String()) - } - - return retErr -} - -// Get retrieves a plugin with the specified name from the catalog. It first -// looks for external plugins with this name and then looks for builtin plugins. -// It returns a PluginRunner or an error if no plugin was found. -func (c *PluginCatalog) Get(ctx context.Context, name string, pluginType consts.PluginType) (*pluginutil.PluginRunner, error) { - c.lock.RLock() - defer c.lock.RUnlock() - - // If the directory isn't set only look for builtin plugins. - if c.directory != "" { - // Look for external plugins in the barrier - out, err := c.catalogView.Get(ctx, pluginType.String()+"/"+name) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) - } - if out == nil { - // Also look for external plugins under what their name would have been if they - // were registered before plugin types existed. - out, err = c.catalogView.Get(ctx, name) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) - } - } - if out != nil { - entry := new(pluginutil.PluginRunner) - if err := jsonutil.DecodeJSON(out.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode plugin entry: {{err}}", err) - } - if entry.Type != pluginType && entry.Type != consts.PluginTypeUnknown { - return nil, nil - } - - // prepend the plugin directory to the command - entry.Command = filepath.Join(c.directory, entry.Command) - - return entry, nil - } - } - // Look for builtin plugins - if factory, ok := c.builtinRegistry.Get(name, pluginType); ok { - return &pluginutil.PluginRunner{ - Name: name, - Type: pluginType, - Builtin: true, - BuiltinFactory: factory, - }, nil - } - - return nil, nil -} - -// Set registers a new external plugin with the catalog, or updates an existing -// external plugin. It takes the name, command and SHA256 of the plugin. -func (c *PluginCatalog) Set(ctx context.Context, name string, pluginType consts.PluginType, command string, args []string, env []string, sha256 []byte) error { - if c.directory == "" { - return ErrDirectoryNotConfigured - } - - switch { - case strings.Contains(name, ".."): - fallthrough - case strings.Contains(command, ".."): - return consts.ErrPathContainsParentReferences - } - - c.lock.Lock() - defer c.lock.Unlock() - - return c.setInternal(ctx, name, pluginType, command, args, env, sha256) -} - -func (c *PluginCatalog) setInternal(ctx context.Context, name string, pluginType consts.PluginType, command string, args []string, env []string, sha256 []byte) error { - // Best effort check to make sure the command isn't breaking out of the - // configured plugin directory. - commandFull := filepath.Join(c.directory, command) - sym, err := filepath.EvalSymlinks(commandFull) - if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) - } - symAbs, err := filepath.Abs(filepath.Dir(sym)) - if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) - } - - if symAbs != c.directory { - return errors.New("can not execute files outside of configured plugin directory") - } - - // If the plugin type is unknown, we want to attempt to determine the type - if pluginType == consts.PluginTypeUnknown { - // entryTmp should only be used for the below type check, it uses the - // full command instead of the relative command. - entryTmp := &pluginutil.PluginRunner{ - Name: name, - Command: commandFull, - Args: args, - Env: env, - Sha256: sha256, - Builtin: false, - } - - pluginType, err = c.getPluginTypeFromUnknown(ctx, entryTmp) - if err != nil || pluginType == consts.PluginTypeUnknown { - return ErrPluginBadType - } - } - - entry := &pluginutil.PluginRunner{ - Name: name, - Type: pluginType, - Command: command, - Args: args, - Env: env, - Sha256: sha256, - Builtin: false, - } - - buf, err := json.Marshal(entry) - if err != nil { - return errwrap.Wrapf("failed to encode plugin entry: {{err}}", err) - } - - logicalEntry := logical.StorageEntry{ - Key: pluginType.String() + "/" + name, - Value: buf, - } - if err := c.catalogView.Put(ctx, &logicalEntry); err != nil { - return errwrap.Wrapf("failed to persist plugin entry: {{err}}", err) - } - return nil -} - -// Delete is used to remove an external plugin from the catalog. Builtin plugins -// can not be deleted. -func (c *PluginCatalog) Delete(ctx context.Context, name string, pluginType consts.PluginType) error { - c.lock.Lock() - defer c.lock.Unlock() - - // Check the name under which the plugin exists, but if it's unfound, don't return any error. - pluginKey := pluginType.String() + "/" + name - out, err := c.catalogView.Get(ctx, pluginKey) - if err != nil || out == nil { - pluginKey = name - } - - return c.catalogView.Delete(ctx, pluginKey) -} - -// List returns a list of all the known plugin names. If an external and builtin -// plugin share the same name, only one instance of the name will be returned. -func (c *PluginCatalog) List(ctx context.Context, pluginType consts.PluginType) ([]string, error) { - c.lock.RLock() - defer c.lock.RUnlock() - - // Collect keys for external plugins in the barrier. - keys, err := logical.CollectKeys(ctx, c.catalogView) - if err != nil { - return nil, err - } - - // Get the builtin plugins. - builtinKeys := c.builtinRegistry.Keys(pluginType) - - // Use a map to unique the two lists. - mapKeys := make(map[string]bool) - - pluginTypePrefix := pluginType.String() + "/" - - for _, plugin := range keys { - - // Only list user-added plugins if they're of the given type. - if entry, err := c.Get(ctx, plugin, pluginType); err == nil && entry != nil { - - // Some keys will be prepended with the plugin type, but other ones won't. - // Users don't expect to see the plugin type, so we need to strip that here. - idx := strings.Index(plugin, pluginTypePrefix) - if idx == 0 { - plugin = plugin[len(pluginTypePrefix):] - } - mapKeys[plugin] = true - } - } - - for _, plugin := range builtinKeys { - mapKeys[plugin] = true - } - - retList := make([]string, len(mapKeys)) - i := 0 - for k := range mapKeys { - retList[i] = k - i++ - } - // sort for consistent ordering of builtin plugins - sort.Strings(retList) - - return retList, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/plugin_reload.go b/vendor/github.com/hashicorp/vault/vault/plugin_reload.go deleted file mode 100644 index fdd095cd..00000000 --- a/vendor/github.com/hashicorp/vault/vault/plugin_reload.go +++ /dev/null @@ -1,193 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/namespace" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -// reloadPluginMounts reloads provided mounts, regardless of -// plugin name, as long as the backend type is plugin. -func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) error { - c.mountsLock.RLock() - defer c.mountsLock.RUnlock() - c.authLock.RLock() - defer c.authLock.RUnlock() - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - var errors error - for _, mount := range mounts { - entry := c.router.MatchingMountEntry(ctx, mount) - if entry == nil { - errors = multierror.Append(errors, fmt.Errorf("cannot fetch mount entry on %q", mount)) - continue - } - - var isAuth bool - fullPath := c.router.MatchingMount(ctx, mount) - if strings.HasPrefix(fullPath, credentialRoutePrefix) { - isAuth = true - } - - // We dont reload mounts that are not in the same namespace - if ns.ID != entry.Namespace().ID { - continue - } - - err := c.reloadBackendCommon(ctx, entry, isAuth) - if err != nil { - errors = multierror.Append(errors, errwrap.Wrapf(fmt.Sprintf("cannot reload plugin on %q: {{err}}", mount), err)) - continue - } - c.logger.Info("successfully reloaded plugin", "plugin", entry.Type, "path", entry.Path) - } - return errors -} - -// reloadPlugin reloads all mounted backends that are of -// plugin pluginName (name of the plugin as registered in -// the plugin catalog). -func (c *Core) reloadMatchingPlugin(ctx context.Context, pluginName string) error { - c.mountsLock.RLock() - defer c.mountsLock.RUnlock() - c.authLock.RLock() - defer c.authLock.RUnlock() - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - // Filter mount entries that only matches the plugin name - for _, entry := range c.mounts.Entries { - // We dont reload mounts that are not in the same namespace - if ns.ID != entry.Namespace().ID { - continue - } - if entry.Type == pluginName || (entry.Type == "plugin" && entry.Config.PluginName == pluginName) { - err := c.reloadBackendCommon(ctx, entry, false) - if err != nil { - return err - } - c.logger.Info("successfully reloaded plugin", "plugin", pluginName, "path", entry.Path) - } - } - - // Filter auth mount entries that ony matches the plugin name - for _, entry := range c.auth.Entries { - // We dont reload mounts that are not in the same namespace - if ns.ID != entry.Namespace().ID { - continue - } - - if entry.Type == pluginName || (entry.Type == "plugin" && entry.Config.PluginName == pluginName) { - err := c.reloadBackendCommon(ctx, entry, true) - if err != nil { - return err - } - c.logger.Info("successfully reloaded plugin", "plugin", pluginName, "path", entry.Path) - } - } - - return nil -} - -// reloadBackendCommon is a generic method to reload a backend provided a -// MountEntry. -func (c *Core) reloadBackendCommon(ctx context.Context, entry *MountEntry, isAuth bool) error { - // We don't want to reload the singleton mounts. They often have specific - // inmemory elements and we don't want to touch them here. - if strutil.StrListContains(singletonMounts, entry.Type) { - c.logger.Debug("skipping reload of singleton mount", "type", entry.Type) - return nil - } - - path := entry.Path - - if isAuth { - path = credentialRoutePrefix + path - } - - // Fast-path out if the backend doesn't exist - raw, ok := c.router.root.Get(path) - if !ok { - return nil - } - - re := raw.(*routeEntry) - - // Grab the lock, this allows requests to drain before we cleanup the - // client. - re.l.Lock() - defer re.l.Unlock() - - // Only call Cleanup if backend is initialized - if re.backend != nil { - // Call backend's Cleanup routine - re.backend.Cleanup(ctx) - } - - view := re.storageView - viewPath := entry.UUID + "/" - switch entry.Table { - case mountTableType: - viewPath = backendBarrierPrefix + viewPath - case credentialTableType: - viewPath = credentialBarrierPrefix + viewPath - } - - removePathCheckers(c, entry, viewPath) - - sysView := c.mountEntrySysView(entry) - - nilMount, err := preprocessMount(c, entry, view.(*BarrierView)) - if err != nil { - return err - } - - var backend logical.Backend - if !isAuth { - // Dispense a new backend - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - } else { - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - } - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend of type %q returned from creation function", entry.Type) - } - - addPathCheckers(c, entry, backend, viewPath) - - if nilMount { - backend.Cleanup(ctx) - backend = nil - } - - // Set the backend back - re.backend = backend - - if backend != nil { - // Set paths as well - paths := backend.SpecialPaths() - if paths != nil { - re.rootPaths.Store(pathsToRadix(paths.Root)) - re.loginPaths.Store(pathsToRadix(paths.Unauthenticated)) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy.go b/vendor/github.com/hashicorp/vault/vault/policy.go deleted file mode 100644 index 7bf448a3..00000000 --- a/vendor/github.com/hashicorp/vault/vault/policy.go +++ /dev/null @@ -1,461 +0,0 @@ -package vault - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/helper/hclutil" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/mitchellh/copystructure" -) - -const ( - DenyCapability = "deny" - CreateCapability = "create" - ReadCapability = "read" - UpdateCapability = "update" - DeleteCapability = "delete" - ListCapability = "list" - SudoCapability = "sudo" - RootCapability = "root" - - // Backwards compatibility - OldDenyPathPolicy = "deny" - OldReadPathPolicy = "read" - OldWritePathPolicy = "write" - OldSudoPathPolicy = "sudo" -) - -const ( - DenyCapabilityInt uint32 = 1 << iota - CreateCapabilityInt - ReadCapabilityInt - UpdateCapabilityInt - DeleteCapabilityInt - ListCapabilityInt - SudoCapabilityInt -) - -type PolicyType uint32 - -const ( - PolicyTypeACL PolicyType = iota - PolicyTypeRGP - PolicyTypeEGP - - // Triggers a lookup in the map to figure out if ACL or RGP - PolicyTypeToken -) - -func (p PolicyType) String() string { - switch p { - case PolicyTypeACL: - return "acl" - case PolicyTypeRGP: - return "rgp" - case PolicyTypeEGP: - return "egp" - } - - return "" -} - -var ( - cap2Int = map[string]uint32{ - DenyCapability: DenyCapabilityInt, - CreateCapability: CreateCapabilityInt, - ReadCapability: ReadCapabilityInt, - UpdateCapability: UpdateCapabilityInt, - DeleteCapability: DeleteCapabilityInt, - ListCapability: ListCapabilityInt, - SudoCapability: SudoCapabilityInt, - } -) - -type egpPath struct { - Path string `json:"path"` - Glob bool `json:"glob"` -} - -// Policy is used to represent the policy specified by an ACL configuration. -type Policy struct { - sentinelPolicy - Name string `hcl:"name"` - Paths []*PathRules `hcl:"-"` - Raw string - Type PolicyType - Templated bool - namespace *namespace.Namespace -} - -// ShallowClone returns a shallow clone of the policy. This should not be used -// if any of the reference-typed fields are going to be modified -func (p *Policy) ShallowClone() *Policy { - return &Policy{ - sentinelPolicy: p.sentinelPolicy, - Name: p.Name, - Paths: p.Paths, - Raw: p.Raw, - Type: p.Type, - namespace: p.namespace, - } -} - -// PathRules represents a policy for a path in the namespace. -type PathRules struct { - Prefix string - Policy string - Permissions *ACLPermissions - Glob bool - Capabilities []string - - // These keys are used at the top level to make the HCL nicer; we store in - // the ACLPermissions object though - MinWrappingTTLHCL interface{} `hcl:"min_wrapping_ttl"` - MaxWrappingTTLHCL interface{} `hcl:"max_wrapping_ttl"` - AllowedParametersHCL map[string][]interface{} `hcl:"allowed_parameters"` - DeniedParametersHCL map[string][]interface{} `hcl:"denied_parameters"` - RequiredParametersHCL []string `hcl:"required_parameters"` - MFAMethodsHCL []string `hcl:"mfa_methods"` - ControlGroupHCL *ControlGroupHCL `hcl:"control_group"` -} - -type ControlGroupHCL struct { - TTL interface{} `hcl:"ttl"` - Factors map[string]*ControlGroupFactor `hcl:"factor"` -} - -type ControlGroup struct { - TTL time.Duration - Factors []*ControlGroupFactor -} - -type ControlGroupFactor struct { - Name string - Identity *IdentityFactor `hcl:"identity"` -} - -type IdentityFactor struct { - GroupIDs []string `hcl:"group_ids"` - GroupNames []string `hcl:"group_names"` - ApprovalsRequired int `hcl:"approvals"` -} - -type ACLPermissions struct { - CapabilitiesBitmap uint32 - MinWrappingTTL time.Duration - MaxWrappingTTL time.Duration - AllowedParameters map[string][]interface{} - DeniedParameters map[string][]interface{} - RequiredParameters []string - MFAMethods []string - ControlGroup *ControlGroup -} - -func (p *ACLPermissions) Clone() (*ACLPermissions, error) { - ret := &ACLPermissions{ - CapabilitiesBitmap: p.CapabilitiesBitmap, - MinWrappingTTL: p.MinWrappingTTL, - MaxWrappingTTL: p.MaxWrappingTTL, - RequiredParameters: p.RequiredParameters[:], - } - - switch { - case p.AllowedParameters == nil: - case len(p.AllowedParameters) == 0: - ret.AllowedParameters = make(map[string][]interface{}) - default: - clonedAllowed, err := copystructure.Copy(p.AllowedParameters) - if err != nil { - return nil, err - } - ret.AllowedParameters = clonedAllowed.(map[string][]interface{}) - } - - switch { - case p.DeniedParameters == nil: - case len(p.DeniedParameters) == 0: - ret.DeniedParameters = make(map[string][]interface{}) - default: - clonedDenied, err := copystructure.Copy(p.DeniedParameters) - if err != nil { - return nil, err - } - ret.DeniedParameters = clonedDenied.(map[string][]interface{}) - } - - switch { - case p.MFAMethods == nil: - case len(p.MFAMethods) == 0: - ret.MFAMethods = []string{} - default: - clonedMFAMethods, err := copystructure.Copy(p.MFAMethods) - if err != nil { - return nil, err - } - ret.MFAMethods = clonedMFAMethods.([]string) - } - - switch { - case p.ControlGroup == nil: - default: - clonedControlGroup, err := copystructure.Copy(p.ControlGroup) - if err != nil { - return nil, err - } - ret.ControlGroup = clonedControlGroup.(*ControlGroup) - } - - return ret, nil -} - -// ParseACLPolicy is used to parse the specified ACL rules into an -// intermediary set of policies, before being compiled into -// the ACL -func ParseACLPolicy(ns *namespace.Namespace, rules string) (*Policy, error) { - return parseACLPolicyWithTemplating(ns, rules, false, nil, nil) -} - -// parseACLPolicyWithTemplating performs the actual work and checks whether we -// should perform substitutions. If performTemplating is true we know that it -// is templated so we don't check again, otherwise we check to see if it's a -// templated policy. -func parseACLPolicyWithTemplating(ns *namespace.Namespace, rules string, performTemplating bool, entity *identity.Entity, groups []*identity.Group) (*Policy, error) { - // Parse the rules - root, err := hcl.Parse(rules) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Top-level item should be the object list - list, ok := root.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("failed to parse policy: does not contain a root object") - } - - // Check for invalid top-level keys - valid := []string{ - "name", - "path", - } - if err := hclutil.CheckHCLKeys(list, valid); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Create the initial policy and store the raw text of the rules - p := Policy{ - Raw: rules, - Type: PolicyTypeACL, - namespace: ns, - } - if err := hcl.DecodeObject(&p, list); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - if o := list.Filter("path"); len(o.Items) > 0 { - if err := parsePaths(&p, o, performTemplating, entity, groups); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - } - - return &p, nil -} - -func parsePaths(result *Policy, list *ast.ObjectList, performTemplating bool, entity *identity.Entity, groups []*identity.Group) error { - paths := make([]*PathRules, 0, len(list.Items)) - for _, item := range list.Items { - key := "path" - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - // Check the path - if performTemplating { - _, templated, err := identity.PopulateString(&identity.PopulateStringInput{ - String: key, - Entity: entity, - Groups: groups, - Namespace: result.namespace, - }) - if err != nil { - continue - } - key = templated - } else { - hasTemplating, _, err := identity.PopulateString(&identity.PopulateStringInput{ - ValidityCheckOnly: true, - String: key, - }) - if err != nil { - return errwrap.Wrapf("failed to validate policy templating: {{err}}", err) - } - if hasTemplating { - result.Templated = true - } - } - - valid := []string{ - "comment", - "policy", - "capabilities", - "allowed_parameters", - "denied_parameters", - "required_parameters", - "min_wrapping_ttl", - "max_wrapping_ttl", - "mfa_methods", - "control_group", - } - if err := hclutil.CheckHCLKeys(item.Val, valid); err != nil { - return multierror.Prefix(err, fmt.Sprintf("path %q:", key)) - } - - var pc PathRules - - // allocate memory so that DecodeObject can initialize the ACLPermissions struct - pc.Permissions = new(ACLPermissions) - - pc.Prefix = key - - if err := hcl.DecodeObject(&pc, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("path %q:", key)) - } - - // Strip a leading '/' as paths in Vault start after the / in the API path - if len(pc.Prefix) > 0 && pc.Prefix[0] == '/' { - pc.Prefix = pc.Prefix[1:] - } - - // Ensure we are using the full request path internally - pc.Prefix = result.namespace.Path + pc.Prefix - - // Strip the glob character if found - if strings.HasSuffix(pc.Prefix, "*") { - pc.Prefix = strings.TrimSuffix(pc.Prefix, "*") - pc.Glob = true - } - - // Map old-style policies into capabilities - if len(pc.Policy) > 0 { - switch pc.Policy { - case OldDenyPathPolicy: - pc.Capabilities = []string{DenyCapability} - case OldReadPathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{ReadCapability, ListCapability}...) - case OldWritePathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability}...) - case OldSudoPathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability}...) - default: - return fmt.Errorf("path %q: invalid policy %q", key, pc.Policy) - } - } - - // Initialize the map - pc.Permissions.CapabilitiesBitmap = 0 - for _, cap := range pc.Capabilities { - switch cap { - // If it's deny, don't include any other capability - case DenyCapability: - pc.Capabilities = []string{DenyCapability} - pc.Permissions.CapabilitiesBitmap = DenyCapabilityInt - goto PathFinished - case CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability: - pc.Permissions.CapabilitiesBitmap |= cap2Int[cap] - default: - return fmt.Errorf("path %q: invalid capability %q", key, cap) - } - } - - if pc.AllowedParametersHCL != nil { - pc.Permissions.AllowedParameters = make(map[string][]interface{}, len(pc.AllowedParametersHCL)) - for key, val := range pc.AllowedParametersHCL { - pc.Permissions.AllowedParameters[strings.ToLower(key)] = val - } - } - if pc.DeniedParametersHCL != nil { - pc.Permissions.DeniedParameters = make(map[string][]interface{}, len(pc.DeniedParametersHCL)) - - for key, val := range pc.DeniedParametersHCL { - pc.Permissions.DeniedParameters[strings.ToLower(key)] = val - } - } - if pc.MinWrappingTTLHCL != nil { - dur, err := parseutil.ParseDurationSecond(pc.MinWrappingTTLHCL) - if err != nil { - return errwrap.Wrapf("error parsing min_wrapping_ttl: {{err}}", err) - } - pc.Permissions.MinWrappingTTL = dur - } - if pc.MaxWrappingTTLHCL != nil { - dur, err := parseutil.ParseDurationSecond(pc.MaxWrappingTTLHCL) - if err != nil { - return errwrap.Wrapf("error parsing max_wrapping_ttl: {{err}}", err) - } - pc.Permissions.MaxWrappingTTL = dur - } - if pc.MFAMethodsHCL != nil { - pc.Permissions.MFAMethods = make([]string, len(pc.MFAMethodsHCL)) - for idx, item := range pc.MFAMethodsHCL { - pc.Permissions.MFAMethods[idx] = item - } - } - if pc.ControlGroupHCL != nil { - pc.Permissions.ControlGroup = new(ControlGroup) - if pc.ControlGroupHCL.TTL != nil { - dur, err := parseutil.ParseDurationSecond(pc.ControlGroupHCL.TTL) - if err != nil { - return errwrap.Wrapf("error parsing control group max ttl: {{err}}", err) - } - pc.Permissions.ControlGroup.TTL = dur - } - - var factors []*ControlGroupFactor - if pc.ControlGroupHCL.Factors != nil { - for key, factor := range pc.ControlGroupHCL.Factors { - // Although we only have one factor here, we need to check to make sure there is at least - // one factor defined in this factor block. - if factor.Identity == nil { - return errors.New("no control_group factor provided") - } - - if factor.Identity.ApprovalsRequired <= 0 || - (len(factor.Identity.GroupIDs) == 0 && len(factor.Identity.GroupNames) == 0) { - return errors.New("must provide more than one identity group and approvals > 0") - } - - factors = append(factors, &ControlGroupFactor{ - Name: key, - Identity: factor.Identity, - }) - } - } - if len(factors) == 0 { - return errors.New("no control group factors provided") - } - pc.Permissions.ControlGroup.Factors = factors - } - if pc.Permissions.MinWrappingTTL != 0 && - pc.Permissions.MaxWrappingTTL != 0 && - pc.Permissions.MaxWrappingTTL < pc.Permissions.MinWrappingTTL { - return errors.New("max_wrapping_ttl cannot be less than min_wrapping_ttl") - } - if len(pc.RequiredParametersHCL) > 0 { - pc.Permissions.RequiredParameters = pc.RequiredParametersHCL[:] - } - - PathFinished: - paths = append(paths, &pc) - } - - result.Paths = paths - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy_store.go b/vendor/github.com/hashicorp/vault/vault/policy_store.go deleted file mode 100644 index 2c7e1296..00000000 --- a/vendor/github.com/hashicorp/vault/vault/policy_store.go +++ /dev/null @@ -1,840 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "path" - "strings" - "sync" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/golang-lru" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - // policySubPath is the sub-path used for the policy store view. This is - // nested under the system view. policyRGPSubPath/policyEGPSubPath are - // similar but for RGPs/EGPs. - policyACLSubPath = "policy/" - policyRGPSubPath = "policy-rgp/" - policyEGPSubPath = "policy-egp/" - - // policyCacheSize is the number of policies that are kept cached - policyCacheSize = 1024 - - // defaultPolicyName is the name of the default policy - defaultPolicyName = "default" - - // responseWrappingPolicyName is the name of the fixed policy - responseWrappingPolicyName = "response-wrapping" - - // controlGroupPolicyName is the name of the fixed policy for control group - // tokens - controlGroupPolicyName = "control-group" - - // responseWrappingPolicy is the policy that ensures cubbyhole response - // wrapping can always succeed. - responseWrappingPolicy = ` -path "cubbyhole/response" { - capabilities = ["create", "read"] -} - -path "sys/wrapping/unwrap" { - capabilities = ["update"] -} -` - // controlGroupPolicy is the policy that ensures control group requests can - // commit themselves - controlGroupPolicy = ` -path "cubbyhole/control-group" { - capabilities = ["update", "create", "read"] -} - -path "sys/wrapping/unwrap" { - capabilities = ["update"] -} -` - // defaultPolicy is the "default" policy - defaultPolicy = ` -# Allow tokens to look up their own properties -path "auth/token/lookup-self" { - capabilities = ["read"] -} - -# Allow tokens to renew themselves -path "auth/token/renew-self" { - capabilities = ["update"] -} - -# Allow tokens to revoke themselves -path "auth/token/revoke-self" { - capabilities = ["update"] -} - -# Allow a token to look up its own capabilities on a path -path "sys/capabilities-self" { - capabilities = ["update"] -} - -# Allow a token to look up its resultant ACL from all policies. This is useful -# for UIs. It is an internal path because the format may change at any time -# based on how the internal ACL features and capabilities change. -path "sys/internal/ui/resultant-acl" { - capabilities = ["read"] -} - -# Allow a token to renew a lease via lease_id in the request body; old path for -# old clients, new path for newer -path "sys/renew" { - capabilities = ["update"] -} -path "sys/leases/renew" { - capabilities = ["update"] -} - -# Allow looking up lease properties. This requires knowing the lease ID ahead -# of time and does not divulge any sensitive information. -path "sys/leases/lookup" { - capabilities = ["update"] -} - -# Allow a token to manage its own cubbyhole -path "cubbyhole/*" { - capabilities = ["create", "read", "update", "delete", "list"] -} - -# Allow a token to wrap arbitrary values in a response-wrapping token -path "sys/wrapping/wrap" { - capabilities = ["update"] -} - -# Allow a token to look up the creation time and TTL of a given -# response-wrapping token -path "sys/wrapping/lookup" { - capabilities = ["update"] -} - -# Allow a token to unwrap a response-wrapping token. This is a convenience to -# avoid client token swapping since this is also part of the response wrapping -# policy. -path "sys/wrapping/unwrap" { - capabilities = ["update"] -} - -# Allow general purpose tools -path "sys/tools/hash" { - capabilities = ["update"] -} -path "sys/tools/hash/*" { - capabilities = ["update"] -} -path "sys/tools/random" { - capabilities = ["update"] -} -path "sys/tools/random/*" { - capabilities = ["update"] -} - -# Allow checking the status of a Control Group request if the user has the -# accessor -path "sys/control-group/request" { - capabilities = ["update"] -} -` -) - -var ( - immutablePolicies = []string{ - "root", - responseWrappingPolicyName, - controlGroupPolicyName, - } - nonAssignablePolicies = []string{ - responseWrappingPolicyName, - controlGroupPolicyName, - } -) - -// PolicyStore is used to provide durable storage of policy, and to -// manage ACLs associated with them. -type PolicyStore struct { - entPolicyStore - - core *Core - aclView *BarrierView - rgpView *BarrierView - egpView *BarrierView - - tokenPoliciesLRU *lru.TwoQueueCache - egpLRU *lru.TwoQueueCache - - // This is used to ensure that writes to the store (acl/rgp) or to the egp - // path tree don't happen concurrently. We are okay reading stale data so - // long as there aren't concurrent writes. - modifyLock *sync.RWMutex - - // Stores whether a token policy is ACL or RGP - policyTypeMap sync.Map - - // logger is the server logger copied over from core - logger log.Logger -} - -// PolicyEntry is used to store a policy by name -type PolicyEntry struct { - sentinelPolicy - - Version int - Raw string - Templated bool - Type PolicyType -} - -// NewPolicyStore creates a new PolicyStore that is backed -// using a given view. It used used to durable store and manage named policy. -func NewPolicyStore(ctx context.Context, core *Core, baseView *BarrierView, system logical.SystemView, logger log.Logger) (*PolicyStore, error) { - ps := &PolicyStore{ - aclView: baseView.SubView(policyACLSubPath), - rgpView: baseView.SubView(policyRGPSubPath), - egpView: baseView.SubView(policyEGPSubPath), - modifyLock: new(sync.RWMutex), - logger: logger, - core: core, - } - - ps.extraInit() - - if !system.CachingDisabled() { - cache, _ := lru.New2Q(policyCacheSize) - ps.tokenPoliciesLRU = cache - cache, _ = lru.New2Q(policyCacheSize) - ps.egpLRU = cache - } - - aclView := ps.getACLView(namespace.RootNamespace) - keys, err := logical.CollectKeys(namespace.RootContext(ctx), aclView) - if err != nil { - ps.logger.Error("error collecting acl policy keys", "error", err) - return nil, err - } - for _, key := range keys { - index := ps.cacheKey(namespace.RootNamespace, ps.sanitizeName(key)) - ps.policyTypeMap.Store(index, PolicyTypeACL) - } - - if err := ps.loadNamespacePolicies(ctx, core); err != nil { - return nil, err - } - - // Special-case root; doesn't exist on disk but does need to be found - ps.policyTypeMap.Store(ps.cacheKey(namespace.RootNamespace, "root"), PolicyTypeACL) - return ps, nil -} - -// setupPolicyStore is used to initialize the policy store -// when the vault is being unsealed. -func (c *Core) setupPolicyStore(ctx context.Context) error { - // Create the policy store - var err error - sysView := &dynamicSystemView{core: c} - psLogger := c.baseLogger.Named("policy") - c.AddLogger(psLogger) - c.policyStore, err = NewPolicyStore(ctx, c, c.systemBarrierView, sysView, psLogger) - if err != nil { - return err - } - - if c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - // Policies will sync from the primary - return nil - } - - // Ensure that the default policy exists, and if not, create it - if err := c.policyStore.loadACLPolicy(ctx, defaultPolicyName, defaultPolicy); err != nil { - return err - } - // Ensure that the response wrapping policy exists - if err := c.policyStore.loadACLPolicy(ctx, responseWrappingPolicyName, responseWrappingPolicy); err != nil { - return err - } - // Ensure that the control group policy exists - if err := c.policyStore.loadACLPolicy(ctx, controlGroupPolicyName, controlGroupPolicy); err != nil { - return err - } - - return nil -} - -// teardownPolicyStore is used to reverse setupPolicyStore -// when the vault is being sealed. -func (c *Core) teardownPolicyStore() error { - c.policyStore = nil - return nil -} - -func (ps *PolicyStore) invalidate(ctx context.Context, name string, policyType PolicyType) { - ns, err := namespace.FromContext(ctx) - if err != nil { - ps.logger.Error("unable to invalidate key, no namespace info passed", "key", name) - return - } - - // This may come with a prefixed "/" due to joining the file path - saneName := strings.TrimPrefix(name, "/") - index := ps.cacheKey(ns, saneName) - - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - - // We don't lock before removing from the LRU here because the worst that - // can happen is we load again if something since added it - switch policyType { - case PolicyTypeACL, PolicyTypeRGP: - if ps.tokenPoliciesLRU != nil { - ps.tokenPoliciesLRU.Remove(index) - } - - case PolicyTypeEGP: - if ps.egpLRU != nil { - ps.egpLRU.Remove(index) - } - - default: - // Can't do anything - return - } - - // Force a reload - out, err := ps.switchedGetPolicy(ctx, name, policyType, false) - if err != nil { - ps.logger.Error("error fetching policy after invalidation", "name", saneName) - } - - // If true, the invalidation was actually a delete, so we may need to - // perform further deletion tasks. We skip the physical deletion just in - // case another process has re-written the policy; instead next time Get is - // called the values will be loaded back in. - if out == nil { - ps.switchedDeletePolicy(ctx, name, policyType, false) - } - - return -} - -// SetPolicy is used to create or update the given policy -func (ps *PolicyStore) SetPolicy(ctx context.Context, p *Policy) error { - defer metrics.MeasureSince([]string{"policy", "set_policy"}, time.Now()) - if p == nil { - return fmt.Errorf("nil policy passed in for storage") - } - if p.Name == "" { - return fmt.Errorf("policy name missing") - } - // Policies are normalized to lower-case - p.Name = ps.sanitizeName(p.Name) - if strutil.StrListContains(immutablePolicies, p.Name) { - return fmt.Errorf("cannot update %q policy", p.Name) - } - - return ps.setPolicyInternal(ctx, p) -} - -func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - - // Get the appropriate view based on policy type and namespace - view := ps.getBarrierView(p.namespace, p.Type) - if view == nil { - return fmt.Errorf("unable to get the barrier subview for policy type %q", p.Type) - } - - if err := ps.parseEGPPaths(p); err != nil { - return err - } - - // Create the entry - entry, err := logical.StorageEntryJSON(p.Name, &PolicyEntry{ - Version: 2, - Raw: p.Raw, - Type: p.Type, - Templated: p.Templated, - sentinelPolicy: p.sentinelPolicy, - }) - if err != nil { - return errwrap.Wrapf("failed to create entry: {{err}}", err) - } - - // Construct the cache key - index := ps.cacheKey(p.namespace, p.Name) - - switch p.Type { - case PolicyTypeACL: - rgpView := ps.getRGPView(p.namespace) - rgp, err := rgpView.Get(ctx, entry.Key) - if err != nil { - return errwrap.Wrapf("failed looking up conflicting policy: {{err}}", err) - } - if rgp != nil { - return fmt.Errorf("cannot reuse policy names between ACLs and RGPs") - } - - if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist policy: {{err}}", err) - } - - ps.policyTypeMap.Store(index, PolicyTypeACL) - - if ps.tokenPoliciesLRU != nil { - ps.tokenPoliciesLRU.Add(index, p) - } - - case PolicyTypeRGP: - aclView := ps.getACLView(p.namespace) - acl, err := aclView.Get(ctx, entry.Key) - if err != nil { - return errwrap.Wrapf("failed looking up conflicting policy: {{err}}", err) - } - if acl != nil { - return fmt.Errorf("cannot reuse policy names between ACLs and RGPs") - } - - if err := ps.handleSentinelPolicy(ctx, p, view, entry); err != nil { - return err - } - - ps.policyTypeMap.Store(index, PolicyTypeRGP) - - // We load here after successfully loading into Sentinel so that on - // error we will try loading again on the next get - if ps.tokenPoliciesLRU != nil { - ps.tokenPoliciesLRU.Add(index, p) - } - - case PolicyTypeEGP: - if err := ps.handleSentinelPolicy(ctx, p, view, entry); err != nil { - return err - } - - // We load here after successfully loading into Sentinel so that on - // error we will try loading again on the next get - if ps.egpLRU != nil { - ps.egpLRU.Add(index, p) - } - - default: - return fmt.Errorf("unknown policy type, cannot set") - } - - return nil -} - -// GetPolicy is used to fetch the named policy -func (ps *PolicyStore) GetPolicy(ctx context.Context, name string, policyType PolicyType) (*Policy, error) { - return ps.switchedGetPolicy(ctx, name, policyType, true) -} - -func (ps *PolicyStore) switchedGetPolicy(ctx context.Context, name string, policyType PolicyType, grabLock bool) (*Policy, error) { - defer metrics.MeasureSince([]string{"policy", "get_policy"}, time.Now()) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - // Policies are normalized to lower-case - name = ps.sanitizeName(name) - index := ps.cacheKey(ns, name) - - var cache *lru.TwoQueueCache - var view *BarrierView - - switch policyType { - case PolicyTypeACL: - cache = ps.tokenPoliciesLRU - view = ps.getACLView(ns) - case PolicyTypeRGP: - cache = ps.tokenPoliciesLRU - view = ps.getRGPView(ns) - case PolicyTypeEGP: - cache = ps.egpLRU - view = ps.getEGPView(ns) - case PolicyTypeToken: - cache = ps.tokenPoliciesLRU - val, ok := ps.policyTypeMap.Load(index) - if !ok { - // Doesn't exist - return nil, nil - } - policyType = val.(PolicyType) - switch policyType { - case PolicyTypeACL: - view = ps.getACLView(ns) - case PolicyTypeRGP: - view = ps.getRGPView(ns) - default: - return nil, fmt.Errorf("invalid type of policy in type map: %q", policyType) - } - } - - if cache != nil { - // Check for cached policy - if raw, ok := cache.Get(index); ok { - return raw.(*Policy), nil - } - } - - // Special case the root policy - if policyType == PolicyTypeACL && name == "root" && ns.ID == namespace.RootNamespaceID { - p := &Policy{ - Name: "root", - namespace: namespace.RootNamespace, - } - if cache != nil { - cache.Add(index, p) - } - return p, nil - } - - if grabLock { - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - } - - // See if anything has added it since we got the lock - if cache != nil { - if raw, ok := cache.Get(index); ok { - return raw.(*Policy), nil - } - } - - // Nil-check on the view before proceeding to retrive from storage - if view == nil { - return nil, fmt.Errorf("unable to get the barrier subview for policy type %q", policyType) - } - - out, err := view.Get(ctx, name) - if err != nil { - return nil, errwrap.Wrapf("failed to read policy: {{err}}", err) - } - - if out == nil { - return nil, nil - } - - policyEntry := new(PolicyEntry) - policy := new(Policy) - err = out.DecodeJSON(policyEntry) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Set these up here so that they're available for loading into - // Sentinel - policy.Name = name - policy.Raw = policyEntry.Raw - policy.Type = policyEntry.Type - policy.Templated = policyEntry.Templated - policy.sentinelPolicy = policyEntry.sentinelPolicy - policy.namespace = ns - switch policyEntry.Type { - case PolicyTypeACL: - // Parse normally - p, err := ParseACLPolicy(ns, policyEntry.Raw) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - policy.Paths = p.Paths - - // Reset this in case they set the name in the policy itself - policy.Name = name - - ps.policyTypeMap.Store(index, PolicyTypeACL) - - case PolicyTypeRGP: - if err := ps.handleSentinelPolicy(ctx, policy, nil, nil); err != nil { - return nil, err - } - - ps.policyTypeMap.Store(index, PolicyTypeRGP) - - case PolicyTypeEGP: - if err := ps.handleSentinelPolicy(ctx, policy, nil, nil); err != nil { - return nil, err - } - - default: - return nil, fmt.Errorf("unknown policy type %q", policyEntry.Type.String()) - } - - if cache != nil { - // Update the LRU cache - cache.Add(index, policy) - } - - return policy, nil -} - -// ListPolicies is used to list the available policies -func (ps *PolicyStore) ListPolicies(ctx context.Context, policyType PolicyType) ([]string, error) { - defer metrics.MeasureSince([]string{"policy", "list_policies"}, time.Now()) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns == nil { - return nil, namespace.ErrNoNamespace - } - - // Get the appropriate view based on policy type and namespace - view := ps.getBarrierView(ns, policyType) - if view == nil { - return []string{}, fmt.Errorf("unable to get the barrier subview for policy type %q", policyType) - } - - // Scan the view, since the policy names are the same as the - // key names. - var keys []string - switch policyType { - case PolicyTypeACL: - keys, err = logical.CollectKeys(ctx, view) - case PolicyTypeRGP: - return logical.CollectKeys(ctx, view) - case PolicyTypeEGP: - return logical.CollectKeys(ctx, view) - default: - return nil, fmt.Errorf("unknown policy type %q", policyType) - } - - // We only have non-assignable ACL policies at the moment - for _, nonAssignable := range nonAssignablePolicies { - deleteIndex := -1 - // Find indices of non-assignable policies in keys - for index, key := range keys { - if key == nonAssignable { - // Delete collection outside the loop - deleteIndex = index - break - } - } - // Remove non-assignable policies when found - if deleteIndex != -1 { - keys = append(keys[:deleteIndex], keys[deleteIndex+1:]...) - } - } - - return keys, err -} - -// DeletePolicy is used to delete the named policy -func (ps *PolicyStore) DeletePolicy(ctx context.Context, name string, policyType PolicyType) error { - return ps.switchedDeletePolicy(ctx, name, policyType, true) -} - -func (ps *PolicyStore) switchedDeletePolicy(ctx context.Context, name string, policyType PolicyType, physicalDeletion bool) error { - defer metrics.MeasureSince([]string{"policy", "delete_policy"}, time.Now()) - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - // If not set, the call comes from invalidation, where we'll already have - // grabbed the lock - if physicalDeletion { - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - } - - // Policies are normalized to lower-case - name = ps.sanitizeName(name) - index := ps.cacheKey(ns, name) - - view := ps.getBarrierView(ns, policyType) - if view == nil { - return fmt.Errorf("unable to get the barrier subview for policy type %q", policyType) - } - - switch policyType { - case PolicyTypeACL: - if strutil.StrListContains(immutablePolicies, name) { - return fmt.Errorf("cannot delete %q policy", name) - } - if name == "default" { - return fmt.Errorf("cannot delete default policy") - } - - if physicalDeletion { - err := view.Delete(ctx, name) - if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) - } - } - - if ps.tokenPoliciesLRU != nil { - // Clear the cache - ps.tokenPoliciesLRU.Remove(index) - } - - ps.policyTypeMap.Delete(index) - - case PolicyTypeRGP: - if physicalDeletion { - err := view.Delete(ctx, name) - if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) - } - } - - if ps.tokenPoliciesLRU != nil { - // Clear the cache - ps.tokenPoliciesLRU.Remove(index) - } - - ps.policyTypeMap.Delete(index) - - defer ps.core.invalidateSentinelPolicy(policyType, index) - - case PolicyTypeEGP: - if physicalDeletion { - err := view.Delete(ctx, name) - if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) - } - } - - if ps.egpLRU != nil { - // Clear the cache - ps.egpLRU.Remove(index) - } - - defer ps.core.invalidateSentinelPolicy(policyType, index) - - ps.invalidateEGPTreePath(index) - } - - return nil -} - -type TemplateError struct { - Err error -} - -func (t *TemplateError) WrappedErrors() []error { - return []error{t.Err} -} - -func (t *TemplateError) Error() string { - return t.Err.Error() -} - -// ACL is used to return an ACL which is built using the -// named policies. -func (ps *PolicyStore) ACL(ctx context.Context, entity *identity.Entity, policyNames map[string][]string) (*ACL, error) { - var policies []*Policy - // Fetch the policies - for nsID, nsPolicyNames := range policyNames { - policyNS, err := NamespaceByID(ctx, nsID, ps.core) - if err != nil { - return nil, err - } - if policyNS == nil { - return nil, namespace.ErrNoNamespace - } - policyCtx := namespace.ContextWithNamespace(ctx, policyNS) - for _, nsPolicyName := range nsPolicyNames { - p, err := ps.GetPolicy(policyCtx, nsPolicyName, PolicyTypeToken) - if err != nil { - return nil, errwrap.Wrapf("failed to get policy: {{err}}", err) - } - if p != nil { - policies = append(policies, p) - } - } - } - - var fetchedGroups bool - var groups []*identity.Group - for i, policy := range policies { - if policy.Type == PolicyTypeACL && policy.Templated { - if !fetchedGroups { - fetchedGroups = true - if entity != nil { - directGroups, inheritedGroups, err := ps.core.identityStore.groupsByEntityID(entity.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group memberships: {{err}}", err) - } - groups = append(directGroups, inheritedGroups...) - } - } - p, err := parseACLPolicyWithTemplating(policy.namespace, policy.Raw, true, entity, groups) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing templated policy %q: {{err}}", policy.Name), err) - } - p.Name = policy.Name - policies[i] = p - } - } - - // Construct the ACL - acl, err := NewACL(ctx, policies) - if err != nil { - return nil, errwrap.Wrapf("failed to construct ACL: {{err}}", err) - } - - return acl, nil -} - -// loadACLPolicy is used to load default ACL policies. The default policies will -// be loaded to all namespaces. -func (ps *PolicyStore) loadACLPolicy(ctx context.Context, policyName, policyText string) error { - return ps.loadACLPolicyNamespaces(ctx, policyName, policyText) -} - -// loadACLPolicyInternal is used to load default ACL policies in a specific -// namespace. -func (ps *PolicyStore) loadACLPolicyInternal(ctx context.Context, policyName, policyText string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - - // Check if the policy already exists - policy, err := ps.GetPolicy(ctx, policyName, PolicyTypeACL) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching %s policy from store: {{err}}", policyName), err) - } - if policy != nil { - if !strutil.StrListContains(immutablePolicies, policyName) || policyText == policy.Raw { - return nil - } - } - - policy, err = ParseACLPolicy(ns, policyText) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error parsing %s policy: {{err}}", policyName), err) - } - - if policy == nil { - return fmt.Errorf("parsing %q policy resulted in nil policy", policyName) - } - - policy.Name = policyName - policy.Type = PolicyTypeACL - return ps.setPolicyInternal(ctx, policy) -} - -func (ps *PolicyStore) sanitizeName(name string) string { - return strings.ToLower(strings.TrimSpace(name)) -} - -func (ps *PolicyStore) cacheKey(ns *namespace.Namespace, name string) string { - return path.Join(ns.ID, name) -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy_store_util.go b/vendor/github.com/hashicorp/vault/vault/policy_store_util.go deleted file mode 100644 index c2c7a35a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/policy_store_util.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -type entPolicyStore struct{} - -func (ps *PolicyStore) extraInit() { -} - -func (ps *PolicyStore) loadNamespacePolicies(context.Context, *Core) error { return nil } - -func (ps *PolicyStore) getACLView(*namespace.Namespace) *BarrierView { - return ps.aclView -} - -func (ps *PolicyStore) getRGPView(ns *namespace.Namespace) *BarrierView { - return ps.rgpView -} - -func (ps *PolicyStore) getEGPView(ns *namespace.Namespace) *BarrierView { - return ps.egpView -} - -func (ps *PolicyStore) getBarrierView(ns *namespace.Namespace, _ PolicyType) *BarrierView { - return ps.getACLView(ns) -} - -func (ps *PolicyStore) handleSentinelPolicy(context.Context, *Policy, *BarrierView, *logical.StorageEntry) error { - return nil -} - -func (ps *PolicyStore) parseEGPPaths(*Policy) error { return nil } - -func (ps *PolicyStore) invalidateEGPTreePath(string) {} - -func (ps *PolicyStore) pathsToEGPPaths(*Policy) ([]*egpPath, error) { return nil, nil } - -func (ps *PolicyStore) loadACLPolicyNamespaces(ctx context.Context, policyName, policyText string) error { - return ps.loadACLPolicyInternal(namespace.RootContext(ctx), policyName, policyText) -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy_util.go b/vendor/github.com/hashicorp/vault/vault/policy_util.go deleted file mode 100644 index 74b92639..00000000 --- a/vendor/github.com/hashicorp/vault/vault/policy_util.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !enterprise - -package vault - -type sentinelPolicy struct{} diff --git a/vendor/github.com/hashicorp/vault/vault/rekey.go b/vendor/github.com/hashicorp/vault/vault/rekey.go deleted file mode 100644 index ad7d914f..00000000 --- a/vendor/github.com/hashicorp/vault/vault/rekey.go +++ /dev/null @@ -1,972 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/subtle" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/shamir" -) - -const ( - // coreUnsealKeysBackupPath is the path used to backup encrypted unseal - // keys if specified during a rekey operation. This is outside of the - // barrier. - coreBarrierUnsealKeysBackupPath = "core/unseal-keys-backup" - - // coreRecoveryUnsealKeysBackupPath is the path used to backup encrypted - // recovery keys if specified during a rekey operation. This is outside of - // the barrier. - coreRecoveryUnsealKeysBackupPath = "core/recovery-keys-backup" -) - -// RekeyResult is used to provide the key parts back after -// they are generated as part of the rekey. -type RekeyResult struct { - SecretShares [][]byte - PGPFingerprints []string - Backup bool - RecoveryKey bool - VerificationRequired bool - VerificationNonce string -} - -type RekeyVerifyResult struct { - Complete bool - Nonce string -} - -// RekeyBackup stores the backup copy of PGP-encrypted keys -type RekeyBackup struct { - Nonce string - Keys map[string][]string -} - -// RekeyThreshold returns the secret threshold for the current seal -// config. This threshold can either be the barrier key threshold or -// the recovery key threshold, depending on whether rekey is being -// performed on the recovery key, or whether the seal supports -// recovery keys. -func (c *Core) RekeyThreshold(ctx context.Context, recovery bool) (int, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return 0, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return 0, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var config *SealConfig - var err error - // If we are rekeying the recovery key, or if the seal supports - // recovery keys and we are rekeying the barrier key, we use the - // recovery config as the threshold instead. - if recovery || c.seal.RecoveryKeySupported() { - config, err = c.seal.RecoveryConfig(ctx) - } else { - config, err = c.seal.BarrierConfig(ctx) - } - if err != nil { - return 0, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("unable to look up config: {{err}}", err).Error()) - } - if config == nil { - return 0, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - return config.SecretThreshold, nil -} - -// RekeyProgress is used to return the rekey progress (num shares). -func (c *Core) RekeyProgress(recovery, verification bool) (bool, int, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return false, 0, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return false, 0, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var conf *SealConfig - if recovery { - conf = c.recoveryRekeyConfig - } else { - conf = c.barrierRekeyConfig - } - - if conf == nil { - return false, 0, logical.CodedError(http.StatusBadRequest, "rekey operation not in progress") - } - - if verification { - return len(conf.VerificationKey) > 0, len(conf.VerificationProgress), nil - } - return true, len(conf.RekeyProgress), nil -} - -// RekeyConfig is used to read the rekey configuration -func (c *Core) RekeyConfig(recovery bool) (*SealConfig, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Copy the seal config if any - var conf *SealConfig - if recovery { - if c.recoveryRekeyConfig != nil { - conf = c.recoveryRekeyConfig.Clone() - } - } else { - if c.barrierRekeyConfig != nil { - conf = c.barrierRekeyConfig.Clone() - } - } - - return conf, nil -} - -// RekeyInit will either initialize the rekey of barrier or recovery key. -// recovery determines whether this is a rekey on the barrier or recovery key. -func (c *Core) RekeyInit(config *SealConfig, recovery bool) logical.HTTPCodedError { - if config.SecretThreshold > config.SecretShares { - return logical.CodedError(http.StatusBadRequest, "provided threshold greater than the total shares") - } - - if recovery { - return c.RecoveryRekeyInit(config) - } - return c.BarrierRekeyInit(config) -} - -// BarrierRekeyInit is used to initialize the rekey settings for the barrier key -func (c *Core) BarrierRekeyInit(config *SealConfig) logical.HTTPCodedError { - if c.seal.StoredKeysSupported() { - c.logger.Warn("stored keys supported, forcing rekey shares/threshold to 1") - config.SecretShares = 1 - config.SecretThreshold = 1 - config.StoredShares = 1 - } - - if config.StoredShares > 0 { - if !c.seal.StoredKeysSupported() { - return logical.CodedError(http.StatusBadRequest, "storing keys not supported by barrier seal") - } - if len(config.PGPKeys) > 0 { - return logical.CodedError(http.StatusBadRequest, "PGP key encryption not supported when using stored keys") - } - if config.Backup { - return logical.CodedError(http.StatusBadRequest, "key backup not supported when using stored keys") - } - - if c.seal.RecoveryKeySupported() { - if config.VerificationRequired { - return logical.CodedError(http.StatusBadRequest, "requiring verification not supported when rekeying the barrier key with recovery keys") - } - c.logger.Debug("using recovery seal configuration to rekey barrier key") - } - } - - // Check if the seal configuration is valid - if err := config.Validate(); err != nil { - c.logger.Error("invalid rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid rekey seal configuration: {{err}}", err).Error()) - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Prevent multiple concurrent re-keys - if c.barrierRekeyConfig != nil { - return logical.CodedError(http.StatusBadRequest, "rekey already in progress") - } - - // Copy the configuration - c.barrierRekeyConfig = config.Clone() - - // Initialize the nonce - nonce, err := uuid.GenerateUUID() - if err != nil { - c.barrierRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) - } - c.barrierRekeyConfig.Nonce = nonce - - if c.logger.IsInfo() { - c.logger.Info("rekey initialized", "nonce", c.barrierRekeyConfig.Nonce, "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold, "validation_required", c.barrierRekeyConfig.VerificationRequired) - } - return nil -} - -// RecoveryRekeyInit is used to initialize the rekey settings for the recovery key -func (c *Core) RecoveryRekeyInit(config *SealConfig) logical.HTTPCodedError { - if config.StoredShares > 0 { - return logical.CodedError(http.StatusBadRequest, "stored shares not supported by recovery key") - } - - // Check if the seal configuration is valid - if err := config.Validate(); err != nil { - c.logger.Error("invalid recovery configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid recovery configuration: {{err}}", err).Error()) - } - - if !c.seal.RecoveryKeySupported() { - return logical.CodedError(http.StatusBadRequest, "recovery keys not supported") - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Prevent multiple concurrent re-keys - if c.recoveryRekeyConfig != nil { - return logical.CodedError(http.StatusBadRequest, "rekey already in progress") - } - - // Copy the configuration - c.recoveryRekeyConfig = config.Clone() - - // Initialize the nonce - nonce, err := uuid.GenerateUUID() - if err != nil { - c.recoveryRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) - } - c.recoveryRekeyConfig.Nonce = nonce - - if c.logger.IsInfo() { - c.logger.Info("rekey initialized", "nonce", c.recoveryRekeyConfig.Nonce, "shares", c.recoveryRekeyConfig.SecretShares, "threshold", c.recoveryRekeyConfig.SecretThreshold, "validation_required", c.recoveryRekeyConfig.VerificationRequired) - } - return nil -} - -// RekeyUpdate is used to provide a new key part for the barrier or recovery key. -func (c *Core) RekeyUpdate(ctx context.Context, key []byte, nonce string, recovery bool) (*RekeyResult, logical.HTTPCodedError) { - if recovery { - return c.RecoveryRekeyUpdate(ctx, key, nonce) - } - return c.BarrierRekeyUpdate(ctx, key, nonce) -} - -// BarrierRekeyUpdate is used to provide a new key part. Barrier rekey can be done -// with unseal keys, or recovery keys if that's supported and we are storing the barrier -// key. -// -// N.B.: If recovery keys are used to rekey, the new barrier key shares are not returned. -func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) (*RekeyResult, logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Get the seal configuration - var existingConfig *SealConfig - var err error - var useRecovery bool // Determines whether recovery key is being used to rekey the master key - if c.seal.StoredKeysSupported() && c.seal.RecoveryKeySupported() { - existingConfig, err = c.seal.RecoveryConfig(ctx) - useRecovery = true - } else { - existingConfig, err = c.seal.BarrierConfig(ctx) - } - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing config: {{err}}", err).Error()) - } - // Ensure the barrier is initialized - if existingConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - // Ensure a rekey is in progress - if c.barrierRekeyConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no barrier rekey in progress") - } - - if len(c.barrierRekeyConfig.VerificationKey) > 0 { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("rekey operation already finished; verification must be performed; nonce for the verification operation is %q", c.barrierRekeyConfig.VerificationNonce)) - } - - if nonce != c.barrierRekeyConfig.Nonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this rekey operation is %q", c.barrierRekeyConfig.Nonce)) - } - - // Check if we already have this piece - for _, existing := range c.barrierRekeyConfig.RekeyProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this generation operation") - } - } - - // Store this key - c.barrierRekeyConfig.RekeyProgress = append(c.barrierRekeyConfig.RekeyProgress, key) - - // Check if we don't have enough keys to unlock - if len(c.barrierRekeyConfig.RekeyProgress) < existingConfig.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot rekey yet, not enough keys", "keys", len(c.barrierRekeyConfig.RekeyProgress), "threshold", existingConfig.SecretThreshold) - } - return nil, nil - } - - // Recover the master key or recovery key - var recoveredKey []byte - if existingConfig.SecretThreshold == 1 { - recoveredKey = c.barrierRekeyConfig.RekeyProgress[0] - c.barrierRekeyConfig.RekeyProgress = nil - } else { - recoveredKey, err = shamir.Combine(c.barrierRekeyConfig.RekeyProgress) - c.barrierRekeyConfig.RekeyProgress = nil - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute master key: {{err}}", err).Error()) - } - } - - if useRecovery { - if err := c.seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil { - c.logger.Error("rekey recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) - } - } else { - if err := c.barrier.VerifyMaster(recoveredKey); err != nil { - c.logger.Error("master key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("master key verification failed: {{err}}", err).Error()) - } - } - - // Generate a new master key - newMasterKey, err := c.barrier.GenerateKey() - if err != nil { - c.logger.Error("failed to generate master key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("master key generation failed: {{err}}", err).Error()) - } - - results := &RekeyResult{ - Backup: c.barrierRekeyConfig.Backup, - } - // Set result.SecretShares to the master key if only a single key - // part is used -- no Shamir split required. - if c.barrierRekeyConfig.SecretShares == 1 { - results.SecretShares = append(results.SecretShares, newMasterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(newMasterKey, c.barrierRekeyConfig.SecretShares, c.barrierRekeyConfig.SecretThreshold) - if err != nil { - c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) - } - results.SecretShares = shares - } - - // If we are storing any shares, add them to the shares to store and remove - // from the returned keys - var keysToStore [][]byte - if c.seal.StoredKeysSupported() && c.barrierRekeyConfig.StoredShares > 0 { - for i := 0; i < c.barrierRekeyConfig.StoredShares; i++ { - keysToStore = append(keysToStore, results.SecretShares[0]) - results.SecretShares = results.SecretShares[1:] - } - } - - // If PGP keys are passed in, encrypt shares with corresponding PGP keys. - if len(c.barrierRekeyConfig.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(results.SecretShares)) - for i, _ := range results.SecretShares { - hexEncodedShares[i] = []byte(hex.EncodeToString(results.SecretShares[i])) - } - results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.barrierRekeyConfig.PGPKeys) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) - } - - // If backup is enabled, store backup info in vault.coreBarrierUnsealKeysBackupPath - if c.barrierRekeyConfig.Backup { - backupInfo := map[string][]string{} - for i := 0; i < len(results.PGPFingerprints); i++ { - encShare := bytes.NewBuffer(results.SecretShares[i]) - if backupInfo[results.PGPFingerprints[i]] == nil { - backupInfo[results.PGPFingerprints[i]] = []string{hex.EncodeToString(encShare.Bytes())} - } else { - backupInfo[results.PGPFingerprints[i]] = append(backupInfo[results.PGPFingerprints[i]], hex.EncodeToString(encShare.Bytes())) - } - } - - backupVals := &RekeyBackup{ - Nonce: c.barrierRekeyConfig.Nonce, - Keys: backupInfo, - } - buf, err := json.Marshal(backupVals) - if err != nil { - c.logger.Error("failed to marshal unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal unseal key backup: {{err}}", err).Error()) - } - pe := &physical.Entry{ - Key: coreBarrierUnsealKeysBackupPath, - Value: buf, - } - if err = c.physical.Put(ctx, pe); err != nil { - c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) - } - } - } - - if keysToStore != nil { - if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { - c.logger.Error("failed to store keys", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to store keys: {{err}}", err).Error()) - } - } - - // If we are requiring validation, return now; otherwise rekey the barrier - if c.barrierRekeyConfig.VerificationRequired { - nonce, err := uuid.GenerateUUID() - if err != nil { - c.barrierRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) - } - c.barrierRekeyConfig.VerificationNonce = nonce - c.barrierRekeyConfig.VerificationKey = newMasterKey - - results.VerificationRequired = true - results.VerificationNonce = nonce - return results, nil - } - - if err := c.performBarrierRekey(ctx, newMasterKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform barrier rekey: {{err}}", err).Error()) - } - - c.barrierRekeyConfig = nil - return results, nil -} - -func (c *Core) performBarrierRekey(ctx context.Context, newMasterKey []byte) logical.HTTPCodedError { - // Rekey the barrier - if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { - c.logger.Error("failed to rekey barrier", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to rekey barrier: {{err}}", err).Error()) - } - if c.logger.IsInfo() { - c.logger.Info("security barrier rekeyed", "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold) - } - - c.barrierRekeyConfig.VerificationKey = nil - - if err := c.seal.SetBarrierConfig(ctx, c.barrierRekeyConfig); err != nil { - c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := c.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(c.barrierRekeyConfig.Nonce), - }); err != nil { - c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) - } - - c.barrierRekeyConfig.RekeyProgress = nil - - return nil -} - -// RecoveryRekeyUpdate is used to provide a new key part -func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string) (*RekeyResult, logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Get the seal configuration - existingConfig, err := c.seal.RecoveryConfig(ctx) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing recovery config: {{err}}", err).Error()) - } - // Ensure the seal is initialized - if existingConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - // Ensure a rekey is in progress - if c.recoveryRekeyConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no recovery rekey in progress") - } - - if len(c.recoveryRekeyConfig.VerificationKey) > 0 { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("rekey operation already finished; verification must be performed; nonce for the verification operation is %q", c.recoveryRekeyConfig.VerificationNonce)) - } - - if nonce != c.recoveryRekeyConfig.Nonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this rekey operation is %q", c.recoveryRekeyConfig.Nonce)) - } - - // Check if we already have this piece - for _, existing := range c.recoveryRekeyConfig.RekeyProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this rekey operation") - } - } - - // Store this key - c.recoveryRekeyConfig.RekeyProgress = append(c.recoveryRekeyConfig.RekeyProgress, key) - - // Check if we don't have enough keys to unlock - if len(c.recoveryRekeyConfig.RekeyProgress) < existingConfig.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot rekey yet, not enough keys", "keys", len(c.recoveryRekeyConfig.RekeyProgress), "threshold", existingConfig.SecretThreshold) - } - return nil, nil - } - - // Recover the master key - var recoveryKey []byte - if existingConfig.SecretThreshold == 1 { - recoveryKey = c.recoveryRekeyConfig.RekeyProgress[0] - c.recoveryRekeyConfig.RekeyProgress = nil - } else { - recoveryKey, err = shamir.Combine(c.recoveryRekeyConfig.RekeyProgress) - c.recoveryRekeyConfig.RekeyProgress = nil - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute recovery key: {{err}}", err).Error()) - } - } - - // Verify the recovery key - if err := c.seal.VerifyRecoveryKey(ctx, recoveryKey); err != nil { - c.logger.Error("recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) - } - - // Generate a new master key - newMasterKey, err := c.barrier.GenerateKey() - if err != nil { - c.logger.Error("failed to generate recovery key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("recovery key generation failed: {{err}}", err).Error()) - } - - // Return the master key if only a single key part is used - results := &RekeyResult{ - Backup: c.recoveryRekeyConfig.Backup, - } - - if c.recoveryRekeyConfig.SecretShares == 1 { - results.SecretShares = append(results.SecretShares, newMasterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(newMasterKey, c.recoveryRekeyConfig.SecretShares, c.recoveryRekeyConfig.SecretThreshold) - if err != nil { - c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) - } - results.SecretShares = shares - } - - if len(c.recoveryRekeyConfig.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(results.SecretShares)) - for i, _ := range results.SecretShares { - hexEncodedShares[i] = []byte(hex.EncodeToString(results.SecretShares[i])) - } - results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.recoveryRekeyConfig.PGPKeys) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) - } - - if c.recoveryRekeyConfig.Backup { - backupInfo := map[string][]string{} - for i := 0; i < len(results.PGPFingerprints); i++ { - encShare := bytes.NewBuffer(results.SecretShares[i]) - if backupInfo[results.PGPFingerprints[i]] == nil { - backupInfo[results.PGPFingerprints[i]] = []string{hex.EncodeToString(encShare.Bytes())} - } else { - backupInfo[results.PGPFingerprints[i]] = append(backupInfo[results.PGPFingerprints[i]], hex.EncodeToString(encShare.Bytes())) - } - } - - backupVals := &RekeyBackup{ - Nonce: c.recoveryRekeyConfig.Nonce, - Keys: backupInfo, - } - buf, err := json.Marshal(backupVals) - if err != nil { - c.logger.Error("failed to marshal recovery key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal recovery key backup: {{err}}", err).Error()) - } - pe := &physical.Entry{ - Key: coreRecoveryUnsealKeysBackupPath, - Value: buf, - } - if err = c.physical.Put(ctx, pe); err != nil { - c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) - } - } - } - - // If we are requiring validation, return now; otherwise save the recovery - // key - if c.recoveryRekeyConfig.VerificationRequired { - nonce, err := uuid.GenerateUUID() - if err != nil { - c.recoveryRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) - } - c.recoveryRekeyConfig.VerificationNonce = nonce - c.recoveryRekeyConfig.VerificationKey = newMasterKey - - results.VerificationRequired = true - results.VerificationNonce = nonce - return results, nil - } - - if err := c.performRecoveryRekey(ctx, newMasterKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery rekey: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig = nil - return results, nil -} - -func (c *Core) performRecoveryRekey(ctx context.Context, newMasterKey []byte) logical.HTTPCodedError { - if err := c.seal.SetRecoveryKey(ctx, newMasterKey); err != nil { - c.logger.Error("failed to set recovery key", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to set recovery key: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig.VerificationKey = nil - - if err := c.seal.SetRecoveryConfig(ctx, c.recoveryRekeyConfig); err != nil { - c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := c.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(c.recoveryRekeyConfig.Nonce), - }); err != nil { - c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig.RekeyProgress = nil - - return nil -} - -func (c *Core) RekeyVerify(ctx context.Context, key []byte, nonce string, recovery bool) (ret *RekeyVerifyResult, retErr logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - config := c.barrierRekeyConfig - if recovery { - config = c.recoveryRekeyConfig - } - - // Ensure a rekey is in progress - if config == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no rekey in progress") - } - - if len(config.VerificationKey) == 0 { - return nil, logical.CodedError(http.StatusBadRequest, "no rekey verification in progress") - } - - if nonce != config.VerificationNonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this verify operation is %q", config.VerificationNonce)) - } - - // Check if we already have this piece - for _, existing := range config.VerificationProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this verify operation") - } - } - - // Store this key - config.VerificationProgress = append(config.VerificationProgress, key) - - // Check if we don't have enough keys to unlock - if len(config.VerificationProgress) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot verify yet, not enough keys", "keys", len(config.VerificationProgress), "threshold", config.SecretThreshold) - } - return nil, nil - } - - // Schedule the progress for forgetting and rotate the nonce if possible - defer func() { - config.VerificationProgress = nil - if ret != nil && ret.Complete { - return - } - // Not complete, so rotate nonce - nonce, err := uuid.GenerateUUID() - if err == nil { - config.VerificationNonce = nonce - if ret != nil { - ret.Nonce = nonce - } - } - }() - - // Recover the master key or recovery key - var recoveredKey []byte - if config.SecretThreshold == 1 { - recoveredKey = config.VerificationProgress[0] - } else { - var err error - recoveredKey, err = shamir.Combine(config.VerificationProgress) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute key for verification: {{err}}", err).Error()) - } - } - - if subtle.ConstantTimeCompare(recoveredKey, config.VerificationKey) != 1 { - c.logger.Error("rekey verification failed") - return nil, logical.CodedError(http.StatusBadRequest, "rekey verification failed; incorrect key shares supplied") - } - - switch recovery { - case false: - if err := c.performBarrierRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform rekey: {{err}}", err).Error()) - } - c.barrierRekeyConfig = nil - default: - if err := c.performRecoveryRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery key rekey: {{err}}", err).Error()) - } - c.recoveryRekeyConfig = nil - } - - res := &RekeyVerifyResult{ - Nonce: config.VerificationNonce, - Complete: true, - } - - return res, nil -} - -// RekeyCancel is used to cancel an in-progress rekey -func (c *Core) RekeyCancel(recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Clear any progress or config - if recovery { - c.recoveryRekeyConfig = nil - } else { - c.barrierRekeyConfig = nil - } - return nil -} - -// RekeyVerifyRestart is used to start the verification process over -func (c *Core) RekeyVerifyRestart(recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Attempt to generate a new nonce, but don't bail if it doesn't succeed - // (which is extraordinarily unlikely) - nonce, nonceErr := uuid.GenerateUUID() - - // Clear any progress or config - if recovery { - c.recoveryRekeyConfig.VerificationProgress = nil - if nonceErr == nil { - c.recoveryRekeyConfig.VerificationNonce = nonce - } - } else { - c.barrierRekeyConfig.VerificationProgress = nil - if nonceErr == nil { - c.barrierRekeyConfig.VerificationNonce = nonce - } - } - - return nil -} - -// RekeyRetrieveBackup is used to retrieve any backed-up PGP-encrypted unseal -// keys -func (c *Core) RekeyRetrieveBackup(ctx context.Context, recovery bool) (*RekeyBackup, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var entry *physical.Entry - var err error - if recovery { - entry, err = c.physical.Get(ctx, coreRecoveryUnsealKeysBackupPath) - } else { - entry, err = c.physical.Get(ctx, coreBarrierUnsealKeysBackupPath) - } - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error getting keys from backup: {{err}}", err).Error()) - } - if entry == nil { - return nil, nil - } - - ret := &RekeyBackup{} - err = jsonutil.DecodeJSON(entry.Value, ret) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error decoding backup keys: {{err}}", err).Error()) - } - - return ret, nil -} - -// RekeyDeleteBackup is used to delete any backed-up PGP-encrypted unseal keys -func (c *Core) RekeyDeleteBackup(ctx context.Context, recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - if recovery { - err := c.physical.Delete(ctx, coreRecoveryUnsealKeysBackupPath) - if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) - } - return nil - } - err := c.physical.Delete(ctx, coreBarrierUnsealKeysBackupPath) - if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/replication_cluster_util.go b/vendor/github.com/hashicorp/vault/vault/replication_cluster_util.go deleted file mode 100644 index 013cc8f7..00000000 --- a/vendor/github.com/hashicorp/vault/vault/replication_cluster_util.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !enterprise - -package vault - -import "github.com/hashicorp/vault/helper/consts" - -type ReplicatedCluster struct { - State consts.ReplicationState - ClusterID string - PrimaryClusterAddr string -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding.go deleted file mode 100644 index d0fbd286..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding.go +++ /dev/null @@ -1,479 +0,0 @@ -package vault - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - math "math" - "net" - "net/http" - "net/url" - "sync" - "sync/atomic" - "time" - - cache "github.com/patrickmn/go-cache" - - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/forwarding" - "golang.org/x/net/http2" - "google.golang.org/grpc" - "google.golang.org/grpc/keepalive" -) - -const ( - clusterListenerAcceptDeadline = 500 * time.Millisecond - - // 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" -) - -var ( - // Making this a package var allows tests to modify - HeartbeatInterval = 5 * time.Second -) - -type SecondaryConnsCacheVals struct { - ID string - Token string - Connection net.Conn - Mode consts.ReplicationState -} - -// Starts the listeners and servers necessary to handle forwarded requests -func (c *Core) startForwarding(ctx context.Context) error { - c.logger.Debug("cluster listener setup function") - defer c.logger.Debug("leaving cluster listener setup function") - - // Clean up in case we have transitioned from a client to a server - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - // Resolve locally to avoid races - ha := c.ha != nil - - var perfStandbyRepCluster *ReplicatedCluster - if ha { - id, err := uuid.GenerateUUID() - if err != nil { - return err - } - - perfStandbyRepCluster = &ReplicatedCluster{ - State: consts.ReplicationPerformanceStandby, - ClusterID: id, - PrimaryClusterAddr: c.clusterAddr, - } - if err = c.setupReplicatedClusterPrimary(perfStandbyRepCluster); err != nil { - return err - } - } - - // Get our TLS config - tlsConfig, err := c.ClusterTLSConfig(ctx, nil, perfStandbyRepCluster) - if err != nil { - c.logger.Error("failed to get tls configuration when starting forwarding", "error", err) - return err - } - - // The server supports all of the possible protos - tlsConfig.NextProtos = []string{"h2", requestForwardingALPN, perfStandbyALPN, PerformanceReplicationALPN, DRReplicationALPN} - - if !atomic.CompareAndSwapUint32(c.rpcServerActive, 0, 1) { - c.logger.Warn("forwarding rpc server already running") - return nil - } - - fwRPCServer := grpc.NewServer( - grpc.KeepaliveParams(keepalive.ServerParameters{ - Time: 2 * HeartbeatInterval, - }), - grpc.MaxRecvMsgSize(math.MaxInt32), - grpc.MaxSendMsgSize(math.MaxInt32), - ) - - // Setup performance standby RPC servers - perfStandbyCount := 0 - if !c.IsDRSecondary() && !c.disablePerfStandby { - perfStandbyCount = c.perfStandbyCount() - } - perfStandbySlots := make(chan struct{}, perfStandbyCount) - - perfStandbyCache := cache.New(2*HeartbeatInterval, 1*time.Second) - perfStandbyCache.OnEvicted(func(secondaryID string, _ interface{}) { - c.logger.Debug("removing performance standby", "id", secondaryID) - c.removePerfStandbySecondary(context.Background(), secondaryID) - select { - case <-perfStandbySlots: - default: - c.logger.Warn("perf secondary timeout hit but no slot to free") - } - }) - - perfStandbyReplicationRPCServer := perfStandbyRPCServer(c, perfStandbyCache) - - if ha && c.clusterHandler != nil { - RegisterRequestForwardingServer(fwRPCServer, &forwardedRequestRPCServer{ - core: c, - handler: c.clusterHandler, - perfStandbySlots: perfStandbySlots, - perfStandbyRepCluster: perfStandbyRepCluster, - perfStandbyCache: perfStandbyCache, - }) - } - - // Create the HTTP/2 server that will be shared by both RPC and regular - // duties. Doing it this way instead of listening via the server and gRPC - // allows us to re-use the same port via ALPN. We can just tell the server - // to serve a given conn and which handler to use. - fws := &http2.Server{ - // Our forwarding connections heartbeat regularly so anything else we - // want to go away/get cleaned up pretty rapidly - IdleTimeout: 5 * HeartbeatInterval, - } - - // Shutdown coordination logic - shutdown := new(uint32) - shutdownWg := &sync.WaitGroup{} - - for _, addr := range c.clusterListenerAddrs { - shutdownWg.Add(1) - - // Force a local resolution to avoid data races - laddr := addr - - // Start our listening loop - go func() { - defer shutdownWg.Done() - - // closeCh is used to shutdown the spawned goroutines once this - // function returns - closeCh := make(chan struct{}) - defer func() { - close(closeCh) - }() - - if c.logger.IsInfo() { - c.logger.Info("starting listener", "listener_address", laddr) - } - - // Create a TCP listener. We do this separately and specifically - // with TCP so that we can set deadlines. - tcpLn, err := net.ListenTCP("tcp", laddr) - if err != nil { - c.logger.Error("error starting listener", "error", err) - return - } - - // Wrap the listener with TLS - tlsLn := tls.NewListener(tcpLn, tlsConfig) - defer tlsLn.Close() - - if c.logger.IsInfo() { - c.logger.Info("serving cluster requests", "cluster_listen_address", tlsLn.Addr()) - } - - for { - if atomic.LoadUint32(shutdown) > 0 { - return - } - - // Set the deadline for the accept call. If it passes we'll get - // an error, causing us to check the condition at the top - // again. - tcpLn.SetDeadline(time.Now().Add(clusterListenerAcceptDeadline)) - - // Accept the connection - conn, err := tlsLn.Accept() - if err != nil { - if err, ok := err.(net.Error); ok && !err.Timeout() { - c.logger.Debug("non-timeout error accepting on cluster port", "error", err) - } - if conn != nil { - conn.Close() - } - continue - } - if conn == nil { - continue - } - - // Type assert to TLS connection and handshake to populate the - // connection state - tlsConn := conn.(*tls.Conn) - - // Set a deadline for the handshake. This will cause clients - // that don't successfully auth to be kicked out quickly. - // Cluster connections should be reliable so being marginally - // aggressive here is fine. - err = tlsConn.SetDeadline(time.Now().Add(30 * time.Second)) - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error setting deadline for cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - err = tlsConn.Handshake() - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error handshaking cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - // Now, set it back to unlimited - err = tlsConn.SetDeadline(time.Time{}) - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error setting deadline for cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - switch tlsConn.ConnectionState().NegotiatedProtocol { - case requestForwardingALPN: - if !ha { - tlsConn.Close() - continue - } - - c.logger.Debug("got request forwarding connection") - - shutdownWg.Add(2) - // quitCh is used to close the connection and the second - // goroutine if the server closes before closeCh. - quitCh := make(chan struct{}) - go func() { - select { - case <-quitCh: - case <-closeCh: - } - tlsConn.Close() - shutdownWg.Done() - }() - - go func() { - fws.ServeConn(tlsConn, &http2.ServeConnOpts{ - Handler: fwRPCServer, - BaseConfig: &http.Server{ - ErrorLog: c.logger.StandardLogger(nil), - }, - }) - // close the quitCh which will close the connection and - // the other goroutine. - close(quitCh) - shutdownWg.Done() - }() - - case PerformanceReplicationALPN, DRReplicationALPN, perfStandbyALPN: - handleReplicationConn(ctx, c, shutdownWg, closeCh, fws, perfStandbyReplicationRPCServer, perfStandbyCache, tlsConn) - default: - c.logger.Debug("unknown negotiated protocol on cluster port") - tlsConn.Close() - continue - } - } - }() - } - - // This is in its own goroutine so that we don't block the main thread, and - // thus we use atomic and channels to coordinate - // However, because you can't query the status of a channel, we set a bool - // here while we have the state lock to know whether to actually send a - // shutdown (e.g. whether the channel will block). See issue #2083. - c.clusterListenersRunning = true - go func() { - // If we get told to shut down... - <-c.clusterListenerShutdownCh - - // Stop the RPC server - c.logger.Info("shutting down forwarding rpc listeners") - fwRPCServer.Stop() - - // Set the shutdown flag. This will cause the listeners to shut down - // within the deadline in clusterListenerAcceptDeadline - atomic.StoreUint32(shutdown, 1) - c.logger.Info("forwarding rpc listeners stopped") - - // Wait for them all to shut down - shutdownWg.Wait() - c.logger.Info("rpc listeners successfully shut down") - - // Clear us up to run this function again - atomic.StoreUint32(c.rpcServerActive, 0) - - // Tell the main thread that shutdown is done. - c.clusterListenerShutdownSuccessCh <- struct{}{} - }() - - return nil -} - -// refreshRequestForwardingConnection ensures that the client/transport are -// alive and that the current active address value matches the most -// recently-known address. -func (c *Core) refreshRequestForwardingConnection(ctx context.Context, clusterAddr string) error { - c.logger.Debug("refreshing forwarding connection") - defer c.logger.Debug("done refreshing forwarding connection") - - c.requestForwardingConnectionLock.Lock() - defer c.requestForwardingConnectionLock.Unlock() - - // Clean things up first - c.clearForwardingClients() - - // If we don't have anything to connect to, just return - if clusterAddr == "" { - return nil - } - - clusterURL, err := url.Parse(clusterAddr) - if err != nil { - c.logger.Error("error parsing cluster address attempting to refresh forwarding connection", "error", err) - return err - } - - // Set up grpc forwarding handling - // It's not really insecure, but we have to dial manually to get the - // ALPN header right. It's just "insecure" because GRPC isn't managing - // the TLS state. - dctx, cancelFunc := context.WithCancel(ctx) - c.rpcClientConn, err = grpc.DialContext(dctx, clusterURL.Host, - grpc.WithDialer(c.getGRPCDialer(ctx, requestForwardingALPN, "", nil, nil, nil)), - grpc.WithInsecure(), // it's not, we handle it in the dialer - grpc.WithKeepaliveParams(keepalive.ClientParameters{ - Time: 2 * HeartbeatInterval, - }), - grpc.WithDefaultCallOptions( - grpc.MaxCallRecvMsgSize(math.MaxInt32), - grpc.MaxCallSendMsgSize(math.MaxInt32), - )) - if err != nil { - cancelFunc() - c.logger.Error("err setting up forwarding rpc client", "error", err) - return err - } - c.rpcClientConnContext = dctx - c.rpcClientConnCancelFunc = cancelFunc - c.rpcForwardingClient = &forwardingClient{ - RequestForwardingClient: NewRequestForwardingClient(c.rpcClientConn), - core: c, - echoTicker: time.NewTicker(HeartbeatInterval), - echoContext: dctx, - } - c.rpcForwardingClient.startHeartbeat() - - return nil -} - -func (c *Core) clearForwardingClients() { - c.logger.Debug("clearing forwarding clients") - defer c.logger.Debug("done clearing forwarding clients") - - if c.rpcClientConnCancelFunc != nil { - c.rpcClientConnCancelFunc() - c.rpcClientConnCancelFunc = nil - } - if c.rpcClientConn != nil { - c.rpcClientConn.Close() - c.rpcClientConn = nil - } - - c.rpcClientConnContext = nil - c.rpcForwardingClient = nil -} - -// ForwardRequest forwards a given request to the active node and returns the -// response. -func (c *Core) ForwardRequest(req *http.Request) (int, http.Header, []byte, error) { - c.requestForwardingConnectionLock.RLock() - defer c.requestForwardingConnectionLock.RUnlock() - - if c.rpcForwardingClient == nil { - return 0, nil, nil, ErrCannotForward - } - - origPath := req.URL.Path - defer func() { - req.URL.Path = origPath - }() - - req.URL.Path = req.Context().Value("original_request_path").(string) - - freq, err := forwarding.GenerateForwardedRequest(req) - if err != nil { - c.logger.Error("error creating forwarding RPC request", "error", err) - return 0, nil, nil, fmt.Errorf("error creating forwarding RPC request") - } - if freq == nil { - c.logger.Error("got nil forwarding RPC request") - return 0, nil, nil, fmt.Errorf("got nil forwarding RPC request") - } - resp, err := c.rpcForwardingClient.ForwardRequest(c.rpcClientConnContext, freq) - if err != nil { - c.logger.Error("error during forwarded RPC request", "error", err) - return 0, nil, nil, fmt.Errorf("error during forwarding RPC request") - } - - var header http.Header - if resp.HeaderEntries != nil { - header = make(http.Header) - for k, v := range resp.HeaderEntries { - header[k] = v.Values - } - } - - // If we are a perf standby and the request was forwarded to the active node - // we should attempt to wait for the WAL to ship to offer best effort read after - // write guarantees - if c.perfStandby && resp.LastRemoteWal > 0 { - WaitUntilWALShipped(req.Context(), c, resp.LastRemoteWal) - } - - return int(resp.StatusCode), header, resp.Body, nil -} - -// getGRPCDialer is used to return a dialer that has the correct TLS -// configuration. Otherwise gRPC tries to be helpful and stomps all over our -// NextProtos. -func (c *Core) getGRPCDialer(ctx context.Context, alpnProto, serverName string, caCert *x509.Certificate, repClusters *ReplicatedClusters, perfStandbyCluster *ReplicatedCluster) func(string, time.Duration) (net.Conn, error) { - return func(addr string, timeout time.Duration) (net.Conn, error) { - tlsConfig, err := c.ClusterTLSConfig(ctx, repClusters, perfStandbyCluster) - if err != nil { - c.logger.Error("failed to get tls configuration", "error", err) - return nil, err - } - if serverName != "" { - tlsConfig.ServerName = serverName - } - if caCert != nil { - pool := x509.NewCertPool() - pool.AddCert(caCert) - tlsConfig.RootCAs = pool - tlsConfig.ClientCAs = pool - } - c.logger.Debug("creating rpc dialer", "host", tlsConfig.ServerName) - - tlsConfig.NextProtos = []string{alpnProto} - dialer := &net.Dialer{ - Timeout: timeout, - } - return tls.DialWithDialer(dialer, "tcp", addr, tlsConfig) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc.go deleted file mode 100644 index b3b6e0b0..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc.go +++ /dev/null @@ -1,133 +0,0 @@ -package vault - -import ( - "context" - "net/http" - "runtime" - "sync/atomic" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/forwarding" - cache "github.com/patrickmn/go-cache" -) - -type forwardedRequestRPCServer struct { - core *Core - handler http.Handler - perfStandbySlots chan struct{} - perfStandbyRepCluster *ReplicatedCluster - perfStandbyCache *cache.Cache -} - -func (s *forwardedRequestRPCServer) ForwardRequest(ctx context.Context, freq *forwarding.Request) (*forwarding.Response, error) { - // Parse an http.Request out of it - req, err := forwarding.ParseForwardedRequest(freq) - if err != nil { - return nil, err - } - - // A very dummy response writer that doesn't follow normal semantics, just - // lets you write a status code (last written wins) and a body. But it - // meets the interface requirements. - w := forwarding.NewRPCResponseWriter() - - resp := &forwarding.Response{} - - runRequest := func() { - defer func() { - // Logic here comes mostly from the Go source code - if err := recover(); err != nil { - const size = 64 << 10 - buf := make([]byte, size) - buf = buf[:runtime.Stack(buf, false)] - s.core.logger.Error("panic serving forwarded request", "path", req.URL.Path, "error", err, "stacktrace", string(buf)) - } - }() - s.handler.ServeHTTP(w, req) - } - runRequest() - resp.StatusCode = uint32(w.StatusCode()) - resp.Body = w.Body().Bytes() - - header := w.Header() - if header != nil { - resp.HeaderEntries = make(map[string]*forwarding.HeaderEntry, len(header)) - for k, v := range header { - resp.HeaderEntries[k] = &forwarding.HeaderEntry{ - Values: v, - } - } - } - - resp.LastRemoteWal = LastRemoteWAL(s.core) - - return resp, nil -} - -func (s *forwardedRequestRPCServer) Echo(ctx context.Context, in *EchoRequest) (*EchoReply, error) { - if in.ClusterAddr != "" { - s.core.clusterPeerClusterAddrsCache.Set(in.ClusterAddr, nil, 0) - } - return &EchoReply{ - Message: "pong", - ReplicationState: uint32(s.core.ReplicationState()), - }, nil -} - -type forwardingClient struct { - RequestForwardingClient - - core *Core - - echoTicker *time.Ticker - echoContext context.Context -} - -// NOTE: we also take advantage of gRPC's keepalive bits, but as we send data -// with these requests it's useful to keep this as well -func (c *forwardingClient) startHeartbeat() { - go func() { - tick := func() { - c.core.stateLock.RLock() - clusterAddr := c.core.clusterAddr - c.core.stateLock.RUnlock() - - ctx, cancel := context.WithTimeout(c.echoContext, 2*time.Second) - resp, err := c.RequestForwardingClient.Echo(ctx, &EchoRequest{ - Message: "ping", - ClusterAddr: clusterAddr, - }) - cancel() - if err != nil { - c.core.logger.Debug("forwarding: error sending echo request to active node", "error", err) - return - } - if resp == nil { - c.core.logger.Debug("forwarding: empty echo response from active node") - return - } - if resp.Message != "pong" { - c.core.logger.Debug("forwarding: unexpected echo response from active node", "message", resp.Message) - return - } - // Store the active node's replication state to display in - // sys/health calls - atomic.StoreUint32(c.core.activeNodeReplicationState, resp.ReplicationState) - } - - tick() - - for { - select { - case <-c.echoContext.Done(): - c.echoTicker.Stop() - c.core.logger.Debug("forwarding: stopping heartbeating") - atomic.StoreUint32(c.core.activeNodeReplicationState, uint32(consts.ReplicationUnknown)) - return - case <-c.echoTicker.C: - tick() - } - } - }() -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc_util.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc_util.go deleted file mode 100644 index f4cd607d..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_rpc_util.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" -) - -func (s *forwardedRequestRPCServer) PerformanceStandbyElectionRequest(in *PerfStandbyElectionInput, reqServ RequestForwarding_PerformanceStandbyElectionRequestServer) error { - return nil -} - -type ReplicationTokenInfo struct{} - -func (c *forwardingClient) PerformanceStandbyElection(ctx context.Context) (*ReplicationTokenInfo, error) { - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go deleted file mode 100644 index 6f1ce084..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go +++ /dev/null @@ -1,527 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: vault/request_forwarding_service.proto - -package vault - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - forwarding "github.com/hashicorp/vault/helper/forwarding" - 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 EchoRequest struct { - Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - // ClusterAddr is used to send up a standby node's address to the active - // node upon heartbeat - ClusterAddr string `protobuf:"bytes,2,opt,name=cluster_addr,json=clusterAddr,proto3" json:"cluster_addr,omitempty"` - // ClusterAddrs is used to send up a list of cluster addresses to a dr - // primary from a dr secondary - ClusterAddrs []string `protobuf:"bytes,3,rep,name=cluster_addrs,json=clusterAddrs,proto3" json:"cluster_addrs,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoRequest) Reset() { *m = EchoRequest{} } -func (m *EchoRequest) String() string { return proto.CompactTextString(m) } -func (*EchoRequest) ProtoMessage() {} -func (*EchoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f5f7512e4ab7b58a, []int{0} -} - -func (m *EchoRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoRequest.Unmarshal(m, b) -} -func (m *EchoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoRequest.Marshal(b, m, deterministic) -} -func (m *EchoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoRequest.Merge(m, src) -} -func (m *EchoRequest) XXX_Size() int { - return xxx_messageInfo_EchoRequest.Size(m) -} -func (m *EchoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_EchoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoRequest proto.InternalMessageInfo - -func (m *EchoRequest) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *EchoRequest) GetClusterAddr() string { - if m != nil { - return m.ClusterAddr - } - return "" -} - -func (m *EchoRequest) GetClusterAddrs() []string { - if m != nil { - return m.ClusterAddrs - } - return nil -} - -type EchoReply struct { - Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - ClusterAddrs []string `protobuf:"bytes,2,rep,name=cluster_addrs,json=clusterAddrs,proto3" json:"cluster_addrs,omitempty"` - ReplicationState uint32 `protobuf:"varint,3,opt,name=replication_state,json=replicationState,proto3" json:"replication_state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoReply) Reset() { *m = EchoReply{} } -func (m *EchoReply) String() string { return proto.CompactTextString(m) } -func (*EchoReply) ProtoMessage() {} -func (*EchoReply) Descriptor() ([]byte, []int) { - return fileDescriptor_f5f7512e4ab7b58a, []int{1} -} - -func (m *EchoReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoReply.Unmarshal(m, b) -} -func (m *EchoReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoReply.Marshal(b, m, deterministic) -} -func (m *EchoReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoReply.Merge(m, src) -} -func (m *EchoReply) XXX_Size() int { - return xxx_messageInfo_EchoReply.Size(m) -} -func (m *EchoReply) XXX_DiscardUnknown() { - xxx_messageInfo_EchoReply.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoReply proto.InternalMessageInfo - -func (m *EchoReply) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *EchoReply) GetClusterAddrs() []string { - if m != nil { - return m.ClusterAddrs - } - return nil -} - -func (m *EchoReply) GetReplicationState() uint32 { - if m != nil { - return m.ReplicationState - } - return 0 -} - -type ClientKey struct { - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - X []byte `protobuf:"bytes,2,opt,name=x,proto3" json:"x,omitempty"` - Y []byte `protobuf:"bytes,3,opt,name=y,proto3" json:"y,omitempty"` - D []byte `protobuf:"bytes,4,opt,name=d,proto3" json:"d,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientKey) Reset() { *m = ClientKey{} } -func (m *ClientKey) String() string { return proto.CompactTextString(m) } -func (*ClientKey) ProtoMessage() {} -func (*ClientKey) Descriptor() ([]byte, []int) { - return fileDescriptor_f5f7512e4ab7b58a, []int{2} -} - -func (m *ClientKey) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientKey.Unmarshal(m, b) -} -func (m *ClientKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientKey.Marshal(b, m, deterministic) -} -func (m *ClientKey) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientKey.Merge(m, src) -} -func (m *ClientKey) XXX_Size() int { - return xxx_messageInfo_ClientKey.Size(m) -} -func (m *ClientKey) XXX_DiscardUnknown() { - xxx_messageInfo_ClientKey.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientKey proto.InternalMessageInfo - -func (m *ClientKey) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *ClientKey) GetX() []byte { - if m != nil { - return m.X - } - return nil -} - -func (m *ClientKey) GetY() []byte { - if m != nil { - return m.Y - } - return nil -} - -func (m *ClientKey) GetD() []byte { - if m != nil { - return m.D - } - return nil -} - -type PerfStandbyElectionInput struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PerfStandbyElectionInput) Reset() { *m = PerfStandbyElectionInput{} } -func (m *PerfStandbyElectionInput) String() string { return proto.CompactTextString(m) } -func (*PerfStandbyElectionInput) ProtoMessage() {} -func (*PerfStandbyElectionInput) Descriptor() ([]byte, []int) { - return fileDescriptor_f5f7512e4ab7b58a, []int{3} -} - -func (m *PerfStandbyElectionInput) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PerfStandbyElectionInput.Unmarshal(m, b) -} -func (m *PerfStandbyElectionInput) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PerfStandbyElectionInput.Marshal(b, m, deterministic) -} -func (m *PerfStandbyElectionInput) XXX_Merge(src proto.Message) { - xxx_messageInfo_PerfStandbyElectionInput.Merge(m, src) -} -func (m *PerfStandbyElectionInput) XXX_Size() int { - return xxx_messageInfo_PerfStandbyElectionInput.Size(m) -} -func (m *PerfStandbyElectionInput) XXX_DiscardUnknown() { - xxx_messageInfo_PerfStandbyElectionInput.DiscardUnknown(m) -} - -var xxx_messageInfo_PerfStandbyElectionInput proto.InternalMessageInfo - -type PerfStandbyElectionResponse struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - ClusterId string `protobuf:"bytes,2,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"` - PrimaryClusterAddr string `protobuf:"bytes,3,opt,name=primary_cluster_addr,json=primaryClusterAddr,proto3" json:"primary_cluster_addr,omitempty"` - CaCert []byte `protobuf:"bytes,4,opt,name=ca_cert,json=caCert,proto3" json:"ca_cert,omitempty"` - ClientCert []byte `protobuf:"bytes,5,opt,name=client_cert,json=clientCert,proto3" json:"client_cert,omitempty"` - ClientKey *ClientKey `protobuf:"bytes,6,opt,name=client_key,json=clientKey,proto3" json:"client_key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PerfStandbyElectionResponse) Reset() { *m = PerfStandbyElectionResponse{} } -func (m *PerfStandbyElectionResponse) String() string { return proto.CompactTextString(m) } -func (*PerfStandbyElectionResponse) ProtoMessage() {} -func (*PerfStandbyElectionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f5f7512e4ab7b58a, []int{4} -} - -func (m *PerfStandbyElectionResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PerfStandbyElectionResponse.Unmarshal(m, b) -} -func (m *PerfStandbyElectionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PerfStandbyElectionResponse.Marshal(b, m, deterministic) -} -func (m *PerfStandbyElectionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PerfStandbyElectionResponse.Merge(m, src) -} -func (m *PerfStandbyElectionResponse) XXX_Size() int { - return xxx_messageInfo_PerfStandbyElectionResponse.Size(m) -} -func (m *PerfStandbyElectionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PerfStandbyElectionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PerfStandbyElectionResponse proto.InternalMessageInfo - -func (m *PerfStandbyElectionResponse) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *PerfStandbyElectionResponse) GetClusterId() string { - if m != nil { - return m.ClusterId - } - return "" -} - -func (m *PerfStandbyElectionResponse) GetPrimaryClusterAddr() string { - if m != nil { - return m.PrimaryClusterAddr - } - return "" -} - -func (m *PerfStandbyElectionResponse) GetCaCert() []byte { - if m != nil { - return m.CaCert - } - return nil -} - -func (m *PerfStandbyElectionResponse) GetClientCert() []byte { - if m != nil { - return m.ClientCert - } - return nil -} - -func (m *PerfStandbyElectionResponse) GetClientKey() *ClientKey { - if m != nil { - return m.ClientKey - } - return nil -} - -func init() { - proto.RegisterType((*EchoRequest)(nil), "vault.EchoRequest") - proto.RegisterType((*EchoReply)(nil), "vault.EchoReply") - proto.RegisterType((*ClientKey)(nil), "vault.ClientKey") - proto.RegisterType((*PerfStandbyElectionInput)(nil), "vault.PerfStandbyElectionInput") - proto.RegisterType((*PerfStandbyElectionResponse)(nil), "vault.PerfStandbyElectionResponse") -} - -// 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 - -// RequestForwardingClient is the client API for RequestForwarding service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RequestForwardingClient interface { - ForwardRequest(ctx context.Context, in *forwarding.Request, opts ...grpc.CallOption) (*forwarding.Response, error) - Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error) - PerformanceStandbyElectionRequest(ctx context.Context, in *PerfStandbyElectionInput, opts ...grpc.CallOption) (RequestForwarding_PerformanceStandbyElectionRequestClient, error) -} - -type requestForwardingClient struct { - cc *grpc.ClientConn -} - -func NewRequestForwardingClient(cc *grpc.ClientConn) RequestForwardingClient { - return &requestForwardingClient{cc} -} - -func (c *requestForwardingClient) ForwardRequest(ctx context.Context, in *forwarding.Request, opts ...grpc.CallOption) (*forwarding.Response, error) { - out := new(forwarding.Response) - err := c.cc.Invoke(ctx, "/vault.RequestForwarding/ForwardRequest", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *requestForwardingClient) Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error) { - out := new(EchoReply) - err := c.cc.Invoke(ctx, "/vault.RequestForwarding/Echo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *requestForwardingClient) PerformanceStandbyElectionRequest(ctx context.Context, in *PerfStandbyElectionInput, opts ...grpc.CallOption) (RequestForwarding_PerformanceStandbyElectionRequestClient, error) { - stream, err := c.cc.NewStream(ctx, &_RequestForwarding_serviceDesc.Streams[0], "/vault.RequestForwarding/PerformanceStandbyElectionRequest", opts...) - if err != nil { - return nil, err - } - x := &requestForwardingPerformanceStandbyElectionRequestClient{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 RequestForwarding_PerformanceStandbyElectionRequestClient interface { - Recv() (*PerfStandbyElectionResponse, error) - grpc.ClientStream -} - -type requestForwardingPerformanceStandbyElectionRequestClient struct { - grpc.ClientStream -} - -func (x *requestForwardingPerformanceStandbyElectionRequestClient) Recv() (*PerfStandbyElectionResponse, error) { - m := new(PerfStandbyElectionResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// RequestForwardingServer is the server API for RequestForwarding service. -type RequestForwardingServer interface { - ForwardRequest(context.Context, *forwarding.Request) (*forwarding.Response, error) - Echo(context.Context, *EchoRequest) (*EchoReply, error) - PerformanceStandbyElectionRequest(*PerfStandbyElectionInput, RequestForwarding_PerformanceStandbyElectionRequestServer) error -} - -func RegisterRequestForwardingServer(s *grpc.Server, srv RequestForwardingServer) { - s.RegisterService(&_RequestForwarding_serviceDesc, srv) -} - -func _RequestForwarding_ForwardRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(forwarding.Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RequestForwardingServer).ForwardRequest(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/vault.RequestForwarding/ForwardRequest", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RequestForwardingServer).ForwardRequest(ctx, req.(*forwarding.Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _RequestForwarding_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EchoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RequestForwardingServer).Echo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/vault.RequestForwarding/Echo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RequestForwardingServer).Echo(ctx, req.(*EchoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _RequestForwarding_PerformanceStandbyElectionRequest_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(PerfStandbyElectionInput) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RequestForwardingServer).PerformanceStandbyElectionRequest(m, &requestForwardingPerformanceStandbyElectionRequestServer{stream}) -} - -type RequestForwarding_PerformanceStandbyElectionRequestServer interface { - Send(*PerfStandbyElectionResponse) error - grpc.ServerStream -} - -type requestForwardingPerformanceStandbyElectionRequestServer struct { - grpc.ServerStream -} - -func (x *requestForwardingPerformanceStandbyElectionRequestServer) Send(m *PerfStandbyElectionResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _RequestForwarding_serviceDesc = grpc.ServiceDesc{ - ServiceName: "vault.RequestForwarding", - HandlerType: (*RequestForwardingServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ForwardRequest", - Handler: _RequestForwarding_ForwardRequest_Handler, - }, - { - MethodName: "Echo", - Handler: _RequestForwarding_Echo_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "PerformanceStandbyElectionRequest", - Handler: _RequestForwarding_PerformanceStandbyElectionRequest_Handler, - ServerStreams: true, - }, - }, - Metadata: "vault/request_forwarding_service.proto", -} - -func init() { - proto.RegisterFile("vault/request_forwarding_service.proto", fileDescriptor_f5f7512e4ab7b58a) -} - -var fileDescriptor_f5f7512e4ab7b58a = []byte{ - // 493 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x53, 0x41, 0x6f, 0x1a, 0x3d, - 0x10, 0x8d, 0x81, 0x10, 0x31, 0x90, 0x88, 0xf8, 0x8b, 0xf4, 0xad, 0xa8, 0xa2, 0x90, 0xad, 0x54, - 0x21, 0x55, 0xda, 0x8d, 0xd2, 0x73, 0x0f, 0x2d, 0x4a, 0x25, 0xd4, 0x4b, 0xb5, 0xb9, 0xf5, 0xb2, - 0x32, 0xf6, 0x04, 0xac, 0x2e, 0x6b, 0xd7, 0x36, 0x49, 0xf6, 0x27, 0xf7, 0xd6, 0x9f, 0x50, 0xad, - 0xd7, 0x04, 0x10, 0x4d, 0x2f, 0x68, 0xe7, 0xcd, 0x63, 0xde, 0xf8, 0xf9, 0x19, 0xde, 0x3d, 0xb2, - 0x75, 0xe1, 0x52, 0x83, 0x3f, 0xd7, 0x68, 0x5d, 0xfe, 0xa0, 0xcc, 0x13, 0x33, 0x42, 0x96, 0x8b, - 0xdc, 0xa2, 0x79, 0x94, 0x1c, 0x13, 0x6d, 0x94, 0x53, 0xf4, 0xd8, 0xf3, 0x46, 0x97, 0x4b, 0x2c, - 0x34, 0x9a, 0x74, 0xcb, 0x4b, 0x5d, 0xa5, 0xd1, 0x36, 0xac, 0x58, 0x41, 0xff, 0x8e, 0x2f, 0x55, - 0xd6, 0x4c, 0xa3, 0x11, 0x9c, 0xac, 0xd0, 0x5a, 0xb6, 0xc0, 0x88, 0x8c, 0xc9, 0xa4, 0x97, 0x6d, - 0x4a, 0x7a, 0x0d, 0x03, 0x5e, 0xac, 0xad, 0x43, 0x93, 0x33, 0x21, 0x4c, 0xd4, 0xf2, 0xed, 0x7e, - 0xc0, 0x3e, 0x09, 0x61, 0xe8, 0x5b, 0x38, 0xdd, 0xa5, 0xd8, 0xa8, 0x3d, 0x6e, 0x4f, 0x7a, 0xd9, - 0x60, 0x87, 0x63, 0xe3, 0x27, 0xe8, 0x35, 0x82, 0xba, 0xa8, 0xfe, 0x21, 0x77, 0x30, 0xab, 0x75, - 0x38, 0x8b, 0xbe, 0x87, 0x73, 0x83, 0xba, 0x90, 0x9c, 0x39, 0xa9, 0xca, 0xdc, 0x3a, 0xe6, 0x30, - 0x6a, 0x8f, 0xc9, 0xe4, 0x34, 0x1b, 0xee, 0x34, 0xee, 0x6b, 0x3c, 0x9e, 0x41, 0x6f, 0x5a, 0x48, - 0x2c, 0xdd, 0x57, 0xac, 0x28, 0x85, 0x4e, 0xed, 0x42, 0x50, 0xf5, 0xdf, 0x74, 0x00, 0xe4, 0xd9, - 0x1f, 0x6b, 0x90, 0x91, 0xe7, 0xba, 0xaa, 0xfc, 0xac, 0x41, 0x46, 0xaa, 0xba, 0x12, 0x51, 0xa7, - 0xa9, 0x44, 0x3c, 0x82, 0xe8, 0x1b, 0x9a, 0x87, 0x7b, 0xc7, 0x4a, 0x31, 0xaf, 0xee, 0x0a, 0xe4, - 0xb5, 0xcc, 0xac, 0xd4, 0x6b, 0x17, 0xff, 0x22, 0xf0, 0xe6, 0x2f, 0xcd, 0x0c, 0xad, 0x56, 0xa5, - 0x45, 0x7a, 0x06, 0x2d, 0x29, 0x82, 0x6e, 0x4b, 0x0a, 0x7a, 0x09, 0xb0, 0x39, 0xa8, 0x14, 0xc1, - 0xd5, 0x5e, 0x40, 0x66, 0x82, 0xde, 0xc0, 0x85, 0x36, 0x72, 0xc5, 0x4c, 0x95, 0xef, 0xd9, 0xdf, - 0xf6, 0x44, 0x1a, 0x7a, 0xd3, 0x9d, 0x5b, 0xf8, 0x1f, 0x4e, 0x38, 0xcb, 0x39, 0x1a, 0x17, 0x16, - 0xee, 0x72, 0x36, 0x45, 0xe3, 0xe8, 0x15, 0xf4, 0xb9, 0x37, 0xa0, 0x69, 0x1e, 0xfb, 0x26, 0x34, - 0x90, 0x27, 0xa4, 0x10, 0xaa, 0xfc, 0x07, 0x56, 0x51, 0x77, 0x4c, 0x26, 0xfd, 0xdb, 0x61, 0xe2, - 0x63, 0x94, 0xbc, 0x58, 0x57, 0x2f, 0x17, 0x3e, 0x6f, 0x7f, 0x13, 0x38, 0x0f, 0xc9, 0xf9, 0xf2, - 0x12, 0x2f, 0xfa, 0x11, 0xce, 0x42, 0xb5, 0x49, 0xd5, 0x7f, 0xc9, 0x36, 0x7d, 0x49, 0x00, 0x47, - 0x17, 0xfb, 0x60, 0x63, 0x4f, 0x7c, 0x44, 0x13, 0xe8, 0xd4, 0x01, 0xa1, 0x34, 0x28, 0xef, 0xc4, - 0x73, 0x34, 0xdc, 0xc3, 0x74, 0x51, 0xc5, 0x47, 0xb4, 0x80, 0xeb, 0xda, 0x6f, 0x65, 0x56, 0xac, - 0xe4, 0x78, 0x60, 0x7b, 0xb3, 0xc1, 0x55, 0xf8, 0xe3, 0x6b, 0xd7, 0x36, 0x8a, 0x5f, 0x27, 0x6c, - 0x77, 0xbb, 0x21, 0x9f, 0xe3, 0xef, 0xe3, 0x85, 0x74, 0xcb, 0xf5, 0x3c, 0xe1, 0x6a, 0x95, 0x2e, - 0x99, 0x5d, 0x4a, 0xae, 0x8c, 0x4e, 0x9b, 0x47, 0xe9, 0x7f, 0xe7, 0x5d, 0xff, 0xb4, 0x3e, 0xfc, - 0x09, 0x00, 0x00, 0xff, 0xff, 0x03, 0x94, 0x0a, 0x17, 0xaa, 0x03, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto b/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto deleted file mode 100644 index 3429aaf5..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto +++ /dev/null @@ -1,46 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/vault"; - -import "helper/forwarding/types.proto"; - -package vault; - -message EchoRequest { - string message = 1; - // ClusterAddr is used to send up a standby node's address to the active - // node upon heartbeat - string cluster_addr = 2; - // ClusterAddrs is used to send up a list of cluster addresses to a dr - // primary from a dr secondary - repeated string cluster_addrs = 3; -} - -message EchoReply { - string message = 1; - repeated string cluster_addrs = 2; - uint32 replication_state = 3; -} - -message ClientKey { - string type = 1; - bytes x = 2; - bytes y = 3; - bytes d = 4; -} - -message PerfStandbyElectionInput {} -message PerfStandbyElectionResponse { - string id = 1; - string cluster_id = 2; - string primary_cluster_addr = 3; - bytes ca_cert = 4; - bytes client_cert = 5; - ClientKey client_key = 6; -} - -service RequestForwarding { - rpc ForwardRequest(forwarding.Request) returns (forwarding.Response) {} - rpc Echo(EchoRequest) returns (EchoReply) {} - rpc PerformanceStandbyElectionRequest(PerfStandbyElectionInput) returns (stream PerfStandbyElectionResponse) {} -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_util.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding_util.go deleted file mode 100644 index 20fae15f..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_util.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - "crypto/tls" - "sync" - - cache "github.com/patrickmn/go-cache" - "golang.org/x/net/http2" - grpc "google.golang.org/grpc" -) - -func perfStandbyRPCServer(*Core, *cache.Cache) *grpc.Server { return nil } - -func handleReplicationConn(context.Context, *Core, *sync.WaitGroup, chan struct{}, *http2.Server, *grpc.Server, *cache.Cache, *tls.Conn) { -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_handling.go b/vendor/github.com/hashicorp/vault/vault/request_handling.go deleted file mode 100644 index eb432666..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_handling.go +++ /dev/null @@ -1,1141 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - replTimeout = 10 * time.Second -) - -var ( - // DefaultMaxRequestDuration is the amount of time we'll wait for a request - // to complete, unless overridden on a per-handler basis - DefaultMaxRequestDuration = 90 * time.Second - - egpDebugLogging bool -) - -// HandlerProperties is used to seed configuration into a vaulthttp.Handler. -// It's in this package to avoid a circular dependency -type HandlerProperties struct { - Core *Core - MaxRequestSize int64 - MaxRequestDuration time.Duration - DisablePrintableCheck bool -} - -// fetchEntityAndDerivedPolicies returns the entity object for the given entity -// ID. If the entity is merged into a different entity object, the entity into -// which the given entity ID is merged into will be returned. This function -// also returns the cumulative list of policies that the entity is entitled to. -// This list includes the policies from the entity itself and from all the -// groups in which the given entity ID is a member of. -func (c *Core) fetchEntityAndDerivedPolicies(ctx context.Context, tokenNS *namespace.Namespace, entityID string) (*identity.Entity, map[string][]string, error) { - if entityID == "" || c.identityStore == nil { - return nil, nil, nil - } - - //c.logger.Debug("entity set on the token", "entity_id", te.EntityID) - - // Fetch the entity - entity, err := c.identityStore.MemDBEntityByID(entityID, false) - if err != nil { - c.logger.Error("failed to lookup entity using its ID", "error", err) - return nil, nil, err - } - - if entity == nil { - // If there was no corresponding entity object found, it is - // possible that the entity got merged into another entity. Try - // finding entity based on the merged entity index. - entity, err = c.identityStore.MemDBEntityByMergedEntityID(entityID, false) - if err != nil { - c.logger.Error("failed to lookup entity in merged entity ID index", "error", err) - return nil, nil, err - } - } - - policies := make(map[string][]string) - if entity != nil { - //c.logger.Debug("entity successfully fetched; adding entity policies to token's policies to create ACL") - - // Attach the policies on the entity - if len(entity.Policies) != 0 { - policies[entity.NamespaceID] = append(policies[entity.NamespaceID], entity.Policies...) - } - - groupPolicies, err := c.identityStore.groupPoliciesByEntityID(entity.ID) - if err != nil { - c.logger.Error("failed to fetch group policies", "error", err) - return nil, nil, err - } - - // Filter and add the policies to the resultant set - for nsID, nsPolicies := range groupPolicies { - ns, err := NamespaceByID(ctx, nsID, c) - if err != nil { - return nil, nil, err - } - if ns == nil { - return nil, nil, namespace.ErrNoNamespace - } - if tokenNS.Path != ns.Path && !ns.HasParent(tokenNS) { - continue - } - nsPolicies = strutil.RemoveDuplicates(nsPolicies, false) - if len(nsPolicies) != 0 { - policies[nsID] = append(policies[nsID], nsPolicies...) - } - } - } - - return entity, policies, err -} - -func (c *Core) fetchACLTokenEntryAndEntity(ctx context.Context, req *logical.Request) (*ACL, *logical.TokenEntry, *identity.Entity, map[string][]string, error) { - defer metrics.MeasureSince([]string{"core", "fetch_acl_and_token"}, time.Now()) - - // Ensure there is a client token - if req.ClientToken == "" { - return nil, nil, nil, nil, fmt.Errorf("missing client token") - } - - if c.tokenStore == nil { - c.logger.Error("token store is unavailable") - return nil, nil, nil, nil, ErrInternalError - } - - // Resolve the token policy - var te *logical.TokenEntry - switch req.TokenEntry() { - case nil: - var err error - te, err = c.tokenStore.Lookup(ctx, req.ClientToken) - if err != nil { - c.logger.Error("failed to lookup token", "error", err) - return nil, nil, nil, nil, ErrInternalError - } - default: - te = req.TokenEntry() - } - - // Ensure the token is valid - if te == nil { - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - - // CIDR checks bind all tokens except non-expiring root tokens - if te.TTL != 0 && len(te.BoundCIDRs) > 0 { - var valid bool - remoteSockAddr, err := sockaddr.NewSockAddr(req.Connection.RemoteAddr) - if err != nil { - if c.Logger().IsDebug() { - c.Logger().Debug("could not parse remote addr into sockaddr", "error", err, "remote_addr", req.Connection.RemoteAddr) - } - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - for _, cidr := range te.BoundCIDRs { - if cidr.Contains(remoteSockAddr) { - valid = true - break - } - } - if !valid { - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - } - - policies := make(map[string][]string) - // Add tokens policies - policies[te.NamespaceID] = append(policies[te.NamespaceID], te.Policies...) - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, c) - if err != nil { - c.logger.Error("failed to fetch token namespace", "error", err) - return nil, nil, nil, nil, ErrInternalError - } - if tokenNS == nil { - c.logger.Error("failed to fetch token namespace", "error", namespace.ErrNoNamespace) - return nil, nil, nil, nil, ErrInternalError - } - - // Add identity policies from all the namespaces - entity, identityPolicies, err := c.fetchEntityAndDerivedPolicies(ctx, tokenNS, te.EntityID) - if err != nil { - return nil, nil, nil, nil, ErrInternalError - } - for nsID, nsPolicies := range identityPolicies { - policies[nsID] = append(policies[nsID], nsPolicies...) - } - - // Attach token's namespace information to the context. Wrapping tokens by - // should be able to be used anywhere, so we also special case behavior. - var tokenCtx context.Context - if len(policies) == 1 && - len(policies[te.NamespaceID]) == 1 && - (policies[te.NamespaceID][0] == responseWrappingPolicyName || - policies[te.NamespaceID][0] == controlGroupPolicyName) && - (strings.HasSuffix(req.Path, "sys/wrapping/unwrap") || - strings.HasSuffix(req.Path, "sys/wrapping/lookup") || - strings.HasSuffix(req.Path, "sys/wrapping/rewrap")) { - // Use the request namespace; will find the copy of the policy for the - // local namespace - tokenCtx = ctx - } else { - // Use the token's namespace for looking up policy - tokenCtx = namespace.ContextWithNamespace(ctx, tokenNS) - } - - // Construct the corresponding ACL object. ACL construction should be - // performed on the token's namespace. - acl, err := c.policyStore.ACL(tokenCtx, entity, policies) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - return nil, nil, nil, nil, err - } - c.logger.Error("failed to construct ACL", "error", err) - return nil, nil, nil, nil, ErrInternalError - } - - return acl, te, entity, identityPolicies, nil -} - -func (c *Core) checkToken(ctx context.Context, req *logical.Request, unauth bool) (*logical.Auth, *logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"core", "check_token"}, time.Now()) - - var acl *ACL - var te *logical.TokenEntry - var entity *identity.Entity - var identityPolicies map[string][]string - var err error - - // Even if unauth, if a token is provided, there's little reason not to - // gather as much info as possible for the audit log and to e.g. control - // trace mode for EGPs. - if !unauth || (unauth && req.ClientToken != "") { - acl, te, entity, identityPolicies, err = c.fetchACLTokenEntryAndEntity(ctx, req) - // In the unauth case we don't want to fail the command, since it's - // unauth, we just have no information to attach to the request, so - // ignore errors...this was best-effort anyways - if err != nil && !unauth { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor") - err = logical.ErrPermissionDenied - } - return nil, te, err - } - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - return nil, te, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - return nil, te, logical.ErrPermissionDenied - } - - // Check if this is a root protected path - rootPath := c.router.RootPath(ctx, req.Path) - - if rootPath && unauth { - return nil, nil, errors.New("cannot access root path in unauthenticated request") - } - - // When we receive a write of either type, rather than require clients to - // PUT/POST and trust the operation, we ask the backend to give us the real - // skinny -- if the backend implements an existence check, it can tell us - // whether a particular resource exists. Then we can mark it as an update - // or creation as appropriate. - if req.Operation == logical.CreateOperation || req.Operation == logical.UpdateOperation { - existsResp, checkExists, resourceExists, err := c.router.RouteExistenceCheck(ctx, req) - switch err { - case logical.ErrUnsupportedPath: - // fail later via bad path to avoid confusing items in the log - checkExists = false - case nil: - if existsResp != nil && existsResp.IsError() { - return nil, te, existsResp.Error() - } - // Otherwise, continue on - default: - c.logger.Error("failed to run existence check", "error", err) - if _, ok := err.(errutil.UserError); ok { - return nil, te, err - } else { - return nil, te, ErrInternalError - } - } - - switch { - case checkExists == false: - // No existence check, so always treat it as an update operation, which is how it is pre 0.5 - req.Operation = logical.UpdateOperation - case resourceExists == true: - // It exists, so force an update operation - req.Operation = logical.UpdateOperation - case resourceExists == false: - // It doesn't exist, force a create operation - req.Operation = logical.CreateOperation - default: - panic("unreachable code") - } - } - // Create the auth response - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Accessor: req.ClientTokenAccessor, - } - - if te != nil { - auth.IdentityPolicies = identityPolicies[te.NamespaceID] - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies[te.NamespaceID]...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - delete(identityPolicies, te.NamespaceID) - auth.ExternalNamespacePolicies = identityPolicies - // Store the entity ID in the request object - req.EntityID = te.EntityID - auth.TokenType = te.Type - } - - // Check the standard non-root ACLs. Return the token entry if it's not - // allowed so we can decrement the use count. - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - Unauth: unauth, - RootPrivsRequired: rootPath, - }) - - if !authResults.Allowed { - retErr := authResults.Error - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return auth, te, retErr - } - - return auth, te, nil -} - -// HandleRequest is used to handle a new incoming request -func (c *Core) HandleRequest(httpCtx context.Context, req *logical.Request) (resp *logical.Response, err error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby && !c.perfStandby { - return nil, consts.ErrStandby - } - - ctx, cancel := context.WithCancel(c.activeContext) - defer cancel() - - go func(ctx context.Context, httpCtx context.Context) { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }(ctx, httpCtx) - - // Allowing writing to a path ending in / makes it extremely difficult to - // understand user intent for the filesystem-like backends (kv, - // cubbyhole) -- did they want a key named foo/ or did they want to write - // to a directory foo/ with no (or forgotten) key, or...? It also affects - // lookup, because paths ending in / are considered prefixes by some - // backends. Basically, it's all just terrible, so don't allow it. - if strings.HasSuffix(req.Path, "/") && - (req.Operation == logical.UpdateOperation || - req.Operation == logical.CreateOperation) { - return logical.ErrorResponse("cannot write to a path ending in '/'"), nil - } - - err = waitForReplicationState(ctx, c, req) - if err != nil { - return nil, err - } - - ns, err := namespace.FromContext(httpCtx) - if err != nil { - return nil, errwrap.Wrapf("could not parse namespace from http context: {{err}}", err) - } - ctx = namespace.ContextWithNamespace(ctx, ns) - - if !hasNamespaces(c) && ns.Path != "" { - return nil, logical.CodedError(403, "namespaces feature not enabled") - } - - var auth *logical.Auth - if c.router.LoginPath(ctx, req.Path) { - resp, auth, err = c.handleLoginRequest(ctx, req) - } else { - resp, auth, err = c.handleRequest(ctx, req) - } - - // Ensure we don't leak internal data - if resp != nil { - if resp.Secret != nil { - resp.Secret.InternalData = nil - } - if resp.Auth != nil { - resp.Auth.InternalData = nil - } - } - - // We are wrapping if there is anything to wrap (not a nil response) and a - // TTL was specified for the token. Errors on a call should be returned to - // the caller, so wrapping is turned off if an error is hit and the error - // is logged to the audit log. - wrapping := resp != nil && - err == nil && - !resp.IsError() && - resp.WrapInfo != nil && - resp.WrapInfo.TTL != 0 && - resp.WrapInfo.Token == "" - - if wrapping { - cubbyResp, cubbyErr := c.wrapInCubbyhole(ctx, req, resp, auth) - // If not successful, returns either an error response from the - // cubbyhole backend or an error; if either is set, set resp and err to - // those and continue so that that's what we audit log. Otherwise - // finish the wrapping and audit log that. - if cubbyResp != nil || cubbyErr != nil { - resp = cubbyResp - err = cubbyErr - } else { - wrappingResp := &logical.Response{ - WrapInfo: resp.WrapInfo, - Warnings: resp.Warnings, - } - resp = wrappingResp - } - } - - auditResp := resp - // When unwrapping we want to log the actual response that will be written - // out. We still want to return the raw value to avoid automatic updating - // to any of it. - if req.Path == "sys/wrapping/unwrap" && - resp != nil && - resp.Data != nil && - resp.Data[logical.HTTPRawBody] != nil { - - // Decode the JSON - if resp.Data[logical.HTTPRawBodyAlreadyJSONDecoded] != nil { - delete(resp.Data, logical.HTTPRawBodyAlreadyJSONDecoded) - } else { - httpResp := &logical.HTTPResponse{} - err := jsonutil.DecodeJSON(resp.Data[logical.HTTPRawBody].([]byte), httpResp) - if err != nil { - c.logger.Error("failed to unmarshal wrapped HTTP response for audit logging", "error", err) - return nil, ErrInternalError - } - - auditResp = logical.HTTPResponseToLogicalResponse(httpResp) - } - } - - var nonHMACReqDataKeys []string - var nonHMACRespDataKeys []string - entry := c.router.MatchingMountEntry(ctx, req.Path) - if entry != nil { - // Get and set ignored HMAC'd value. Reset those back to empty afterwards. - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - nonHMACReqDataKeys = rawVals.([]string) - } - - // Get and set ignored HMAC'd value. Reset those back to empty afterwards. - if auditResp != nil { - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - nonHMACRespDataKeys = rawVals.([]string) - } - } - } - - // Create an audit trail of the response - if !isControlGroupRun(req) { - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - Response: auditResp, - OuterErr: err, - NonHMACReqDataKeys: nonHMACReqDataKeys, - NonHMACRespDataKeys: nonHMACRespDataKeys, - } - if auditErr := c.auditBroker.LogResponse(ctx, logInput, c.auditedHeaders); auditErr != nil { - c.logger.Error("failed to audit response", "request_path", req.Path, "error", auditErr) - return nil, ErrInternalError - } - } - - return -} - -func isControlGroupRun(req *logical.Request) bool { - return req.ControlGroup != nil -} - -func (c *Core) handleRequest(ctx context.Context, req *logical.Request) (retResp *logical.Response, retAuth *logical.Auth, retErr error) { - defer metrics.MeasureSince([]string{"core", "handle_request"}, time.Now()) - - var nonHMACReqDataKeys []string - entry := c.router.MatchingMountEntry(ctx, req.Path) - if entry != nil { - // Get and set ignored HMAC'd value. - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - nonHMACReqDataKeys = rawVals.([]string) - } - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - c.logger.Error("failed to get namespace from context", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return - } - - // Validate the token - auth, te, ctErr := c.checkToken(ctx, req, false) - // We run this logic first because we want to decrement the use count even in the case of an error - if te != nil && !isControlGroupRun(req) { - // Attempt to use the token (decrement NumUses) - var err error - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, nil, retErr - } - if te == nil { - // Token has been revoked by this point - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - return nil, nil, retErr - } - if te.NumUses == tokenRevocationPending { - // We defer a revocation until after logic has run, since this is a - // valid request (this is the token's final use). We pass the ID in - // directly just to be safe in case something else modifies te later. - defer func(id string) { - nsActiveCtx := namespace.ContextWithNamespace(c.activeContext, ns) - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(nsActiveCtx, te) - if err == nil { - err = c.expiration.LazyRevoke(ctx, leaseID) - } - if err != nil { - c.logger.Error("failed to revoke token", "error", err) - retResp = nil - retAuth = nil - retErr = multierror.Append(retErr, ErrInternalError) - } - if retResp != nil && retResp.Secret != nil && - // Some backends return a TTL even without a Lease ID - retResp.Secret.LeaseID != "" { - retResp = logical.ErrorResponse("Secret cannot be returned; token had one use left, so leased credentials were immediately revoked.") - return - } - }(te.ID) - } - } - - if ctErr != nil { - newCtErr, cgResp, cgAuth, cgRetErr := checkNeedsCG(ctx, c, req, auth, ctErr, nonHMACReqDataKeys) - switch { - case newCtErr != nil: - ctErr = err - case cgResp != nil || cgAuth != nil: - if cgRetErr != nil { - retErr = multierror.Append(retErr, cgRetErr) - } - return cgResp, cgAuth, retErr - } - - // If it is an internal error we return that, otherwise we - // return invalid request so that the status codes can be correct - switch { - case ctErr == ErrInternalError, - errwrap.Contains(ctErr, ErrInternalError.Error()), - ctErr == logical.ErrPermissionDenied, - errwrap.Contains(ctErr, logical.ErrPermissionDenied.Error()): - switch ctErr.(type) { - case *multierror.Error: - retErr = ctErr - default: - retErr = multierror.Append(retErr, ctErr) - } - default: - retErr = multierror.Append(retErr, logical.ErrInvalidRequest) - } - - if !isControlGroupRun(req) { - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - OuterErr: ctErr, - NonHMACReqDataKeys: nonHMACReqDataKeys, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - } - } - - if errwrap.Contains(retErr, ErrInternalError.Error()) { - return nil, auth, retErr - } - return logical.ErrorResponse(ctErr.Error()), auth, retErr - } - - // Attach the display name - req.DisplayName = auth.DisplayName - - // Create an audit trail of the request - if !isControlGroupRun(req) { - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - NonHMACReqDataKeys: nonHMACReqDataKeys, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - } - - // Route the request - resp, routeErr := c.router.Route(ctx, req) - // If we're replicating and we get a read-only error from a backend, need to forward to primary - if routeErr != nil { - resp, routeErr = possiblyForward(ctx, c, req, resp, routeErr) - } - if resp != nil { - // If wrapping is used, use the shortest between the request and response - var wrapTTL time.Duration - var wrapFormat, creationPath string - var sealWrap bool - - // Ensure no wrap info information is set other than, possibly, the TTL - if resp.WrapInfo != nil { - if resp.WrapInfo.TTL > 0 { - wrapTTL = resp.WrapInfo.TTL - } - wrapFormat = resp.WrapInfo.Format - creationPath = resp.WrapInfo.CreationPath - sealWrap = resp.WrapInfo.SealWrap - resp.WrapInfo = nil - } - - if req.WrapInfo != nil { - if req.WrapInfo.TTL > 0 { - switch { - case wrapTTL == 0: - wrapTTL = req.WrapInfo.TTL - case req.WrapInfo.TTL < wrapTTL: - wrapTTL = req.WrapInfo.TTL - } - } - // If the wrap format hasn't been set by the response, set it to - // the request format - if req.WrapInfo.Format != "" && wrapFormat == "" { - wrapFormat = req.WrapInfo.Format - } - } - - if wrapTTL > 0 { - resp.WrapInfo = &wrapping.ResponseWrapInfo{ - TTL: wrapTTL, - Format: wrapFormat, - CreationPath: creationPath, - SealWrap: sealWrap, - } - } - } - - // If there is a secret, we must register it with the expiration manager. - // We exclude renewal of a lease, since it does not need to be re-registered - if resp != nil && resp.Secret != nil && !strings.HasPrefix(req.Path, "sys/renew") && - !strings.HasPrefix(req.Path, "sys/leases/renew") { - // KV mounts should return the TTL but not register - // for a lease as this provides a massive slowdown - registerLease := true - - matchingMountEntry := c.router.MatchingMountEntry(ctx, req.Path) - if matchingMountEntry == nil { - c.logger.Error("unable to retrieve kv mount entry from router") - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - switch matchingMountEntry.Type { - case "kv", "generic": - // If we are kv type, first see if we are an older passthrough - // backend, and otherwise check the mount entry options. - matchingBackend := c.router.MatchingBackend(ctx, req.Path) - if matchingBackend == nil { - c.logger.Error("unable to retrieve kv backend from router") - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - if ptbe, ok := matchingBackend.(*PassthroughBackend); ok { - if !ptbe.GeneratesLeases() { - registerLease = false - resp.Secret.Renewable = false - } - } else if matchingMountEntry.Options == nil || matchingMountEntry.Options["leased_passthrough"] != "true" { - registerLease = false - resp.Secret.Renewable = false - } - - case "plugin": - // If we are a plugin type and the plugin name is "kv" check the - // mount entry options. - if matchingMountEntry.Config.PluginName == "kv" && (matchingMountEntry.Options == nil || matchingMountEntry.Options["leased_passthrough"] != "true") { - registerLease = false - resp.Secret.Renewable = false - } - } - - if registerLease { - sysView := c.router.MatchingSystemView(ctx, req.Path) - if sysView == nil { - c.logger.Error("unable to look up sys view for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - ttl, warnings, err := framework.CalculateTTL(sysView, 0, resp.Secret.TTL, 0, resp.Secret.MaxTTL, 0, time.Time{}) - if err != nil { - return nil, nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - resp.Secret.TTL = ttl - - registerFunc, funcGetErr := getLeaseRegisterFunc(c) - if funcGetErr != nil { - retErr = multierror.Append(retErr, funcGetErr) - return nil, auth, retErr - } - - leaseID, err := registerFunc(ctx, req, resp) - if err != nil { - c.logger.Error("failed to register lease", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - resp.Secret.LeaseID = leaseID - - // Get the actual time of the lease - le, err := c.expiration.FetchLeaseTimes(ctx, leaseID) - if err != nil { - c.logger.Error("failed to fetch updated lease time", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - // We round here because the clock will have already started - // ticking, so we'll end up always returning 299 instead of 300 or - // 26399 instead of 26400, say, even if it's just a few - // microseconds. This provides a nicer UX. - resp.Secret.TTL = le.ExpireTime.Sub(time.Now()).Round(time.Second) - } - } - - // Only the token store is allowed to return an auth block, for any - // other request this is an internal error. We exclude renewal of a token, - // since it does not need to be re-registered - if resp != nil && resp.Auth != nil && !strings.HasPrefix(req.Path, "auth/token/renew") { - if !strings.HasPrefix(req.Path, "auth/token/") { - c.logger.Error("unexpected Auth response for non-token backend", "request_path", req.Path) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - // Fetch the namespace to which the token belongs - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, c) - if err != nil { - c.logger.Error("failed to fetch token's namespace", "error", err) - retErr = multierror.Append(retErr, err) - return nil, auth, retErr - } - if tokenNS == nil { - c.logger.Error(namespace.ErrNoNamespace.Error()) - retErr = multierror.Append(retErr, namespace.ErrNoNamespace) - return nil, auth, retErr - } - - _, identityPolicies, err := c.fetchEntityAndDerivedPolicies(ctx, tokenNS, resp.Auth.EntityID) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - return nil, nil, ErrInternalError - } - - resp.Auth.TokenPolicies = policyutil.SanitizePolicies(resp.Auth.Policies, policyutil.DoNotAddDefaultPolicy) - switch resp.Auth.TokenType { - case logical.TokenTypeBatch: - case logical.TokenTypeService: - if err := c.expiration.RegisterAuth(ctx, &logical.TokenEntry{ - Path: resp.Auth.CreationPath, - NamespaceID: ns.ID, - }, resp.Auth); err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register token lease", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - } - - // We do these later since it's not meaningful for backends/expmgr to - // have what is purely a snapshot of current identity policies, and - // plugins can be confused if they are checking contents of - // Auth.Policies instead of Auth.TokenPolicies - resp.Auth.Policies = policyutil.SanitizePolicies(append(resp.Auth.Policies, identityPolicies[te.NamespaceID]...), policyutil.DoNotAddDefaultPolicy) - resp.Auth.IdentityPolicies = policyutil.SanitizePolicies(identityPolicies[te.NamespaceID], policyutil.DoNotAddDefaultPolicy) - delete(identityPolicies, te.NamespaceID) - resp.Auth.ExternalNamespacePolicies = identityPolicies - } - - if resp != nil && - req.Path == "cubbyhole/response" && - len(te.Policies) == 1 && - te.Policies[0] == responseWrappingPolicyName { - resp.AddWarning("Reading from 'cubbyhole/response' is deprecated. Please use sys/wrapping/unwrap to unwrap responses, as it provides additional security checks and other benefits.") - } - - // Return the response and error - if routeErr != nil { - retErr = multierror.Append(retErr, routeErr) - } - - return resp, auth, retErr -} - -// handleLoginRequest is used to handle a login request, which is an -// unauthenticated request to the backend. -func (c *Core) handleLoginRequest(ctx context.Context, req *logical.Request) (retResp *logical.Response, retAuth *logical.Auth, retErr error) { - defer metrics.MeasureSince([]string{"core", "handle_login_request"}, time.Now()) - - req.Unauthenticated = true - - var auth *logical.Auth - - // Do an unauth check. This will cause EGP policies to be checked - var ctErr error - auth, _, ctErr = c.checkToken(ctx, req, true) - if ctErr != nil { - // If it is an internal error we return that, otherwise we - // return invalid request so that the status codes can be correct - var errType error - switch ctErr { - case ErrInternalError, logical.ErrPermissionDenied: - errType = ctErr - default: - errType = logical.ErrInvalidRequest - } - - var nonHMACReqDataKeys []string - entry := c.router.MatchingMountEntry(ctx, req.Path) - if entry != nil { - // Get and set ignored HMAC'd value. - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - nonHMACReqDataKeys = rawVals.([]string) - } - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - OuterErr: ctErr, - NonHMACReqDataKeys: nonHMACReqDataKeys, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - return nil, nil, ErrInternalError - } - - if errType != nil { - retErr = multierror.Append(retErr, errType) - } - if ctErr == ErrInternalError { - return nil, auth, retErr - } - return logical.ErrorResponse(ctErr.Error()), auth, retErr - } - - // Create an audit trail of the request. Attach auth if it was returned, - // e.g. if a token was provided. - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - return nil, nil, ErrInternalError - } - - // The token store uses authentication even when creating a new token, - // so it's handled in handleRequest. It should not be reached here. - if strings.HasPrefix(req.Path, "auth/token/") { - c.logger.Error("unexpected login request for token backend", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - // Route the request - resp, routeErr := c.router.Route(ctx, req) - // If we're replicating and we get a read-only error from a backend, need to forward to primary - if routeErr != nil { - resp, routeErr = possiblyForward(ctx, c, req, resp, routeErr) - } - if resp != nil { - // If wrapping is used, use the shortest between the request and response - var wrapTTL time.Duration - var wrapFormat, creationPath string - var sealWrap bool - - // Ensure no wrap info information is set other than, possibly, the TTL - if resp.WrapInfo != nil { - if resp.WrapInfo.TTL > 0 { - wrapTTL = resp.WrapInfo.TTL - } - wrapFormat = resp.WrapInfo.Format - creationPath = resp.WrapInfo.CreationPath - sealWrap = resp.WrapInfo.SealWrap - resp.WrapInfo = nil - } - - if req.WrapInfo != nil { - if req.WrapInfo.TTL > 0 { - switch { - case wrapTTL == 0: - wrapTTL = req.WrapInfo.TTL - case req.WrapInfo.TTL < wrapTTL: - wrapTTL = req.WrapInfo.TTL - } - } - if req.WrapInfo.Format != "" && wrapFormat == "" { - wrapFormat = req.WrapInfo.Format - } - } - - if wrapTTL > 0 { - resp.WrapInfo = &wrapping.ResponseWrapInfo{ - TTL: wrapTTL, - Format: wrapFormat, - CreationPath: creationPath, - SealWrap: sealWrap, - } - } - } - - // A login request should never return a secret! - if resp != nil && resp.Secret != nil { - c.logger.Error("unexpected Secret response for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - // If the response generated an authentication, then generate the token - if resp != nil && resp.Auth != nil { - - var entity *identity.Entity - auth = resp.Auth - - mEntry := c.router.MatchingMountEntry(ctx, req.Path) - - if auth.Alias != nil && - mEntry != nil && - !mEntry.Local && - c.identityStore != nil { - // Overwrite the mount type and mount path in the alias - // information - auth.Alias.MountType = req.MountType - auth.Alias.MountAccessor = req.MountAccessor - - if auth.Alias.Name == "" { - return nil, nil, fmt.Errorf("missing name in alias") - } - - var err error - - // Fetch the entity for the alias, or create an entity if one - // doesn't exist. - entity, err = c.identityStore.CreateOrFetchEntity(ctx, auth.Alias) - if err != nil { - entity, err = possiblyForwardAliasCreation(ctx, c, err, auth, entity) - } - if err != nil { - return nil, nil, err - } - if entity == nil { - return nil, nil, fmt.Errorf("failed to create an entity for the authenticated alias") - } - - if entity.Disabled { - return nil, nil, logical.ErrPermissionDenied - } - - auth.EntityID = entity.ID - if auth.GroupAliases != nil { - validAliases, err := c.identityStore.refreshExternalGroupMembershipsByEntityID(auth.EntityID, auth.GroupAliases) - if err != nil { - return nil, nil, err - } - auth.GroupAliases = validAliases - } - } - - // Determine the source of the login - source := c.router.MatchingMount(ctx, req.Path) - source = strings.TrimPrefix(source, credentialRoutePrefix) - source = strings.Replace(source, "/", "-", -1) - - // Prepend the source to the display name - auth.DisplayName = strings.TrimSuffix(source+auth.DisplayName, "-") - - sysView := c.router.MatchingSystemView(ctx, req.Path) - if sysView == nil { - c.logger.Error("unable to look up sys view for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - tokenTTL, warnings, err := framework.CalculateTTL(sysView, 0, auth.TTL, auth.Period, auth.MaxTTL, auth.ExplicitMaxTTL, time.Time{}) - if err != nil { - return nil, nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, nil, err - } - _, identityPolicies, err := c.fetchEntityAndDerivedPolicies(ctx, ns, auth.EntityID) - if err != nil { - return nil, nil, ErrInternalError - } - - auth.TokenPolicies = policyutil.SanitizePolicies(auth.Policies, policyutil.AddDefaultPolicy) - allPolicies := policyutil.SanitizePolicies(append(auth.TokenPolicies, identityPolicies[ns.ID]...), policyutil.DoNotAddDefaultPolicy) - - // Prevent internal policies from being assigned to tokens. We check - // this on auth.Policies including derived ones from Identity before - // actually making the token. - for _, policy := range allPolicies { - if policy == "root" { - return logical.ErrorResponse("auth methods cannot create root tokens"), nil, logical.ErrInvalidRequest - } - if strutil.StrListContains(nonAssignablePolicies, policy) { - return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil, logical.ErrInvalidRequest - } - } - - var registerFunc RegisterAuthFunc - var funcGetErr error - // Batch tokens should not be forwarded to perf standby - if auth.TokenType == logical.TokenTypeBatch { - registerFunc = c.RegisterAuth - } else { - registerFunc, funcGetErr = getAuthRegisterFunc(c) - } - if funcGetErr != nil { - retErr = multierror.Append(retErr, funcGetErr) - return nil, auth, retErr - } - - err = registerFunc(ctx, tokenTTL, req.Path, auth) - switch { - case err == nil: - case err == ErrInternalError: - return nil, auth, err - default: - return logical.ErrorResponse(err.Error()), auth, logical.ErrInvalidRequest - } - - auth.IdentityPolicies = policyutil.SanitizePolicies(identityPolicies[ns.ID], policyutil.DoNotAddDefaultPolicy) - delete(identityPolicies, ns.ID) - auth.ExternalNamespacePolicies = identityPolicies - auth.Policies = allPolicies - - // Attach the display name, might be used by audit backends - req.DisplayName = auth.DisplayName - - } - - return resp, auth, routeErr -} - -func (c *Core) RegisterAuth(ctx context.Context, tokenTTL time.Duration, path string, auth *logical.Auth) error { - // We first assign token policies to what was returned from the backend - // via auth.Policies. Then, we get the full set of policies into - // auth.Policies from the backend + entity information -- this is not - // stored in the token, but we perform sanity checks on it and return - // that information to the user. - - // Generate a token - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - te := logical.TokenEntry{ - Path: path, - Meta: auth.Metadata, - DisplayName: auth.DisplayName, - CreationTime: time.Now().Unix(), - TTL: tokenTTL, - NumUses: auth.NumUses, - EntityID: auth.EntityID, - BoundCIDRs: auth.BoundCIDRs, - Policies: auth.TokenPolicies, - NamespaceID: ns.ID, - ExplicitMaxTTL: auth.ExplicitMaxTTL, - Type: auth.TokenType, - } - - if err := c.tokenStore.create(ctx, &te); err != nil { - c.logger.Error("failed to create token", "error", err) - return ErrInternalError - } - - // Populate the client token, accessor, and TTL - auth.ClientToken = te.ID - auth.Accessor = te.Accessor - auth.TTL = te.TTL - - switch auth.TokenType { - case logical.TokenTypeBatch: - // Ensure it's not marked renewable since it isn't - auth.Renewable = false - case logical.TokenTypeService: - // Register with the expiration manager - if err := c.expiration.RegisterAuth(ctx, &te, auth); err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register token lease", "request_path", path, "error", err) - return ErrInternalError - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_handling_util.go b/vendor/github.com/hashicorp/vault/vault/request_handling_util.go deleted file mode 100644 index ffcc419a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/request_handling_util.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/logical" -) - -func waitForReplicationState(context.Context, *Core, *logical.Request) error { return nil } - -func checkNeedsCG(context.Context, *Core, *logical.Request, *logical.Auth, error, []string) (error, *logical.Response, *logical.Auth, error) { - return nil, nil, nil, nil -} - -func possiblyForward(ctx context.Context, c *Core, req *logical.Request, resp *logical.Response, routeErr error) (*logical.Response, error) { - return resp, routeErr -} - -func getLeaseRegisterFunc(c *Core) (func(context.Context, *logical.Request, *logical.Response) (string, error), error) { - return c.expiration.Register, nil -} - -func getAuthRegisterFunc(c *Core) (RegisterAuthFunc, error) { - return c.RegisterAuth, nil -} - -func possiblyForwardAliasCreation(ctx context.Context, c *Core, inErr error, auth *logical.Auth, entity *identity.Entity) (*identity.Entity, error) { - return entity, inErr -} diff --git a/vendor/github.com/hashicorp/vault/vault/rollback.go b/vendor/github.com/hashicorp/vault/vault/rollback.go deleted file mode 100644 index f9b49539..00000000 --- a/vendor/github.com/hashicorp/vault/vault/rollback.go +++ /dev/null @@ -1,282 +0,0 @@ -package vault - -import ( - "context" - "errors" - "strings" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -const ( - // rollbackPeriod is how often we attempt rollbacks for all the backends - rollbackPeriod = time.Minute -) - -// RollbackManager is responsible for performing rollbacks of partial -// secrets within logical backends. -// -// During normal operations, it is possible for logical backends to -// error partially through an operation. These are called "partial secrets": -// they are never sent back to a user, but they do need to be cleaned up. -// This manager handles that by periodically (on a timer) requesting that the -// backends clean up. -// -// The RollbackManager periodically initiates a logical.RollbackOperation -// on every mounted logical backend. It ensures that only one rollback operation -// is in-flight at any given time within a single seal/unseal phase. -type RollbackManager struct { - logger log.Logger - - // This gives the current mount table of both logical and credential backends, - // plus a RWMutex that is locked for reading. It is up to the caller to RUnlock - // it when done with the mount table. - backends func() []*MountEntry - - router *Router - period time.Duration - - inflightAll sync.WaitGroup - inflight map[string]*rollbackState - inflightLock sync.RWMutex - - doneCh chan struct{} - shutdown bool - shutdownCh chan struct{} - shutdownLock sync.Mutex - quitContext context.Context - - core *Core -} - -// rollbackState is used to track the state of a single rollback attempt -type rollbackState struct { - lastError error - sync.WaitGroup -} - -// NewRollbackManager is used to create a new rollback manager -func NewRollbackManager(ctx context.Context, logger log.Logger, backendsFunc func() []*MountEntry, router *Router, core *Core) *RollbackManager { - r := &RollbackManager{ - logger: logger, - backends: backendsFunc, - router: router, - period: rollbackPeriod, - inflight: make(map[string]*rollbackState), - doneCh: make(chan struct{}), - shutdownCh: make(chan struct{}), - quitContext: ctx, - core: core, - } - return r -} - -// Start starts the rollback manager -func (m *RollbackManager) Start() { - go m.run() -} - -// Stop stops the running manager. This will wait for any in-flight -// rollbacks to complete. -func (m *RollbackManager) Stop() { - m.shutdownLock.Lock() - defer m.shutdownLock.Unlock() - if !m.shutdown { - m.shutdown = true - close(m.shutdownCh) - <-m.doneCh - } - m.inflightAll.Wait() -} - -// run is a long running routine to periodically invoke rollback -func (m *RollbackManager) run() { - m.logger.Info("starting rollback manager") - tick := time.NewTicker(m.period) - defer tick.Stop() - defer close(m.doneCh) - for { - select { - case <-tick.C: - m.triggerRollbacks() - - case <-m.shutdownCh: - m.logger.Info("stopping rollback manager") - return - } - } -} - -// triggerRollbacks is used to trigger the rollbacks across all the backends -func (m *RollbackManager) triggerRollbacks() { - - backends := m.backends() - - for _, e := range backends { - path := e.Path - if e.Table == credentialTableType { - path = credentialRoutePrefix + path - } - - // When the mount is filtered, the backend will be nil - ctx := namespace.ContextWithNamespace(m.quitContext, e.namespace) - backend := m.router.MatchingBackend(ctx, path) - if backend == nil { - continue - } - fullPath := e.namespace.Path + path - - m.inflightLock.RLock() - _, ok := m.inflight[fullPath] - m.inflightLock.RUnlock() - if !ok { - m.startRollback(ctx, fullPath, true) - } - } -} - -// startRollback is used to start an async rollback attempt. -// This must be called with the inflightLock held. -func (m *RollbackManager) startRollback(ctx context.Context, fullPath string, grabStatelock bool) *rollbackState { - rs := &rollbackState{} - rs.Add(1) - m.inflightAll.Add(1) - m.inflightLock.Lock() - m.inflight[fullPath] = rs - m.inflightLock.Unlock() - go m.attemptRollback(ctx, fullPath, rs, grabStatelock) - return rs -} - -// attemptRollback invokes a RollbackOperation for the given path -func (m *RollbackManager) attemptRollback(ctx context.Context, fullPath string, rs *rollbackState, grabStatelock bool) (err error) { - defer metrics.MeasureSince([]string{"rollback", "attempt", strings.Replace(fullPath, "/", "-", -1)}, time.Now()) - if m.logger.IsDebug() { - m.logger.Debug("attempting rollback", "path", fullPath) - } - - defer func() { - rs.lastError = err - rs.Done() - m.inflightAll.Done() - m.inflightLock.Lock() - delete(m.inflight, fullPath) - m.inflightLock.Unlock() - }() - - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - if ns == nil { - return namespace.ErrNoNamespace - } - - // Invoke a RollbackOperation - req := &logical.Request{ - Operation: logical.RollbackOperation, - Path: ns.TrimmedPath(fullPath), - } - - if grabStatelock { - // Grab the statelock or stop - if stopped := grabLockOrStop(m.core.stateLock.RLock, m.core.stateLock.RUnlock, m.shutdownCh); stopped { - return errors.New("rollback shutting down") - } - } - - var cancelFunc context.CancelFunc - ctx, cancelFunc = context.WithTimeout(ctx, DefaultMaxRequestDuration) - _, err = m.router.Route(ctx, req) - if grabStatelock { - m.core.stateLock.RUnlock() - } - cancelFunc() - - // If the error is an unsupported operation, then it doesn't - // matter, the backend doesn't support it. - if err == logical.ErrUnsupportedOperation { - err = nil - } - // If we failed due to read-only storage, we can't do anything; ignore - if err != nil && strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - err = nil - } - if err != nil { - m.logger.Error("error rolling back", "path", fullPath, "error", err) - } - return -} - -// Rollback is used to trigger an immediate rollback of the path, -// or to join an existing rollback operation if in flight. Caller should have -// core's statelock held -func (m *RollbackManager) Rollback(ctx context.Context, path string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - fullPath := ns.Path + path - - // Check for an existing attempt and start one if none - m.inflightLock.RLock() - rs, ok := m.inflight[fullPath] - m.inflightLock.RUnlock() - if !ok { - rs = m.startRollback(ctx, fullPath, false) - } - - // Wait for the attempt to finish - rs.Wait() - - // Return the last error - return rs.lastError -} - -// The methods below are the hooks from core that are called pre/post seal. - -// startRollback is used to start the rollback manager after unsealing -func (c *Core) startRollback() error { - backendsFunc := func() []*MountEntry { - ret := []*MountEntry{} - c.mountsLock.RLock() - defer c.mountsLock.RUnlock() - // During teardown/setup after a leader change or unseal there could be - // something racy here so make sure the table isn't nil - if c.mounts != nil { - for _, entry := range c.mounts.Entries { - ret = append(ret, entry) - } - } - c.authLock.RLock() - defer c.authLock.RUnlock() - // During teardown/setup after a leader change or unseal there could be - // something racy here so make sure the table isn't nil - if c.auth != nil { - for _, entry := range c.auth.Entries { - ret = append(ret, entry) - } - } - return ret - } - rollbackLogger := c.baseLogger.Named("rollback") - c.AddLogger(rollbackLogger) - c.rollback = NewRollbackManager(c.activeContext, rollbackLogger, backendsFunc, c.router, c) - c.rollback.Start() - return nil -} - -// stopRollback is used to stop running the rollback manager before sealing -func (c *Core) stopRollback() error { - if c.rollback != nil { - c.rollback.Stop() - c.rollback = nil - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/router.go b/vendor/github.com/hashicorp/vault/vault/router.go deleted file mode 100644 index 66c1ef23..00000000 --- a/vendor/github.com/hashicorp/vault/vault/router.go +++ /dev/null @@ -1,823 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - "github.com/armon/go-radix" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -var ( - denylistHeaders = []string{ - "Authorization", - consts.AuthHeaderName, - } -) - -// Router is used to do prefix based routing of a request to a logical backend -type Router struct { - l sync.RWMutex - root *radix.Tree - mountUUIDCache *radix.Tree - mountAccessorCache *radix.Tree - tokenStoreSaltFunc func(context.Context) (*salt.Salt, error) - // storagePrefix maps the prefix used for storage (ala the BarrierView) - // to the backend. This is used to map a key back into the backend that owns it. - // For example, logical/uuid1/foobar -> secrets/ (kv backend) + foobar - storagePrefix *radix.Tree -} - -// NewRouter returns a new router -func NewRouter() *Router { - r := &Router{ - root: radix.New(), - storagePrefix: radix.New(), - mountUUIDCache: radix.New(), - mountAccessorCache: radix.New(), - } - return r -} - -// routeEntry is used to represent a mount point in the router -type routeEntry struct { - tainted bool - backend logical.Backend - mountEntry *MountEntry - storageView logical.Storage - storagePrefix string - rootPaths atomic.Value - loginPaths atomic.Value - l sync.RWMutex -} - -type validateMountResponse struct { - MountType string `json:"mount_type" structs:"mount_type" mapstructure:"mount_type"` - MountAccessor string `json:"mount_accessor" structs:"mount_accessor" mapstructure:"mount_accessor"` - MountPath string `json:"mount_path" structs:"mount_path" mapstructure:"mount_path"` - MountLocal bool `json:"mount_local" structs:"mount_local" mapstructure:"mount_local"` -} - -// validateMountByAccessor returns the mount type and ID for a given mount -// accessor -func (r *Router) validateMountByAccessor(accessor string) *validateMountResponse { - if accessor == "" { - return nil - } - - mountEntry := r.MatchingMountByAccessor(accessor) - if mountEntry == nil { - return nil - } - - mountPath := mountEntry.Path - if mountEntry.Table == credentialTableType { - mountPath = credentialRoutePrefix + mountPath - } - - return &validateMountResponse{ - MountAccessor: mountEntry.Accessor, - MountType: mountEntry.Type, - MountPath: mountPath, - MountLocal: mountEntry.Local, - } -} - -// SaltID is used to apply a salt and hash to an ID to make sure its not reversible -func (re *routeEntry) SaltID(id string) string { - return salt.SaltID(re.mountEntry.UUID, id, salt.SHA1Hash) -} - -// Mount is used to expose a logical backend at a given prefix, using a unique salt, -// and the barrier view for that path. -func (r *Router) Mount(backend logical.Backend, prefix string, mountEntry *MountEntry, storageView *BarrierView) error { - r.l.Lock() - defer r.l.Unlock() - - // prepend namespace - prefix = mountEntry.Namespace().Path + prefix - - // Check if this is a nested mount - if existing, _, ok := r.root.LongestPrefix(prefix); ok && existing != "" { - return fmt.Errorf("cannot mount under existing mount %q", existing) - } - - // Build the paths - paths := new(logical.Paths) - if backend != nil { - specialPaths := backend.SpecialPaths() - if specialPaths != nil { - paths = specialPaths - } - } - - // Create a mount entry - re := &routeEntry{ - tainted: false, - backend: backend, - mountEntry: mountEntry, - storagePrefix: storageView.prefix, - storageView: storageView, - } - re.rootPaths.Store(pathsToRadix(paths.Root)) - re.loginPaths.Store(pathsToRadix(paths.Unauthenticated)) - - switch { - case prefix == "": - return fmt.Errorf("missing prefix to be used for router entry; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.storagePrefix == "": - return fmt.Errorf("missing storage view prefix; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.mountEntry.UUID == "": - return fmt.Errorf("missing mount identifier; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.mountEntry.Accessor == "": - return fmt.Errorf("missing mount accessor; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - } - - r.root.Insert(prefix, re) - r.storagePrefix.Insert(re.storagePrefix, re) - r.mountUUIDCache.Insert(re.mountEntry.UUID, re.mountEntry) - r.mountAccessorCache.Insert(re.mountEntry.Accessor, re.mountEntry) - - return nil -} - -// Unmount is used to remove a logical backend from a given prefix -func (r *Router) Unmount(ctx context.Context, prefix string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - prefix = ns.Path + prefix - - r.l.Lock() - defer r.l.Unlock() - - // Fast-path out if the backend doesn't exist - raw, ok := r.root.Get(prefix) - if !ok { - return nil - } - - // Call backend's Cleanup routine - re := raw.(*routeEntry) - if re.backend != nil { - re.backend.Cleanup(ctx) - } - - // Purge from the radix trees - r.root.Delete(prefix) - r.storagePrefix.Delete(re.storagePrefix) - r.mountUUIDCache.Delete(re.mountEntry.UUID) - r.mountAccessorCache.Delete(re.mountEntry.Accessor) - - return nil -} - -// Remount is used to change the mount location of a logical backend -func (r *Router) Remount(ctx context.Context, src, dst string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - src = ns.Path + src - dst = ns.Path + dst - - r.l.Lock() - defer r.l.Unlock() - - // Check for existing mount - raw, ok := r.root.Get(src) - if !ok { - return fmt.Errorf("no mount at %q", src) - } - - // Update the mount point - r.root.Delete(src) - r.root.Insert(dst, raw) - return nil -} - -// Taint is used to mark a path as tainted. This means only RollbackOperation -// RevokeOperation requests are allowed to proceed -func (r *Router) Taint(ctx context.Context, path string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - path = ns.Path + path - - r.l.Lock() - defer r.l.Unlock() - _, raw, ok := r.root.LongestPrefix(path) - if ok { - raw.(*routeEntry).tainted = true - } - return nil -} - -// Untaint is used to unmark a path as tainted. -func (r *Router) Untaint(ctx context.Context, path string) error { - ns, err := namespace.FromContext(ctx) - if err != nil { - return err - } - path = ns.Path + path - - r.l.Lock() - defer r.l.Unlock() - _, raw, ok := r.root.LongestPrefix(path) - if ok { - raw.(*routeEntry).tainted = false - } - return nil -} - -func (r *Router) MatchingMountByUUID(mountID string) *MountEntry { - if mountID == "" { - return nil - } - - r.l.RLock() - - _, raw, ok := r.mountUUIDCache.LongestPrefix(mountID) - if !ok { - r.l.RUnlock() - return nil - } - - r.l.RUnlock() - return raw.(*MountEntry) -} - -// MatchingMountByAccessor returns the MountEntry by accessor lookup -func (r *Router) MatchingMountByAccessor(mountAccessor string) *MountEntry { - if mountAccessor == "" { - return nil - } - - r.l.RLock() - - _, raw, ok := r.mountAccessorCache.LongestPrefix(mountAccessor) - if !ok { - r.l.RUnlock() - return nil - } - - r.l.RUnlock() - return raw.(*MountEntry) -} - -// MatchingMount returns the mount prefix that would be used for a path -func (r *Router) MatchingMount(ctx context.Context, path string) string { - r.l.RLock() - mount := r.matchingMountInternal(ctx, path) - r.l.RUnlock() - return mount -} - -func (r *Router) matchingMountInternal(ctx context.Context, path string) string { - ns, err := namespace.FromContext(ctx) - if err != nil { - return "" - } - path = ns.Path + path - - mount, _, ok := r.root.LongestPrefix(path) - if !ok { - return "" - } - return mount -} - -// matchingPrefixInternal returns a mount prefix that a path may be a part of -func (r *Router) matchingPrefixInternal(ctx context.Context, path string) string { - ns, err := namespace.FromContext(ctx) - if err != nil { - return "" - } - path = ns.Path + path - - var existing string - fn := func(existingPath string, v interface{}) bool { - if strings.HasPrefix(existingPath, path) { - existing = existingPath - return true - } - return false - } - r.root.WalkPrefix(path, fn) - return existing -} - -// MountConflict determines if there are potential path conflicts -func (r *Router) MountConflict(ctx context.Context, path string) string { - r.l.RLock() - defer r.l.RUnlock() - if exactMatch := r.matchingMountInternal(ctx, path); exactMatch != "" { - return exactMatch - } - if prefixMatch := r.matchingPrefixInternal(ctx, path); prefixMatch != "" { - return prefixMatch - } - return "" -} - -// MatchingStorageByAPIPath/StoragePath returns the storage used for -// API/Storage paths respectively -func (r *Router) MatchingStorageByAPIPath(ctx context.Context, path string) logical.Storage { - return r.matchingStorage(ctx, path, true) -} -func (r *Router) MatchingStorageByStoragePath(ctx context.Context, path string) logical.Storage { - return r.matchingStorage(ctx, path, false) -} -func (r *Router) matchingStorage(ctx context.Context, path string, apiPath bool) logical.Storage { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil - } - path = ns.Path + path - - var raw interface{} - var ok bool - r.l.RLock() - if apiPath { - _, raw, ok = r.root.LongestPrefix(path) - } else { - _, raw, ok = r.storagePrefix.LongestPrefix(path) - } - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).storageView -} - -// MatchingMountEntry returns the MountEntry used for a path -func (r *Router) MatchingMountEntry(ctx context.Context, path string) *MountEntry { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil - } - path = ns.Path + path - - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).mountEntry -} - -// MatchingBackend returns the backend used for a path -func (r *Router) MatchingBackend(ctx context.Context, path string) logical.Backend { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil - } - path = ns.Path + path - - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).backend -} - -// MatchingSystemView returns the SystemView used for a path -func (r *Router) MatchingSystemView(ctx context.Context, path string) logical.SystemView { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil - } - path = ns.Path + path - - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).backend.System() -} - -// MatchingStoragePrefixByAPIPath the storage prefix for the given api path -func (r *Router) MatchingStoragePrefixByAPIPath(ctx context.Context, path string) (string, bool) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return "", false - } - path = ns.Path + path - - _, prefix, found := r.matchingMountEntryByPath(ctx, path, true) - return prefix, found -} - -// MatchingAPIPrefixByStoragePath the api path information for the given storage path -func (r *Router) MatchingAPIPrefixByStoragePath(ctx context.Context, path string) (*namespace.Namespace, string, string, bool) { - me, prefix, found := r.matchingMountEntryByPath(ctx, path, false) - if !found { - return nil, "", "", found - } - - mountPath := me.Path - // Add back the prefix for credential backends - if strings.HasPrefix(path, credentialBarrierPrefix) { - mountPath = credentialRoutePrefix + mountPath - } - - return me.Namespace(), mountPath, prefix, found -} - -func (r *Router) matchingMountEntryByPath(ctx context.Context, path string, apiPath bool) (*MountEntry, string, bool) { - var raw interface{} - var ok bool - r.l.RLock() - if apiPath { - _, raw, ok = r.root.LongestPrefix(path) - } else { - _, raw, ok = r.storagePrefix.LongestPrefix(path) - } - r.l.RUnlock() - if !ok { - return nil, "", false - } - - // Extract the mount path and storage prefix - re := raw.(*routeEntry) - prefix := re.storagePrefix - - return re.mountEntry, prefix, true -} - -// Route is used to route a given request -func (r *Router) Route(ctx context.Context, req *logical.Request) (*logical.Response, error) { - resp, _, _, err := r.routeCommon(ctx, req, false) - return resp, err -} - -// RouteExistenceCheck is used to route a given existence check request -func (r *Router) RouteExistenceCheck(ctx context.Context, req *logical.Request) (*logical.Response, bool, bool, error) { - resp, ok, exists, err := r.routeCommon(ctx, req, true) - return resp, ok, exists, err -} - -func (r *Router) routeCommon(ctx context.Context, req *logical.Request, existenceCheck bool) (*logical.Response, bool, bool, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, false, false, err - } - - // Find the mount point - r.l.RLock() - adjustedPath := req.Path - mount, raw, ok := r.root.LongestPrefix(ns.Path + adjustedPath) - if !ok && !strings.HasSuffix(adjustedPath, "/") { - // Re-check for a backend by appending a slash. This lets "foo" mean - // "foo/" at the root level which is almost always what we want. - adjustedPath += "/" - mount, raw, ok = r.root.LongestPrefix(ns.Path + adjustedPath) - } - r.l.RUnlock() - if !ok { - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - req.Path = adjustedPath - defer metrics.MeasureSince([]string{"route", string(req.Operation), - strings.Replace(mount, "/", "-", -1)}, time.Now()) - re := raw.(*routeEntry) - - // Grab a read lock on the route entry, this protects against the backend - // being reloaded during a request. - re.l.RLock() - defer re.l.RUnlock() - - // Filtered mounts will have a nil backend - if re.backend == nil { - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - - // If the path is tainted, we reject any operation except for - // Rollback and Revoke - if re.tainted { - switch req.Operation { - case logical.RevokeOperation, logical.RollbackOperation: - default: - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - } - - // Adjust the path to exclude the routing prefix - originalPath := req.Path - req.Path = strings.TrimPrefix(ns.Path+req.Path, mount) - req.MountPoint = mount - req.MountType = re.mountEntry.Type - if req.Path == "/" { - req.Path = "" - } - - originalEntReq := req.EntReq() - - // Attach the storage view for the request - req.Storage = re.storageView - - originalEntityID := req.EntityID - - // Hash the request token unless the request is being routed to the token - // or system backend. - clientToken := req.ClientToken - switch { - case strings.HasPrefix(originalPath, "auth/token/"): - case strings.HasPrefix(originalPath, "sys/"): - case strings.HasPrefix(originalPath, cubbyholeMountPath): - if req.Operation == logical.RollbackOperation { - // Backend doesn't support this and it can't properly look up a - // cubbyhole ID so just return here - return nil, false, false, nil - } - - te := req.TokenEntry() - - if te == nil { - return nil, false, false, fmt.Errorf("nil token entry") - } - - if te.Type != logical.TokenTypeService { - return logical.ErrorResponse(`cubbyhole operations are only supported by "service" type tokens`), false, false, nil - } - - switch { - case te.NamespaceID == namespace.RootNamespaceID && !strings.HasPrefix(req.ClientToken, "s."): - // In order for the token store to revoke later, we need to have the same - // salted ID, so we double-salt what's going to the cubbyhole backend - salt, err := r.tokenStoreSaltFunc(ctx) - if err != nil { - return nil, false, false, err - } - req.ClientToken = re.SaltID(salt.SaltID(req.ClientToken)) - - default: - if te.CubbyholeID == "" { - return nil, false, false, fmt.Errorf("empty cubbyhole id") - } - req.ClientToken = te.CubbyholeID - } - - default: - req.ClientToken = re.SaltID(req.ClientToken) - } - - // Cache the pointer to the original connection object - originalConn := req.Connection - - // Cache the identifier of the request - originalReqID := req.ID - - // Cache the client token's number of uses in the request - originalClientTokenRemainingUses := req.ClientTokenRemainingUses - req.ClientTokenRemainingUses = 0 - - origMFACreds := req.MFACreds - req.MFACreds = nil - - // Cache the headers - headers := req.Headers - - // Filter and add passthrough headers to the backend - var passthroughRequestHeaders []string - if rawVal, ok := re.mountEntry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - passthroughRequestHeaders = rawVal.([]string) - } - req.Headers = filteredPassthroughHeaders(headers, passthroughRequestHeaders) - - // Cache the wrap info of the request - var wrapInfo *logical.RequestWrapInfo - if req.WrapInfo != nil { - wrapInfo = &logical.RequestWrapInfo{ - TTL: req.WrapInfo.TTL, - Format: req.WrapInfo.Format, - SealWrap: req.WrapInfo.SealWrap, - } - } - - originalPolicyOverride := req.PolicyOverride - reqTokenEntry := req.TokenEntry() - req.SetTokenEntry(nil) - - // Reset the request before returning - defer func() { - req.Path = originalPath - req.MountPoint = mount - req.MountType = re.mountEntry.Type - req.Connection = originalConn - req.ID = originalReqID - req.Storage = nil - req.ClientToken = clientToken - req.ClientTokenRemainingUses = originalClientTokenRemainingUses - req.WrapInfo = wrapInfo - req.Headers = headers - req.PolicyOverride = originalPolicyOverride - // This is only set in one place, after routing, so should never be set - // by a backend - req.SetLastRemoteWAL(0) - - // This will be used for attaching the mount accessor for the identities - // returned by the authentication backends - req.MountAccessor = re.mountEntry.Accessor - - req.EntityID = originalEntityID - - req.MFACreds = origMFACreds - - req.SetTokenEntry(reqTokenEntry) - req.SetEntReq(originalEntReq) - }() - - // Invoke the backend - if existenceCheck { - ok, exists, err := re.backend.HandleExistenceCheck(ctx, req) - return nil, ok, exists, err - } else { - resp, err := re.backend.HandleRequest(ctx, req) - if resp != nil && - resp.Auth != nil { - // When a token gets renewed, the request hits this path and - // reaches token store. Token store delegates the renewal to the - // expiration manager. Expiration manager in-turn creates a - // different logical request and forwards the request to the auth - // backend that had initially authenticated the login request. The - // forwarding to auth backend will make this code path hit for the - // second time for the same renewal request. The accessors in the - // Alias structs should be of the auth backend and not of the token - // store. Therefore, avoiding the overwriting of accessors by - // having a check for path prefix having "renew". This gets applied - // for "renew" and "renew-self" requests. - if !strings.HasPrefix(req.Path, "renew") { - if resp.Auth.Alias != nil { - resp.Auth.Alias.MountAccessor = re.mountEntry.Accessor - } - for _, alias := range resp.Auth.GroupAliases { - alias.MountAccessor = re.mountEntry.Accessor - } - } - - switch re.mountEntry.Type { - case "token", "ns_token": - // Nothing; we respect what the token store is telling us and - // we don't allow tuning - default: - switch re.mountEntry.Config.TokenType { - case logical.TokenTypeService, logical.TokenTypeBatch: - resp.Auth.TokenType = re.mountEntry.Config.TokenType - case logical.TokenTypeDefault, logical.TokenTypeDefaultService: - if resp.Auth.TokenType == logical.TokenTypeDefault { - resp.Auth.TokenType = logical.TokenTypeService - } - case logical.TokenTypeDefaultBatch: - if resp.Auth.TokenType == logical.TokenTypeDefault { - resp.Auth.TokenType = logical.TokenTypeBatch - } - } - } - } - - return resp, false, false, err - } -} - -// RootPath checks if the given path requires root privileges -func (r *Router) RootPath(ctx context.Context, path string) bool { - ns, err := namespace.FromContext(ctx) - if err != nil { - return false - } - - adjustedPath := ns.Path + path - - r.l.RLock() - mount, raw, ok := r.root.LongestPrefix(adjustedPath) - r.l.RUnlock() - if !ok { - return false - } - re := raw.(*routeEntry) - - // Trim to get remaining path - remain := strings.TrimPrefix(adjustedPath, mount) - - // Check the rootPaths of this backend - rootPaths := re.rootPaths.Load().(*radix.Tree) - match, raw, ok := rootPaths.LongestPrefix(remain) - if !ok { - return false - } - prefixMatch := raw.(bool) - - // Handle the prefix match case - if prefixMatch { - return strings.HasPrefix(remain, match) - } - - // Handle the exact match case - return match == remain -} - -// LoginPath checks if the given path is used for logins -func (r *Router) LoginPath(ctx context.Context, path string) bool { - ns, err := namespace.FromContext(ctx) - if err != nil { - return false - } - - adjustedPath := ns.Path + path - - r.l.RLock() - mount, raw, ok := r.root.LongestPrefix(adjustedPath) - r.l.RUnlock() - if !ok { - return false - } - re := raw.(*routeEntry) - - // Trim to get remaining path - remain := strings.TrimPrefix(adjustedPath, mount) - - // Check the loginPaths of this backend - loginPaths := re.loginPaths.Load().(*radix.Tree) - match, raw, ok := loginPaths.LongestPrefix(remain) - if !ok { - return false - } - prefixMatch := raw.(bool) - - // Handle the prefix match case - if prefixMatch { - return strings.HasPrefix(remain, match) - } - - // Handle the exact match case - return match == remain -} - -// pathsToRadix converts a the mapping of special paths to a mapping -// of special paths to radix trees. -func pathsToRadix(paths []string) *radix.Tree { - tree := radix.New() - for _, path := range paths { - // Check if this is a prefix or exact match - prefixMatch := len(path) >= 1 && path[len(path)-1] == '*' - if prefixMatch { - path = path[:len(path)-1] - } - - tree.Insert(path, prefixMatch) - } - - return tree -} - -// filteredPassthroughHeaders returns a headers map[string][]string that -// contains the filtered values contained in passthroughHeaders. Filtering of -// passthroughHeaders from the origHeaders is done is a case-insensitive manner. -// Headers that match values from denylistHeaders will be ignored. -func filteredPassthroughHeaders(origHeaders map[string][]string, passthroughHeaders []string) map[string][]string { - retHeaders := make(map[string][]string) - - // Short-circuit if there's nothing to filter - if len(passthroughHeaders) == 0 { - return retHeaders - } - - // Filter passthroughHeaders values through denyListHeaders first. Returns the - // lowercased the complement set. - passthroughHeadersSubset := strutil.Difference(passthroughHeaders, denylistHeaders, true) - - // Create a map that uses lowercased header values as the key and the original - // header naming as the value for comparison down below. - lowerHeadersRef := make(map[string]string, len(origHeaders)) - for key := range origHeaders { - lowerHeadersRef[strings.ToLower(key)] = key - } - - // Case-insensitive compare of passthrough headers against originating - // headers. The returned headers will be the same casing as the originating - // header name. - for _, ph := range passthroughHeadersSubset { - if header, ok := lowerHeadersRef[ph]; ok { - retHeaders[header] = origHeaders[header] - } - } - - return retHeaders -} diff --git a/vendor/github.com/hashicorp/vault/vault/router_access.go b/vendor/github.com/hashicorp/vault/vault/router_access.go deleted file mode 100644 index 90335d7a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/router_access.go +++ /dev/null @@ -1,16 +0,0 @@ -package vault - -import "context" - -// RouterAccess provides access into some things necessary for testing -type RouterAccess struct { - c *Core -} - -func NewRouterAccess(c *Core) *RouterAccess { - return &RouterAccess{c: c} -} - -func (r *RouterAccess) StoragePrefixByAPIPath(ctx context.Context, path string) (string, bool) { - return r.c.router.MatchingStoragePrefixByAPIPath(ctx, path) -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal.go b/vendor/github.com/hashicorp/vault/vault/seal.go deleted file mode 100644 index 08249a0a..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal.go +++ /dev/null @@ -1,376 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/subtle" - "encoding/base64" - "encoding/json" - "fmt" - "sync/atomic" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/vault/seal" - - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -const ( - // barrierSealConfigPath is the path used to store our seal configuration. - // This value is stored in plaintext, since we must be able to read it even - // with the Vault sealed. This is required so that we know how many secret - // parts must be used to reconstruct the master key. - barrierSealConfigPath = "core/seal-config" - - // recoverySealConfigPath is the path to the recovery key seal - // configuration. It lives inside the barrier. - // DEPRECATED: Use recoverySealConfigPlaintextPath instead. - recoverySealConfigPath = "core/recovery-seal-config" - - // recoverySealConfigPlaintextPath is the path to the recovery key seal - // configuration. This is stored in plaintext so that we can perform - // auto-unseal. - recoverySealConfigPlaintextPath = "core/recovery-config" - - // recoveryKeyPath is the path to the recovery key - recoveryKeyPath = "core/recovery-key" - - // StoredBarrierKeysPath is the path used for storing HSM-encrypted unseal keys - StoredBarrierKeysPath = "core/hsm/barrier-unseal-keys" - - // hsmStoredIVPath is the path to the initialization vector for stored keys - hsmStoredIVPath = "core/hsm/iv" -) - -const ( - RecoveryTypeUnsupported = "unsupported" - RecoveryTypeShamir = "shamir" -) - -type Seal interface { - SetCore(*Core) - Init(context.Context) error - Finalize(context.Context) error - - StoredKeysSupported() bool - SetStoredKeys(context.Context, [][]byte) error - GetStoredKeys(context.Context) ([][]byte, error) - - BarrierType() string - BarrierConfig(context.Context) (*SealConfig, error) - SetBarrierConfig(context.Context, *SealConfig) error - SetCachedBarrierConfig(*SealConfig) - - RecoveryKeySupported() bool - RecoveryType() string - RecoveryConfig(context.Context) (*SealConfig, error) - SetRecoveryConfig(context.Context, *SealConfig) error - SetCachedRecoveryConfig(*SealConfig) - SetRecoveryKey(context.Context, []byte) error - VerifyRecoveryKey(context.Context, []byte) error -} - -type defaultSeal struct { - config atomic.Value - core *Core - PretendToAllowStoredShares bool - PretendToAllowRecoveryKeys bool - PretendRecoveryKey []byte -} - -func NewDefaultSeal() Seal { - ret := &defaultSeal{} - ret.config.Store((*SealConfig)(nil)) - return ret -} - -func (d *defaultSeal) checkCore() error { - if d.core == nil { - return fmt.Errorf("seal does not have a core set") - } - return nil -} - -func (d *defaultSeal) SetCore(core *Core) { - d.core = core -} - -func (d *defaultSeal) Init(ctx context.Context) error { - return nil -} - -func (d *defaultSeal) Finalize(ctx context.Context) error { - return nil -} - -func (d *defaultSeal) BarrierType() string { - return seal.Shamir -} - -func (d *defaultSeal) StoredKeysSupported() bool { - return d.PretendToAllowStoredShares -} - -func (d *defaultSeal) RecoveryKeySupported() bool { - return d.PretendToAllowRecoveryKeys -} - -func (d *defaultSeal) SetStoredKeys(ctx context.Context, keys [][]byte) error { - return fmt.Errorf("stored keys are not supported") -} - -func (d *defaultSeal) GetStoredKeys(ctx context.Context) ([][]byte, error) { - return nil, fmt.Errorf("stored keys are not supported") -} - -func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { - if d.config.Load().(*SealConfig) != nil { - return d.config.Load().(*SealConfig).Clone(), nil - } - - if err := d.checkCore(); err != nil { - return nil, err - } - - // Fetch the core configuration - pe, err := d.core.physical.Get(ctx, barrierSealConfigPath) - if err != nil { - d.core.logger.Error("failed to read seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to check seal configuration: {{err}}", err) - } - - // If the seal configuration is missing, we are not initialized - if pe == nil { - d.core.logger.Info("seal configuration missing, not initialized") - return nil, nil - } - - var conf SealConfig - - // Decode the barrier entry - if err := jsonutil.DecodeJSON(pe.Value, &conf); err != nil { - d.core.logger.Error("failed to decode seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to decode seal configuration: {{err}}", err) - } - - switch conf.Type { - // This case should not be valid for other types as only this is the default - case "": - conf.Type = d.BarrierType() - case d.BarrierType(): - default: - d.core.logger.Error("barrier seal type does not match expected type", "barrier_seal_type", conf.Type, "loaded_seal_type", d.BarrierType()) - return nil, fmt.Errorf("barrier seal type of %q does not match expected type of %q", conf.Type, d.BarrierType()) - } - - // Check for a valid seal configuration - if err := conf.Validate(); err != nil { - d.core.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("seal validation failed: {{err}}", err) - } - - d.config.Store(&conf) - return conf.Clone(), nil -} - -func (d *defaultSeal) SetBarrierConfig(ctx context.Context, config *SealConfig) error { - if err := d.checkCore(); err != nil { - return err - } - - // Provide a way to wipe out the cached value (also prevents actually - // saving a nil config) - if config == nil { - d.config.Store((*SealConfig)(nil)) - return nil - } - - config.Type = d.BarrierType() - - // Encode the seal configuration - buf, err := json.Marshal(config) - if err != nil { - return errwrap.Wrapf("failed to encode seal configuration: {{err}}", err) - } - - // Store the seal configuration - pe := &physical.Entry{ - Key: barrierSealConfigPath, - Value: buf, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - d.core.logger.Error("failed to write seal configuration", "error", err) - return errwrap.Wrapf("failed to write seal configuration: {{err}}", err) - } - - d.config.Store(config.Clone()) - - return nil -} - -func (d *defaultSeal) SetCachedBarrierConfig(config *SealConfig) { - d.config.Store(config) -} - -func (d *defaultSeal) RecoveryType() string { - if d.PretendToAllowRecoveryKeys { - return RecoveryTypeShamir - } - return RecoveryTypeUnsupported -} - -func (d *defaultSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { - if d.PretendToAllowRecoveryKeys { - return &SealConfig{ - SecretShares: 5, - SecretThreshold: 3, - }, nil - } - return nil, fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) SetRecoveryConfig(ctx context.Context, config *SealConfig) error { - if d.PretendToAllowRecoveryKeys { - return nil - } - return fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) SetCachedRecoveryConfig(config *SealConfig) { -} - -func (d *defaultSeal) VerifyRecoveryKey(ctx context.Context, key []byte) error { - if d.PretendToAllowRecoveryKeys { - if subtle.ConstantTimeCompare(key, d.PretendRecoveryKey) == 1 { - return nil - } - return fmt.Errorf("mismatch") - } - return fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) SetRecoveryKey(ctx context.Context, key []byte) error { - if d.PretendToAllowRecoveryKeys { - d.PretendRecoveryKey = key - return nil - } - return fmt.Errorf("recovery not supported") -} - -// SealConfig is used to describe the seal configuration -type SealConfig struct { - // The type, for sanity checking - Type string `json:"type"` - - // SecretShares is the number of shares the secret is split into. This is - // the N value of Shamir. - SecretShares int `json:"secret_shares"` - - // SecretThreshold is the number of parts required to open the vault. This - // is the T value of Shamir. - SecretThreshold int `json:"secret_threshold"` - - // PGPKeys is the array of public PGP keys used, if requested, to encrypt - // the output unseal tokens. If provided, it sets the value of - // SecretShares. Ordering is important. - PGPKeys []string `json:"pgp_keys"` - - // Nonce is a nonce generated by Vault used to ensure that when unseal keys - // are submitted for a rekey operation, the rekey operation itself is the - // one intended. This prevents hijacking of the rekey operation, since it - // is unauthenticated. - Nonce string `json:"nonce"` - - // Backup indicates whether or not a backup of PGP-encrypted unseal keys - // should be stored at coreUnsealKeysBackupPath after successful rekeying. - Backup bool `json:"backup"` - - // How many keys to store, for seals that support storage. - StoredShares int `json:"stored_shares"` - - // Stores the progress of the rekey operation (key shares) - RekeyProgress [][]byte `json:"-"` - - // VerificationRequired indicates that after a rekey validation must be - // performed (via providing shares from the new key) before the new key is - // actually installed. This is omitted from JSON as we don't persist the - // new key, it lives only in memory. - VerificationRequired bool `json:"-"` - - // VerificationKey is the new key that we will roll to after successful - // validation - VerificationKey []byte `json:"-"` - - // VerificationNonce stores the current operation nonce for verification - VerificationNonce string `json:"-"` - - // Stores the progress of the verification operation (key shares) - VerificationProgress [][]byte `json:"-"` -} - -// Validate is used to sanity check the seal configuration -func (s *SealConfig) Validate() error { - if s.SecretShares < 1 { - return fmt.Errorf("shares must be at least one") - } - if s.SecretThreshold < 1 { - return fmt.Errorf("threshold must be at least one") - } - if s.SecretShares > 1 && s.SecretThreshold == 1 { - return fmt.Errorf("threshold must be greater than one for multiple shares") - } - if s.SecretShares > 255 { - return fmt.Errorf("shares must be less than 256") - } - if s.SecretThreshold > 255 { - return fmt.Errorf("threshold must be less than 256") - } - if s.SecretThreshold > s.SecretShares { - return fmt.Errorf("threshold cannot be larger than shares") - } - if s.StoredShares > s.SecretShares { - return fmt.Errorf("stored keys cannot be larger than shares") - } - if len(s.PGPKeys) > 0 && len(s.PGPKeys) != s.SecretShares-s.StoredShares { - return fmt.Errorf("count mismatch between number of provided PGP keys and number of shares") - } - if len(s.PGPKeys) > 0 { - for _, keystring := range s.PGPKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - _, err = openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - } - } - return nil -} - -func (s *SealConfig) Clone() *SealConfig { - ret := &SealConfig{ - Type: s.Type, - SecretShares: s.SecretShares, - SecretThreshold: s.SecretThreshold, - Nonce: s.Nonce, - Backup: s.Backup, - StoredShares: s.StoredShares, - VerificationRequired: s.VerificationRequired, - VerificationNonce: s.VerificationNonce, - } - if len(s.PGPKeys) > 0 { - ret.PGPKeys = make([]string, len(s.PGPKeys)) - copy(ret.PGPKeys, s.PGPKeys) - } - if len(s.VerificationKey) > 0 { - ret.VerificationKey = make([]byte, len(s.VerificationKey)) - copy(ret.VerificationKey, s.VerificationKey) - } - return ret -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal/envelope.go b/vendor/github.com/hashicorp/vault/vault/seal/envelope.go deleted file mode 100644 index cdd6fcb8..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal/envelope.go +++ /dev/null @@ -1,72 +0,0 @@ -package seal - -import ( - "crypto/aes" - "crypto/cipher" - "errors" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" -) - -type Envelope struct{} - -type EnvelopeInfo struct { - Ciphertext []byte - Key []byte - IV []byte -} - -func NewEnvelope() *Envelope { - return &Envelope{} -} - -func (e *Envelope) Encrypt(plaintext []byte) (*EnvelopeInfo, error) { - defer metrics.MeasureSince([]string{"seal", "envelope", "encrypt"}, time.Now()) - - // Generate DEK - key, err := uuid.GenerateRandomBytes(32) - if err != nil { - return nil, err - } - iv, err := uuid.GenerateRandomBytes(12) - if err != nil { - return nil, err - } - aead, err := e.aeadEncrypter(key) - if err != nil { - return nil, err - } - return &EnvelopeInfo{ - Ciphertext: aead.Seal(nil, iv, plaintext, nil), - Key: key, - IV: iv, - }, nil -} - -func (e *Envelope) Decrypt(data *EnvelopeInfo) ([]byte, error) { - defer metrics.MeasureSince([]string{"seal", "envelope", "decrypt"}, time.Now()) - - aead, err := e.aeadEncrypter(data.Key) - if err != nil { - return nil, err - } - return aead.Open(nil, data.IV, data.Ciphertext, nil) -} - -func (e *Envelope) aeadEncrypter(key []byte) (cipher.AEAD, error) { - aesCipher, err := aes.NewCipher(key) - if err != nil { - return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err) - } - - // Create the GCM mode AEAD - gcm, err := cipher.NewGCM(aesCipher) - if err != nil { - return nil, errors.New("failed to initialize GCM mode") - } - - return gcm, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal/seal.go b/vendor/github.com/hashicorp/vault/vault/seal/seal.go deleted file mode 100644 index b80217a0..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal/seal.go +++ /dev/null @@ -1,34 +0,0 @@ -package seal - -import ( - "context" - - "github.com/hashicorp/vault/physical" -) - -const ( - Shamir = "shamir" - PKCS11 = "pkcs11" - AliCloudKMS = "alicloudkms" - AWSKMS = "awskms" - GCPCKMS = "gcpckms" - AzureKeyVault = "azurekeyvault" - Test = "test-auto" - - // HSMAutoDeprecated is a deprecated seal type prior to 0.9.0. - // It is still referenced in certain code paths for upgrade purporses - HSMAutoDeprecated = "hsm-auto" -) - -// Access is the embedded implemention of autoSeal that contains logic -// specific to encrypting and decrypting data, or in this case keys. -type Access interface { - SealType() string - KeyID() string - - Init(context.Context) error - Finalize(context.Context) error - - Encrypt(context.Context, []byte) (*physical.EncryptedBlobInfo, error) - Decrypt(context.Context, *physical.EncryptedBlobInfo) ([]byte, error) -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal/seal_testing.go b/vendor/github.com/hashicorp/vault/vault/seal/seal_testing.go deleted file mode 100644 index 6ce03b42..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal/seal_testing.go +++ /dev/null @@ -1,56 +0,0 @@ -package seal - -import ( - "context" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" -) - -type TestSeal struct { - logger log.Logger -} - -var _ Access = (*TestSeal)(nil) - -func NewTestSeal(logger log.Logger) *TestSeal { - return &TestSeal{ - logger: logger, - } -} - -func (s *TestSeal) Init(_ context.Context) error { - return nil -} - -func (t *TestSeal) Finalize(_ context.Context) error { - return nil -} - -func (t *TestSeal) SealType() string { - return Test -} - -func (t *TestSeal) KeyID() string { - return "static-key" -} - -func (t *TestSeal) Encrypt(_ context.Context, plaintext []byte) (*physical.EncryptedBlobInfo, error) { - return &physical.EncryptedBlobInfo{ - Ciphertext: ReverseBytes(plaintext), - }, nil -} - -func (t *TestSeal) Decrypt(_ context.Context, dwi *physical.EncryptedBlobInfo) ([]byte, error) { - return ReverseBytes(dwi.Ciphertext), nil -} - -// reverseBytes is a helper to simulate "encryption/decryption" -// on protected values. -func ReverseBytes(in []byte) []byte { - out := make([]byte, len(in)) - for i := 0; i < len(in); i++ { - out[i] = in[len(in)-1-i] - } - return out -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_access.go b/vendor/github.com/hashicorp/vault/vault/seal_access.go deleted file mode 100644 index f4a31dc9..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_access.go +++ /dev/null @@ -1,67 +0,0 @@ -package vault - -import ( - "context" - "fmt" -) - -// SealAccess is a wrapper around Seal that exposes accessor methods -// through Core.SealAccess() while restricting the ability to modify -// Core.seal itself. -type SealAccess struct { - seal Seal -} - -func NewSealAccess(seal Seal) *SealAccess { - return &SealAccess{seal: seal} -} - -func (s *SealAccess) StoredKeysSupported() bool { - return s.seal.StoredKeysSupported() -} - -func (s *SealAccess) BarrierType() string { - return s.seal.BarrierType() -} - -func (s *SealAccess) BarrierConfig(ctx context.Context) (*SealConfig, error) { - return s.seal.BarrierConfig(ctx) -} - -func (s *SealAccess) RecoveryKeySupported() bool { - return s.seal.RecoveryKeySupported() -} - -func (s *SealAccess) RecoveryConfig(ctx context.Context) (*SealConfig, error) { - return s.seal.RecoveryConfig(ctx) -} - -func (s *SealAccess) VerifyRecoveryKey(ctx context.Context, key []byte) error { - return s.seal.VerifyRecoveryKey(ctx, key) -} - -func (s *SealAccess) ClearCaches(ctx context.Context) { - s.seal.SetBarrierConfig(ctx, nil) - if s.RecoveryKeySupported() { - s.seal.SetRecoveryConfig(ctx, nil) - } -} - -type SealAccessTestingParams struct { - PretendToAllowStoredShares bool - PretendToAllowRecoveryKeys bool - PretendRecoveryKey []byte -} - -func (s *SealAccess) SetTestingParams(params *SealAccessTestingParams) error { - d, ok := s.seal.(*defaultSeal) - if !ok { - return fmt.Errorf("not a defaultseal") - } - d.PretendToAllowRecoveryKeys = params.PretendToAllowRecoveryKeys - d.PretendToAllowStoredShares = params.PretendToAllowStoredShares - if params.PretendRecoveryKey != nil { - d.PretendRecoveryKey = params.PretendRecoveryKey - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_autoseal.go b/vendor/github.com/hashicorp/vault/vault/seal_autoseal.go deleted file mode 100644 index 1a46d263..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_autoseal.go +++ /dev/null @@ -1,467 +0,0 @@ -package vault - -import ( - "context" - "crypto/subtle" - "encoding/json" - "fmt" - "sync/atomic" - - proto "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/vault/seal" -) - -// barrierTypeUpgradeCheck checks for backwards compat on barrier type, not -// applicable in the OSS side -var barrierTypeUpgradeCheck = func(_ string, _ *SealConfig) {} - -// autoSeal is a Seal implementation that contains logic for encrypting and -// decrypting stored keys via an underlying AutoSealAccess implementation, as -// well as logic related to recovery keys and barrier config. -type autoSeal struct { - seal.Access - - barrierConfig atomic.Value - recoveryConfig atomic.Value - core *Core -} - -// Ensure we are implementing the Seal interface -var _ Seal = (*autoSeal)(nil) - -func NewAutoSeal(lowLevel seal.Access) Seal { - ret := &autoSeal{ - Access: lowLevel, - } - ret.barrierConfig.Store((*SealConfig)(nil)) - ret.recoveryConfig.Store((*SealConfig)(nil)) - return ret -} - -func (d *autoSeal) checkCore() error { - if d.core == nil { - return fmt.Errorf("seal does not have a core set") - } - return nil -} - -func (d *autoSeal) SetCore(core *Core) { - d.core = core -} - -func (d *autoSeal) Init(ctx context.Context) error { - return d.Access.Init(ctx) -} - -func (d *autoSeal) Finalize(ctx context.Context) error { - return d.Access.Finalize(ctx) -} - -func (d *autoSeal) BarrierType() string { - return d.SealType() -} - -func (d *autoSeal) StoredKeysSupported() bool { - return true -} - -func (d *autoSeal) RecoveryKeySupported() bool { - return true -} - -// SetStoredKeys uses the autoSeal.Access.Encrypts method to wrap the keys. The stored entry -// does not need to be seal wrapped in this case. -func (d *autoSeal) SetStoredKeys(ctx context.Context, keys [][]byte) error { - if keys == nil { - return fmt.Errorf("keys were nil") - } - if len(keys) == 0 { - return fmt.Errorf("no keys provided") - } - - buf, err := json.Marshal(keys) - if err != nil { - return errwrap.Wrapf("failed to encode keys for storage: {{err}}", err) - } - - // Encrypt and marshal the keys - blobInfo, err := d.Encrypt(ctx, buf) - if err != nil { - return errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err) - } - - value, err := proto.Marshal(blobInfo) - if err != nil { - return errwrap.Wrapf("failed to marshal value for storage: {{err}}", err) - } - - // Store the seal configuration. - pe := &physical.Entry{ - Key: StoredBarrierKeysPath, - Value: value, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to write keys to storage: {{err}}", err) - } - - return nil -} - -// GetStoredKeys retrieves the key shares by unwrapping the encrypted key using the -// autoseal. -func (d *autoSeal) GetStoredKeys(ctx context.Context) ([][]byte, error) { - pe, err := d.core.physical.Get(ctx, StoredBarrierKeysPath) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch stored keys: {{err}}", err) - } - - // This is not strictly an error; we may not have any stored keys, for - // instance, if we're not initialized - if pe == nil { - return nil, nil - } - - blobInfo := &physical.EncryptedBlobInfo{} - if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return nil, errwrap.Wrapf("failed to proto decode stored keys: {{err}}", err) - } - - pt, err := d.Decrypt(ctx, blobInfo) - if err != nil { - return nil, errwrap.Wrapf("failed to decrypt encrypted stored keys: {{err}}", err) - } - - // Decode the barrier entry - var keys [][]byte - if err := json.Unmarshal(pt, &keys); err != nil { - return nil, fmt.Errorf("failed to decode stored keys: %v, plaintext was %q", err, pe.Value) - } - - return keys, nil -} - -func (d *autoSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { - if d.barrierConfig.Load().(*SealConfig) != nil { - return d.barrierConfig.Load().(*SealConfig).Clone(), nil - } - - if err := d.checkCore(); err != nil { - return nil, err - } - - sealType := "barrier" - - entry, err := d.core.physical.Get(ctx, barrierSealConfigPath) - if err != nil { - d.core.logger.Error("autoseal: failed to read seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read %q seal configuration: {{err}}", sealType), err) - } - - // If the seal configuration is missing, we are not initialized - if entry == nil { - if d.core.logger.IsInfo() { - d.core.logger.Info("autoseal: seal configuration missing, not initialized", "seal_type", sealType) - } - return nil, nil - } - - conf := &SealConfig{} - err = json.Unmarshal(entry.Value, conf) - if err != nil { - d.core.logger.Error("autoseal: failed to decode seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode %q seal configuration: {{err}}", sealType), err) - } - - // Check for a valid seal configuration - if err := conf.Validate(); err != nil { - d.core.logger.Error("autoseal: invalid seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("%q seal validation failed: {{err}}", sealType), err) - } - - barrierTypeUpgradeCheck(d.BarrierType(), conf) - - if conf.Type != d.BarrierType() { - d.core.logger.Error("autoseal: barrier seal type does not match loaded type", "seal_type", conf.Type, "loaded_type", d.BarrierType()) - return nil, fmt.Errorf("barrier seal type of %q does not match loaded type of %q", conf.Type, d.BarrierType()) - } - - d.barrierConfig.Store(conf) - return conf.Clone(), nil -} - -func (d *autoSeal) SetBarrierConfig(ctx context.Context, conf *SealConfig) error { - if err := d.checkCore(); err != nil { - return err - } - - if conf == nil { - d.barrierConfig.Store((*SealConfig)(nil)) - return nil - } - - conf.Type = d.BarrierType() - - // Encode the seal configuration - buf, err := json.Marshal(conf) - if err != nil { - return errwrap.Wrapf("failed to encode barrier seal configuration: {{err}}", err) - } - - // Store the seal configuration - pe := &physical.Entry{ - Key: barrierSealConfigPath, - Value: buf, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - d.core.logger.Error("autoseal: failed to write barrier seal configuration", "error", err) - return errwrap.Wrapf("failed to write barrier seal configuration: {{err}}", err) - } - - d.barrierConfig.Store(conf.Clone()) - - return nil -} - -func (d *autoSeal) SetCachedBarrierConfig(config *SealConfig) { - d.barrierConfig.Store(config) -} - -func (d *autoSeal) RecoveryType() string { - return RecoveryTypeShamir -} - -// RecoveryConfig returns the recovery config on recoverySealConfigPlaintextPath. -func (d *autoSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { - if d.recoveryConfig.Load().(*SealConfig) != nil { - return d.recoveryConfig.Load().(*SealConfig).Clone(), nil - } - - if err := d.checkCore(); err != nil { - return nil, err - } - - sealType := "recovery" - - var entry *physical.Entry - var err error - entry, err = d.core.physical.Get(ctx, recoverySealConfigPlaintextPath) - if err != nil { - d.core.logger.Error("autoseal: failed to read seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read %q seal configuration: {{err}}", sealType), err) - } - - if entry == nil { - if d.core.Sealed() { - d.core.logger.Info("autoseal: seal configuration missing, but cannot check old path as core is sealed", "seal_type", sealType) - return nil, nil - } - - // Check the old recovery seal config path so an upgraded standby will - // return the correct seal config - be, err := d.core.barrier.Get(ctx, recoverySealConfigPath) - if err != nil { - return nil, errwrap.Wrapf("failed to read old recovery seal configuration: {{err}}", err) - } - - // If the seal configuration is missing, then we are not initialized. - if be == nil { - if d.core.logger.IsInfo() { - d.core.logger.Info("autoseal: seal configuration missing, not initialized", "seal_type", sealType) - } - return nil, nil - } - - // Reconstruct the physical entry - entry = &physical.Entry{ - Key: be.Key, - Value: be.Value, - } - } - - conf := &SealConfig{} - if err := json.Unmarshal(entry.Value, conf); err != nil { - d.core.logger.Error("autoseal: failed to decode seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("failed to decode %q seal configuration: {{err}}", sealType), err) - } - - // Check for a valid seal configuration - if err := conf.Validate(); err != nil { - d.core.logger.Error("autoseal: invalid seal configuration", "seal_type", sealType, "error", err) - return nil, errwrap.Wrapf(fmt.Sprintf("%q seal validation failed: {{err}}", sealType), err) - } - - if conf.Type != d.RecoveryType() { - d.core.logger.Error("autoseal: recovery seal type does not match loaded type", "seal_type", conf.Type, "loaded_type", d.RecoveryType()) - return nil, fmt.Errorf("recovery seal type of %q does not match loaded type of %q", conf.Type, d.RecoveryType()) - } - - d.recoveryConfig.Store(conf) - return conf.Clone(), nil -} - -// SetRecoveryConfig writes the recovery configuration to the physical storage -// and sets it as the seal's recoveryConfig. -func (d *autoSeal) SetRecoveryConfig(ctx context.Context, conf *SealConfig) error { - if err := d.checkCore(); err != nil { - return err - } - - // Perform migration if applicable - if err := d.migrateRecoveryConfig(ctx); err != nil { - return err - } - - if conf == nil { - d.recoveryConfig.Store((*SealConfig)(nil)) - return nil - } - - conf.Type = d.RecoveryType() - - // Encode the seal configuration - buf, err := json.Marshal(conf) - if err != nil { - return errwrap.Wrapf("failed to encode recovery seal configuration: {{err}}", err) - } - - // Store the seal configuration directly in the physical storage - pe := &physical.Entry{ - Key: recoverySealConfigPlaintextPath, - Value: buf, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - d.core.logger.Error("autoseal: failed to write recovery seal configuration", "error", err) - return errwrap.Wrapf("failed to write recovery seal configuration: {{err}}", err) - } - - d.recoveryConfig.Store(conf.Clone()) - - return nil -} - -func (d *autoSeal) SetCachedRecoveryConfig(config *SealConfig) { - d.recoveryConfig.Store(config) -} - -func (d *autoSeal) VerifyRecoveryKey(ctx context.Context, key []byte) error { - if key == nil { - return fmt.Errorf("recovery key to verify is nil") - } - - pe, err := d.core.physical.Get(ctx, recoveryKeyPath) - if err != nil { - d.core.logger.Error("autoseal: failed to read recovery key", "error", err) - return errwrap.Wrapf("failed to read recovery key: {{err}}", err) - } - if pe == nil { - d.core.logger.Warn("autoseal: no recovery key found") - return fmt.Errorf("no recovery key found") - } - - blobInfo := &physical.EncryptedBlobInfo{} - if err := proto.Unmarshal(pe.Value, blobInfo); err != nil { - return errwrap.Wrapf("failed to proto decode stored keys: {{err}}", err) - } - - pt, err := d.Decrypt(ctx, blobInfo) - if err != nil { - return errwrap.Wrapf("failed to decrypt encrypted stored keys: {{err}}", err) - } - - // Check if provided key is same as the decrypted key - if subtle.ConstantTimeCompare(key, pt) != 1 { - // We may need to upgrade if the key is barrier-wrapped, so check - barrierDec, err := d.core.BarrierEncryptorAccess().Decrypt(ctx, recoveryKeyPath, pt) - if err == nil { - // If we hit this, it got barrier-wrapped, so we need to re-set the - // recovery key after unwrapping - err := d.SetRecoveryKey(ctx, barrierDec) - if err != nil { - return err - } - } - // Set pt to barrierDec for re-checking - pt = barrierDec - } - - if subtle.ConstantTimeCompare(key, pt) != 1 { - return fmt.Errorf("recovery key does not match submitted values") - } - - return nil -} - -func (d *autoSeal) SetRecoveryKey(ctx context.Context, key []byte) error { - if err := d.checkCore(); err != nil { - return err - } - - if key == nil { - return fmt.Errorf("recovery key to store is nil") - } - - // Encrypt and marshal the keys - blobInfo, err := d.Encrypt(ctx, key) - if err != nil { - return errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err) - } - - value, err := proto.Marshal(blobInfo) - if err != nil { - return errwrap.Wrapf("failed to marshal value for storage: {{err}}", err) - } - - be := &physical.Entry{ - Key: recoveryKeyPath, - Value: value, - } - - if err := d.core.physical.Put(ctx, be); err != nil { - d.core.logger.Error("autoseal: failed to write recovery key", "error", err) - return errwrap.Wrapf("failed to write recovery key: {{err}}", err) - } - - return nil -} - -// migrateRecoveryConfig is a helper func to migrate the recovery config to -// live outside the barrier. This is called from SetRecoveryConfig which is -// always called with the stateLock. -func (d *autoSeal) migrateRecoveryConfig(ctx context.Context) error { - // Get config from the old recoverySealConfigPath path - be, err := d.core.barrier.Get(ctx, recoverySealConfigPath) - if err != nil { - return errwrap.Wrapf("failed to read old recovery seal configuration during migration: {{err}}", err) - } - - // If this entry is nil, then skip migration - if be == nil { - return nil - } - - // Only log if we are performing the migration - d.core.logger.Debug("migrating recovery seal configuration") - defer d.core.logger.Debug("done migrating recovery seal configuration") - - // Perform migration - pe := &physical.Entry{ - Key: recoverySealConfigPlaintextPath, - Value: be.Value, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to write recovery seal configuration during migration: {{err}}", err) - } - - // Perform deletion of the old entry - if err := d.core.barrier.Delete(ctx, recoverySealConfigPath); err != nil { - return errwrap.Wrapf("failed to delete old recovery seal configuration during migration: {{err}}", err) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_testing.go b/vendor/github.com/hashicorp/vault/vault/seal_testing.go deleted file mode 100644 index d97281b3..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_testing.go +++ /dev/null @@ -1,90 +0,0 @@ -package vault - -import ( - "context" - - "github.com/mitchellh/go-testing-interface" -) - -var ( - TestCoreUnsealedWithConfigs = testCoreUnsealedWithConfigs - TestSealDefConfigs = testSealDefConfigs -) - -type TestSealOpts struct { - StoredKeysDisabled bool - RecoveryKeysDisabled bool -} - -func testCoreUnsealedWithConfigs(t testing.T, barrierConf, recoveryConf *SealConfig) (*Core, [][]byte, [][]byte, string) { - t.Helper() - var opts *TestSealOpts - if recoveryConf == nil { - opts = &TestSealOpts{ - StoredKeysDisabled: true, - RecoveryKeysDisabled: true, - } - } - seal := NewTestSeal(t, opts) - core := TestCoreWithSeal(t, seal, false) - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConf, - RecoveryConfig: recoveryConf, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - err = core.UnsealWithStoredKeys(context.Background()) - if err != nil { - t.Fatalf("err: %s", err) - } - if core.Sealed() { - for _, key := range result.SecretShares { - if _, err := core.Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - } - - return core, result.SecretShares, result.RecoveryShares, result.RootToken -} - -func testSealDefConfigs() (*SealConfig, *SealConfig) { - return &SealConfig{ - SecretShares: 5, - SecretThreshold: 3, - }, nil -} - -func TestCoreUnsealedWithConfigSealOpts(t testing.T, barrierConf, recoveryConf *SealConfig, sealOpts *TestSealOpts) (*Core, [][]byte, [][]byte, string) { - seal := NewTestSeal(t, sealOpts) - core := TestCoreWithSeal(t, seal, false) - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConf, - RecoveryConfig: recoveryConf, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - err = core.UnsealWithStoredKeys(context.Background()) - if err != nil { - t.Fatalf("err: %s", err) - } - if core.Sealed() { - for _, key := range result.SecretShares { - if _, err := core.Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - } - - return core, result.SecretShares, result.RecoveryShares, result.RootToken -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_testing_util.go b/vendor/github.com/hashicorp/vault/vault/seal_testing_util.go deleted file mode 100644 index 76568fad..00000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_testing_util.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build !enterprise - -package vault - -import "github.com/mitchellh/go-testing-interface" - -func NewTestSeal(testing.T, *TestSealOpts) Seal { - return NewDefaultSeal() -} diff --git a/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go b/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go deleted file mode 100644 index c249fd77..00000000 --- a/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go +++ /dev/null @@ -1,180 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - "fmt" - "sync/atomic" - - proto "github.com/golang/protobuf/proto" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/physical" -) - -// NewSealUnwrapper creates a new seal unwrapper -func NewSealUnwrapper(underlying physical.Backend, logger log.Logger) physical.Backend { - ret := &sealUnwrapper{ - underlying: underlying, - logger: logger, - locks: locksutil.CreateLocks(), - allowUnwraps: new(uint32), - } - - if underTxn, ok := underlying.(physical.Transactional); ok { - return &transactionalSealUnwrapper{ - sealUnwrapper: ret, - Transactional: underTxn, - } - } - - return ret -} - -var _ physical.Backend = (*sealUnwrapper)(nil) -var _ physical.Transactional = (*transactionalSealUnwrapper)(nil) - -type sealUnwrapper struct { - underlying physical.Backend - logger log.Logger - locks []*locksutil.LockEntry - allowUnwraps *uint32 -} - -// transactionalSealUnwrapper is a seal unwrapper that wraps a physical that is transactional -type transactionalSealUnwrapper struct { - *sealUnwrapper - physical.Transactional -} - -func (d *sealUnwrapper) Put(ctx context.Context, entry *physical.Entry) error { - if entry == nil { - return nil - } - - locksutil.LockForKey(d.locks, entry.Key).Lock() - defer locksutil.LockForKey(d.locks, entry.Key).Unlock() - - return d.underlying.Put(ctx, entry) -} - -func (d *sealUnwrapper) Get(ctx context.Context, key string) (*physical.Entry, error) { - entry, err := d.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var performUnwrap bool - se := &physical.EncryptedBlobInfo{} - // If the value ends in our canary value, try to decode the bytes. - eLen := len(entry.Value) - if eLen > 0 && entry.Value[eLen-1] == 's' { - if err := proto.Unmarshal(entry.Value[:eLen-1], se); err == nil { - // We unmarshaled successfully which means we need to store it as a - // non-proto message - performUnwrap = true - } - } - if !performUnwrap { - return entry, nil - } - // It's actually encrypted and we can't read it - if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) - } - if atomic.LoadUint32(d.allowUnwraps) != 1 { - return &physical.Entry{ - Key: entry.Key, - Value: se.Ciphertext, - }, nil - } - - locksutil.LockForKey(d.locks, key).Lock() - defer locksutil.LockForKey(d.locks, key).Unlock() - - // At this point we need to re-read and re-check - entry, err = d.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - performUnwrap = false - se = &physical.EncryptedBlobInfo{} - // If the value ends in our canary value, try to decode the bytes. - eLen = len(entry.Value) - if eLen > 0 && entry.Value[eLen-1] == 's' { - // We ignore an error because the canary is not a guarantee; if it - // doesn't decode, proceed normally - if err := proto.Unmarshal(entry.Value[:eLen-1], se); err == nil { - // We unmarshaled successfully which means we need to store it as a - // non-proto message - performUnwrap = true - } - } - if !performUnwrap { - return entry, nil - } - if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) - } - - entry = &physical.Entry{ - Key: entry.Key, - Value: se.Ciphertext, - } - - if atomic.LoadUint32(d.allowUnwraps) != 1 { - return entry, nil - } - return entry, d.underlying.Put(ctx, entry) -} - -func (d *sealUnwrapper) Delete(ctx context.Context, key string) error { - locksutil.LockForKey(d.locks, key).Lock() - defer locksutil.LockForKey(d.locks, key).Unlock() - - return d.underlying.Delete(ctx, key) -} - -func (d *sealUnwrapper) List(ctx context.Context, prefix string) ([]string, error) { - return d.underlying.List(ctx, prefix) -} - -func (d *transactionalSealUnwrapper) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - // 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(d.locks, keys) { - l.Lock() - defer l.Unlock() - } - - if err := d.Transactional.Transaction(ctx, txns); err != nil { - return err - } - - return nil -} - -// This should only run during preSeal which ensures that it can't be run -// concurrently and that it will be run only by the active node -func (d *sealUnwrapper) stopUnwraps() { - atomic.StoreUint32(d.allowUnwraps, 0) -} - -func (d *sealUnwrapper) runUnwraps() { - // Allow key unwraps on key gets. This gets set only when running on the - // active node to prevent standbys from changing data underneath the - // primary - atomic.StoreUint32(d.allowUnwraps, 1) -} diff --git a/vendor/github.com/hashicorp/vault/vault/testing.go b/vendor/github.com/hashicorp/vault/vault/testing.go deleted file mode 100644 index 91aa3802..00000000 --- a/vendor/github.com/hashicorp/vault/vault/testing.go +++ /dev/null @@ -1,1550 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "encoding/pem" - "errors" - "fmt" - "io" - "io/ioutil" - "math/big" - mathrand "math/rand" - "net" - "net/http" - "os" - "os/exec" - "path/filepath" - "sync" - "sync/atomic" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/mitchellh/copystructure" - - "golang.org/x/crypto/ssh" - "golang.org/x/net/http2" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/reload" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/hashicorp/vault/physical" - dbMysql "github.com/hashicorp/vault/plugins/database/mysql" - dbPostgres "github.com/hashicorp/vault/plugins/database/postgresql" - "github.com/mitchellh/go-testing-interface" - - physInmem "github.com/hashicorp/vault/physical/inmem" -) - -// This file contains a number of methods that are useful for unit -// tests within other packages. - -const ( - testSharedPublicKey = ` -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9i+hFxZHGo6KblVme4zrAcJstR6I0PTJozW286X4WyvPnkMYDQ5mnhEYC7UWCvjoTWbPEXPX7NjhRtwQTGD67bV+lrxgfyzK1JZbUXK4PwgKJvQD+XyyWYMzDgGSQY61KUSqCxymSm/9NZkPU3ElaQ9xQuTzPpztM4ROfb8f2Yv6/ZESZsTo0MTAkp8Pcy+WkioI/uJ1H7zqs0EA4OMY4aDJRu0UtP4rTVeYNEAuRXdX+eH4aW3KMvhzpFTjMbaJHJXlEeUm2SaX5TNQyTOvghCeQILfYIL/Ca2ij8iwCmulwdV6eQGfd4VDu40PvSnmfoaE38o6HaPnX0kUcnKiT -` - testSharedPrivateKey = ` ------BEGIN RSA PRIVATE KEY----- -MIIEogIBAAKCAQEAvYvoRcWRxqOim5VZnuM6wHCbLUeiND0yaM1tvOl+Fsrz55DG -A0OZp4RGAu1Fgr46E1mzxFz1+zY4UbcEExg+u21fpa8YH8sytSWW1FyuD8ICib0A -/l8slmDMw4BkkGOtSlEqgscpkpv/TWZD1NxJWkPcULk8z6c7TOETn2/H9mL+v2RE -mbE6NDEwJKfD3MvlpIqCP7idR+86rNBAODjGOGgyUbtFLT+K01XmDRALkV3V/nh+ -GltyjL4c6RU4zG2iRyV5RHlJtkml+UzUMkzr4IQnkCC32CC/wmtoo/IsAprpcHVe -nkBn3eFQ7uND70p5n6GhN/KOh2j519JFHJyokwIDAQABAoIBAHX7VOvBC3kCN9/x -+aPdup84OE7Z7MvpX6w+WlUhXVugnmsAAVDczhKoUc/WktLLx2huCGhsmKvyVuH+ -MioUiE+vx75gm3qGx5xbtmOfALVMRLopjCnJYf6EaFA0ZeQ+NwowNW7Lu0PHmAU8 -Z3JiX8IwxTz14DU82buDyewO7v+cEr97AnERe3PUcSTDoUXNaoNxjNpEJkKREY6h -4hAY676RT/GsRcQ8tqe/rnCqPHNd7JGqL+207FK4tJw7daoBjQyijWuB7K5chSal -oPInylM6b13ASXuOAOT/2uSUBWmFVCZPDCmnZxy2SdnJGbsJAMl7Ma3MUlaGvVI+ -Tfh1aQkCgYEA4JlNOabTb3z42wz6mz+Nz3JRwbawD+PJXOk5JsSnV7DtPtfgkK9y -6FTQdhnozGWShAvJvc+C4QAihs9AlHXoaBY5bEU7R/8UK/pSqwzam+MmxmhVDV7G -IMQPV0FteoXTaJSikhZ88mETTegI2mik+zleBpVxvfdhE5TR+lq8Br0CgYEA2AwJ -CUD5CYUSj09PluR0HHqamWOrJkKPFPwa+5eiTTCzfBBxImYZh7nXnWuoviXC0sg2 -AuvCW+uZ48ygv/D8gcz3j1JfbErKZJuV+TotK9rRtNIF5Ub7qysP7UjyI7zCssVM -kuDd9LfRXaB/qGAHNkcDA8NxmHW3gpln4CFdSY8CgYANs4xwfercHEWaJ1qKagAe -rZyrMpffAEhicJ/Z65lB0jtG4CiE6w8ZeUMWUVJQVcnwYD+4YpZbX4S7sJ0B8Ydy -AhkSr86D/92dKTIt2STk6aCN7gNyQ1vW198PtaAWH1/cO2UHgHOy3ZUt5X/Uwxl9 -cex4flln+1Viumts2GgsCQKBgCJH7psgSyPekK5auFdKEr5+Gc/jB8I/Z3K9+g4X -5nH3G1PBTCJYLw7hRzw8W/8oALzvddqKzEFHphiGXK94Lqjt/A4q1OdbCrhiE68D -My21P/dAKB1UYRSs9Y8CNyHCjuZM9jSMJ8vv6vG/SOJPsnVDWVAckAbQDvlTHC9t -O98zAoGAcbW6uFDkrv0XMCpB9Su3KaNXOR0wzag+WIFQRXCcoTvxVi9iYfUReQPi -oOyBJU/HMVvBfv4g+OVFLVgSwwm6owwsouZ0+D/LasbuHqYyqYqdyPJQYzWA2Y+F -+B6f4RoPdSXj24JHPg/ioRxjaj094UXJxua2yfkcecGNEuBQHSs= ------END RSA PRIVATE KEY----- -` -) - -// TestCore returns a pure in-memory, uninitialized core for testing. -func TestCore(t testing.T) *Core { - return TestCoreWithSeal(t, nil, false) -} - -// TestCoreRaw returns a pure in-memory, uninitialized core for testing. The raw -// storage endpoints are enabled with this core. -func TestCoreRaw(t testing.T) *Core { - return TestCoreWithSeal(t, nil, true) -} - -// TestCoreNewSeal returns a pure in-memory, uninitialized core with -// the new seal configuration. -func TestCoreNewSeal(t testing.T) *Core { - seal := NewTestSeal(t, nil) - return TestCoreWithSeal(t, seal, false) -} - -// TestCoreWithConfig returns a pure in-memory, uninitialized core with the -// specified core configurations overridden for testing. -func TestCoreWithConfig(t testing.T, conf *CoreConfig) *Core { - return TestCoreWithSealAndUI(t, conf) -} - -// TestCoreWithSeal returns a pure in-memory, uninitialized core with the -// specified seal for testing. -func TestCoreWithSeal(t testing.T, testSeal Seal, enableRaw bool) *Core { - conf := &CoreConfig{ - Seal: testSeal, - EnableUI: false, - EnableRaw: enableRaw, - BuiltinRegistry: NewMockBuiltinRegistry(), - } - return TestCoreWithSealAndUI(t, conf) -} - -func TestCoreUI(t testing.T, enableUI bool) *Core { - conf := &CoreConfig{ - EnableUI: enableUI, - EnableRaw: true, - BuiltinRegistry: NewMockBuiltinRegistry(), - } - return TestCoreWithSealAndUI(t, conf) -} - -func TestCoreWithSealAndUI(t testing.T, opts *CoreConfig) *Core { - logger := logging.NewVaultLogger(log.Trace) - physicalBackend, err := physInmem.NewInmem(nil, logger) - if err != nil { - t.Fatal(err) - } - - // Start off with base test core config - conf := testCoreConfig(t, physicalBackend, logger) - - // Override config values with ones that gets passed in - conf.EnableUI = opts.EnableUI - conf.EnableRaw = opts.EnableRaw - conf.Seal = opts.Seal - conf.LicensingConfig = opts.LicensingConfig - conf.DisableKeyEncodingChecks = opts.DisableKeyEncodingChecks - - c, err := NewCore(conf) - if err != nil { - t.Fatalf("err: %s", err) - } - - return c -} - -func testCoreConfig(t testing.T, physicalBackend physical.Backend, logger log.Logger) *CoreConfig { - t.Helper() - noopAudits := map[string]audit.Factory{ - "noop": func(_ context.Context, config *audit.BackendConfig) (audit.Backend, error) { - view := &logical.InmemStorage{} - view.Put(context.Background(), &logical.StorageEntry{ - Key: "salt", - Value: []byte("foo"), - }) - config.SaltConfig = &salt.Config{ - HMAC: sha256.New, - HMACType: "hmac-sha256", - } - config.SaltView = view - return &noopAudit{ - Config: config, - }, nil - }, - } - - noopBackends := make(map[string]logical.Factory) - noopBackends["noop"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - b := new(framework.Backend) - b.Setup(ctx, config) - b.BackendType = logical.TypeCredential - return b, nil - } - noopBackends["http"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - return new(rawHTTP), nil - } - - credentialBackends := make(map[string]logical.Factory) - for backendName, backendFactory := range noopBackends { - credentialBackends[backendName] = backendFactory - } - for backendName, backendFactory := range testCredentialBackends { - credentialBackends[backendName] = backendFactory - } - - logicalBackends := make(map[string]logical.Factory) - for backendName, backendFactory := range noopBackends { - logicalBackends[backendName] = backendFactory - } - - logicalBackends["kv"] = LeasedPassthroughBackendFactory - for backendName, backendFactory := range testLogicalBackends { - logicalBackends[backendName] = backendFactory - } - - conf := &CoreConfig{ - Physical: physicalBackend, - AuditBackends: noopAudits, - LogicalBackends: logicalBackends, - CredentialBackends: credentialBackends, - DisableMlock: true, - Logger: logger, - BuiltinRegistry: NewMockBuiltinRegistry(), - } - - return conf -} - -// TestCoreInit initializes the core with a single key, and returns -// the key that must be used to unseal the core and a root token. -func TestCoreInit(t testing.T, core *Core) ([][]byte, string) { - t.Helper() - secretShares, _, root := TestCoreInitClusterWrapperSetup(t, core, nil, nil) - return secretShares, root -} - -func TestCoreInitClusterWrapperSetup(t testing.T, core *Core, clusterAddrs []*net.TCPAddr, handler http.Handler) ([][]byte, [][]byte, string) { - t.Helper() - core.SetClusterListenerAddrs(clusterAddrs) - core.SetClusterHandler(handler) - - barrierConfig := &SealConfig{ - SecretShares: 3, - SecretThreshold: 3, - } - - // If we support storing barrier keys, then set that to equal the min threshold to unseal - if core.seal.StoredKeysSupported() { - barrierConfig.StoredShares = barrierConfig.SecretThreshold - } - - recoveryConfig := &SealConfig{ - SecretShares: 3, - SecretThreshold: 3, - } - - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConfig, - RecoveryConfig: recoveryConfig, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - return result.SecretShares, result.RecoveryShares, result.RootToken -} - -func TestCoreUnseal(core *Core, key []byte) (bool, error) { - return core.Unseal(key) -} - -func TestCoreUnsealWithRecoveryKeys(core *Core, key []byte) (bool, error) { - return core.UnsealWithRecoveryKeys(key) -} - -// TestCoreUnsealed returns a pure in-memory core that is already -// initialized and unsealed. -func TestCoreUnsealed(t testing.T) (*Core, [][]byte, string) { - t.Helper() - core := TestCore(t) - return testCoreUnsealed(t, core) -} - -// TestCoreUnsealedRaw returns a pure in-memory core that is already -// initialized, unsealed, and with raw endpoints enabled. -func TestCoreUnsealedRaw(t testing.T) (*Core, [][]byte, string) { - t.Helper() - core := TestCoreRaw(t) - return testCoreUnsealed(t, core) -} - -// TestCoreUnsealedWithConfig returns a pure in-memory core that is already -// initialized, unsealed, with the any provided core config values overridden. -func TestCoreUnsealedWithConfig(t testing.T, conf *CoreConfig) (*Core, [][]byte, string) { - t.Helper() - core := TestCoreWithConfig(t, conf) - return testCoreUnsealed(t, core) -} - -func testCoreUnsealed(t testing.T, core *Core) (*Core, [][]byte, string) { - t.Helper() - keys, token := TestCoreInit(t, core) - for _, key := range keys { - if _, err := TestCoreUnseal(core, TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - - return core, keys, token -} - -func TestCoreUnsealedBackend(t testing.T, backend physical.Backend) (*Core, [][]byte, string) { - t.Helper() - logger := logging.NewVaultLogger(log.Trace) - conf := testCoreConfig(t, backend, logger) - conf.Seal = NewTestSeal(t, nil) - - core, err := NewCore(conf) - if err != nil { - t.Fatalf("err: %s", err) - } - - keys, token := TestCoreInit(t, core) - for _, key := range keys { - if _, err := TestCoreUnseal(core, TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if err := core.UnsealWithStoredKeys(context.Background()); err != nil { - t.Fatal(err) - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - - return core, keys, token -} - -// TestKeyCopy is a silly little function to just copy the key so that -// it can be used with Unseal easily. -func TestKeyCopy(key []byte) []byte { - result := make([]byte, len(key)) - copy(result, key) - return result -} - -func TestDynamicSystemView(c *Core) *dynamicSystemView { - me := &MountEntry{ - Config: MountConfig{ - DefaultLeaseTTL: 24 * time.Hour, - MaxLeaseTTL: 2 * 24 * time.Hour, - }, - } - - return &dynamicSystemView{c, me} -} - -// TestAddTestPlugin registers the testFunc as part of the plugin command to the -// plugin catalog. If provided, uses tmpDir as the plugin directory. -func TestAddTestPlugin(t testing.T, c *Core, name string, pluginType consts.PluginType, testFunc string, env []string, tempDir string) { - file, err := os.Open(os.Args[0]) - if err != nil { - t.Fatal(err) - } - defer file.Close() - - dirPath := filepath.Dir(os.Args[0]) - fileName := filepath.Base(os.Args[0]) - - if tempDir != "" { - fi, err := file.Stat() - if err != nil { - t.Fatal(err) - } - - // Copy over the file to the temp dir - dst := filepath.Join(tempDir, fileName) - out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode()) - if err != nil { - t.Fatal(err) - } - defer out.Close() - - if _, err = io.Copy(out, file); err != nil { - t.Fatal(err) - } - err = out.Sync() - if err != nil { - t.Fatal(err) - } - - dirPath = tempDir - } - - // Determine plugin directory full path, evaluating potential symlink path - fullPath, err := filepath.EvalSymlinks(dirPath) - if err != nil { - t.Fatal(err) - } - - reader, err := os.Open(filepath.Join(fullPath, fileName)) - if err != nil { - t.Fatal(err) - } - defer reader.Close() - - // Find out the sha256 - hash := sha256.New() - - _, err = io.Copy(hash, reader) - if err != nil { - t.Fatal(err) - } - - sum := hash.Sum(nil) - - // Set core's plugin directory and plugin catalog directory - c.pluginDirectory = fullPath - c.pluginCatalog.directory = fullPath - - args := []string{fmt.Sprintf("--test.run=%s", testFunc)} - err = c.pluginCatalog.Set(context.Background(), name, pluginType, fileName, args, env, sum) - if err != nil { - t.Fatal(err) - } -} - -var testLogicalBackends = map[string]logical.Factory{} -var testCredentialBackends = map[string]logical.Factory{} - -// StartSSHHostTestServer starts the test server which responds to SSH -// authentication. Used to test the SSH secret backend. -func StartSSHHostTestServer() (string, error) { - pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(testSharedPublicKey)) - if err != nil { - return "", fmt.Errorf("error parsing public key") - } - serverConfig := &ssh.ServerConfig{ - PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { - if bytes.Compare(pubKey.Marshal(), key.Marshal()) == 0 { - return &ssh.Permissions{}, nil - } else { - return nil, fmt.Errorf("key does not match") - } - }, - } - signer, err := ssh.ParsePrivateKey([]byte(testSharedPrivateKey)) - if err != nil { - panic("Error parsing private key") - } - serverConfig.AddHostKey(signer) - - soc, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", fmt.Errorf("error listening to connection") - } - - go func() { - for { - conn, err := soc.Accept() - if err != nil { - panic(fmt.Sprintf("Error accepting incoming connection: %s", err)) - } - defer conn.Close() - sshConn, chanReqs, _, err := ssh.NewServerConn(conn, serverConfig) - if err != nil { - panic(fmt.Sprintf("Handshaking error: %v", err)) - } - - go func() { - for chanReq := range chanReqs { - go func(chanReq ssh.NewChannel) { - if chanReq.ChannelType() != "session" { - chanReq.Reject(ssh.UnknownChannelType, "unknown channel type") - return - } - - ch, requests, err := chanReq.Accept() - if err != nil { - panic(fmt.Sprintf("Error accepting channel: %s", err)) - } - - go func(ch ssh.Channel, in <-chan *ssh.Request) { - for req := range in { - executeServerCommand(ch, req) - } - }(ch, requests) - }(chanReq) - } - sshConn.Close() - }() - } - }() - return soc.Addr().String(), nil -} - -// This executes the commands requested to be run on the server. -// Used to test the SSH secret backend. -func executeServerCommand(ch ssh.Channel, req *ssh.Request) { - command := string(req.Payload[4:]) - cmd := exec.Command("/bin/bash", []string{"-c", command}...) - req.Reply(true, nil) - - cmd.Stdout = ch - cmd.Stderr = ch - cmd.Stdin = ch - - err := cmd.Start() - if err != nil { - panic(fmt.Sprintf("Error starting the command: '%s'", err)) - } - - go func() { - _, err := cmd.Process.Wait() - if err != nil { - panic(fmt.Sprintf("Error while waiting for command to finish:'%s'", err)) - } - ch.Close() - }() -} - -// This adds a credential backend for the test core. This needs to be -// invoked before the test core is created. -func AddTestCredentialBackend(name string, factory logical.Factory) error { - if name == "" { - return fmt.Errorf("missing backend name") - } - if factory == nil { - return fmt.Errorf("missing backend factory function") - } - testCredentialBackends[name] = factory - return nil -} - -// This adds a logical backend for the test core. This needs to be -// invoked before the test core is created. -func AddTestLogicalBackend(name string, factory logical.Factory) error { - if name == "" { - return fmt.Errorf("missing backend name") - } - if factory == nil { - return fmt.Errorf("missing backend factory function") - } - testLogicalBackends[name] = factory - return nil -} - -type noopAudit struct { - Config *audit.BackendConfig - salt *salt.Salt - saltMutex sync.RWMutex -} - -func (n *noopAudit) GetHash(ctx context.Context, data string) (string, error) { - salt, err := n.Salt(ctx) - if err != nil { - return "", err - } - return salt.GetIdentifiedHMAC(data), nil -} - -func (n *noopAudit) LogRequest(_ context.Context, _ *audit.LogInput) error { - return nil -} - -func (n *noopAudit) LogResponse(_ context.Context, _ *audit.LogInput) error { - return nil -} - -func (n *noopAudit) Reload(_ context.Context) error { - return nil -} - -func (n *noopAudit) Invalidate(_ context.Context) { - n.saltMutex.Lock() - defer n.saltMutex.Unlock() - n.salt = nil -} - -func (n *noopAudit) Salt(ctx context.Context) (*salt.Salt, error) { - n.saltMutex.RLock() - if n.salt != nil { - defer n.saltMutex.RUnlock() - return n.salt, nil - } - n.saltMutex.RUnlock() - n.saltMutex.Lock() - defer n.saltMutex.Unlock() - if n.salt != nil { - return n.salt, nil - } - salt, err := salt.NewSalt(ctx, n.Config.SaltView, n.Config.SaltConfig) - if err != nil { - return nil, err - } - n.salt = salt - return salt, nil -} - -type rawHTTP struct{} - -func (n *rawHTTP) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - return &logical.Response{ - Data: map[string]interface{}{ - logical.HTTPStatusCode: 200, - logical.HTTPContentType: "plain/text", - logical.HTTPRawBody: []byte("hello world"), - }, - }, nil -} - -func (n *rawHTTP) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - return false, false, nil -} - -func (n *rawHTTP) SpecialPaths() *logical.Paths { - return &logical.Paths{Unauthenticated: []string{"*"}} -} - -func (n *rawHTTP) System() logical.SystemView { - return logical.StaticSystemView{ - DefaultLeaseTTLVal: time.Hour * 24, - MaxLeaseTTLVal: time.Hour * 24 * 32, - } -} - -func (n *rawHTTP) Logger() log.Logger { - return logging.NewVaultLogger(log.Trace) -} - -func (n *rawHTTP) Cleanup(ctx context.Context) { - // noop -} - -func (n *rawHTTP) Initialize(ctx context.Context) error { - // noop - return nil -} - -func (n *rawHTTP) InvalidateKey(context.Context, string) { - // noop -} - -func (n *rawHTTP) Setup(ctx context.Context, config *logical.BackendConfig) error { - // noop - return nil -} - -func (n *rawHTTP) Type() logical.BackendType { - return logical.TypeLogical -} - -func GenerateRandBytes(length int) ([]byte, error) { - if length < 0 { - return nil, fmt.Errorf("length must be >= 0") - } - - buf := make([]byte, length) - if length == 0 { - return buf, nil - } - - n, err := rand.Read(buf) - if err != nil { - return nil, err - } - if n != length { - return nil, fmt.Errorf("unable to read %d bytes; only read %d", length, n) - } - - return buf, nil -} - -func TestWaitActive(t testing.T, core *Core) { - t.Helper() - if err := TestWaitActiveWithError(core); err != nil { - t.Fatal(err) - } -} - -func TestWaitActiveWithError(core *Core) error { - start := time.Now() - var standby bool - var err error - for time.Now().Sub(start) < time.Second { - standby, err = core.Standby() - if err != nil { - return err - } - if !standby { - break - } - } - if standby { - return errors.New("should not be in standby mode") - } - return nil -} - -type TestCluster struct { - BarrierKeys [][]byte - RecoveryKeys [][]byte - CACert *x509.Certificate - CACertBytes []byte - CACertPEM []byte - CACertPEMFile string - CAKey *ecdsa.PrivateKey - CAKeyPEM []byte - Cores []*TestClusterCore - ID string - RootToken string - RootCAs *x509.CertPool - TempDir string -} - -func (c *TestCluster) Start() { - for _, core := range c.Cores { - if core.Server != nil { - for _, ln := range core.Listeners { - go core.Server.Serve(ln) - } - } - } -} - -// UnsealCores uses the cluster barrier keys to unseal the test cluster cores -func (c *TestCluster) UnsealCores(t testing.T) { - if err := c.UnsealCoresWithError(); err != nil { - t.Fatal(err) - } -} - -func (c *TestCluster) UnsealCoresWithError() error { - numCores := len(c.Cores) - - // Unseal first core - for _, key := range c.BarrierKeys { - if _, err := c.Cores[0].Unseal(TestKeyCopy(key)); err != nil { - return fmt.Errorf("unseal err: %s", err) - } - } - - // Verify unsealed - if c.Cores[0].Sealed() { - return fmt.Errorf("should not be sealed") - } - - if err := TestWaitActiveWithError(c.Cores[0].Core); err != nil { - return err - } - - // Unseal other cores - for i := 1; i < numCores; i++ { - for _, key := range c.BarrierKeys { - if _, err := c.Cores[i].Core.Unseal(TestKeyCopy(key)); err != nil { - return fmt.Errorf("unseal err: %s", err) - } - } - } - - // Let them come fully up to standby - time.Sleep(2 * time.Second) - - // Ensure cluster connection info is populated. - // Other cores should not come up as leaders. - for i := 1; i < numCores; i++ { - isLeader, _, _, err := c.Cores[i].Leader() - if err != nil { - return err - } - if isLeader { - return fmt.Errorf("core[%d] should not be leader", i) - } - } - - return nil -} - -func (c *TestCluster) EnsureCoresSealed(t testing.T) { - t.Helper() - if err := c.ensureCoresSealed(); err != nil { - t.Fatal(err) - } -} - -func CleanupClusters(clusters []*TestCluster) { - wg := &sync.WaitGroup{} - for _, cluster := range clusters { - wg.Add(1) - lc := cluster - go func() { - defer wg.Done() - lc.Cleanup() - }() - } - wg.Wait() -} - -func (c *TestCluster) Cleanup() { - // Close listeners - wg := &sync.WaitGroup{} - for _, core := range c.Cores { - wg.Add(1) - lc := core - - go func() { - defer wg.Done() - if lc.Listeners != nil { - for _, ln := range lc.Listeners { - ln.Close() - } - } - if lc.licensingStopCh != nil { - close(lc.licensingStopCh) - lc.licensingStopCh = nil - } - - if err := lc.Shutdown(); err != nil { - lc.Logger().Error("error during shutdown; abandoning sealing", "error", err) - } else { - timeout := time.Now().Add(60 * time.Second) - for { - if time.Now().After(timeout) { - lc.Logger().Error("timeout waiting for core to seal") - } - if lc.Sealed() { - break - } - time.Sleep(250 * time.Millisecond) - } - } - }() - } - - wg.Wait() - - // Remove any temp dir that exists - if c.TempDir != "" { - os.RemoveAll(c.TempDir) - } - - // Give time to actually shut down/clean up before the next test - time.Sleep(time.Second) -} - -func (c *TestCluster) ensureCoresSealed() error { - for _, core := range c.Cores { - if err := core.Shutdown(); err != nil { - return err - } - timeout := time.Now().Add(60 * time.Second) - for { - if time.Now().After(timeout) { - return fmt.Errorf("timeout waiting for core to seal") - } - if core.Sealed() { - break - } - time.Sleep(250 * time.Millisecond) - } - } - return nil -} - -// UnsealWithStoredKeys uses stored keys to unseal the test cluster cores -func (c *TestCluster) UnsealWithStoredKeys(t testing.T) error { - for _, core := range c.Cores { - if err := core.UnsealWithStoredKeys(context.Background()); err != nil { - return err - } - timeout := time.Now().Add(60 * time.Second) - for { - if time.Now().After(timeout) { - return fmt.Errorf("timeout waiting for core to unseal") - } - if !core.Sealed() { - break - } - time.Sleep(250 * time.Millisecond) - } - } - return nil -} - -func SetReplicationFailureMode(core *TestClusterCore, mode uint32) { - atomic.StoreUint32(core.Core.replicationFailure, mode) -} - -type TestListener struct { - net.Listener - Address *net.TCPAddr -} - -type TestClusterCore struct { - *Core - CoreConfig *CoreConfig - Client *api.Client - Handler http.Handler - Listeners []*TestListener - ReloadFuncs *map[string][]reload.ReloadFunc - ReloadFuncsLock *sync.RWMutex - Server *http.Server - ServerCert *x509.Certificate - ServerCertBytes []byte - ServerCertPEM []byte - ServerKey *ecdsa.PrivateKey - ServerKeyPEM []byte - TLSConfig *tls.Config - UnderlyingStorage physical.Backend -} - -type TestClusterOptions struct { - KeepStandbysSealed bool - SkipInit bool - HandlerFunc func(*HandlerProperties) http.Handler - BaseListenAddress string - NumCores int - SealFunc func() Seal - Logger log.Logger - TempDir string - CACert []byte - CAKey *ecdsa.PrivateKey -} - -var DefaultNumCores = 3 - -type certInfo struct { - cert *x509.Certificate - certPEM []byte - certBytes []byte - key *ecdsa.PrivateKey - keyPEM []byte -} - -// NewTestCluster creates a new test cluster based on the provided core config -// and test cluster options. -// -// N.B. Even though a single base CoreConfig is provided, NewTestCluster will instantiate a -// core config for each core it creates. If separate seal per core is desired, opts.SealFunc -// can be provided to generate a seal for each one. Otherwise, the provided base.Seal will be -// shared among cores. NewCore's default behavior is to generate a new DefaultSeal if the -// provided Seal in coreConfig (i.e. base.Seal) is nil. -func NewTestCluster(t testing.T, base *CoreConfig, opts *TestClusterOptions) *TestCluster { - var err error - - var numCores int - if opts == nil || opts.NumCores == 0 { - numCores = DefaultNumCores - } else { - numCores = opts.NumCores - } - - certIPs := []net.IP{ - net.IPv6loopback, - net.ParseIP("127.0.0.1"), - } - var baseAddr *net.TCPAddr - if opts != nil && opts.BaseListenAddress != "" { - baseAddr, err = net.ResolveTCPAddr("tcp", opts.BaseListenAddress) - if err != nil { - t.Fatal("could not parse given base IP") - } - certIPs = append(certIPs, baseAddr.IP) - } - - var testCluster TestCluster - if opts != nil && opts.TempDir != "" { - if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) { - if err := os.MkdirAll(opts.TempDir, 0700); err != nil { - t.Fatal(err) - } - } - testCluster.TempDir = opts.TempDir - } else { - tempDir, err := ioutil.TempDir("", "vault-test-cluster-") - if err != nil { - t.Fatal(err) - } - testCluster.TempDir = tempDir - } - - var caKey *ecdsa.PrivateKey - if opts != nil && opts.CAKey != nil { - caKey = opts.CAKey - } else { - caKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - } - testCluster.CAKey = caKey - var caBytes []byte - if opts != nil && len(opts.CACert) > 0 { - caBytes = opts.CACert - } else { - caCertTemplate := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: "localhost", - }, - DNSNames: []string{"localhost"}, - IPAddresses: certIPs, - KeyUsage: x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign), - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - BasicConstraintsValid: true, - IsCA: true, - } - caBytes, err = x509.CreateCertificate(rand.Reader, caCertTemplate, caCertTemplate, caKey.Public(), caKey) - if err != nil { - t.Fatal(err) - } - } - caCert, err := x509.ParseCertificate(caBytes) - if err != nil { - t.Fatal(err) - } - testCluster.CACert = caCert - testCluster.CACertBytes = caBytes - testCluster.RootCAs = x509.NewCertPool() - testCluster.RootCAs.AddCert(caCert) - caCertPEMBlock := &pem.Block{ - Type: "CERTIFICATE", - Bytes: caBytes, - } - testCluster.CACertPEM = pem.EncodeToMemory(caCertPEMBlock) - testCluster.CACertPEMFile = filepath.Join(testCluster.TempDir, "ca_cert.pem") - err = ioutil.WriteFile(testCluster.CACertPEMFile, testCluster.CACertPEM, 0755) - if err != nil { - t.Fatal(err) - } - marshaledCAKey, err := x509.MarshalECPrivateKey(caKey) - if err != nil { - t.Fatal(err) - } - caKeyPEMBlock := &pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: marshaledCAKey, - } - testCluster.CAKeyPEM = pem.EncodeToMemory(caKeyPEMBlock) - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "ca_key.pem"), testCluster.CAKeyPEM, 0755) - if err != nil { - t.Fatal(err) - } - - var certInfoSlice []*certInfo - - // - // Certs generation - // - for i := 0; i < numCores; i++ { - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - certTemplate := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: "localhost", - }, - DNSNames: []string{"localhost"}, - IPAddresses: certIPs, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageServerAuth, - x509.ExtKeyUsageClientAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement, - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - } - certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, caCert, key.Public(), caKey) - if err != nil { - t.Fatal(err) - } - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - t.Fatal(err) - } - certPEMBlock := &pem.Block{ - Type: "CERTIFICATE", - Bytes: certBytes, - } - certPEM := pem.EncodeToMemory(certPEMBlock) - marshaledKey, err := x509.MarshalECPrivateKey(key) - if err != nil { - t.Fatal(err) - } - keyPEMBlock := &pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: marshaledKey, - } - keyPEM := pem.EncodeToMemory(keyPEMBlock) - - certInfoSlice = append(certInfoSlice, &certInfo{ - cert: cert, - certPEM: certPEM, - certBytes: certBytes, - key: key, - keyPEM: keyPEM, - }) - } - - // - // Listener setup - // - logger := logging.NewVaultLogger(log.Trace) - ports := make([]int, numCores) - if baseAddr != nil { - for i := 0; i < numCores; i++ { - ports[i] = baseAddr.Port + i - } - } else { - baseAddr = &net.TCPAddr{ - IP: net.ParseIP("127.0.0.1"), - Port: 0, - } - } - - listeners := [][]*TestListener{} - servers := []*http.Server{} - handlers := []http.Handler{} - tlsConfigs := []*tls.Config{} - certGetters := []*reload.CertificateGetter{} - for i := 0; i < numCores; i++ { - baseAddr.Port = ports[i] - ln, err := net.ListenTCP("tcp", baseAddr) - if err != nil { - t.Fatal(err) - } - certFile := filepath.Join(testCluster.TempDir, fmt.Sprintf("node%d_port_%d_cert.pem", i+1, ln.Addr().(*net.TCPAddr).Port)) - keyFile := filepath.Join(testCluster.TempDir, fmt.Sprintf("node%d_port_%d_key.pem", i+1, ln.Addr().(*net.TCPAddr).Port)) - err = ioutil.WriteFile(certFile, certInfoSlice[i].certPEM, 0755) - if err != nil { - t.Fatal(err) - } - err = ioutil.WriteFile(keyFile, certInfoSlice[i].keyPEM, 0755) - if err != nil { - t.Fatal(err) - } - tlsCert, err := tls.X509KeyPair(certInfoSlice[i].certPEM, certInfoSlice[i].keyPEM) - if err != nil { - t.Fatal(err) - } - certGetter := reload.NewCertificateGetter(certFile, keyFile, "") - certGetters = append(certGetters, certGetter) - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{tlsCert}, - RootCAs: testCluster.RootCAs, - ClientCAs: testCluster.RootCAs, - ClientAuth: tls.RequestClientCert, - NextProtos: []string{"h2", "http/1.1"}, - GetCertificate: certGetter.GetCertificate, - } - tlsConfig.BuildNameToCertificate() - tlsConfigs = append(tlsConfigs, tlsConfig) - lns := []*TestListener{&TestListener{ - Listener: tls.NewListener(ln, tlsConfig), - Address: ln.Addr().(*net.TCPAddr), - }, - } - listeners = append(listeners, lns) - var handler http.Handler = http.NewServeMux() - handlers = append(handlers, handler) - server := &http.Server{ - Handler: handler, - ErrorLog: logger.StandardLogger(nil), - } - servers = append(servers, server) - } - - // Create three cores with the same physical and different redirect/cluster - // addrs. - // N.B.: On OSX, instead of random ports, it assigns new ports to new - // listeners sequentially. Aside from being a bad idea in a security sense, - // it also broke tests that assumed it was OK to just use the port above - // the redirect addr. This has now been changed to 105 ports above, but if - // we ever do more than three nodes in a cluster it may need to be bumped. - // Note: it's 105 so that we don't conflict with a running Consul by - // default. - coreConfig := &CoreConfig{ - LogicalBackends: make(map[string]logical.Factory), - CredentialBackends: make(map[string]logical.Factory), - AuditBackends: make(map[string]audit.Factory), - RedirectAddr: fmt.Sprintf("https://127.0.0.1:%d", listeners[0][0].Address.Port), - ClusterAddr: fmt.Sprintf("https://127.0.0.1:%d", listeners[0][0].Address.Port+105), - DisableMlock: true, - EnableUI: true, - EnableRaw: true, - BuiltinRegistry: NewMockBuiltinRegistry(), - } - - if base != nil { - coreConfig.DisableCache = base.DisableCache - coreConfig.EnableUI = base.EnableUI - coreConfig.DefaultLeaseTTL = base.DefaultLeaseTTL - coreConfig.MaxLeaseTTL = base.MaxLeaseTTL - coreConfig.CacheSize = base.CacheSize - coreConfig.PluginDirectory = base.PluginDirectory - coreConfig.Seal = base.Seal - coreConfig.DevToken = base.DevToken - coreConfig.EnableRaw = base.EnableRaw - coreConfig.DisableSealWrap = base.DisableSealWrap - coreConfig.DevLicenseDuration = base.DevLicenseDuration - coreConfig.DisableCache = base.DisableCache - if base.BuiltinRegistry != nil { - coreConfig.BuiltinRegistry = base.BuiltinRegistry - } - - if !coreConfig.DisableMlock { - base.DisableMlock = false - } - - if base.Physical != nil { - coreConfig.Physical = base.Physical - } - - if base.HAPhysical != nil { - coreConfig.HAPhysical = base.HAPhysical - } - - // Used to set something non-working to test fallback - switch base.ClusterAddr { - case "empty": - coreConfig.ClusterAddr = "" - case "": - default: - coreConfig.ClusterAddr = base.ClusterAddr - } - - if base.LogicalBackends != nil { - for k, v := range base.LogicalBackends { - coreConfig.LogicalBackends[k] = v - } - } - if base.CredentialBackends != nil { - for k, v := range base.CredentialBackends { - coreConfig.CredentialBackends[k] = v - } - } - if base.AuditBackends != nil { - for k, v := range base.AuditBackends { - coreConfig.AuditBackends[k] = v - } - } - if base.Logger != nil { - coreConfig.Logger = base.Logger - } - - coreConfig.ClusterCipherSuites = base.ClusterCipherSuites - - coreConfig.DisableCache = base.DisableCache - - coreConfig.DevToken = base.DevToken - } - - if coreConfig.Physical == nil { - coreConfig.Physical, err = physInmem.NewInmem(nil, logger) - if err != nil { - t.Fatal(err) - } - } - if coreConfig.HAPhysical == nil { - haPhys, err := physInmem.NewInmemHA(nil, logger) - if err != nil { - t.Fatal(err) - } - coreConfig.HAPhysical = haPhys.(physical.HABackend) - } - - pubKey, priKey, err := testGenerateCoreKeys() - if err != nil { - t.Fatalf("err: %v", err) - } - - cores := []*Core{} - coreConfigs := []*CoreConfig{} - for i := 0; i < numCores; i++ { - localConfig := *coreConfig - localConfig.RedirectAddr = fmt.Sprintf("https://127.0.0.1:%d", listeners[i][0].Address.Port) - if localConfig.ClusterAddr != "" { - localConfig.ClusterAddr = fmt.Sprintf("https://127.0.0.1:%d", listeners[i][0].Address.Port+105) - } - - // if opts.SealFunc is provided, use that to generate a seal for the config instead - if opts != nil && opts.SealFunc != nil { - localConfig.Seal = opts.SealFunc() - } - - if opts != nil && opts.Logger != nil { - localConfig.Logger = opts.Logger.Named(fmt.Sprintf("core%d", i)) - } - - localConfig.LicensingConfig = testGetLicensingConfig(pubKey) - - c, err := NewCore(&localConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - cores = append(cores, c) - coreConfigs = append(coreConfigs, &localConfig) - if opts != nil && opts.HandlerFunc != nil { - handlers[i] = opts.HandlerFunc(&HandlerProperties{ - Core: c, - MaxRequestDuration: DefaultMaxRequestDuration, - }) - servers[i].Handler = handlers[i] - } - - // Set this in case the Seal was manually set before the core was - // created - if localConfig.Seal != nil { - localConfig.Seal.SetCore(c) - } - } - - // - // Clustering setup - // - clusterAddrGen := func(lns []*TestListener) []*net.TCPAddr { - ret := make([]*net.TCPAddr, len(lns)) - for i, ln := range lns { - ret[i] = &net.TCPAddr{ - IP: ln.Address.IP, - Port: ln.Address.Port + 105, - } - } - return ret - } - - for i := 0; i < numCores; i++ { - if coreConfigs[i].ClusterAddr != "" { - cores[i].SetClusterListenerAddrs(clusterAddrGen(listeners[i])) - cores[i].SetClusterHandler(handlers[i]) - } - } - - if opts == nil || !opts.SkipInit { - bKeys, rKeys, root := TestCoreInitClusterWrapperSetup(t, cores[0], clusterAddrGen(listeners[0]), handlers[0]) - barrierKeys, _ := copystructure.Copy(bKeys) - testCluster.BarrierKeys = barrierKeys.([][]byte) - recoveryKeys, _ := copystructure.Copy(rKeys) - testCluster.RecoveryKeys = recoveryKeys.([][]byte) - testCluster.RootToken = root - - // Write root token and barrier keys - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "root_token"), []byte(root), 0755) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - for i, key := range testCluster.BarrierKeys { - buf.Write([]byte(base64.StdEncoding.EncodeToString(key))) - if i < len(testCluster.BarrierKeys)-1 { - buf.WriteRune('\n') - } - } - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "barrier_keys"), buf.Bytes(), 0755) - if err != nil { - t.Fatal(err) - } - for i, key := range testCluster.RecoveryKeys { - buf.Write([]byte(base64.StdEncoding.EncodeToString(key))) - if i < len(testCluster.RecoveryKeys)-1 { - buf.WriteRune('\n') - } - } - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "recovery_keys"), buf.Bytes(), 0755) - if err != nil { - t.Fatal(err) - } - - // Unseal first core - for _, key := range bKeys { - if _, err := cores[0].Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - ctx := context.Background() - - // If stored keys is supported, the above will no no-op, so trigger auto-unseal - // using stored keys to try to unseal - if err := cores[0].UnsealWithStoredKeys(ctx); err != nil { - t.Fatal(err) - } - - // Verify unsealed - if cores[0].Sealed() { - t.Fatal("should not be sealed") - } - - TestWaitActive(t, cores[0]) - - // Unseal other cores unless otherwise specified - if (opts == nil || !opts.KeepStandbysSealed) && numCores > 1 { - for i := 1; i < numCores; i++ { - for _, key := range bKeys { - if _, err := cores[i].Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - // If stored keys is supported, the above will no no-op, so trigger auto-unseal - // using stored keys - if err := cores[i].UnsealWithStoredKeys(ctx); err != nil { - t.Fatal(err) - } - } - - // Let them come fully up to standby - time.Sleep(2 * time.Second) - - // Ensure cluster connection info is populated. - // Other cores should not come up as leaders. - for i := 1; i < numCores; i++ { - isLeader, _, _, err := cores[i].Leader() - if err != nil { - t.Fatal(err) - } - if isLeader { - t.Fatalf("core[%d] should not be leader", i) - } - } - } - - // - // Set test cluster core(s) and test cluster - // - cluster, err := cores[0].Cluster(context.Background()) - if err != nil { - t.Fatal(err) - } - testCluster.ID = cluster.ID - } - - getAPIClient := func(port int, tlsConfig *tls.Config) *api.Client { - transport := cleanhttp.DefaultPooledTransport() - transport.TLSClientConfig = tlsConfig.Clone() - if err := http2.ConfigureTransport(transport); err != nil { - t.Fatal(err) - } - client := &http.Client{ - Transport: transport, - CheckRedirect: func(*http.Request, []*http.Request) error { - // This can of course be overridden per-test by using its own client - return fmt.Errorf("redirects not allowed in these tests") - }, - } - config := api.DefaultConfig() - if config.Error != nil { - t.Fatal(config.Error) - } - config.Address = fmt.Sprintf("https://127.0.0.1:%d", port) - config.HttpClient = client - config.MaxRetries = 0 - apiClient, err := api.NewClient(config) - if err != nil { - t.Fatal(err) - } - if opts == nil || !opts.SkipInit { - apiClient.SetToken(testCluster.RootToken) - } - return apiClient - } - - var ret []*TestClusterCore - for i := 0; i < numCores; i++ { - tcc := &TestClusterCore{ - Core: cores[i], - CoreConfig: coreConfigs[i], - ServerKey: certInfoSlice[i].key, - ServerKeyPEM: certInfoSlice[i].keyPEM, - ServerCert: certInfoSlice[i].cert, - ServerCertBytes: certInfoSlice[i].certBytes, - ServerCertPEM: certInfoSlice[i].certPEM, - Listeners: listeners[i], - Handler: handlers[i], - Server: servers[i], - TLSConfig: tlsConfigs[i], - Client: getAPIClient(listeners[i][0].Address.Port, tlsConfigs[i]), - } - tcc.ReloadFuncs = &cores[i].reloadFuncs - tcc.ReloadFuncsLock = &cores[i].reloadFuncsLock - tcc.ReloadFuncsLock.Lock() - (*tcc.ReloadFuncs)["listener|tcp"] = []reload.ReloadFunc{certGetters[i].Reload} - tcc.ReloadFuncsLock.Unlock() - - testAdjustTestCore(base, tcc) - - ret = append(ret, tcc) - } - - testCluster.Cores = ret - - testExtraClusterCoresTestSetup(t, priKey, testCluster.Cores) - - return &testCluster -} - -func NewMockBuiltinRegistry() *mockBuiltinRegistry { - return &mockBuiltinRegistry{ - forTesting: map[string]consts.PluginType{ - "mysql-database-plugin": consts.PluginTypeDatabase, - "postgresql-database-plugin": consts.PluginTypeDatabase, - }, - } -} - -type mockBuiltinRegistry struct { - forTesting map[string]consts.PluginType -} - -func (m *mockBuiltinRegistry) Get(name string, pluginType consts.PluginType) (func() (interface{}, error), bool) { - testPluginType, ok := m.forTesting[name] - if !ok { - return nil, false - } - if pluginType != testPluginType { - return nil, false - } - if name == "postgresql-database-plugin" { - return dbPostgres.New, true - } - return dbMysql.New(dbMysql.MetadataLen, dbMysql.MetadataLen, dbMysql.UsernameLen), true -} - -// Keys only supports getting a realistic list of the keys for database plugins. -func (m *mockBuiltinRegistry) Keys(pluginType consts.PluginType) []string { - if pluginType != consts.PluginTypeDatabase { - return []string{} - } - /* - This is a hard-coded reproduction of the db plugin keys in helper/builtinplugins/registry.go. - The registry isn't directly used because it causes import cycles. - */ - return []string{ - "mysql-database-plugin", - "mysql-aurora-database-plugin", - "mysql-rds-database-plugin", - "mysql-legacy-database-plugin", - "postgresql-database-plugin", - "mssql-database-plugin", - "cassandra-database-plugin", - "mongodb-database-plugin", - "hana-database-plugin", - } -} - -func (m *mockBuiltinRegistry) Contains(name string, pluginType consts.PluginType) bool { - return false -} diff --git a/vendor/github.com/hashicorp/vault/vault/testing_util.go b/vendor/github.com/hashicorp/vault/vault/testing_util.go deleted file mode 100644 index 3aff71e1..00000000 --- a/vendor/github.com/hashicorp/vault/vault/testing_util.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !enterprise - -package vault - -import "github.com/mitchellh/go-testing-interface" - -func testGenerateCoreKeys() (interface{}, interface{}, error) { return nil, nil, nil } -func testGetLicensingConfig(interface{}) *LicensingConfig { return &LicensingConfig{} } -func testAdjustTestCore(*CoreConfig, *TestClusterCore) {} -func testExtraClusterCoresTestSetup(testing.T, interface{}, []*TestClusterCore) {} diff --git a/vendor/github.com/hashicorp/vault/vault/token_store.go b/vendor/github.com/hashicorp/vault/vault/token_store.go deleted file mode 100644 index 3acebe66..00000000 --- a/vendor/github.com/hashicorp/vault/vault/token_store.go +++ /dev/null @@ -1,3166 +0,0 @@ -package vault - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "sync" - "sync/atomic" - - "regexp" - "strings" - "time" - - proto "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - sockaddr "github.com/hashicorp/go-sockaddr" - - "github.com/armon/go-metrics" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/base62" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/hashicorp/vault/logical/plugin/pb" - "github.com/mitchellh/mapstructure" -) - -const ( - // idPrefix is the prefix used to store tokens for their - // primary ID based index - idPrefix = "id/" - - // accessorPrefix is the prefix used to store the index from - // Accessor to Token ID - accessorPrefix = "accessor/" - - // parentPrefix is the prefix used to store tokens for their - // secondar parent based index - parentPrefix = "parent/" - - // tokenSubPath is the sub-path used for the token store - // view. This is nested under the system view. - tokenSubPath = "token/" - - // rolesPrefix is the prefix used to store role information - rolesPrefix = "roles/" - - // tokenRevocationPending indicates that the token should not be used - // again. If this is encountered during an existing request flow, it means - // that the token is but is currently fulfilling its final use; after this - // request it will not be able to be looked up as being valid. - tokenRevocationPending = -1 -) - -var ( - // TokenLength is the size of tokens we are currently generating, without - // any namespace information - TokenLength = 24 - - // displayNameSanitize is used to sanitize a display name given to a token. - displayNameSanitize = regexp.MustCompile("[^a-zA-Z0-9-]") - - // pathSuffixSanitize is used to ensure a path suffix in a role is valid. - pathSuffixSanitize = regexp.MustCompile("\\w[\\w-.]+\\w") - - destroyCubbyhole = func(ctx context.Context, ts *TokenStore, te *logical.TokenEntry) error { - if ts.cubbyholeBackend == nil { - // Should only ever happen in testing - return nil - } - - if te == nil { - return errors.New("nil token entry") - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, ts.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - switch tokenNS.ID { - case namespace.RootNamespaceID: - saltedID, err := ts.SaltID(ctx, te.ID) - if err != nil { - return err - } - return ts.cubbyholeBackend.revoke(ctx, salt.SaltID(ts.cubbyholeBackend.saltUUID, saltedID, salt.SHA1Hash)) - - default: - if te.CubbyholeID == "" { - return fmt.Errorf("missing cubbyhole ID while destroying") - } - return ts.cubbyholeBackend.revoke(ctx, te.CubbyholeID) - } - } -) - -func (ts *TokenStore) paths() []*framework.Path { - return []*framework.Path{ - { - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: ts.tokenStoreRoleList, - }, - - HelpSynopsis: tokenListRolesHelp, - HelpDescription: tokenListRolesHelp, - }, - - { - Pattern: "accessors/$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: ts.tokenStoreAccessorList, - }, - - HelpSynopsis: tokenListAccessorsHelp, - HelpDescription: tokenListAccessorsHelp, - }, - - { - Pattern: "roles/" + framework.GenericNameRegex("role_name"), - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "allowed_policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: tokenAllowedPoliciesHelp, - }, - - "disallowed_policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: tokenDisallowedPoliciesHelp, - }, - - "orphan": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: tokenOrphanHelp, - }, - - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: tokenPeriodHelp, - }, - - "path_suffix": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: tokenPathSuffixHelp + pathSuffixSanitize.String(), - }, - - "explicit_max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: tokenExplicitMaxTTLHelp, - }, - - "renewable": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: tokenRenewableHelp, - }, - - "bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or JSON list of CIDR blocks. If set, specifies the blocks of IP addresses which are allowed to use the generated token.`, - }, - - "token_type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "service", - Description: "The type of token to generate, service or batch", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: ts.tokenStoreRoleRead, - logical.CreateOperation: ts.tokenStoreRoleCreateUpdate, - logical.UpdateOperation: ts.tokenStoreRoleCreateUpdate, - logical.DeleteOperation: ts.tokenStoreRoleDelete, - }, - - ExistenceCheck: ts.tokenStoreRoleExistenceCheck, - }, - - { - Pattern: "create-orphan$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleCreateOrphan, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateOrphanHelp), - HelpDescription: strings.TrimSpace(tokenCreateOrphanHelp), - }, - - { - Pattern: "create/" + framework.GenericNameRegex("role_name"), - - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleCreateAgainstRole, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateRoleHelp), - HelpDescription: strings.TrimSpace(tokenCreateRoleHelp), - }, - - { - Pattern: "create$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleCreate, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateHelp), - HelpDescription: strings.TrimSpace(tokenCreateHelp), - }, - - { - Pattern: "lookup", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to lookup (POST request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: ts.handleLookup, - logical.UpdateOperation: ts.handleLookup, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupHelp), - HelpDescription: strings.TrimSpace(tokenLookupHelp), - }, - - { - Pattern: "lookup-accessor", - - Fields: map[string]*framework.FieldSchema{ - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token to look up (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleUpdateLookupAccessor, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupAccessorHelp), - HelpDescription: strings.TrimSpace(tokenLookupAccessorHelp), - }, - - { - Pattern: "lookup-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to look up (unused, does not need to be set)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleLookupSelf, - logical.ReadOperation: ts.handleLookupSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupHelp), - HelpDescription: strings.TrimSpace(tokenLookupHelp), - }, - - { - Pattern: "revoke-accessor", - - Fields: map[string]*framework.FieldSchema{ - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleUpdateRevokeAccessor, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeAccessorHelp), - HelpDescription: strings.TrimSpace(tokenRevokeAccessorHelp), - }, - - { - Pattern: "revoke-self$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleRevokeSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeSelfHelp), - HelpDescription: strings.TrimSpace(tokenRevokeSelfHelp), - }, - - { - Pattern: "revoke", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to revoke (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleRevokeTree, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeHelp), - HelpDescription: strings.TrimSpace(tokenRevokeHelp), - }, - - { - Pattern: "revoke-orphan", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to revoke (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleRevokeOrphan, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeOrphanHelp), - HelpDescription: strings.TrimSpace(tokenRevokeOrphanHelp), - }, - - { - Pattern: "renew-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to renew (unused, does not need to be set)", - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The desired increment in seconds to the token expiration", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleRenewSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenRenewSelfHelp), - HelpDescription: strings.TrimSpace(tokenRenewSelfHelp), - }, - - { - Pattern: "renew", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to renew (request body)", - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The desired increment in seconds to the token expiration", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleRenew, - }, - - HelpSynopsis: strings.TrimSpace(tokenRenewHelp), - HelpDescription: strings.TrimSpace(tokenRenewHelp), - }, - - { - Pattern: "tidy$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: ts.handleTidy, - }, - - HelpSynopsis: strings.TrimSpace(tokenTidyHelp), - HelpDescription: strings.TrimSpace(tokenTidyDesc), - }, - } -} - -// LookupToken returns the properties of the token from the token store. This -// is particularly useful to fetch the accessor of the client token and get it -// populated in the logical request along with the client token. The accessor -// of the client token can get audit logged. -func (c *Core) LookupToken(ctx context.Context, token string) (*logical.TokenEntry, error) { - if c.Sealed() { - return nil, consts.ErrSealed - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - - if c.standby && !c.perfStandby { - return nil, consts.ErrStandby - } - - // Many tests don't have a token store running - if c.tokenStore == nil || c.tokenStore.expiration == nil { - return nil, nil - } - - return c.tokenStore.Lookup(ctx, token) -} - -// TokenStore is used to manage client tokens. Tokens are used for -// clients to authenticate, and each token is mapped to an applicable -// set of policy which is used for authorization. -type TokenStore struct { - *framework.Backend - - activeContext context.Context - - core *Core - - batchTokenEncryptor BarrierEncryptor - - baseBarrierView *BarrierView - idBarrierView *BarrierView - accessorBarrierView *BarrierView - parentBarrierView *BarrierView - rolesBarrierView *BarrierView - - expiration *ExpirationManager - - cubbyholeBackend *CubbyholeBackend - - tokenLocks []*locksutil.LockEntry - - // tokenPendingDeletion stores tokens that are being revoked. If the token is - // not in the map, it means that there's no deletion in progress. If the value - // is true it means deletion is in progress, and if false it means deletion - // failed. Revocation needs to handle these states accordingly. - tokensPendingDeletion *sync.Map - - cubbyholeDestroyer func(context.Context, *TokenStore, *logical.TokenEntry) error - - logger log.Logger - - saltLock sync.RWMutex - salts map[string]*salt.Salt - - tidyLock *uint32 - - identityPoliciesDeriverFunc func(string) (*identity.Entity, []string, error) - - quitContext context.Context -} - -// NewTokenStore is used to construct a token store that is -// backed by the given barrier view. -func NewTokenStore(ctx context.Context, logger log.Logger, core *Core, config *logical.BackendConfig) (*TokenStore, error) { - // Create a sub-view - view := core.systemBarrierView.SubView(tokenSubPath) - - // Initialize the store - t := &TokenStore{ - activeContext: ctx, - core: core, - batchTokenEncryptor: core.barrier, - baseBarrierView: view, - idBarrierView: view.SubView(idPrefix), - accessorBarrierView: view.SubView(accessorPrefix), - parentBarrierView: view.SubView(parentPrefix), - rolesBarrierView: view.SubView(rolesPrefix), - cubbyholeDestroyer: destroyCubbyhole, - logger: logger, - tokenLocks: locksutil.CreateLocks(), - tokensPendingDeletion: &sync.Map{}, - saltLock: sync.RWMutex{}, - tidyLock: new(uint32), - quitContext: core.activeContext, - salts: make(map[string]*salt.Salt), - } - - // Setup the framework endpoints - t.Backend = &framework.Backend{ - AuthRenew: t.authRenew, - - PathsSpecial: &logical.Paths{ - Root: []string{ - "revoke-orphan/*", - "accessors*", - }, - - // Most token store items are local since tokens are local, but a - // notable exception is roles - LocalStorage: []string{ - idPrefix, - accessorPrefix, - parentPrefix, - salt.DefaultLocation, - }, - }, - BackendType: logical.TypeCredential, - } - - t.Backend.Paths = append(t.Backend.Paths, t.paths()...) - - t.Backend.Setup(ctx, config) - - return t, nil -} - -func (ts *TokenStore) Invalidate(ctx context.Context, key string) { - //ts.logger.Debug("invalidating key", "key", key) - - switch key { - case tokenSubPath + salt.DefaultLocation: - ts.saltLock.Lock() - ts.salts = make(map[string]*salt.Salt) - ts.saltLock.Unlock() - } -} - -func (ts *TokenStore) Salt(ctx context.Context) (*salt.Salt, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - ts.saltLock.RLock() - if salt, ok := ts.salts[ns.ID]; ok { - defer ts.saltLock.RUnlock() - return salt, nil - } - ts.saltLock.RUnlock() - ts.saltLock.Lock() - defer ts.saltLock.Unlock() - if salt, ok := ts.salts[ns.ID]; ok { - return salt, nil - } - - salt, err := salt.NewSalt(ctx, ts.baseView(ns), &salt.Config{ - HashFunc: salt.SHA1Hash, - Location: salt.DefaultLocation, - }) - if err != nil { - return nil, err - } - ts.salts[ns.ID] = salt - return salt, nil -} - -// tsRoleEntry contains token store role information -type tsRoleEntry struct { - // The name of the role. Embedded so it can be used for pathing - Name string `json:"name" mapstructure:"name" structs:"name"` - - // The policies that creation functions using this role can assign to a token, - // escaping or further locking down normal subset checking - AllowedPolicies []string `json:"allowed_policies" mapstructure:"allowed_policies" structs:"allowed_policies"` - - // List of policies to be not allowed during token creation using this role - DisallowedPolicies []string `json:"disallowed_policies" mapstructure:"disallowed_policies" structs:"disallowed_policies"` - - // If true, tokens created using this role will be orphans - Orphan bool `json:"orphan" mapstructure:"orphan" structs:"orphan"` - - // If non-zero, tokens created using this role will be able to be renewed - // forever, but will have a fixed renewal period of this value - Period time.Duration `json:"period" mapstructure:"period" structs:"period"` - - // If set, a suffix will be set on the token path, making it easier to - // revoke using 'revoke-prefix' - PathSuffix string `json:"path_suffix" mapstructure:"path_suffix" structs:"path_suffix"` - - // If set, controls whether created tokens are marked as being renewable - Renewable bool `json:"renewable" mapstructure:"renewable" structs:"renewable"` - - // If set, the token entry will have an explicit maximum TTL set, rather - // than deferring to role/mount values - ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl"` - - // The set of CIDRs that tokens generated using this role will be bound to - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` - - // The type of token this role should issue - TokenType logical.TokenType `json:"token_type" mapstructure:"token_type"` -} - -type accessorEntry struct { - TokenID string `json:"token_id"` - AccessorID string `json:"accessor_id"` - NamespaceID string `json:"namespace_id"` -} - -// SetExpirationManager is used to provide the token store with -// an expiration manager. This is used to manage prefix based revocation -// of tokens and to tidy entries when removed from the token store. -func (ts *TokenStore) SetExpirationManager(exp *ExpirationManager) { - ts.expiration = exp -} - -// SaltID is used to apply a salt and hash to an ID to make sure its not reversible -func (ts *TokenStore) SaltID(ctx context.Context, id string) (string, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return "", namespace.ErrNoNamespace - } - - s, err := ts.Salt(ctx) - if err != nil { - return "", err - } - - // For tokens of older format and belonging to the root namespace, use SHA1 - // hash for salting. - if ns.ID == namespace.RootNamespaceID && !strings.Contains(id, ".") { - return s.SaltID(id), nil - } - - // For all other tokens, use SHA2-256 HMAC for salting. This includes - // tokens of older format, but belonging to a namespace other than the root - // namespace. - return "h" + s.GetHMAC(id), nil -} - -// rootToken is used to generate a new token with root privileges and no parent -func (ts *TokenStore) rootToken(ctx context.Context) (*logical.TokenEntry, error) { - ctx = namespace.ContextWithNamespace(ctx, namespace.RootNamespace) - te := &logical.TokenEntry{ - Policies: []string{"root"}, - Path: "auth/token/root", - DisplayName: "root", - CreationTime: time.Now().Unix(), - NamespaceID: namespace.RootNamespaceID, - Type: logical.TokenTypeService, - } - if err := ts.create(ctx, te); err != nil { - return nil, err - } - return te, nil -} - -func (ts *TokenStore) tokenStoreAccessorList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - nsID := ns.ID - - entries, err := ts.accessorView(ns).List(ctx, "") - if err != nil { - return nil, err - } - - resp := &logical.Response{} - - ret := make([]string, 0, len(entries)) - for _, entry := range entries { - aEntry, err := ts.lookupByAccessor(ctx, entry, true, false) - if err != nil { - resp.AddWarning("Found an accessor entry that could not be successfully decoded") - continue - } - - if aEntry.TokenID == "" { - resp.AddWarning(fmt.Sprintf("Found an accessor entry missing a token: %v", aEntry.AccessorID)) - continue - } - - if aEntry.NamespaceID == nsID { - ret = append(ret, aEntry.AccessorID) - } - } - - resp.Data = map[string]interface{}{ - "keys": ret, - } - return resp, nil -} - -// createAccessor is used to create an identifier for the token ID. -// A storage index, mapping the accessor to the token ID is also created. -func (ts *TokenStore) createAccessor(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "createAccessor"}, time.Now()) - - var err error - // Create a random accessor - entry.Accessor, err = base62.Random(TokenLength, true) - if err != nil { - return err - } - - tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - if tokenNS.ID != namespace.RootNamespaceID { - entry.Accessor = fmt.Sprintf("%s.%s", entry.Accessor, tokenNS.ID) - } - - // Create index entry, mapping the accessor to the token ID - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltID, err := ts.SaltID(saltCtx, entry.Accessor) - if err != nil { - return err - } - - aEntry := &accessorEntry{ - TokenID: entry.ID, - AccessorID: entry.Accessor, - NamespaceID: entry.NamespaceID, - } - - aEntryBytes, err := jsonutil.EncodeJSON(aEntry) - if err != nil { - return errwrap.Wrapf("failed to marshal accessor index entry: {{err}}", err) - } - - le := &logical.StorageEntry{Key: saltID, Value: aEntryBytes} - if err := ts.accessorView(tokenNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) - } - return nil -} - -// Create is used to create a new token entry. The entry is assigned -// a newly generated ID if not provided. -func (ts *TokenStore) create(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "create"}, time.Now()) - - tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - entry.Policies = policyutil.SanitizePolicies(entry.Policies, policyutil.DoNotAddDefaultPolicy) - - switch entry.Type { - case logical.TokenTypeDefault, logical.TokenTypeService: - // In case it was default, force to service - entry.Type = logical.TokenTypeService - - // Generate an ID if necessary - userSelectedID := true - if entry.ID == "" { - userSelectedID = false - var err error - entry.ID, err = base62.Random(TokenLength, true) - if err != nil { - return err - } - } - - if userSelectedID && strings.HasPrefix(entry.ID, "s.") { - return fmt.Errorf("custom token ID cannot have the 's.' prefix") - } - - if !userSelectedID { - entry.ID = fmt.Sprintf("s.%s", entry.ID) - } - - // Attach namespace ID for tokens that are not belonging to the root - // namespace - if tokenNS.ID != namespace.RootNamespaceID { - entry.ID = fmt.Sprintf("%s.%s", entry.ID, tokenNS.ID) - } - - if tokenNS.ID != namespace.RootNamespaceID || strings.HasPrefix(entry.ID, "s.") { - if entry.CubbyholeID == "" { - cubbyholeID, err := base62.Random(TokenLength, true) - if err != nil { - return err - } - entry.CubbyholeID = cubbyholeID - } - } - - // If the user didn't specifically pick the ID, e.g. because they were - // sudo/root, check for collision; otherwise trust the process - if userSelectedID { - exist, _ := ts.lookupInternal(ctx, entry.ID, false, true) - if exist != nil { - return fmt.Errorf("cannot create a token with a duplicate ID") - } - } - - err = ts.createAccessor(ctx, entry) - if err != nil { - return err - } - - return ts.storeCommon(ctx, entry, true) - - case logical.TokenTypeBatch: - // Ensure fields we don't support/care about are nilled, proto marshal, - // encrypt, skip persistence - entry.ID = "" - pEntry := &pb.TokenEntry{ - Parent: entry.Parent, - Policies: entry.Policies, - Path: entry.Path, - Meta: entry.Meta, - DisplayName: entry.DisplayName, - CreationTime: entry.CreationTime, - TTL: int64(entry.TTL), - Role: entry.Role, - EntityID: entry.EntityID, - NamespaceID: entry.NamespaceID, - Type: uint32(entry.Type), - } - - boundCIDRs := make([]string, len(entry.BoundCIDRs)) - for i, cidr := range entry.BoundCIDRs { - boundCIDRs[i] = cidr.String() - } - pEntry.BoundCIDRs = boundCIDRs - - mEntry, err := proto.Marshal(pEntry) - if err != nil { - return err - } - - eEntry, err := ts.batchTokenEncryptor.Encrypt(ctx, "", mEntry) - if err != nil { - return err - } - - bEntry := base64.RawURLEncoding.EncodeToString(eEntry) - entry.ID = fmt.Sprintf("b.%s", bEntry) - - if tokenNS.ID != namespace.RootNamespaceID { - entry.ID = fmt.Sprintf("%s.%s", entry.ID, tokenNS.ID) - } - - return nil - - default: - return fmt.Errorf("cannot create a token of type %d", entry.Type) - } -} - -// Store is used to store an updated token entry without writing the -// secondary index. -func (ts *TokenStore) store(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "store"}, time.Now()) - return ts.storeCommon(ctx, entry, false) -} - -// storeCommon handles the actual storage of an entry, possibly generating -// secondary indexes -func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry, writeSecondary bool) error { - tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - saltCtx := namespace.ContextWithNamespace(ctx, tokenNS) - saltedID, err := ts.SaltID(saltCtx, entry.ID) - if err != nil { - return err - } - - // Marshal the entry - enc, err := json.Marshal(entry) - if err != nil { - return errwrap.Wrapf("failed to encode entry: {{err}}", err) - } - - if writeSecondary { - // Write the secondary index if necessary. This is done before the - // primary index because we'd rather have a dangling pointer with - // a missing primary instead of missing the parent index and potentially - // escaping the revocation chain. - if entry.Parent != "" { - // Ensure the parent exists - parent, err := ts.Lookup(ctx, entry.Parent) - if err != nil { - return errwrap.Wrapf("failed to lookup parent: {{err}}", err) - } - if parent == nil { - return fmt.Errorf("parent token not found") - } - - parentNS, err := NamespaceByID(ctx, parent.NamespaceID, ts.core) - if err != nil { - return err - } - if parentNS == nil { - return namespace.ErrNoNamespace - } - - parentCtx := namespace.ContextWithNamespace(ctx, parentNS) - - // Create the index entry - parentSaltedID, err := ts.SaltID(parentCtx, entry.Parent) - if err != nil { - return err - } - - path := parentSaltedID + "/" + saltedID - if tokenNS.ID != namespace.RootNamespaceID { - path = fmt.Sprintf("%s.%s", path, tokenNS.ID) - } - - le := &logical.StorageEntry{Key: path} - if err := ts.parentView(parentNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) - } - } - } - - // Write the primary ID - le := &logical.StorageEntry{Key: saltedID, Value: enc} - if len(entry.Policies) == 1 && entry.Policies[0] == "root" { - le.SealWrap = true - } - if err := ts.idView(tokenNS).Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) - } - return nil -} - -// UseToken is used to manage restricted use tokens and decrement their -// available uses. Returns two values: a potentially updated entry or, if the -// token has been revoked, nil; and whether an error was encountered. The -// locking here isn't perfect, as other parts of the code may update an entry, -// but usually none after the entry is already created...so this is pretty -// good. -func (ts *TokenStore) UseToken(ctx context.Context, te *logical.TokenEntry) (*logical.TokenEntry, error) { - if te == nil { - return nil, fmt.Errorf("invalid token entry provided for use count decrementing") - } - - // This case won't be hit with a token with restricted uses because we go - // from 1 to -1. So it's a nice optimization to check this without a read - // lock. - if te.NumUses == 0 { - return te, nil - } - - // If we are attempting to unwrap a control group request, don't use the token. - // It will be manually revoked by the handler. - if len(te.Policies) == 1 && te.Policies[0] == controlGroupPolicyName { - return te, nil - } - - lock := locksutil.LockForKey(ts.tokenLocks, te.ID) - lock.Lock() - defer lock.Unlock() - - var err error - te, err = ts.lookupInternal(ctx, te.ID, false, false) - if err != nil { - return nil, errwrap.Wrapf("failed to refresh entry: {{err}}", err) - } - // If it can't be found we shouldn't be trying to use it, so if we get nil - // back, it is because it has been revoked in the interim or will be - // revoked (NumUses is -1) - if te == nil { - return nil, fmt.Errorf("token not found or fully used already") - } - - // Decrement the count. If this is our last use count, we need to indicate - // that this is no longer valid, but revocation is deferred to the end of - // the call, so this will make sure that any Lookup that happens doesn't - // return an entry. This essentially acts as a write-ahead lock and is - // especially useful since revocation can end up (via the expiration - // manager revoking children) attempting to acquire the same lock - // repeatedly. - if te.NumUses == 1 { - te.NumUses = tokenRevocationPending - } else { - te.NumUses-- - } - - err = ts.store(ctx, te) - if err != nil { - return nil, err - } - - return te, nil -} - -func (ts *TokenStore) UseTokenByID(ctx context.Context, id string) (*logical.TokenEntry, error) { - te, err := ts.Lookup(ctx, id) - if err != nil { - return te, err - } - - return ts.UseToken(ctx, te) -} - -// Lookup is used to find a token given its ID. It acquires a read lock, then calls lookupInternal. -func (ts *TokenStore) Lookup(ctx context.Context, id string) (*logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"token", "lookup"}, time.Now()) - if id == "" { - return nil, fmt.Errorf("cannot lookup blank token") - } - - // If it starts with "b." it's a batch token - if len(id) > 2 && strings.HasPrefix(id, "b.") { - return ts.lookupBatchToken(ctx, id) - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - return ts.lookupInternal(ctx, id, false, false) -} - -// lookupTainted is used to find a token that may or may not be tainted given -// its ID. It acquires a read lock, then calls lookupInternal. -func (ts *TokenStore) lookupTainted(ctx context.Context, id string) (*logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"token", "lookup"}, time.Now()) - if id == "" { - return nil, fmt.Errorf("cannot lookup blank token") - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - return ts.lookupInternal(ctx, id, false, true) -} - -func (ts *TokenStore) lookupBatchToken(ctx context.Context, id string) (*logical.TokenEntry, error) { - // Strip the b. from the front and namespace ID from the back - bEntry, _ := namespace.SplitIDFromString(id[2:]) - - eEntry, err := base64.RawURLEncoding.DecodeString(bEntry) - if err != nil { - return nil, err - } - - mEntry, err := ts.batchTokenEncryptor.Decrypt(ctx, "", eEntry) - if err != nil { - return nil, nil - } - - pEntry := new(pb.TokenEntry) - if err := proto.Unmarshal(mEntry, pEntry); err != nil { - return nil, err - } - - te, err := pb.ProtoTokenEntryToLogicalTokenEntry(pEntry) - if err != nil { - return nil, err - } - - if time.Now().After(time.Unix(te.CreationTime, 0).Add(te.TTL)) { - return nil, nil - } - - if te.Parent != "" { - pte, err := ts.Lookup(ctx, te.Parent) - if err != nil { - return nil, err - } - if pte == nil { - return nil, nil - } - } - - te.ID = id - return te, nil -} - -// lookupInternal is used to find a token given its (possibly salted) ID. If -// tainted is true, entries that are in some revocation state (currently, -// indicated by num uses < 0), the entry will be returned anyways -func (ts *TokenStore) lookupInternal(ctx context.Context, id string, salted, tainted bool) (*logical.TokenEntry, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, errwrap.Wrapf("failed to find namespace in context: {{err}}", err) - } - - // If it starts with "b." it's a batch token - if len(id) > 2 && strings.HasPrefix(id, "b.") { - return ts.lookupBatchToken(ctx, id) - } - - var raw *logical.StorageEntry - lookupID := id - - if !salted { - // If possible, always use the token's namespace. If it doesn't match - // the request namespace, ensure the request namespace is a child - _, nsID := namespace.SplitIDFromString(id) - if nsID != "" { - tokenNS, err := NamespaceByID(ctx, nsID, ts.core) - if err != nil { - return nil, errwrap.Wrapf("failed to look up namespace from the token: {{err}}", err) - } - if tokenNS != nil { - if tokenNS.ID != ns.ID { - ns = tokenNS - ctx = namespace.ContextWithNamespace(ctx, tokenNS) - } - } - } else { - // Any non-root-ns token should have an accessor and child - // namespaces cannot have custom IDs. If someone omits or tampers - // with it, the lookup in the root namespace simply won't work. - ns = namespace.RootNamespace - ctx = namespace.ContextWithNamespace(ctx, ns) - } - - lookupID, err = ts.SaltID(ctx, id) - if err != nil { - return nil, err - } - } - - raw, err = ts.idView(ns).Get(ctx, lookupID) - if err != nil { - return nil, errwrap.Wrapf("failed to read entry: {{err}}", err) - } - - // Bail if not found - if raw == nil { - return nil, nil - } - - // Unmarshal the token - entry := new(logical.TokenEntry) - if err := jsonutil.DecodeJSON(raw.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode entry: {{err}}", err) - } - - // This is a token that is awaiting deferred revocation or tainted - if entry.NumUses < 0 && !tainted { - return nil, nil - } - - if entry.NamespaceID == "" { - entry.NamespaceID = namespace.RootNamespaceID - } - - // This will be the upgrade case - if entry.Type == logical.TokenTypeDefault { - entry.Type = logical.TokenTypeService - } - - persistNeeded := false - - // Upgrade the deprecated fields - if entry.DisplayNameDeprecated != "" { - if entry.DisplayName == "" { - entry.DisplayName = entry.DisplayNameDeprecated - } - entry.DisplayNameDeprecated = "" - persistNeeded = true - } - - if entry.CreationTimeDeprecated != 0 { - if entry.CreationTime == 0 { - entry.CreationTime = entry.CreationTimeDeprecated - } - entry.CreationTimeDeprecated = 0 - persistNeeded = true - } - - if entry.ExplicitMaxTTLDeprecated != 0 { - if entry.ExplicitMaxTTL == 0 { - entry.ExplicitMaxTTL = entry.ExplicitMaxTTLDeprecated - } - entry.ExplicitMaxTTLDeprecated = 0 - persistNeeded = true - } - - if entry.NumUsesDeprecated != 0 { - if entry.NumUses == 0 || entry.NumUsesDeprecated < entry.NumUses { - entry.NumUses = entry.NumUsesDeprecated - } - entry.NumUsesDeprecated = 0 - persistNeeded = true - } - - // It's a root token with unlimited creation TTL (so never had an - // expiration); this may or may not have a lease (based on when it was - // generated, for later revocation purposes) but it doesn't matter, it's - // allowed. Fast-path this. - if len(entry.Policies) == 1 && entry.Policies[0] == "root" && entry.TTL == 0 { - // If fields are getting upgraded, store the changes - if persistNeeded { - if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) - } - } - return entry, nil - } - - // Perform these checks on upgraded fields, but before persisting - - // If we are still restoring the expiration manager, we want to ensure the - // token is not expired - if ts.expiration == nil { - return nil, errors.New("expiration manager is nil on tokenstore") - } - le, err := ts.expiration.FetchLeaseTimesByToken(ctx, entry) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch lease times: {{err}}", err) - } - - var ret *logical.TokenEntry - - switch { - // It's any kind of expiring token with no lease, immediately delete it - case le == nil: - tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - revokeCtx := namespace.ContextWithNamespace(ts.quitContext, tokenNS) - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(revokeCtx, entry) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(revokeCtx, leaseID) - if err != nil { - return nil, err - } - - // Only return if we're not past lease expiration (or if tainted is true), - // otherwise assume expmgr is working on revocation - default: - if !le.ExpireTime.Before(time.Now()) || tainted { - ret = entry - } - } - - // If fields are getting upgraded, store the changes - if persistNeeded { - if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) - } - } - - return ret, nil -} - -// Revoke is used to invalidate a given token, any child tokens -// will be orphaned. -func (ts *TokenStore) revokeOrphan(ctx context.Context, id string) error { - defer metrics.MeasureSince([]string{"token", "revoke"}, time.Now()) - if id == "" { - return fmt.Errorf("cannot revoke blank token") - } - - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return err - } - - return ts.revokeInternal(ctx, saltedID, false) -} - -// revokeInternal is used to invalidate a given salted token, any child tokens -// will be orphaned unless otherwise specified. skipOrphan should be used -// whenever we are revoking the entire tree starting from a particular parent -// (e.g. revokeTreeInternal). -func (ts *TokenStore) revokeInternal(ctx context.Context, saltedID string, skipOrphan bool) (ret error) { - // Check and set the token deletion state. We only proceed with the deletion - // if we don't have a pending deletion (empty), or if the deletion previously - // failed (state is false) - state, loaded := ts.tokensPendingDeletion.LoadOrStore(saltedID, true) - - // If the entry was loaded and its state is true, we short-circuit - if loaded && state == true { - return nil - } - - // The map check above should protect use from any concurrent revocations, so - // we do another lookup here to make sure we have the right state - entry, err := ts.lookupInternal(ctx, saltedID, true, true) - if err != nil { - return err - } - if entry == nil { - return nil - } - - if entry.NumUses != tokenRevocationPending { - entry.NumUses = tokenRevocationPending - if err := ts.store(ctx, entry); err != nil { - // The only real reason for this is an underlying storage error - // which also means that nothing else in this func or expmgr will - // really work either. So we clear revocation state so the user can - // try again. - ts.logger.Error("failed to mark token as revoked") - ts.tokensPendingDeletion.Store(entry.ID, false) - return err - } - } - - tokenNS, err := NamespaceByID(ctx, entry.NamespaceID, ts.core) - if err != nil { - return err - } - if tokenNS == nil { - return namespace.ErrNoNamespace - } - - defer func() { - // If we succeeded in all other revocation operations after this defer and - // before we return, we can remove the token store entry - if ret == nil { - if err := ts.idView(tokenNS).Delete(ctx, saltedID); err != nil { - ret = errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - // Check on ret again and update the sync.Map accordingly - if ret != nil { - // If we failed on any of the calls within, we store the state as false - // so that the next call to revokeInternal will retry - ts.tokensPendingDeletion.Store(saltedID, false) - } else { - ts.tokensPendingDeletion.Delete(saltedID) - } - }() - - // Destroy the token's cubby. This should go first as it's a - // security-sensitive item. - err = ts.cubbyholeDestroyer(ctx, ts, entry) - if err != nil { - return err - } - - revokeCtx := namespace.ContextWithNamespace(ts.quitContext, tokenNS) - if err := ts.expiration.RevokeByToken(revokeCtx, entry); err != nil { - return err - } - - // Clear the secondary index if any - if entry.Parent != "" { - _, parentNSID := namespace.SplitIDFromString(entry.Parent) - parentCtx := revokeCtx - parentNS := tokenNS - - if parentNSID != tokenNS.ID { - switch { - case parentNSID == "": - parentNS = namespace.RootNamespace - default: - parentNS, err = NamespaceByID(ctx, parentNSID, ts.core) - if err != nil { - return errwrap.Wrapf("failed to get parent namespace: {{err}}", err) - } - if parentNS == nil { - return namespace.ErrNoNamespace - } - } - - parentCtx = namespace.ContextWithNamespace(ctx, parentNS) - } - - parentSaltedID, err := ts.SaltID(parentCtx, entry.Parent) - if err != nil { - return err - } - - path := parentSaltedID + "/" + saltedID - if tokenNS.ID != namespace.RootNamespaceID { - path = fmt.Sprintf("%s.%s", path, tokenNS.ID) - } - - if err = ts.parentView(parentNS).Delete(ctx, path); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - // Clear the accessor index if any - if entry.Accessor != "" { - accessorSaltedID, err := ts.SaltID(revokeCtx, entry.Accessor) - if err != nil { - return err - } - - if err = ts.accessorView(tokenNS).Delete(ctx, accessorSaltedID); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - if !skipOrphan { - // Mark all children token as orphan by removing - // their parent index, and clear the parent entry. - // - // Marking the token as orphan should be skipped if it's called by - // revokeTreeInternal to avoid unnecessary view.List operations. Since - // the deletion occurs in a DFS fashion we don't need to perform a delete - // on child prefixes as there will be none (as saltedID entry is a leaf node). - children, err := ts.parentView(tokenNS).List(ctx, saltedID+"/") - if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) - } - for _, child := range children { - var childNSID string - childCtx := revokeCtx - child, childNSID = namespace.SplitIDFromString(child) - if childNSID != "" { - childNS, err := NamespaceByID(ctx, childNSID, ts.core) - if err != nil { - return errwrap.Wrapf("failed to get child token: {{err}}", err) - } - if childNS == nil { - return namespace.ErrNoNamespace - } - - childCtx = namespace.ContextWithNamespace(ctx, childNS) - } - - entry, err := ts.lookupInternal(childCtx, child, true, true) - if err != nil { - return errwrap.Wrapf("failed to get child token: {{err}}", err) - } - if entry == nil { - // Seems it's already revoked, so nothing to do here except delete the index - err = ts.parentView(tokenNS).Delete(ctx, child) - if err != nil { - return errwrap.Wrapf("failed to delete child entry: {{err}}", err) - } - continue - } - - lock := locksutil.LockForKey(ts.tokenLocks, entry.ID) - lock.Lock() - - entry.Parent = "" - err = ts.store(childCtx, entry) - if err != nil { - lock.Unlock() - return errwrap.Wrapf("failed to update child token: {{err}}", err) - } - lock.Unlock() - - // Delete the the child storage entry after we update the token entry Since - // paths are not deeply nested (i.e. they are simply - // parenPrefix//), we can simply call view.Delete instead - // of logical.ClearView - err = ts.parentView(tokenNS).Delete(ctx, child) - if err != nil { - return errwrap.Wrapf("failed to delete child entry: {{err}}", err) - } - } - } - - return nil -} - -// revokeTree is used to invalidate a given token and all -// child tokens. -func (ts *TokenStore) revokeTree(ctx context.Context, le *leaseEntry) error { - defer metrics.MeasureSince([]string{"token", "revoke-tree"}, time.Now()) - // Verify the token is not blank - if le.ClientToken == "" { - return fmt.Errorf("cannot tree-revoke blank token") - } - - // In case lookup fails for some reason for the token itself, set the - // context for the next call from the lease entry's NS. This function is - // only called when a lease for a given token is expiring, so it should run - // in the context of the token namespace - revCtx := namespace.ContextWithNamespace(ctx, le.namespace) - - saltedID, err := ts.SaltID(revCtx, le.ClientToken) - if err != nil { - return err - } - - // Nuke the entire tree recursively - return ts.revokeTreeInternal(revCtx, saltedID) -} - -// revokeTreeInternal is used to invalidate a given token and all -// child tokens. -// Updated to be non-recursive and revoke child tokens -// before parent tokens(DFS). -func (ts *TokenStore) revokeTreeInternal(ctx context.Context, id string) error { - dfs := []string{id} - seenIDs := make(map[string]struct{}) - - var ns *namespace.Namespace - - te, err := ts.lookupInternal(ctx, id, true, true) - if err != nil { - return err - } - if te == nil { - ns, err = namespace.FromContext(ctx) - if err != nil { - return err - } - } else { - ns, err = NamespaceByID(ctx, te.NamespaceID, ts.core) - if err != nil { - return err - } - } - if ns == nil { - return fmt.Errorf("failed to find namespace for token revocation") - } - - for l := len(dfs); l > 0; l = len(dfs) { - id := dfs[len(dfs)-1] - seenIDs[id] = struct{}{} - - saltedCtx := ctx - saltedNS := ns - saltedID, saltedNSID := namespace.SplitIDFromString(id) - if saltedNSID != "" { - saltedNS, err = NamespaceByID(ctx, saltedNSID, ts.core) - if err != nil { - return errwrap.Wrapf("failed to find namespace for token revocation: {{err}}", err) - } - - saltedCtx = namespace.ContextWithNamespace(ctx, saltedNS) - } - - path := saltedID + "/" - childrenRaw, err := ts.parentView(saltedNS).List(saltedCtx, path) - if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) - } - - // Filter the child list to remove any items that have ever been in the dfs stack. - // This is a robustness check, as a parent/child cycle can lead to an OOM crash. - children := make([]string, 0, len(childrenRaw)) - for _, child := range childrenRaw { - if _, seen := seenIDs[child]; !seen { - children = append(children, child) - } else { - if err = ts.parentView(saltedNS).Delete(saltedCtx, path+child); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - - ts.Logger().Warn("token cycle found", "token", child) - } - } - - // If the length of the children array is zero, - // then we are at a leaf node. - if len(children) == 0 { - // Whenever revokeInternal is called, the token will be removed immediately and - // any underlying secrets will be handed off to the expiration manager which will - // take care of expiring them. If Vault is restarted, any revoked tokens - // would have been deleted, and any pending leases for deletion will be restored - // by the expiration manager. - if err := ts.revokeInternal(saltedCtx, saltedID, true); err != nil { - return errwrap.Wrapf("failed to revoke entry: {{err}}", err) - } - // If the length of l is equal to 1, then the last token has been deleted - if l == 1 { - return nil - } - dfs = dfs[:len(dfs)-1] - } else { - // If we make it here, there are children and they must be appended. - dfs = append(dfs, children...) - } - } - - return nil -} - -func (c *Core) IsBatchTokenCreationRequest(ctx context.Context, path string) (bool, error) { - name := strings.TrimPrefix(path, "auth/token/create/") - roleEntry, err := c.tokenStore.tokenStoreRole(ctx, name) - if err != nil { - return false, err - } - return roleEntry.TokenType == logical.TokenTypeBatch, nil -} - -// handleCreateAgainstRole handles the auth/token/create path for a role -func (ts *TokenStore) handleCreateAgainstRole(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("role_name").(string) - roleEntry, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role %s", name)), nil - } - - return ts.handleCreateCommon(ctx, req, d, false, roleEntry) -} - -func (ts *TokenStore) lookupByAccessor(ctx context.Context, id string, salted, tainted bool) (accessorEntry, error) { - var aEntry accessorEntry - - ns, err := namespace.FromContext(ctx) - if err != nil { - return aEntry, err - } - - lookupID := id - if !salted { - _, nsID := namespace.SplitIDFromString(id) - if nsID != "" { - accessorNS, err := NamespaceByID(ctx, nsID, ts.core) - if err != nil { - return aEntry, err - } - if accessorNS != nil { - if accessorNS.ID != ns.ID { - ns = accessorNS - ctx = namespace.ContextWithNamespace(ctx, accessorNS) - } - } - } else { - // Any non-root-ns token should have an accessor and child - // namespaces cannot have custom IDs. If someone omits or tampers - // with it, the lookup in the root namespace simply won't work. - ns = namespace.RootNamespace - ctx = namespace.ContextWithNamespace(ctx, ns) - } - - lookupID, err = ts.SaltID(ctx, id) - if err != nil { - return aEntry, err - } - } - - entry, err := ts.accessorView(ns).Get(ctx, lookupID) - - if err != nil { - return aEntry, errwrap.Wrapf("failed to read index using accessor: {{err}}", err) - } - if entry == nil { - return aEntry, &logical.StatusBadRequest{Err: "invalid accessor"} - } - - err = jsonutil.DecodeJSON(entry.Value, &aEntry) - // If we hit an error, assume it's a pre-struct straight token ID - if err != nil { - te, err := ts.lookupInternal(ctx, string(entry.Value), false, tainted) - if err != nil { - return accessorEntry{}, errwrap.Wrapf("failed to look up token using accessor index: {{err}}", err) - } - // It's hard to reason about what to do here if te is nil -- it may be - // that the token was revoked async, or that it's an old accessor index - // entry that was somehow not cleared up, or or or. A nonexistent token - // entry on lookup is nil, not an error, so we keep that behavior here - // to be safe...the token ID is simply not filled in. - if te != nil { - aEntry.TokenID = te.ID - aEntry.AccessorID = te.Accessor - aEntry.NamespaceID = te.NamespaceID - } - } - - if aEntry.NamespaceID == "" { - aEntry.NamespaceID = namespace.RootNamespaceID - } - - return aEntry, nil -} - -// handleTidy handles the cleaning up of leaked accessor storage entries and -// cleaning up of leases that are associated to tokens that are expired. -func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if !atomic.CompareAndSwapUint32(ts.tidyLock, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, errwrap.Wrapf("failed get namespace from context: {{err}}", err) - } - - go func() { - defer atomic.StoreUint32(ts.tidyLock, 0) - - logger := ts.logger.Named("tidy") - - var tidyErrors *multierror.Error - - doTidy := func() error { - - ts.logger.Info("beginning tidy operation on tokens") - defer ts.logger.Info("finished tidy operation on tokens") - - quitCtx := namespace.ContextWithNamespace(ts.quitContext, ns) - - // List out all the accessors - saltedAccessorList, err := ts.accessorView(ns).List(quitCtx, "") - if err != nil { - return errwrap.Wrapf("failed to fetch accessor index entries: {{err}}", err) - } - - // First, clean up secondary index entries that are no longer valid - parentList, err := ts.parentView(ns).List(quitCtx, "") - if err != nil { - return errwrap.Wrapf("failed to fetch secondary index entries: {{err}}", err) - } - - var countParentEntries, deletedCountParentEntries, countParentList, deletedCountParentList int64 - - // Scan through the secondary index entries; if there is an entry - // with the token's salt ID at the end, remove it - for _, parent := range parentList { - countParentEntries++ - - // Get the children - children, err := ts.parentView(ns).List(quitCtx, parent) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read secondary index: {{err}}", err)) - continue - } - - // First check if the salt ID of the parent exists, and if not mark this so - // that deletion of children later with this loop below applies to all - // children - originalChildrenCount := int64(len(children)) - exists, _ := ts.lookupInternal(quitCtx, strings.TrimSuffix(parent, "/"), true, true) - if exists == nil { - ts.logger.Debug("deleting invalid parent prefix entry", "index", parentPrefix+parent) - } - - var deletedChildrenCount int64 - for _, child := range children { - countParentList++ - if countParentList%500 == 0 { - ts.logger.Info("checking validity of tokens in secondary index list", "progress", countParentList) - } - - // Look up tainted entries so we can be sure that if this isn't - // found, it doesn't exist. Doing the following without locking - // since appropriate locks cannot be held with salted token IDs. - // Also perform deletion if the parent doesn't exist any more. - te, _ := ts.lookupInternal(quitCtx, child, true, true) - // If the child entry is not nil, but the parent doesn't exist, then turn - // that child token into an orphan token. Theres no deletion in this case. - if te != nil && exists == nil { - lock := locksutil.LockForKey(ts.tokenLocks, te.ID) - lock.Lock() - - te.Parent = "" - err = ts.store(quitCtx, te) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to convert child token into an orphan token: {{err}}", err)) - } - lock.Unlock() - continue - } - // Otherwise, if the entry doesn't exist, or if the parent doesn't exist go - // on with the delete on the secondary index - if te == nil || exists == nil { - index := parent + child - ts.logger.Debug("deleting invalid secondary index", "index", index) - err = ts.parentView(ns).Delete(quitCtx, index) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete secondary index: {{err}}", err)) - continue - } - deletedChildrenCount++ - } - } - // Add current children deleted count to the total count - deletedCountParentList += deletedChildrenCount - // N.B.: We don't call delete on the parent prefix since physical.Backend.Delete - // implementations should be in charge of deleting empty prefixes. - // If we deleted all the children, then add that to our deleted parent entries count. - if originalChildrenCount == deletedChildrenCount { - deletedCountParentEntries++ - } - } - - var countAccessorList, - deletedCountAccessorEmptyToken, - deletedCountAccessorInvalidToken, - deletedCountInvalidTokenInAccessor int64 - - // For each of the accessor, see if the token ID associated with it is - // a valid one. If not, delete the leases associated with that token - // and delete the accessor as well. - for _, saltedAccessor := range saltedAccessorList { - countAccessorList++ - if countAccessorList%500 == 0 { - ts.logger.Info("checking if accessors contain valid tokens", "progress", countAccessorList) - } - - accessorEntry, err := ts.lookupByAccessor(quitCtx, saltedAccessor, true, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read the accessor index: {{err}}", err)) - continue - } - - // A valid accessor storage entry should always have a token ID - // in it. If not, it is an invalid accessor entry and needs to - // be deleted. - if accessorEntry.TokenID == "" { - // If deletion of accessor fails, move on to the next - // item since this is just a best-effort operation - err = ts.accessorView(ns).Delete(quitCtx, saltedAccessor) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete the accessor index: {{err}}", err)) - continue - } - deletedCountAccessorEmptyToken++ - } - - lock := locksutil.LockForKey(ts.tokenLocks, accessorEntry.TokenID) - lock.RLock() - - // Look up tainted variants so we only find entries that truly don't - // exist - te, err := ts.lookupInternal(quitCtx, accessorEntry.TokenID, false, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup tainted ID: {{err}}", err)) - lock.RUnlock() - continue - } - - lock.RUnlock() - - // If token entry is not found assume that the token is not valid any - // more and conclude that accessor, leases, and secondary index entries - // for this token should not exist as well. - if te == nil { - ts.logger.Info("deleting token with nil entry referenced by accessor", "salted_accessor", saltedAccessor) - - // RevokeByToken expects a '*logical.TokenEntry'. For the - // purposes of tidying, it is sufficient if the token - // entry only has ID set. - tokenEntry := &logical.TokenEntry{ - ID: accessorEntry.TokenID, - NamespaceID: accessorEntry.NamespaceID, - } - - // Attempt to revoke the token. This will also revoke - // the leases associated with the token. - err = ts.expiration.RevokeByToken(quitCtx, tokenEntry) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to revoke leases of expired token: {{err}}", err)) - continue - } - deletedCountInvalidTokenInAccessor++ - - // If deletion of accessor fails, move on to the next item since - // this is just a best-effort operation. We do this last so that on - // next run if something above failed we still have the accessor - // entry to try again. - err = ts.accessorView(ns).Delete(quitCtx, saltedAccessor) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete accessor entry: {{err}}", err)) - continue - } - deletedCountAccessorInvalidToken++ - } - } - - ts.logger.Info("number of entries scanned in parent prefix", "count", countParentEntries) - ts.logger.Info("number of entries deleted in parent prefix", "count", deletedCountParentEntries) - ts.logger.Info("number of tokens scanned in parent index list", "count", countParentList) - ts.logger.Info("number of tokens revoked in parent index list", "count", deletedCountParentList) - ts.logger.Info("number of accessors scanned", "count", countAccessorList) - ts.logger.Info("number of deleted accessors which had empty tokens", "count", deletedCountAccessorEmptyToken) - ts.logger.Info("number of revoked tokens which were invalid but present in accessors", "count", deletedCountInvalidTokenInAccessor) - ts.logger.Info("number of deleted accessors which had invalid tokens", "count", deletedCountAccessorInvalidToken) - - return tidyErrors.ErrorOrNil() - } - - if err := doTidy(); err != nil { - logger.Error("error running tidy", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -// handleUpdateLookupAccessor handles the auth/token/lookup-accessor path for returning -// the properties of the token associated with the accessor -func (ts *TokenStore) handleUpdateLookupAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - accessor := data.Get("accessor").(string) - if accessor == "" { - return nil, &logical.StatusBadRequest{Err: "missing accessor"} - } - - aEntry, err := ts.lookupByAccessor(ctx, accessor, false, false) - if err != nil { - return nil, err - } - - // Prepare the field data required for a lookup call - d := &framework.FieldData{ - Raw: map[string]interface{}{ - "token": aEntry.TokenID, - }, - Schema: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to lookup", - }, - }, - } - resp, err := ts.handleLookup(ctx, req, d) - if err != nil { - return nil, err - } - if resp == nil { - return nil, fmt.Errorf("failed to lookup the token") - } - if resp.IsError() { - return resp, nil - - } - - // Remove the token ID from the response - if resp.Data != nil { - resp.Data["id"] = "" - } - - return resp, nil -} - -// handleUpdateRevokeAccessor handles the auth/token/revoke-accessor path for revoking -// the token associated with the accessor -func (ts *TokenStore) handleUpdateRevokeAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - accessor := data.Get("accessor").(string) - if accessor == "" { - return nil, &logical.StatusBadRequest{Err: "missing accessor"} - } - - aEntry, err := ts.lookupByAccessor(ctx, accessor, false, true) - if err != nil { - return nil, err - } - - te, err := ts.Lookup(ctx, aEntry.TokenID) - if err != nil { - return nil, err - } - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, ts.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - revokeCtx := namespace.ContextWithNamespace(ts.quitContext, tokenNS) - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(revokeCtx, te) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(revokeCtx, leaseID) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleCreate handles the auth/token/create path for creation of new orphan -// tokens -func (ts *TokenStore) handleCreateOrphan(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return ts.handleCreateCommon(ctx, req, d, true, nil) -} - -// handleCreate handles the auth/token/create path for creation of new non-orphan -// tokens -func (ts *TokenStore) handleCreate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return ts.handleCreateCommon(ctx, req, d, false, nil) -} - -// handleCreateCommon handles the auth/token/create path for creation of new tokens -func (ts *TokenStore) handleCreateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, orphan bool, role *tsRoleEntry) (*logical.Response, error) { - // Read the parent policy - parent, err := ts.Lookup(ctx, req.ClientToken) - if err != nil { - return nil, errwrap.Wrapf("parent token lookup failed: {{err}}", err) - } - if parent == nil { - return logical.ErrorResponse("parent token lookup failed: no parent found"), logical.ErrInvalidRequest - } - if parent.Type == logical.TokenTypeBatch { - return logical.ErrorResponse("batch tokens cannot create more tokens"), nil - } - - // A token with a restricted number of uses cannot create a new token - // otherwise it could escape the restriction count. - if parent.NumUses > 0 { - return logical.ErrorResponse("restricted use token cannot generate child tokens"), - logical.ErrInvalidRequest - } - - // Check if the client token has sudo/root privileges for the requested path - isSudo := ts.System().SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken) - - // Read and parse the fields - var data struct { - ID string - Policies []string - Metadata map[string]string `mapstructure:"meta"` - NoParent bool `mapstructure:"no_parent"` - NoDefaultPolicy bool `mapstructure:"no_default_policy"` - Lease string - TTL string - Renewable *bool - ExplicitMaxTTL string `mapstructure:"explicit_max_ttl"` - DisplayName string `mapstructure:"display_name"` - NumUses int `mapstructure:"num_uses"` - Period string - Type string `mapstructure:"type"` - } - if err := mapstructure.WeakDecode(req.Data, &data); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error decoding request: %s", err)), logical.ErrInvalidRequest - } - - // If the context's namespace is different from the parent and this is an - // orphan token creation request, then this is an admin token generation for - // the namespace - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - if ns.ID != parent.NamespaceID { - parentNS, err := NamespaceByID(ctx, parent.NamespaceID, ts.core) - if err != nil { - ts.logger.Error("error looking up parent namespace", "error", err, "parent_namespace", parent.NamespaceID) - return nil, ErrInternalError - } - if parentNS == nil { - ts.logger.Error("could not find information for parent namespace", "parent_namespace", parent.NamespaceID) - return nil, ErrInternalError - } - - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required generate a namespace admin token"), logical.ErrInvalidRequest - } - - if strutil.StrListContains(data.Policies, "root") { - return logical.ErrorResponse("root tokens may not be created from a parent namespace"), logical.ErrInvalidRequest - } - } - - renewable := true - if data.Renewable != nil { - renewable = *data.Renewable - } - - tokenType := logical.TokenTypeService - tokenTypeStr := data.Type - if role != nil { - switch role.TokenType { - case logical.TokenTypeDefault, logical.TokenTypeDefaultService: - // Use the user-given value, but fall back to service - case logical.TokenTypeDefaultBatch: - // Use the user-given value, but fall back to batch - if tokenTypeStr == "" { - tokenTypeStr = logical.TokenTypeBatch.String() - } - case logical.TokenTypeService: - tokenTypeStr = logical.TokenTypeService.String() - case logical.TokenTypeBatch: - tokenTypeStr = logical.TokenTypeBatch.String() - default: - return logical.ErrorResponse(fmt.Sprintf("role being used for token creation contains invalid token type %q", role.TokenType.String())), nil - } - } - switch tokenTypeStr { - case "", "service": - case "batch": - var badReason string - switch { - case data.ExplicitMaxTTL != "": - dur, err := parseutil.ParseDurationSecond(data.ExplicitMaxTTL) - if err != nil { - return logical.ErrorResponse(`"explicit_max_ttl" value could not be parsed`), nil - } - if dur != 0 { - badReason = "explicit_max_ttl" - } - case data.NumUses != 0: - badReason = "num_uses" - case data.Period != "": - dur, err := parseutil.ParseDurationSecond(data.Period) - if err != nil { - return logical.ErrorResponse(`"period" value could not be parsed`), nil - } - if dur != 0 { - badReason = "period" - } - } - if badReason != "" { - return logical.ErrorResponse(fmt.Sprintf("batch tokens cannot have %q set", badReason)), nil - } - tokenType = logical.TokenTypeBatch - renewable = false - default: - return logical.ErrorResponse("invalid 'token_type' value"), logical.ErrInvalidRequest - } - - // Verify the number of uses is positive - if data.NumUses < 0 { - return logical.ErrorResponse("number of uses cannot be negative"), - logical.ErrInvalidRequest - } - - // Setup the token entry - te := logical.TokenEntry{ - Parent: req.ClientToken, - - // The mount point is always the same since we have only one token - // store; using req.MountPoint causes trouble in tests since they don't - // have an official mount - Path: fmt.Sprintf("auth/token/%s", req.Path), - - Meta: data.Metadata, - DisplayName: "token", - NumUses: data.NumUses, - CreationTime: time.Now().Unix(), - NamespaceID: ns.ID, - Type: tokenType, - } - - // If the role is not nil, we add the role name as part of the token's - // path. This makes it much easier to later revoke tokens that were issued - // by a role (using revoke-prefix). Users can further specify a PathSuffix - // in the role; that way they can use something like "v1", "v2" to indicate - // role revisions, and revoke only tokens issued with a previous revision. - if role != nil { - te.Role = role.Name - - // If renewable hasn't been disabled in the call and the role has - // renewability disabled, set renewable false - if renewable && !role.Renewable { - renewable = false - } - - if role.PathSuffix != "" { - te.Path = fmt.Sprintf("%s/%s", te.Path, role.PathSuffix) - } - } - - // Attach the given display name if any - if data.DisplayName != "" { - full := "token-" + data.DisplayName - full = displayNameSanitize.ReplaceAllString(full, "-") - full = strings.TrimSuffix(full, "-") - te.DisplayName = full - } - - // Allow specifying the ID of the token if the client has root or sudo privileges - if data.ID != "" { - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to specify token id"), - logical.ErrInvalidRequest - } - if ns.ID != namespace.RootNamespaceID { - return logical.ErrorResponse("token IDs can only be manually specified in the root namespace"), - logical.ErrInvalidRequest - } - te.ID = data.ID - } - - resp := &logical.Response{} - - var addDefault bool - - // N.B.: The logic here uses various calculations as to whether default - // should be added. In the end we decided that if NoDefaultPolicy is set it - // should be stripped out regardless, *but*, the logic of when it should - // and shouldn't be added is kept because we want to do subset comparisons - // based on adding default when it's correct to do so. - switch { - case role != nil && (len(role.AllowedPolicies) > 0 || len(role.DisallowedPolicies) > 0): - // Holds the final set of policies as they get munged - var finalPolicies []string - - // We don't make use of the global one because roles with allowed or - // disallowed set do their own policy rules - var localAddDefault bool - - // If the request doesn't say not to add "default" and if "default" - // isn't in the disallowed list, add it. This is in line with the idea - // that roles, when allowed/disallowed ar set, allow a subset of - // policies to be set disjoint from the parent token's policies. - if !data.NoDefaultPolicy && !strutil.StrListContains(role.DisallowedPolicies, "default") { - localAddDefault = true - } - - // Start with passed-in policies as a baseline, if they exist - if len(data.Policies) > 0 { - finalPolicies = policyutil.SanitizePolicies(data.Policies, localAddDefault) - } - - var sanitizedRolePolicies []string - - // First check allowed policies; if policies are specified they will be - // checked, otherwise if an allowed set exists that will be the set - // that is used - if len(role.AllowedPolicies) > 0 { - // Note that if "default" is already in allowed, and also in - // disallowed, this will still result in an error later since this - // doesn't strip out default - sanitizedRolePolicies = policyutil.SanitizePolicies(role.AllowedPolicies, localAddDefault) - - if len(finalPolicies) == 0 { - finalPolicies = sanitizedRolePolicies - } else { - if !strutil.StrListSubset(sanitizedRolePolicies, finalPolicies) { - return logical.ErrorResponse(fmt.Sprintf("token policies (%q) must be subset of the role's allowed policies (%q)", finalPolicies, sanitizedRolePolicies)), logical.ErrInvalidRequest - } - } - } else { - // Assign parent policies if none have been requested. As this is a - // role, add default unless explicitly disabled. - if len(finalPolicies) == 0 { - finalPolicies = policyutil.SanitizePolicies(parent.Policies, localAddDefault) - } - } - - if len(role.DisallowedPolicies) > 0 { - // We don't add the default here because we only want to disallow it if it's explicitly set - sanitizedRolePolicies = strutil.RemoveDuplicates(role.DisallowedPolicies, true) - - for _, finalPolicy := range finalPolicies { - if strutil.StrListContains(sanitizedRolePolicies, finalPolicy) { - return logical.ErrorResponse(fmt.Sprintf("token policy %q is disallowed by this role", finalPolicy)), logical.ErrInvalidRequest - } - } - } - - data.Policies = finalPolicies - - // We are creating a token from a parent namespace. We should only use the input - // policies. - case ns.ID != parent.NamespaceID: - addDefault = !data.NoDefaultPolicy - - // No policies specified, inherit parent - case len(data.Policies) == 0: - // Only inherit "default" if the parent already has it, so don't touch addDefault here - data.Policies = policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy) - - // When a role is not in use or does not specify allowed/disallowed, only - // permit policies to be a subset unless the client has root or sudo - // privileges. Default is added in this case if the parent has it, unless - // the client specified for it not to be added. - case !isSudo: - // Sanitize passed-in and parent policies before comparison - sanitizedInputPolicies := policyutil.SanitizePolicies(data.Policies, policyutil.DoNotAddDefaultPolicy) - sanitizedParentPolicies := policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy) - - if !strutil.StrListSubset(sanitizedParentPolicies, sanitizedInputPolicies) { - return logical.ErrorResponse("child policies must be subset of parent"), logical.ErrInvalidRequest - } - - // If the parent has default, and they haven't requested not to get it, - // add it. Note that if they have explicitly put "default" in - // data.Policies it will still be added because NoDefaultPolicy - // controls *automatic* adding. - if !data.NoDefaultPolicy && strutil.StrListContains(parent.Policies, "default") { - addDefault = true - } - - // Add default by default in this case unless requested not to - case isSudo: - addDefault = !data.NoDefaultPolicy - } - - te.Policies = policyutil.SanitizePolicies(data.Policies, addDefault) - - // Yes, this is a little inefficient to do it like this, but meh - if data.NoDefaultPolicy { - te.Policies = strutil.StrListDelete(te.Policies, "default") - } - - // Prevent internal policies from being assigned to tokens - for _, policy := range te.Policies { - if strutil.StrListContains(nonAssignablePolicies, policy) { - return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil - } - } - - if strutil.StrListContains(te.Policies, "root") { - // Prevent attempts to create a root token without an actual root token as parent. - // This is to thwart privilege escalation by tokens having 'sudo' privileges. - if !strutil.StrListContains(parent.Policies, "root") { - return logical.ErrorResponse("root tokens may not be created without parent token being root"), logical.ErrInvalidRequest - } - - if te.Type == logical.TokenTypeBatch { - // Batch tokens cannot be revoked so we should never have root batch tokens - return logical.ErrorResponse("batch tokens cannot be root tokens"), nil - } - } - - // - // NOTE: Do not modify policies below this line. We need the checks above - // to be the last checks as they must look at the final policy set. - // - - switch { - case role != nil: - if role.Orphan { - te.Parent = "" - } - - if len(role.BoundCIDRs) > 0 { - te.BoundCIDRs = role.BoundCIDRs - } - - case data.NoParent: - // Only allow an orphan token if the client has sudo policy - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to create orphan token"), - logical.ErrInvalidRequest - } - - te.Parent = "" - - default: - // This comes from create-orphan, which can be properly ACLd - if orphan { - te.Parent = "" - } - } - - // At this point, it is clear whether the token is going to be an orphan or - // not. If the token is not going to be an orphan, inherit the parent's - // entity identifier into the child token. We must also verify that, if - // it's not an orphan, the parent isn't a batch token. - if te.Parent != "" { - te.EntityID = parent.EntityID - } - - var explicitMaxTTLToUse time.Duration - if data.ExplicitMaxTTL != "" { - dur, err := parseutil.ParseDurationSecond(data.ExplicitMaxTTL) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("explicit_max_ttl must be positive"), logical.ErrInvalidRequest - } - te.ExplicitMaxTTL = dur - explicitMaxTTLToUse = dur - } - - var periodToUse time.Duration - if data.Period != "" { - dur, err := parseutil.ParseDurationSecond(data.Period) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - switch { - case dur < 0: - return logical.ErrorResponse("period must be positive"), logical.ErrInvalidRequest - case dur == 0: - default: - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to create periodic token"), - logical.ErrInvalidRequest - } - te.Period = dur - periodToUse = dur - } - } - - // Parse the TTL/lease if any - if data.TTL != "" { - dur, err := parseutil.ParseDurationSecond(data.TTL) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("ttl must be positive"), logical.ErrInvalidRequest - } - te.TTL = dur - } else if data.Lease != "" { - // This block is compatibility - dur, err := time.ParseDuration(data.Lease) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("lease must be positive"), logical.ErrInvalidRequest - } - te.TTL = dur - } - - // Set the lesser period/explicit max TTL if defined both in arguments and - // in role. Batch tokens will error out if not set via role, but here we - // need to explicitly check - if role != nil && te.Type != logical.TokenTypeBatch { - if role.ExplicitMaxTTL != 0 { - switch { - case explicitMaxTTLToUse == 0: - explicitMaxTTLToUse = role.ExplicitMaxTTL - default: - if role.ExplicitMaxTTL < explicitMaxTTLToUse { - explicitMaxTTLToUse = role.ExplicitMaxTTL - } - resp.AddWarning(fmt.Sprintf("Explicit max TTL specified both during creation call and in role; using the lesser value of %d seconds", int64(explicitMaxTTLToUse.Seconds()))) - } - } - if role.Period != 0 { - switch { - case periodToUse == 0: - periodToUse = role.Period - default: - if role.Period < periodToUse { - periodToUse = role.Period - } - resp.AddWarning(fmt.Sprintf("Period specified both during creation call and in role; using the lesser value of %d seconds", int64(periodToUse.Seconds()))) - } - } - } - - sysView := ts.System() - - // Only calculate a TTL if you are A) periodic, B) have a TTL, C) do not have a TTL and are not a root token - if periodToUse > 0 || te.TTL > 0 || (te.TTL == 0 && !strutil.StrListContains(te.Policies, "root")) { - ttl, warnings, err := framework.CalculateTTL(sysView, 0, te.TTL, periodToUse, 0, explicitMaxTTLToUse, time.Unix(te.CreationTime, 0)) - if err != nil { - return nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - te.TTL = ttl - } - - // Root tokens are still bound by explicit max TTL - if te.TTL == 0 && explicitMaxTTLToUse > 0 { - te.TTL = explicitMaxTTLToUse - } - - // Don't advertise non-expiring root tokens as renewable, as attempts to - // renew them are denied. Don't CIDR-restrict these either. - if te.TTL == 0 { - if parent.TTL != 0 { - return logical.ErrorResponse("expiring root tokens cannot create non-expiring root tokens"), logical.ErrInvalidRequest - } - renewable = false - te.BoundCIDRs = nil - } - - if te.ID != "" { - resp.AddWarning("Supplying a custom ID for the token uses the weaker SHA1 hashing instead of the more secure SHA2-256 HMAC for token obfuscation. SHA1 hashed tokens on the wire leads to less secure lookups.") - } - - // Create the token - if err := ts.create(ctx, &te); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - // Generate the response - resp.Auth = &logical.Auth{ - NumUses: te.NumUses, - DisplayName: te.DisplayName, - Policies: te.Policies, - Metadata: te.Meta, - LeaseOptions: logical.LeaseOptions{ - TTL: te.TTL, - Renewable: renewable, - }, - ClientToken: te.ID, - Accessor: te.Accessor, - EntityID: te.EntityID, - Period: periodToUse, - ExplicitMaxTTL: explicitMaxTTLToUse, - CreationPath: te.Path, - TokenType: te.Type, - } - - for _, p := range te.Policies { - policy, err := ts.core.policyStore.GetPolicy(ctx, p, PolicyTypeToken) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not look up policy %s", p)), nil - } - if policy == nil { - resp.AddWarning(fmt.Sprintf("Policy %q does not exist", p)) - } - } - - return resp, nil -} - -// handleRevokeSelf handles the auth/token/revoke-self path for revocation of tokens -// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke -// the token and all children anyways, but that is only available when there is a lease. -func (ts *TokenStore) handleRevokeSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return ts.revokeCommon(ctx, req, data, req.ClientToken) -} - -// handleRevokeTree handles the auth/token/revoke/id path for revocation of tokens -// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke -// the token and all children anyways, but that is only available when there is a lease. -func (ts *TokenStore) handleRevokeTree(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - id := data.Get("token").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - - if resp, err := ts.revokeCommon(ctx, req, data, id); resp != nil || err != nil { - return resp, err - } - - return nil, nil -} - -func (ts *TokenStore) revokeCommon(ctx context.Context, req *logical.Request, data *framework.FieldData, id string) (*logical.Response, error) { - te, err := ts.Lookup(ctx, id) - if err != nil { - return nil, err - } - if te == nil { - return nil, nil - } - - if te.Type == logical.TokenTypeBatch { - return logical.ErrorResponse("batch tokens cannot be revoked"), nil - } - - tokenNS, err := NamespaceByID(ctx, te.NamespaceID, ts.core) - if err != nil { - return nil, err - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - revokeCtx := namespace.ContextWithNamespace(ts.quitContext, tokenNS) - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(revokeCtx, te) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(revokeCtx, leaseID) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleRevokeOrphan handles the auth/token/revoke-orphan/id path for revocation of tokens -// in a way that leaves child tokens orphaned. Normally, using sys/revoke/leaseID will revoke -// the token and all children. -func (ts *TokenStore) handleRevokeOrphan(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Parse the id - id := data.Get("token").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - - // Check if the client token has sudo/root privileges for the requested path - isSudo := ts.System().SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken) - - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to revoke and orphan"), - logical.ErrInvalidRequest - } - - // Do a lookup. Among other things, that will ensure that this is either - // running in the same namespace or a parent. - te, err := ts.Lookup(ctx, id) - if err != nil { - return nil, errwrap.Wrapf("error when looking up token to revoke: {{err}}", err) - } - if te == nil { - return logical.ErrorResponse("token to revoke not found"), logical.ErrInvalidRequest - } - - if te.Type == logical.TokenTypeBatch { - return logical.ErrorResponse("batch tokens cannot be revoked"), nil - } - - // Revoke and orphan - if err := ts.revokeOrphan(ctx, id); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - return nil, nil -} - -func (ts *TokenStore) handleLookupSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - data.Raw["token"] = req.ClientToken - return ts.handleLookup(ctx, req, data) -} - -// handleLookup handles the auth/token/lookup/id path for querying information about -// a particular token. This can be used to see which policies are applicable. -func (ts *TokenStore) handleLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - id := data.Get("token").(string) - if id == "" { - id = req.ClientToken - } - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - out, err := ts.lookupInternal(ctx, id, false, true) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - if out == nil { - return logical.ErrorResponse("bad token"), logical.ErrPermissionDenied - } - - // Generate a response. We purposely omit the parent reference otherwise - // you could escalate your privileges. - resp := &logical.Response{ - Data: map[string]interface{}{ - "id": out.ID, - "accessor": out.Accessor, - "policies": out.Policies, - "path": out.Path, - "meta": out.Meta, - "display_name": out.DisplayName, - "num_uses": out.NumUses, - "orphan": false, - "creation_time": int64(out.CreationTime), - "creation_ttl": int64(out.TTL.Seconds()), - "expire_time": nil, - "ttl": int64(0), - "explicit_max_ttl": int64(out.ExplicitMaxTTL.Seconds()), - "entity_id": out.EntityID, - "type": out.Type.String(), - }, - } - - if out.Parent == "" { - resp.Data["orphan"] = true - } - - if out.Role != "" { - resp.Data["role"] = out.Role - } - - if out.Period != 0 { - resp.Data["period"] = int64(out.Period.Seconds()) - } - - if len(out.BoundCIDRs) > 0 { - resp.Data["bound_cidrs"] = out.BoundCIDRs - } - - tokenNS, err := NamespaceByID(ctx, out.NamespaceID, ts.core) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if tokenNS == nil { - return nil, namespace.ErrNoNamespace - } - - if out.NamespaceID != namespace.RootNamespaceID { - resp.Data["namespace_path"] = tokenNS.Path - } - - // Fetch the last renewal time - leaseTimes, err := ts.expiration.FetchLeaseTimesByToken(ctx, out) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if leaseTimes != nil { - if !leaseTimes.LastRenewalTime.IsZero() { - resp.Data["last_renewal_time"] = leaseTimes.LastRenewalTime.Unix() - resp.Data["last_renewal"] = leaseTimes.LastRenewalTime - } - if !leaseTimes.ExpireTime.IsZero() { - resp.Data["expire_time"] = leaseTimes.ExpireTime - resp.Data["ttl"] = leaseTimes.ttl() - } - renewable, _ := leaseTimes.renewable() - resp.Data["renewable"] = renewable - resp.Data["issue_time"] = leaseTimes.IssueTime - } - - if out.EntityID != "" { - _, identityPolicies, err := ts.core.fetchEntityAndDerivedPolicies(ctx, tokenNS, out.EntityID) - if err != nil { - return nil, err - } - if len(identityPolicies) != 0 { - resp.Data["identity_policies"] = identityPolicies[out.NamespaceID] - delete(identityPolicies, out.NamespaceID) - resp.Data["external_namespace_policies"] = identityPolicies - } - } - - return resp, nil -} - -func (ts *TokenStore) handleRenewSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - data.Raw["token"] = req.ClientToken - return ts.handleRenew(ctx, req, data) -} - -// handleRenew handles the auth/token/renew/id path for renewal of tokens. -// This is used to prevent token expiration and revocation. -func (ts *TokenStore) handleRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - id := data.Get("token").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - incrementRaw := data.Get("increment").(int) - - // Convert the increment - increment := time.Duration(incrementRaw) * time.Second - - // Lookup the token - te, err := ts.Lookup(ctx, id) - if err != nil { - return nil, errwrap.Wrapf("error looking up token to renew: {{err}}", err) - } - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - var resp *logical.Response - - if te.Type == logical.TokenTypeBatch { - return logical.ErrorResponse("batch tokens cannot be renewed"), nil - } - - // Renew the token and its children - resp, err = ts.expiration.RenewToken(ctx, req, te, increment) - - return resp, err -} - -func (ts *TokenStore) authRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.Auth == nil { - return nil, fmt.Errorf("request auth is nil") - } - - te, err := ts.Lookup(ctx, req.Auth.ClientToken) - if err != nil { - return nil, errwrap.Wrapf("error looking up token: {{err}}", err) - } - if te == nil { - return nil, fmt.Errorf("no token entry found during lookup") - } - - if te.Role == "" { - req.Auth.Period = te.Period - req.Auth.ExplicitMaxTTL = te.ExplicitMaxTTL - return &logical.Response{Auth: req.Auth}, nil - } - - role, err := ts.tokenStoreRole(ctx, te.Role) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error looking up role %q: {{err}}", te.Role), err) - } - if role == nil { - return nil, fmt.Errorf("original token role %q could not be found, not renewing", te.Role) - } - - req.Auth.Period = role.Period - req.Auth.ExplicitMaxTTL = role.ExplicitMaxTTL - return &logical.Response{Auth: req.Auth}, nil -} - -func (ts *TokenStore) tokenStoreRole(ctx context.Context, name string) (*tsRoleEntry, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - entry, err := ts.rolesView(ns).Get(ctx, name) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result tsRoleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - if result.TokenType == logical.TokenTypeDefault { - result.TokenType = logical.TokenTypeDefaultService - } - - return &result, nil -} - -func (ts *TokenStore) tokenStoreRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - entries, err := ts.rolesView(ns).List(ctx, "") - if err != nil { - return nil, err - } - - ret := make([]string, len(entries)) - for i, entry := range entries { - ret[i] = strings.TrimPrefix(entry, rolesPrefix) - } - - return logical.ListResponse(ret), nil -} - -func (ts *TokenStore) tokenStoreRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - err = ts.rolesView(ns).Delete(ctx, data.Get("role_name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (ts *TokenStore) tokenStoreRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := ts.tokenStoreRole(ctx, data.Get("role_name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "period": int64(role.Period.Seconds()), - "explicit_max_ttl": int64(role.ExplicitMaxTTL.Seconds()), - "disallowed_policies": role.DisallowedPolicies, - "allowed_policies": role.AllowedPolicies, - "name": role.Name, - "orphan": role.Orphan, - "path_suffix": role.PathSuffix, - "renewable": role.Renewable, - "token_type": role.TokenType.String(), - }, - } - - if len(role.BoundCIDRs) > 0 { - resp.Data["bound_cidrs"] = role.BoundCIDRs - } - - return resp, nil -} - -func (ts *TokenStore) tokenStoreRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - name := data.Get("role_name").(string) - if name == "" { - return false, fmt.Errorf("role name cannot be empty") - } - role, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return false, err - } - - return role != nil, nil -} - -func (ts *TokenStore) tokenStoreRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("role_name").(string) - if name == "" { - return logical.ErrorResponse("role name cannot be empty"), nil - } - entry, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return nil, err - } - - // Due to the existence check, entry will only be nil if it's a create - // operation, so just create a new one - if entry == nil { - entry = &tsRoleEntry{ - Name: name, - } - } - - // In this series of blocks, if we do not find a user-provided value and - // it's a creation operation, we call data.Get to get the appropriate - // default - - orphanInt, ok := data.GetOk("orphan") - if ok { - entry.Orphan = orphanInt.(bool) - } else if req.Operation == logical.CreateOperation { - entry.Orphan = data.Get("orphan").(bool) - } - - periodInt, ok := data.GetOk("period") - if ok { - entry.Period = time.Second * time.Duration(periodInt.(int)) - } else if req.Operation == logical.CreateOperation { - entry.Period = time.Second * time.Duration(data.Get("period").(int)) - } - - renewableInt, ok := data.GetOk("renewable") - if ok { - entry.Renewable = renewableInt.(bool) - } else if req.Operation == logical.CreateOperation { - entry.Renewable = data.Get("renewable").(bool) - } - - boundCIDRsRaw, ok := data.GetOk("bound_cidrs") - if ok { - boundCIDRs := boundCIDRsRaw.([]string) - if len(boundCIDRs) > 0 { - var parsedCIDRs []*sockaddr.SockAddrMarshaler - for _, v := range boundCIDRs { - parsedCIDR, err := sockaddr.NewSockAddr(v) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf(fmt.Sprintf("invalid value %q when parsing bound cidrs: {{err}}", v), err).Error()), nil - } - parsedCIDRs = append(parsedCIDRs, &sockaddr.SockAddrMarshaler{parsedCIDR}) - } - entry.BoundCIDRs = parsedCIDRs - } - } - - var resp *logical.Response - - explicitMaxTTLInt, ok := data.GetOk("explicit_max_ttl") - if ok { - entry.ExplicitMaxTTL = time.Second * time.Duration(explicitMaxTTLInt.(int)) - } else if req.Operation == logical.CreateOperation { - entry.ExplicitMaxTTL = time.Second * time.Duration(data.Get("explicit_max_ttl").(int)) - } - if entry.ExplicitMaxTTL != 0 { - sysView := ts.System() - - if sysView.MaxLeaseTTL() != time.Duration(0) && entry.ExplicitMaxTTL > sysView.MaxLeaseTTL() { - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning(fmt.Sprintf( - "Given explicit max TTL of %d is greater than system/mount allowed value of %d seconds; until this is fixed attempting to create tokens against this role will result in an error", - int64(entry.ExplicitMaxTTL.Seconds()), int64(sysView.MaxLeaseTTL().Seconds()))) - } - } - - pathSuffixInt, ok := data.GetOk("path_suffix") - if ok { - pathSuffix := pathSuffixInt.(string) - if pathSuffix != "" { - matched := pathSuffixSanitize.MatchString(pathSuffix) - if !matched { - return logical.ErrorResponse(fmt.Sprintf( - "given role path suffix contains invalid characters; must match %s", - pathSuffixSanitize.String())), nil - } - entry.PathSuffix = pathSuffix - } - } else if req.Operation == logical.CreateOperation { - entry.PathSuffix = data.Get("path_suffix").(string) - } - - if strings.Contains(entry.PathSuffix, "..") { - return logical.ErrorResponse(fmt.Sprintf("error registering path suffix: %s", consts.ErrPathContainsParentReferences)), nil - } - - allowedPoliciesRaw, ok := data.GetOk("allowed_policies") - if ok { - entry.AllowedPolicies = policyutil.SanitizePolicies(allowedPoliciesRaw.([]string), policyutil.DoNotAddDefaultPolicy) - } else if req.Operation == logical.CreateOperation { - entry.AllowedPolicies = policyutil.SanitizePolicies(data.Get("allowed_policies").([]string), policyutil.DoNotAddDefaultPolicy) - } - - disallowedPoliciesRaw, ok := data.GetOk("disallowed_policies") - if ok { - entry.DisallowedPolicies = strutil.RemoveDuplicates(disallowedPoliciesRaw.([]string), true) - } else if req.Operation == logical.CreateOperation { - entry.DisallowedPolicies = strutil.RemoveDuplicates(data.Get("disallowed_policies").([]string), true) - } - - tokenType := entry.TokenType - if tokenType == logical.TokenTypeDefault { - tokenType = logical.TokenTypeDefaultService - } - tokenTypeRaw, ok := data.GetOk("token_type") - if ok { - tokenTypeStr := tokenTypeRaw.(string) - switch tokenTypeStr { - case "service": - tokenType = logical.TokenTypeService - case "batch": - tokenType = logical.TokenTypeBatch - case "default-service": - tokenType = logical.TokenTypeDefaultService - case "default-batch": - tokenType = logical.TokenTypeDefaultBatch - default: - return logical.ErrorResponse(fmt.Sprintf("invalid 'token_type' value %q", tokenTypeStr)), nil - } - } else if req.Operation == logical.CreateOperation { - tokenType = logical.TokenTypeDefaultService - } - entry.TokenType = tokenType - - if entry.TokenType == logical.TokenTypeBatch { - if !entry.Orphan { - return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate non-orphan tokens"), nil - } - if entry.Period != 0 { - return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate periodic tokens"), nil - } - if entry.Renewable { - return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate renewable tokens"), nil - } - if entry.ExplicitMaxTTL != 0 { - return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate tokens with an explicit max TTL"), nil - } - } - - ns, err := namespace.FromContext(ctx) - if err != nil { - return nil, err - } - - // Store it - jsonEntry, err := logical.StorageEntryJSON(name, entry) - if err != nil { - return nil, err - } - if err := ts.rolesView(ns).Put(ctx, jsonEntry); err != nil { - return nil, err - } - - return resp, nil -} - -const ( - tokenTidyHelp = ` -This endpoint performs cleanup tasks that can be run if certain error -conditions have occurred. -` - tokenTidyDesc = ` -This endpoint performs cleanup tasks that can be run to clean up token and -lease entries after certain error conditions. Usually running this is not -necessary, and is only required if upgrade notes or support personnel suggest -it. -` - tokenBackendHelp = `The token credential backend is always enabled and builtin to Vault. -Client tokens are used to identify a client and to allow Vault to associate policies and ACLs -which are enforced on every request. This backend also allows for generating sub-tokens as well -as revocation of tokens. The tokens are renewable if associated with a lease.` - tokenCreateHelp = `The token create path is used to create new tokens.` - tokenCreateOrphanHelp = `The token create path is used to create new orphan tokens.` - tokenCreateRoleHelp = `This token create path is used to create new tokens adhering to the given role.` - tokenListRolesHelp = `This endpoint lists configured roles.` - tokenLookupAccessorHelp = `This endpoint will lookup a token associated with the given accessor and its properties. Response will not contain the token ID.` - tokenLookupHelp = `This endpoint will lookup a token and its properties.` - tokenPathRolesHelp = `This endpoint allows creating, reading, and deleting roles.` - tokenRevokeAccessorHelp = `This endpoint will delete the token associated with the accessor and all of its child tokens.` - tokenRevokeHelp = `This endpoint will delete the given token and all of its child tokens.` - tokenRevokeSelfHelp = `This endpoint will delete the token used to call it and all of its child tokens.` - tokenRevokeOrphanHelp = `This endpoint will delete the token and orphan its child tokens.` - tokenRenewHelp = `This endpoint will renew the given token and prevent expiration.` - tokenRenewSelfHelp = `This endpoint will renew the token used to call it and prevent expiration.` - tokenAllowedPoliciesHelp = `If set, tokens can be created with any subset of the policies in this -list, rather than the normal semantics of tokens being a subset of the -calling token's policies. The parameter is a comma-delimited string of -policy names.` - tokenDisallowedPoliciesHelp = `If set, successful token creation via this role will require that -no policies in the given list are requested. The parameter is a comma-delimited string of policy names.` - tokenOrphanHelp = `If true, tokens created via this role -will be orphan tokens (have no parent)` - tokenPeriodHelp = `If set, tokens created via this role -will have no max lifetime; instead, their -renewal period will be fixed to this value. -This takes an integer number of seconds, -or a string duration (e.g. "24h").` - tokenPathSuffixHelp = `If set, tokens created via this role -will contain the given suffix as a part of -their path. This can be used to assist use -of the 'revoke-prefix' endpoint later on. -The given suffix must match the regular -expression.` - tokenExplicitMaxTTLHelp = `If set, tokens created via this role -carry an explicit maximum TTL. During renewal, -the current maximum TTL values of the role -and the mount are not checked for changes, -and any updates to these values will have -no effect on the token being renewed.` - tokenRenewableHelp = `Tokens created via this role will be -renewable or not according to this value. -Defaults to "true".` - tokenListAccessorsHelp = `List token accessors, which can then be -be used to iterate and discover their properties -or revoke them. Because this can be used to -cause a denial of service, this endpoint -requires 'sudo' capability in addition to -'list'.` -) diff --git a/vendor/github.com/hashicorp/vault/vault/token_store_util.go b/vendor/github.com/hashicorp/vault/vault/token_store_util.go deleted file mode 100644 index ca1f39a1..00000000 --- a/vendor/github.com/hashicorp/vault/vault/token_store_util.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "github.com/hashicorp/vault/helper/namespace" -) - -func (ts *TokenStore) baseView(ns *namespace.Namespace) *BarrierView { - return ts.baseBarrierView -} - -func (ts *TokenStore) idView(ns *namespace.Namespace) *BarrierView { - return ts.idBarrierView -} - -func (ts *TokenStore) accessorView(ns *namespace.Namespace) *BarrierView { - return ts.accessorBarrierView -} - -func (ts *TokenStore) parentView(ns *namespace.Namespace) *BarrierView { - return ts.parentBarrierView -} - -func (ts *TokenStore) rolesView(ns *namespace.Namespace) *BarrierView { - return ts.rolesBarrierView -} diff --git a/vendor/github.com/hashicorp/vault/vault/ui.go b/vendor/github.com/hashicorp/vault/vault/ui.go deleted file mode 100644 index 7a637f20..00000000 --- a/vendor/github.com/hashicorp/vault/vault/ui.go +++ /dev/null @@ -1,217 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" -) - -const ( - uiConfigKey = "config" - uiConfigPlaintextKey = "config_plaintext" -) - -// UIConfig contains UI configuration. This takes both a physical view and a barrier view -// because it is stored in both plaintext and encrypted to allow for getting the header -// values before the barrier is unsealed -type UIConfig struct { - l sync.RWMutex - physicalStorage physical.Backend - barrierStorage logical.Storage - - enabled bool - defaultHeaders http.Header -} - -// NewUIConfig creates a new UI config -func NewUIConfig(enabled bool, physicalStorage physical.Backend, barrierStorage logical.Storage) *UIConfig { - defaultHeaders := http.Header{} - defaultHeaders.Set("Content-Security-Policy", "default-src 'none'; connect-src 'self'; img-src 'self' data:; script-src 'self'; style-src 'unsafe-inline' 'self'; form-action 'none'; frame-ancestors 'none'") - - return &UIConfig{ - physicalStorage: physicalStorage, - barrierStorage: barrierStorage, - enabled: enabled, - defaultHeaders: defaultHeaders, - } -} - -// Enabled returns if the UI is enabled -func (c *UIConfig) Enabled() bool { - c.l.RLock() - defer c.l.RUnlock() - return c.enabled -} - -// Headers returns the response headers that should be returned in the UI -func (c *UIConfig) Headers(ctx context.Context) (http.Header, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return nil, err - } - headers := make(http.Header) - if config != nil { - headers = config.Headers - } - - for k := range c.defaultHeaders { - if headers.Get(k) == "" { - v := c.defaultHeaders.Get(k) - headers.Set(k, v) - } - } - return headers, nil -} - -// HeaderKeys returns the list of the configured headers -func (c *UIConfig) HeaderKeys(ctx context.Context) ([]string, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - var keys []string - for k := range config.Headers { - keys = append(keys, k) - } - return keys, nil -} - -// GetHeader retrieves the configured value for the given header -func (c *UIConfig) GetHeader(ctx context.Context, header string) (string, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return "", err - } - if config == nil { - return "", nil - } - - value := config.Headers.Get(header) - return value, nil -} - -// SetHeader sets the value for the given header -func (c *UIConfig) SetHeader(ctx context.Context, header, value string) error { - c.l.Lock() - defer c.l.Unlock() - - config, err := c.get(ctx) - if err != nil { - return err - } - if config == nil { - config = &uiConfigEntry{ - Headers: http.Header{}, - } - } - config.Headers.Set(header, value) - return c.save(ctx, config) -} - -// DeleteHeader deletes the header configuration for the given header -func (c *UIConfig) DeleteHeader(ctx context.Context, header string) error { - c.l.Lock() - defer c.l.Unlock() - - config, err := c.get(ctx) - if err != nil { - return err - } - if config == nil { - return nil - } - - config.Headers.Del(header) - return c.save(ctx, config) -} - -func (c *UIConfig) get(ctx context.Context) (*uiConfigEntry, error) { - // Read plaintext always to ensure in sync with barrier value - plaintextConfigRaw, err := c.physicalStorage.Get(ctx, uiConfigPlaintextKey) - if err != nil { - return nil, err - } - - configRaw, err := c.barrierStorage.Get(ctx, uiConfigKey) - if err == nil { - if configRaw == nil { - return nil, nil - } - config := new(uiConfigEntry) - if err := json.Unmarshal(configRaw.Value, config); err != nil { - return nil, err - } - // Check that plaintext value matches barrier value, if not sync values - if plaintextConfigRaw == nil || bytes.Compare(plaintextConfigRaw.Value, configRaw.Value) != 0 { - if err := c.save(ctx, config); err != nil { - return nil, err - } - } - return config, nil - } - - // Respond with error if not sealed - if !strings.Contains(err.Error(), ErrBarrierSealed.Error()) { - return nil, err - } - - // Respond with plaintext value - if configRaw == nil { - return nil, nil - } - config := new(uiConfigEntry) - if err := json.Unmarshal(plaintextConfigRaw.Value, config); err != nil { - return nil, err - } - return config, nil -} - -func (c *UIConfig) save(ctx context.Context, config *uiConfigEntry) error { - if len(config.Headers) == 0 { - if err := c.physicalStorage.Delete(ctx, uiConfigPlaintextKey); err != nil { - return err - } - return c.barrierStorage.Delete(ctx, uiConfigKey) - } - - configRaw, err := json.Marshal(config) - if err != nil { - return err - } - - entry := &physical.Entry{ - Key: uiConfigPlaintextKey, - Value: configRaw, - } - if err := c.physicalStorage.Put(ctx, entry); err != nil { - return err - } - - barrEntry := &logical.StorageEntry{ - Key: uiConfigKey, - Value: configRaw, - } - return c.barrierStorage.Put(ctx, barrEntry) -} - -type uiConfigEntry struct { - Headers http.Header `json:"headers"` -} diff --git a/vendor/github.com/hashicorp/vault/vault/util.go b/vendor/github.com/hashicorp/vault/vault/util.go deleted file mode 100644 index 9e03afd2..00000000 --- a/vendor/github.com/hashicorp/vault/vault/util.go +++ /dev/null @@ -1,42 +0,0 @@ -package vault - -import ( - "crypto/rand" - "fmt" -) - -// memzero is used to zero out a byte buffer. This specific format is optimized -// by the compiler to use memclr to improve performance. See this code review: -// https://codereview.appspot.com/137880043 -// -// Use of memzero is not a guarantee against memory analysis as described in -// the Vault threat model: -// https://www.vaultproject.io/docs/internals/security.html . Vault does not -// provide guarantees against memory analysis or raw memory dumping by -// operators, however it does minimize this exposure by zeroing out buffers -// that contain secrets as soon as they are no longer used. Starting with Go -// 1.5, the garbage collector was changed to become a "generational copying -// garbage collector." This change to the garbage collector makes it -// impossible for Vault to guarantee a buffer with a secret has not been -// copied during a garbage collection. It is therefore possible that secrets -// may be exist in memory that have not been wiped despite a pending memzero -// call. Over time any copied data with a secret will be reused and the -// memory overwritten thereby mitigating some of the risk from this threat -// vector. -func memzero(b []byte) { - if b == nil { - return - } - for i := range b { - b[i] = 0 - } -} - -// randbytes is used to create a buffer of size n filled with random bytes -func randbytes(n int) []byte { - buf := make([]byte, n) - if _, err := rand.Read(buf); err != nil { - panic(fmt.Sprintf("failed to generate %d random bytes: %v", n, err)) - } - return buf -} diff --git a/vendor/github.com/hashicorp/vault/vault/wrapping.go b/vendor/github.com/hashicorp/vault/vault/wrapping.go deleted file mode 100644 index 81c750a0..00000000 --- a/vendor/github.com/hashicorp/vault/vault/wrapping.go +++ /dev/null @@ -1,376 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/SermoDigital/jose/crypto" - "github.com/SermoDigital/jose/jws" - "github.com/SermoDigital/jose/jwt" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" -) - -const ( - // The location of the key used to generate response-wrapping JWTs - coreWrappingJWTKeyPath = "core/wrapping/jwtkey" -) - -func (c *Core) ensureWrappingKey(ctx context.Context) error { - entry, err := c.barrier.Get(ctx, coreWrappingJWTKeyPath) - if err != nil { - return err - } - - var keyParams clusterKeyParams - - if entry == nil { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - return errwrap.Wrapf("failed to generate wrapping key: {{err}}", err) - } - keyParams.D = key.D - keyParams.X = key.X - keyParams.Y = key.Y - keyParams.Type = corePrivateKeyTypeP521 - val, err := jsonutil.EncodeJSON(keyParams) - if err != nil { - return errwrap.Wrapf("failed to encode wrapping key: {{err}}", err) - } - entry = &Entry{ - Key: coreWrappingJWTKeyPath, - Value: val, - } - if err = c.barrier.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to store wrapping key: {{err}}", err) - } - } - - // Redundant if we just created it, but in this case serves as a check anyways - if err = jsonutil.DecodeJSON(entry.Value, &keyParams); err != nil { - return errwrap.Wrapf("failed to decode wrapping key parameters: {{err}}", err) - } - - c.wrappingJWTKey = &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: keyParams.X, - Y: keyParams.Y, - }, - D: keyParams.D, - } - - c.logger.Info("loaded wrapping token key") - - return nil -} - -func (c *Core) wrapInCubbyhole(ctx context.Context, req *logical.Request, resp *logical.Response, auth *logical.Auth) (*logical.Response, error) { - if c.perfStandby { - return forwardWrapRequest(ctx, c, req, resp, auth) - } - - // Before wrapping, obey special rules for listing: if no entries are - // found, 404. This prevents unwrapping only to find empty data. - if req.Operation == logical.ListOperation { - if resp == nil || (len(resp.Data) == 0 && len(resp.Warnings) == 0) { - return nil, logical.ErrUnsupportedPath - } - - keysRaw, ok := resp.Data["keys"] - if !ok || keysRaw == nil { - if len(resp.Data) > 0 || len(resp.Warnings) > 0 { - // We could be returning extra metadata on a list, or returning - // warnings with no data, so handle these cases - goto DONELISTHANDLING - } - return nil, logical.ErrUnsupportedPath - } - - keys, ok := keysRaw.([]string) - if !ok { - return nil, logical.ErrUnsupportedPath - } - if len(keys) == 0 { - return nil, logical.ErrUnsupportedPath - } - } - -DONELISTHANDLING: - var err error - sealWrap := resp.WrapInfo.SealWrap - - var ns *namespace.Namespace - // If we are creating a JWT wrapping token we always want them to live in - // the root namespace. These are only used for replication and plugin setup. - switch resp.WrapInfo.Format { - case "jwt": - ns = namespace.RootNamespace - ctx = namespace.ContextWithNamespace(ctx, ns) - default: - ns, err = namespace.FromContext(ctx) - if err != nil { - return nil, err - } - } - - // If we are wrapping, the first part (performed in this functions) happens - // before auditing so that resp.WrapInfo.Token can contain the HMAC'd - // wrapping token ID in the audit logs, so that it can be determined from - // the audit logs whether the token was ever actually used. - creationTime := time.Now() - te := logical.TokenEntry{ - Path: req.Path, - Policies: []string{"response-wrapping"}, - CreationTime: creationTime.Unix(), - TTL: resp.WrapInfo.TTL, - NumUses: 1, - ExplicitMaxTTL: resp.WrapInfo.TTL, - NamespaceID: ns.ID, - } - - if err := c.tokenStore.create(ctx, &te); err != nil { - c.logger.Error("failed to create wrapping token", "error", err) - return nil, ErrInternalError - } - - resp.WrapInfo.Token = te.ID - resp.WrapInfo.Accessor = te.Accessor - resp.WrapInfo.CreationTime = creationTime - // If this is not a rewrap, store the request path as creation_path - if req.Path != "sys/wrapping/rewrap" { - resp.WrapInfo.CreationPath = req.Path - } - - if auth != nil && auth.EntityID != "" { - resp.WrapInfo.WrappedEntityID = auth.EntityID - } - - // This will only be non-nil if this response contains a token, so in that - // case put the accessor in the wrap info. - if resp.Auth != nil { - resp.WrapInfo.WrappedAccessor = resp.Auth.Accessor - } - - switch resp.WrapInfo.Format { - case "jwt": - // Create the JWT - claims := jws.Claims{} - // Map the JWT ID to the token ID for ease of use - claims.SetJWTID(te.ID) - // Set the issue time to the creation time - claims.SetIssuedAt(creationTime) - // Set the expiration to the TTL - claims.SetExpiration(creationTime.Add(resp.WrapInfo.TTL)) - if resp.Auth != nil { - claims.Set("accessor", resp.Auth.Accessor) - } - claims.Set("type", "wrapping") - claims.Set("addr", c.redirectAddr) - jwt := jws.NewJWT(claims, crypto.SigningMethodES512) - serWebToken, err := jwt.Serialize(c.wrappingJWTKey) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to serialize JWT", "error", err) - return nil, ErrInternalError - } - resp.WrapInfo.Token = string(serWebToken) - if c.redirectAddr == "" { - resp.AddWarning("No redirect address set in Vault so none could be encoded in the token. You may need to supply Vault's API address when unwrapping the token.") - } - } - - cubbyReq := &logical.Request{ - Operation: logical.CreateOperation, - Path: "cubbyhole/response", - ClientToken: te.ID, - } - if sealWrap { - cubbyReq.WrapInfo = &logical.RequestWrapInfo{ - SealWrap: true, - } - } - cubbyReq.SetTokenEntry(&te) - - // During a rewrap, store the original response, don't wrap it again. - if req.Path == "sys/wrapping/rewrap" { - cubbyReq.Data = map[string]interface{}{ - "response": resp.Data["response"], - } - } else { - httpResponse := logical.LogicalResponseToHTTPResponse(resp) - - // Add the unique identifier of the original request to the response - httpResponse.RequestID = req.ID - - // Because of the way that JSON encodes (likely just in Go) we actually get - // mixed-up values for ints if we simply put this object in the response - // and encode the whole thing; so instead we marshal it first, then store - // the string response. This actually ends up making it easier on the - // client side, too, as it becomes a straight read-string-pass-to-unmarshal - // operation. - - marshaledResponse, err := json.Marshal(httpResponse) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to marshal wrapped response", "error", err) - return nil, ErrInternalError - } - - cubbyReq.Data = map[string]interface{}{ - "response": string(marshaledResponse), - } - } - - cubbyResp, err := c.router.Route(ctx, cubbyReq) - if err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapped response information", "error", err) - return nil, ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapped response information", "error", cubbyResp.Data["error"]) - return cubbyResp, nil - } - - // Store info for lookup - cubbyReq.WrapInfo = nil - cubbyReq.Path = "cubbyhole/wrapinfo" - cubbyReq.Data = map[string]interface{}{ - "creation_ttl": resp.WrapInfo.TTL, - "creation_time": creationTime, - } - // Store creation_path if not a rewrap - if req.Path != "sys/wrapping/rewrap" { - cubbyReq.Data["creation_path"] = req.Path - } else { - cubbyReq.Data["creation_path"] = resp.WrapInfo.CreationPath - } - cubbyResp, err = c.router.Route(ctx, cubbyReq) - if err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapping information", "error", err) - return nil, ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapping information", "error", cubbyResp.Data["error"]) - return cubbyResp, nil - } - - wAuth := &logical.Auth{ - ClientToken: te.ID, - Policies: []string{"response-wrapping"}, - LeaseOptions: logical.LeaseOptions{ - TTL: te.TTL, - Renewable: false, - }, - } - - // Register the wrapped token with the expiration manager - if err := c.expiration.RegisterAuth(ctx, &te, wAuth); err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register cubbyhole wrapping token lease", "request_path", req.Path, "error", err) - return nil, ErrInternalError - } - - return nil, nil -} - -// ValidateWrappingToken checks whether a token is a wrapping token. -func (c *Core) ValidateWrappingToken(ctx context.Context, req *logical.Request) (bool, error) { - if req == nil { - return false, fmt.Errorf("invalid request") - } - - var err error - - var token string - var thirdParty bool - if req.Data != nil && req.Data["token"] != nil { - thirdParty = true - if tokenStr, ok := req.Data["token"].(string); !ok { - return false, fmt.Errorf("could not decode token in request body") - } else if tokenStr == "" { - return false, fmt.Errorf("empty token in request body") - } else { - token = tokenStr - } - } else { - token = req.ClientToken - } - - // Check for it being a JWT. If it is, and it is valid, we extract the - // internal client token from it and use that during lookup. - if strings.Count(token, ".") == 2 { - wt, err := jws.ParseJWT([]byte(token)) - // If there's an error we simply fall back to attempting to use it as a regular token - if err == nil && wt != nil { - validator := &jwt.Validator{} - validator.SetClaim("type", "wrapping") - if err = wt.Validate(&c.wrappingJWTKey.PublicKey, crypto.SigningMethodES512, []*jwt.Validator{validator}...); err != nil { - return false, errwrap.Wrapf("wrapping token signature could not be validated: {{err}}", err) - } - token, _ = wt.Claims().JWTID() - // We override the given request client token so that the rest of - // Vault sees the real value. This also ensures audit logs are - // consistent with the actual token that was issued. - if !thirdParty { - req.ClientToken = token - } else { - req.Data["token"] = token - } - } - } - - if token == "" { - return false, fmt.Errorf("token is empty") - } - - if c.Sealed() { - return false, consts.ErrSealed - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.standby && !c.perfStandby { - return false, consts.ErrStandby - } - - te, err := c.tokenStore.Lookup(ctx, token) - if err != nil { - return false, err - } - if te == nil { - return false, nil - } - - if len(te.Policies) != 1 { - return false, nil - } - - if te.Policies[0] != responseWrappingPolicyName && te.Policies[0] != controlGroupPolicyName { - return false, nil - } - - if !thirdParty { - req.ClientTokenAccessor = te.Accessor - req.ClientTokenRemainingUses = te.NumUses - req.SetTokenEntry(te) - } - - return true, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/wrapping_util.go b/vendor/github.com/hashicorp/vault/vault/wrapping_util.go deleted file mode 100644 index 475fd35e..00000000 --- a/vendor/github.com/hashicorp/vault/vault/wrapping_util.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !enterprise - -package vault - -import ( - "context" - - "github.com/hashicorp/vault/logical" -) - -func forwardWrapRequest(context.Context, *Core, *logical.Request, *logical.Response, *logical.Auth) (*logical.Response, error) { - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/version/cgo.go b/vendor/github.com/hashicorp/vault/version/cgo.go deleted file mode 100644 index 2ed493a1..00000000 --- a/vendor/github.com/hashicorp/vault/version/cgo.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build cgo - -package version - -func init() { - CgoEnabled = true -} diff --git a/vendor/github.com/hashicorp/vault/version/version.go b/vendor/github.com/hashicorp/vault/version/version.go deleted file mode 100644 index 0f819333..00000000 --- a/vendor/github.com/hashicorp/vault/version/version.go +++ /dev/null @@ -1,87 +0,0 @@ -package version - -import ( - "bytes" - "fmt" -) - -var ( - // The git commit that was compiled. This will be filled in by the compiler. - GitCommit string - GitDescribe string - - // Whether cgo is enabled or not; set at build time - CgoEnabled bool - - Version = "unknown" - VersionPrerelease = "unknown" - VersionMetadata = "" -) - -// VersionInfo -type VersionInfo struct { - Revision string - Version string - VersionPrerelease string - VersionMetadata string -} - -func GetVersion() *VersionInfo { - ver := Version - rel := VersionPrerelease - md := VersionMetadata - if GitDescribe != "" { - ver = GitDescribe - } - if GitDescribe == "" && rel == "" && VersionPrerelease != "" { - rel = "dev" - } - - return &VersionInfo{ - Revision: GitCommit, - Version: ver, - VersionPrerelease: rel, - VersionMetadata: md, - } -} - -func (c *VersionInfo) VersionNumber() string { - if Version == "unknown" && VersionPrerelease == "unknown" { - return "(version unknown)" - } - - version := fmt.Sprintf("%s", c.Version) - - if c.VersionPrerelease != "" { - version = fmt.Sprintf("%s-%s", version, c.VersionPrerelease) - } - - if c.VersionMetadata != "" { - version = fmt.Sprintf("%s+%s", version, c.VersionMetadata) - } - - return version -} - -func (c *VersionInfo) FullVersionNumber(rev bool) string { - var versionString bytes.Buffer - - if Version == "unknown" && VersionPrerelease == "unknown" { - return "Vault (version unknown)" - } - - fmt.Fprintf(&versionString, "Vault v%s", c.Version) - if c.VersionPrerelease != "" { - fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease) - } - - if c.VersionMetadata != "" { - fmt.Fprintf(&versionString, "+%s", c.VersionMetadata) - } - - if rev && c.Revision != "" { - fmt.Fprintf(&versionString, " (%s)", c.Revision) - } - - return versionString.String() -} diff --git a/vendor/github.com/hashicorp/vault/version/version_base.go b/vendor/github.com/hashicorp/vault/version/version_base.go deleted file mode 100644 index b1a28c8e..00000000 --- a/vendor/github.com/hashicorp/vault/version/version_base.go +++ /dev/null @@ -1,11 +0,0 @@ -package version - -func init() { - // The main version number that is being run at the moment. - Version = "1.0.0" - - // A pre-release marker for the version. If this is "" (empty string) - // then it means that it is a final release. Otherwise, this is a pre-release - // such as "dev" (in development), "beta", "rc1", etc. - VersionPrerelease = "rc1" -} diff --git a/vendor/github.com/hashicorp/yamux/.gitignore b/vendor/github.com/hashicorp/yamux/.gitignore deleted file mode 100644 index 83656241..00000000 --- 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 f0e5c79e..00000000 --- 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 d4db7fc9..00000000 --- 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 be6ebca9..00000000 --- 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() -} - -// LocalAddr 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 4f529382..00000000 --- a/vendor/github.com/hashicorp/yamux/const.go +++ /dev/null @@ -1,157 +0,0 @@ -package yamux - -import ( - "encoding/binary" - "fmt" -) - -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 = fmt.Errorf("i/o deadline reached") - - // 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/go.mod b/vendor/github.com/hashicorp/yamux/go.mod deleted file mode 100644 index 672a0e58..00000000 --- a/vendor/github.com/hashicorp/yamux/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/yamux diff --git a/vendor/github.com/hashicorp/yamux/mux.go b/vendor/github.com/hashicorp/yamux/mux.go deleted file mode 100644 index 18a078c8..00000000 --- a/vendor/github.com/hashicorp/yamux/mux.go +++ /dev/null @@ -1,98 +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 - - // 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, - 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 a80ddec3..00000000 --- a/vendor/github.com/hashicorp/yamux/session.go +++ /dev/null @@ -1,653 +0,0 @@ -package yamux - -import ( - "bufio" - "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{} - - // shutdown is used to safely close a session - shutdown bool - shutdownErr error - shutdownCh chan struct{} - shutdownLock sync.Mutex -} - -// sendReady is used to either mark a stream as ready -// or to directly send a header -type sendReady struct { - Hdr []byte - Body io.Reader - 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{}), - 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() - - // 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 -} - -// 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 - if s.shutdownErr == nil { - s.shutdownErr = ErrSessionShutdown - } - close(s.shutdownCh) - s.conn.Close() - <-s.recvDoneCh - - s.streamLock.Lock() - defer s.streamLock.Unlock() - for _, stream := range s.streams { - stream.forceClose() - } - return nil -} - -// exitErr is used to handle an error that is causing the -// session to terminate. -func (s *Session) exitErr(err error) { - s.shutdownLock.Lock() - if s.shutdownErr == nil { - s.shutdownErr = err - } - s.shutdownLock.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 io.Reader) 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 io.Reader, 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 - } - - select { - case err := <-errCh: - return err - case <-s.shutdownCh: - return ErrSessionShutdown - case <-timer.C: - 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() { - for { - select { - case ready := <-s.sendCh: - // Send a header if ready - if ready.Hdr != nil { - sent := 0 - for sent < len(ready.Hdr) { - n, err := s.conn.Write(ready.Hdr[sent:]) - if err != nil { - s.logger.Printf("[ERR] yamux: Failed to write header: %v", err) - asyncSendErr(ready.Err, err) - s.exitErr(err) - return - } - sent += n - } - } - - // Send data from a body if given - if ready.Body != nil { - _, err := io.Copy(s.conn, ready.Body) - if err != nil { - s.logger.Printf("[ERR] yamux: Failed to write body: %v", err) - asyncSendErr(ready.Err, err) - s.exitErr(err) - return - } - } - - // No error, successful send - asyncSendErr(ready.Err, nil) - case <-s.shutdownCh: - return - } - } -} - -// 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) - stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0) - return s.sendNoWait(stream.sendHdr) - } -} - -// 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 183d797b..00000000 --- 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 aa239197..00000000 --- a/vendor/github.com/hashicorp/yamux/stream.go +++ /dev/null @@ -1,470 +0,0 @@ -package yamux - -import ( - "bytes" - "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 -} - -// 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), - } - 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() - 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 io.Reader -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 = bytes.NewReader(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 { - 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 { - 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 { - 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: - s.stateLock.Unlock() - s.sendClose() - s.notifyWaiting() - if closeStream { - s.session.closeStream(s.id) - } - return nil -} - -// 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 { - // Close the stream without holding the state lock - closeStream := false - defer func() { - if closeStream { - s.session.closeStream(s.id) - } - }() - - s.stateLock.Lock() - defer s.stateLock.Unlock() - if flags&flagACK == flagACK { - if s.state == streamSYNSent { - s.state = streamEstablished - } - 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) -} - -// 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) - 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)) - } - if _, err := io.Copy(s.recvBuf, conn); 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 -= length - 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 future Read calls. -func (s *Stream) SetReadDeadline(t time.Time) error { - s.readDeadline.Store(t) - return nil -} - -// SetWriteDeadline sets the deadline for future Write calls -func (s *Stream) SetWriteDeadline(t time.Time) error { - s.writeDeadline.Store(t) - 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 8a73e924..00000000 --- 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/hpcloud/tail/.gitignore b/vendor/github.com/hpcloud/tail/.gitignore deleted file mode 100644 index 6d9953c3..00000000 --- a/vendor/github.com/hpcloud/tail/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.test -.go - diff --git a/vendor/github.com/hpcloud/tail/.travis.yml b/vendor/github.com/hpcloud/tail/.travis.yml deleted file mode 100644 index 9cf8bb7f..00000000 --- a/vendor/github.com/hpcloud/tail/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go - -script: - - go test -race -v ./... - -go: - - 1.4 - - 1.5 - - 1.6 - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get gopkg.in/fsnotify.v1 - - go get gopkg.in/tomb.v1 diff --git a/vendor/github.com/hpcloud/tail/CHANGES.md b/vendor/github.com/hpcloud/tail/CHANGES.md deleted file mode 100644 index 422790c0..00000000 --- a/vendor/github.com/hpcloud/tail/CHANGES.md +++ /dev/null @@ -1,63 +0,0 @@ -# API v1 (gopkg.in/hpcloud/tail.v1) - -## April, 2016 - -* Migrated to godep, as depman is not longer supported -* Introduced golang vendoring feature -* Fixed issue [#57](https://github.com/hpcloud/tail/issues/57) related to reopen deleted file - -## July, 2015 - -* Fix inotify watcher leak; remove `Cleanup` (#51) - -# API v0 (gopkg.in/hpcloud/tail.v0) - -## June, 2015 - -* Don't return partial lines (PR #40) -* Use stable version of fsnotify (#46) - -## July, 2014 - -* Fix tail for Windows (PR #36) - -## May, 2014 - -* Improved rate limiting using leaky bucket (PR #29) -* Fix odd line splitting (PR #30) - -## Apr, 2014 - -* LimitRate now discards read buffer (PR #28) -* allow reading of longer lines if MaxLineSize is unset (PR #24) -* updated deps.json to latest fsnotify (441bbc86b1) - -## Feb, 2014 - -* added `Config.Logger` to suppress library logging - -## Nov, 2013 - -* add Cleanup to remove leaky inotify watches (PR #20) - -## Aug, 2013 - -* redesigned Location field (PR #12) -* add tail.Tell (PR #14) - -## July, 2013 - -* Rate limiting (PR #10) - -## May, 2013 - -* Detect file deletions/renames in polling file watcher (PR #1) -* Detect file truncation -* Fix potential race condition when reopening the file (issue 5) -* Fix potential blocking of `tail.Stop` (issue 4) -* Fix uncleaned up ChangeEvents goroutines after calling tail.Stop -* Support Follow=false - -## Feb, 2013 - -* Initial open source release diff --git a/vendor/github.com/hpcloud/tail/Dockerfile b/vendor/github.com/hpcloud/tail/Dockerfile deleted file mode 100644 index cd297b94..00000000 --- a/vendor/github.com/hpcloud/tail/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM golang - -RUN mkdir -p $GOPATH/src/github.com/hpcloud/tail/ -ADD . $GOPATH/src/github.com/hpcloud/tail/ - -# expecting to fetch dependencies successfully. -RUN go get -v github.com/hpcloud/tail - -# expecting to run the test successfully. -RUN go test -v github.com/hpcloud/tail - -# expecting to install successfully -RUN go install -v github.com/hpcloud/tail -RUN go install -v github.com/hpcloud/tail/cmd/gotail - -RUN $GOPATH/bin/gotail -h || true - -ENV PATH $GOPATH/bin:$PATH -CMD ["gotail"] diff --git a/vendor/github.com/hpcloud/tail/LICENSE.txt b/vendor/github.com/hpcloud/tail/LICENSE.txt deleted file mode 100644 index 818d802a..00000000 --- a/vendor/github.com/hpcloud/tail/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -# The MIT License (MIT) - -# © Copyright 2015 Hewlett Packard Enterprise Development LP -Copyright (c) 2014 ActiveState - -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/hpcloud/tail/Makefile b/vendor/github.com/hpcloud/tail/Makefile deleted file mode 100644 index 6591b24f..00000000 --- a/vendor/github.com/hpcloud/tail/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -default: test - -test: *.go - go test -v -race ./... - -fmt: - gofmt -w . - -# Run the test in an isolated environment. -fulltest: - docker build -t hpcloud/tail . diff --git a/vendor/github.com/hpcloud/tail/README.md b/vendor/github.com/hpcloud/tail/README.md deleted file mode 100644 index fb7fbc26..00000000 --- a/vendor/github.com/hpcloud/tail/README.md +++ /dev/null @@ -1,28 +0,0 @@ -[![Build Status](https://travis-ci.org/hpcloud/tail.svg)](https://travis-ci.org/hpcloud/tail) -[![Build status](https://ci.appveyor.com/api/projects/status/kohpsf3rvhjhrox6?svg=true)](https://ci.appveyor.com/project/HelionCloudFoundry/tail) - -# Go package for tail-ing files - -A Go package striving to emulate the features of the BSD `tail` program. - -```Go -t, err := tail.TailFile("/var/log/nginx.log", tail.Config{Follow: true}) -for line := range t.Lines { - fmt.Println(line.Text) -} -``` - -See [API documentation](http://godoc.org/github.com/hpcloud/tail). - -## Log rotation - -Tail comes with full support for truncation/move detection as it is -designed to work with log rotation tools. - -## Installing - - go get github.com/hpcloud/tail/... - -## Windows support - -This package [needs assistance](https://github.com/hpcloud/tail/labels/Windows) for full Windows support. diff --git a/vendor/github.com/hpcloud/tail/appveyor.yml b/vendor/github.com/hpcloud/tail/appveyor.yml deleted file mode 100644 index d370055b..00000000 --- a/vendor/github.com/hpcloud/tail/appveyor.yml +++ /dev/null @@ -1,11 +0,0 @@ -version: 0.{build} -skip_tags: true -cache: C:\Users\appveyor\AppData\Local\NuGet\Cache -build_script: -- SET GOPATH=c:\workspace -- go test -v -race ./... -test: off -clone_folder: c:\workspace\src\github.com\hpcloud\tail -branches: - only: - - master diff --git a/vendor/github.com/hpcloud/tail/ratelimiter/Licence b/vendor/github.com/hpcloud/tail/ratelimiter/Licence deleted file mode 100644 index 434aab19..00000000 --- a/vendor/github.com/hpcloud/tail/ratelimiter/Licence +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (C) 2013 99designs - -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/hpcloud/tail/ratelimiter/leakybucket.go b/vendor/github.com/hpcloud/tail/ratelimiter/leakybucket.go deleted file mode 100644 index 358b69e7..00000000 --- a/vendor/github.com/hpcloud/tail/ratelimiter/leakybucket.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package ratelimiter implements the Leaky Bucket ratelimiting algorithm with memcached and in-memory backends. -package ratelimiter - -import ( - "time" -) - -type LeakyBucket struct { - Size uint16 - Fill float64 - LeakInterval time.Duration // time.Duration for 1 unit of size to leak - Lastupdate time.Time - Now func() time.Time -} - -func NewLeakyBucket(size uint16, leakInterval time.Duration) *LeakyBucket { - bucket := LeakyBucket{ - Size: size, - Fill: 0, - LeakInterval: leakInterval, - Now: time.Now, - Lastupdate: time.Now(), - } - - return &bucket -} - -func (b *LeakyBucket) updateFill() { - now := b.Now() - if b.Fill > 0 { - elapsed := now.Sub(b.Lastupdate) - - b.Fill -= float64(elapsed) / float64(b.LeakInterval) - if b.Fill < 0 { - b.Fill = 0 - } - } - b.Lastupdate = now -} - -func (b *LeakyBucket) Pour(amount uint16) bool { - b.updateFill() - - var newfill float64 = b.Fill + float64(amount) - - if newfill > float64(b.Size) { - return false - } - - b.Fill = newfill - - return true -} - -// The time at which this bucket will be completely drained -func (b *LeakyBucket) DrainedAt() time.Time { - return b.Lastupdate.Add(time.Duration(b.Fill * float64(b.LeakInterval))) -} - -// The duration until this bucket is completely drained -func (b *LeakyBucket) TimeToDrain() time.Duration { - return b.DrainedAt().Sub(b.Now()) -} - -func (b *LeakyBucket) TimeSinceLastUpdate() time.Duration { - return b.Now().Sub(b.Lastupdate) -} - -type LeakyBucketSer struct { - Size uint16 - Fill float64 - LeakInterval time.Duration // time.Duration for 1 unit of size to leak - Lastupdate time.Time -} - -func (b *LeakyBucket) Serialise() *LeakyBucketSer { - bucket := LeakyBucketSer{ - Size: b.Size, - Fill: b.Fill, - LeakInterval: b.LeakInterval, - Lastupdate: b.Lastupdate, - } - - return &bucket -} - -func (b *LeakyBucketSer) DeSerialise() *LeakyBucket { - bucket := LeakyBucket{ - Size: b.Size, - Fill: b.Fill, - LeakInterval: b.LeakInterval, - Lastupdate: b.Lastupdate, - Now: time.Now, - } - - return &bucket -} diff --git a/vendor/github.com/hpcloud/tail/ratelimiter/memory.go b/vendor/github.com/hpcloud/tail/ratelimiter/memory.go deleted file mode 100644 index 8f6a5784..00000000 --- a/vendor/github.com/hpcloud/tail/ratelimiter/memory.go +++ /dev/null @@ -1,58 +0,0 @@ -package ratelimiter - -import ( - "errors" - "time" -) - -const GC_SIZE int = 100 - -type Memory struct { - store map[string]LeakyBucket - lastGCCollected time.Time -} - -func NewMemory() *Memory { - m := new(Memory) - m.store = make(map[string]LeakyBucket) - m.lastGCCollected = time.Now() - return m -} - -func (m *Memory) GetBucketFor(key string) (*LeakyBucket, error) { - - bucket, ok := m.store[key] - if !ok { - return nil, errors.New("miss") - } - - return &bucket, nil -} - -func (m *Memory) SetBucketFor(key string, bucket LeakyBucket) error { - - if len(m.store) > GC_SIZE { - m.GarbageCollect() - } - - m.store[key] = bucket - - return nil -} - -func (m *Memory) GarbageCollect() { - now := time.Now() - - // rate limit GC to once per minute - if now.Add(60*time.Second).Unix() > m.lastGCCollected.Unix() { - - for key, bucket := range m.store { - // if the bucket is drained, then GC - if bucket.DrainedAt().Unix() > now.Unix() { - delete(m.store, key) - } - } - - m.lastGCCollected = now - } -} diff --git a/vendor/github.com/hpcloud/tail/ratelimiter/storage.go b/vendor/github.com/hpcloud/tail/ratelimiter/storage.go deleted file mode 100644 index 89b2fe88..00000000 --- a/vendor/github.com/hpcloud/tail/ratelimiter/storage.go +++ /dev/null @@ -1,6 +0,0 @@ -package ratelimiter - -type Storage interface { - GetBucketFor(string) (*LeakyBucket, error) - SetBucketFor(string, LeakyBucket) error -} diff --git a/vendor/github.com/hpcloud/tail/tail.go b/vendor/github.com/hpcloud/tail/tail.go deleted file mode 100644 index 2d252d60..00000000 --- a/vendor/github.com/hpcloud/tail/tail.go +++ /dev/null @@ -1,438 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package tail - -import ( - "bufio" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "strings" - "sync" - "time" - - "github.com/hpcloud/tail/ratelimiter" - "github.com/hpcloud/tail/util" - "github.com/hpcloud/tail/watch" - "gopkg.in/tomb.v1" -) - -var ( - ErrStop = fmt.Errorf("tail should now stop") -) - -type Line struct { - Text string - Time time.Time - Err error // Error from tail -} - -// NewLine returns a Line with present time. -func NewLine(text string) *Line { - return &Line{text, time.Now(), nil} -} - -// SeekInfo represents arguments to `os.Seek` -type SeekInfo struct { - Offset int64 - Whence int // os.SEEK_* -} - -type logger interface { - Fatal(v ...interface{}) - Fatalf(format string, v ...interface{}) - Fatalln(v ...interface{}) - Panic(v ...interface{}) - Panicf(format string, v ...interface{}) - Panicln(v ...interface{}) - Print(v ...interface{}) - Printf(format string, v ...interface{}) - Println(v ...interface{}) -} - -// Config is used to specify how a file must be tailed. -type Config struct { - // File-specifc - Location *SeekInfo // Seek to this location before tailing - ReOpen bool // Reopen recreated files (tail -F) - MustExist bool // Fail early if the file does not exist - Poll bool // Poll for file changes instead of using inotify - Pipe bool // Is a named pipe (mkfifo) - RateLimiter *ratelimiter.LeakyBucket - - // Generic IO - Follow bool // Continue looking for new lines (tail -f) - MaxLineSize int // If non-zero, split longer lines into multiple lines - - // Logger, when nil, is set to tail.DefaultLogger - // To disable logging: set field to tail.DiscardingLogger - Logger logger -} - -type Tail struct { - Filename string - Lines chan *Line - Config - - file *os.File - reader *bufio.Reader - - watcher watch.FileWatcher - changes *watch.FileChanges - - tomb.Tomb // provides: Done, Kill, Dying - - lk sync.Mutex -} - -var ( - // DefaultLogger is used when Config.Logger == nil - DefaultLogger = log.New(os.Stderr, "", log.LstdFlags) - // DiscardingLogger can be used to disable logging output - DiscardingLogger = log.New(ioutil.Discard, "", 0) -) - -// TailFile begins tailing the file. Output stream is made available -// via the `Tail.Lines` channel. To handle errors during tailing, -// invoke the `Wait` or `Err` method after finishing reading from the -// `Lines` channel. -func TailFile(filename string, config Config) (*Tail, error) { - if config.ReOpen && !config.Follow { - util.Fatal("cannot set ReOpen without Follow.") - } - - t := &Tail{ - Filename: filename, - Lines: make(chan *Line), - Config: config, - } - - // when Logger was not specified in config, use default logger - if t.Logger == nil { - t.Logger = log.New(os.Stderr, "", log.LstdFlags) - } - - if t.Poll { - t.watcher = watch.NewPollingFileWatcher(filename) - } else { - t.watcher = watch.NewInotifyFileWatcher(filename) - } - - if t.MustExist { - var err error - t.file, err = OpenFile(t.Filename) - if err != nil { - return nil, err - } - } - - go t.tailFileSync() - - return t, nil -} - -// Return the file's current position, like stdio's ftell(). -// But this value is not very accurate. -// it may readed one line in the chan(tail.Lines), -// so it may lost one line. -func (tail *Tail) Tell() (offset int64, err error) { - if tail.file == nil { - return - } - offset, err = tail.file.Seek(0, os.SEEK_CUR) - if err != nil { - return - } - - tail.lk.Lock() - defer tail.lk.Unlock() - if tail.reader == nil { - return - } - - offset -= int64(tail.reader.Buffered()) - return -} - -// Stop stops the tailing activity. -func (tail *Tail) Stop() error { - tail.Kill(nil) - return tail.Wait() -} - -// StopAtEOF stops tailing as soon as the end of the file is reached. -func (tail *Tail) StopAtEOF() error { - tail.Kill(errStopAtEOF) - return tail.Wait() -} - -var errStopAtEOF = errors.New("tail: stop at eof") - -func (tail *Tail) close() { - close(tail.Lines) - tail.closeFile() -} - -func (tail *Tail) closeFile() { - if tail.file != nil { - tail.file.Close() - tail.file = nil - } -} - -func (tail *Tail) reopen() error { - tail.closeFile() - for { - var err error - tail.file, err = OpenFile(tail.Filename) - if err != nil { - if os.IsNotExist(err) { - tail.Logger.Printf("Waiting for %s to appear...", tail.Filename) - if err := tail.watcher.BlockUntilExists(&tail.Tomb); err != nil { - if err == tomb.ErrDying { - return err - } - return fmt.Errorf("Failed to detect creation of %s: %s", tail.Filename, err) - } - continue - } - return fmt.Errorf("Unable to open file %s: %s", tail.Filename, err) - } - break - } - return nil -} - -func (tail *Tail) readLine() (string, error) { - tail.lk.Lock() - line, err := tail.reader.ReadString('\n') - tail.lk.Unlock() - if err != nil { - // Note ReadString "returns the data read before the error" in - // case of an error, including EOF, so we return it as is. The - // caller is expected to process it if err is EOF. - return line, err - } - - line = strings.TrimRight(line, "\n") - - return line, err -} - -func (tail *Tail) tailFileSync() { - defer tail.Done() - defer tail.close() - - if !tail.MustExist { - // deferred first open. - err := tail.reopen() - if err != nil { - if err != tomb.ErrDying { - tail.Kill(err) - } - return - } - } - - // Seek to requested location on first open of the file. - if tail.Location != nil { - _, err := tail.file.Seek(tail.Location.Offset, tail.Location.Whence) - tail.Logger.Printf("Seeked %s - %+v\n", tail.Filename, tail.Location) - if err != nil { - tail.Killf("Seek error on %s: %s", tail.Filename, err) - return - } - } - - tail.openReader() - - var offset int64 = 0 - var err error - - // Read line by line. - for { - // do not seek in named pipes - if !tail.Pipe { - // grab the position in case we need to back up in the event of a half-line - offset, err = tail.Tell() - if err != nil { - tail.Kill(err) - return - } - } - - line, err := tail.readLine() - - // Process `line` even if err is EOF. - if err == nil { - cooloff := !tail.sendLine(line) - if cooloff { - // Wait a second before seeking till the end of - // file when rate limit is reached. - msg := fmt.Sprintf( - "Too much log activity; waiting a second " + - "before resuming tailing") - tail.Lines <- &Line{msg, time.Now(), fmt.Errorf(msg)} - select { - case <-time.After(time.Second): - case <-tail.Dying(): - return - } - if err := tail.seekEnd(); err != nil { - tail.Kill(err) - return - } - } - } else if err == io.EOF { - if !tail.Follow { - if line != "" { - tail.sendLine(line) - } - return - } - - if tail.Follow && line != "" { - // this has the potential to never return the last line if - // it's not followed by a newline; seems a fair trade here - err := tail.seekTo(SeekInfo{Offset: offset, Whence: 0}) - if err != nil { - tail.Kill(err) - return - } - } - - // When EOF is reached, wait for more data to become - // available. Wait strategy is based on the `tail.watcher` - // implementation (inotify or polling). - err := tail.waitForChanges() - if err != nil { - if err != ErrStop { - tail.Kill(err) - } - return - } - } else { - // non-EOF error - tail.Killf("Error reading %s: %s", tail.Filename, err) - return - } - - select { - case <-tail.Dying(): - if tail.Err() == errStopAtEOF { - continue - } - return - default: - } - } -} - -// waitForChanges waits until the file has been appended, deleted, -// moved or truncated. When moved or deleted - the file will be -// reopened if ReOpen is true. Truncated files are always reopened. -func (tail *Tail) waitForChanges() error { - if tail.changes == nil { - pos, err := tail.file.Seek(0, os.SEEK_CUR) - if err != nil { - return err - } - tail.changes, err = tail.watcher.ChangeEvents(&tail.Tomb, pos) - if err != nil { - return err - } - } - - select { - case <-tail.changes.Modified: - return nil - case <-tail.changes.Deleted: - tail.changes = nil - if tail.ReOpen { - // XXX: we must not log from a library. - tail.Logger.Printf("Re-opening moved/deleted file %s ...", tail.Filename) - if err := tail.reopen(); err != nil { - return err - } - tail.Logger.Printf("Successfully reopened %s", tail.Filename) - tail.openReader() - return nil - } else { - tail.Logger.Printf("Stopping tail as file no longer exists: %s", tail.Filename) - return ErrStop - } - case <-tail.changes.Truncated: - // Always reopen truncated files (Follow is true) - tail.Logger.Printf("Re-opening truncated file %s ...", tail.Filename) - if err := tail.reopen(); err != nil { - return err - } - tail.Logger.Printf("Successfully reopened truncated %s", tail.Filename) - tail.openReader() - return nil - case <-tail.Dying(): - return ErrStop - } - panic("unreachable") -} - -func (tail *Tail) openReader() { - if tail.MaxLineSize > 0 { - // add 2 to account for newline characters - tail.reader = bufio.NewReaderSize(tail.file, tail.MaxLineSize+2) - } else { - tail.reader = bufio.NewReader(tail.file) - } -} - -func (tail *Tail) seekEnd() error { - return tail.seekTo(SeekInfo{Offset: 0, Whence: os.SEEK_END}) -} - -func (tail *Tail) seekTo(pos SeekInfo) error { - _, err := tail.file.Seek(pos.Offset, pos.Whence) - if err != nil { - return fmt.Errorf("Seek error on %s: %s", tail.Filename, err) - } - // Reset the read buffer whenever the file is re-seek'ed - tail.reader.Reset(tail.file) - return nil -} - -// sendLine sends the line(s) to Lines channel, splitting longer lines -// if necessary. Return false if rate limit is reached. -func (tail *Tail) sendLine(line string) bool { - now := time.Now() - lines := []string{line} - - // Split longer lines - if tail.MaxLineSize > 0 && len(line) > tail.MaxLineSize { - lines = util.PartitionString(line, tail.MaxLineSize) - } - - for _, line := range lines { - tail.Lines <- &Line{line, now, nil} - } - - if tail.Config.RateLimiter != nil { - ok := tail.Config.RateLimiter.Pour(uint16(len(lines))) - if !ok { - tail.Logger.Printf("Leaky bucket full (%v); entering 1s cooloff period.\n", - tail.Filename) - return false - } - } - - return true -} - -// Cleanup removes inotify watches added by the tail package. This function is -// meant to be invoked from a process's exit handler. Linux kernel may not -// automatically remove inotify watches after the process exits. -func (tail *Tail) Cleanup() { - watch.Cleanup(tail.Filename) -} diff --git a/vendor/github.com/hpcloud/tail/tail_posix.go b/vendor/github.com/hpcloud/tail/tail_posix.go deleted file mode 100644 index bc4dc335..00000000 --- a/vendor/github.com/hpcloud/tail/tail_posix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux darwin freebsd netbsd openbsd - -package tail - -import ( - "os" -) - -func OpenFile(name string) (file *os.File, err error) { - return os.Open(name) -} diff --git a/vendor/github.com/hpcloud/tail/tail_windows.go b/vendor/github.com/hpcloud/tail/tail_windows.go deleted file mode 100644 index ef2cfca1..00000000 --- a/vendor/github.com/hpcloud/tail/tail_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build windows - -package tail - -import ( - "github.com/hpcloud/tail/winfile" - "os" -) - -func OpenFile(name string) (file *os.File, err error) { - return winfile.OpenFile(name, os.O_RDONLY, 0) -} diff --git a/vendor/github.com/hpcloud/tail/util/util.go b/vendor/github.com/hpcloud/tail/util/util.go deleted file mode 100644 index 54151fe3..00000000 --- a/vendor/github.com/hpcloud/tail/util/util.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package util - -import ( - "fmt" - "log" - "os" - "runtime/debug" -) - -type Logger struct { - *log.Logger -} - -var LOGGER = &Logger{log.New(os.Stderr, "", log.LstdFlags)} - -// fatal is like panic except it displays only the current goroutine's stack. -func Fatal(format string, v ...interface{}) { - // https://github.com/hpcloud/log/blob/master/log.go#L45 - LOGGER.Output(2, fmt.Sprintf("FATAL -- "+format, v...)+"\n"+string(debug.Stack())) - os.Exit(1) -} - -// partitionString partitions the string into chunks of given size, -// with the last chunk of variable size. -func PartitionString(s string, chunkSize int) []string { - if chunkSize <= 0 { - panic("invalid chunkSize") - } - length := len(s) - chunks := 1 + length/chunkSize - start := 0 - end := chunkSize - parts := make([]string, 0, chunks) - for { - if end > length { - end = length - } - parts = append(parts, s[start:end]) - if end == length { - break - } - start, end = end, end+chunkSize - } - return parts -} diff --git a/vendor/github.com/hpcloud/tail/watch/filechanges.go b/vendor/github.com/hpcloud/tail/watch/filechanges.go deleted file mode 100644 index 3ce5dcec..00000000 --- a/vendor/github.com/hpcloud/tail/watch/filechanges.go +++ /dev/null @@ -1,36 +0,0 @@ -package watch - -type FileChanges struct { - Modified chan bool // Channel to get notified of modifications - Truncated chan bool // Channel to get notified of truncations - Deleted chan bool // Channel to get notified of deletions/renames -} - -func NewFileChanges() *FileChanges { - return &FileChanges{ - make(chan bool), make(chan bool), make(chan bool)} -} - -func (fc *FileChanges) NotifyModified() { - sendOnlyIfEmpty(fc.Modified) -} - -func (fc *FileChanges) NotifyTruncated() { - sendOnlyIfEmpty(fc.Truncated) -} - -func (fc *FileChanges) NotifyDeleted() { - sendOnlyIfEmpty(fc.Deleted) -} - -// sendOnlyIfEmpty sends on a bool channel only if the channel has no -// backlog to be read by other goroutines. This concurrency pattern -// can be used to notify other goroutines if and only if they are -// looking for it (i.e., subsequent notifications can be compressed -// into one). -func sendOnlyIfEmpty(ch chan bool) { - select { - case ch <- true: - default: - } -} diff --git a/vendor/github.com/hpcloud/tail/watch/inotify.go b/vendor/github.com/hpcloud/tail/watch/inotify.go deleted file mode 100644 index 4478f1e1..00000000 --- a/vendor/github.com/hpcloud/tail/watch/inotify.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package watch - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/hpcloud/tail/util" - - "gopkg.in/fsnotify.v1" - "gopkg.in/tomb.v1" -) - -// InotifyFileWatcher uses inotify to monitor file changes. -type InotifyFileWatcher struct { - Filename string - Size int64 -} - -func NewInotifyFileWatcher(filename string) *InotifyFileWatcher { - fw := &InotifyFileWatcher{filepath.Clean(filename), 0} - return fw -} - -func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { - err := WatchCreate(fw.Filename) - if err != nil { - return err - } - defer RemoveWatchCreate(fw.Filename) - - // Do a real check now as the file might have been created before - // calling `WatchFlags` above. - if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) { - // file exists, or stat returned an error. - return err - } - - events := Events(fw.Filename) - - for { - select { - case evt, ok := <-events: - if !ok { - return fmt.Errorf("inotify watcher has been closed") - } - evtName, err := filepath.Abs(evt.Name) - if err != nil { - return err - } - fwFilename, err := filepath.Abs(fw.Filename) - if err != nil { - return err - } - if evtName == fwFilename { - return nil - } - case <-t.Dying(): - return tomb.ErrDying - } - } - panic("unreachable") -} - -func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { - err := Watch(fw.Filename) - if err != nil { - return nil, err - } - - changes := NewFileChanges() - fw.Size = pos - - go func() { - defer RemoveWatch(fw.Filename) - - events := Events(fw.Filename) - - for { - prevSize := fw.Size - - var evt fsnotify.Event - var ok bool - - select { - case evt, ok = <-events: - if !ok { - return - } - case <-t.Dying(): - return - } - - switch { - case evt.Op&fsnotify.Remove == fsnotify.Remove: - fallthrough - - case evt.Op&fsnotify.Rename == fsnotify.Rename: - changes.NotifyDeleted() - return - - case evt.Op&fsnotify.Write == fsnotify.Write: - fi, err := os.Stat(fw.Filename) - if err != nil { - if os.IsNotExist(err) { - changes.NotifyDeleted() - return - } - // XXX: report this error back to the user - util.Fatal("Failed to stat file %v: %v", fw.Filename, err) - } - fw.Size = fi.Size() - - if prevSize > 0 && prevSize > fw.Size { - changes.NotifyTruncated() - } else { - changes.NotifyModified() - } - prevSize = fw.Size - } - } - }() - - return changes, nil -} diff --git a/vendor/github.com/hpcloud/tail/watch/inotify_tracker.go b/vendor/github.com/hpcloud/tail/watch/inotify_tracker.go deleted file mode 100644 index 03be4275..00000000 --- a/vendor/github.com/hpcloud/tail/watch/inotify_tracker.go +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package watch - -import ( - "log" - "os" - "path/filepath" - "sync" - "syscall" - - "github.com/hpcloud/tail/util" - - "gopkg.in/fsnotify.v1" -) - -type InotifyTracker struct { - mux sync.Mutex - watcher *fsnotify.Watcher - chans map[string]chan fsnotify.Event - done map[string]chan bool - watchNums map[string]int - watch chan *watchInfo - remove chan *watchInfo - error chan error -} - -type watchInfo struct { - op fsnotify.Op - fname string -} - -func (this *watchInfo) isCreate() bool { - return this.op == fsnotify.Create -} - -var ( - // globally shared InotifyTracker; ensures only one fsnotify.Watcher is used - shared *InotifyTracker - - // these are used to ensure the shared InotifyTracker is run exactly once - once = sync.Once{} - goRun = func() { - shared = &InotifyTracker{ - mux: sync.Mutex{}, - chans: make(map[string]chan fsnotify.Event), - done: make(map[string]chan bool), - watchNums: make(map[string]int), - watch: make(chan *watchInfo), - remove: make(chan *watchInfo), - error: make(chan error), - } - go shared.run() - } - - logger = log.New(os.Stderr, "", log.LstdFlags) -) - -// Watch signals the run goroutine to begin watching the input filename -func Watch(fname string) error { - return watch(&watchInfo{ - fname: fname, - }) -} - -// Watch create signals the run goroutine to begin watching the input filename -// if call the WatchCreate function, don't call the Cleanup, call the RemoveWatchCreate -func WatchCreate(fname string) error { - return watch(&watchInfo{ - op: fsnotify.Create, - fname: fname, - }) -} - -func watch(winfo *watchInfo) error { - // start running the shared InotifyTracker if not already running - once.Do(goRun) - - winfo.fname = filepath.Clean(winfo.fname) - shared.watch <- winfo - return <-shared.error -} - -// RemoveWatch signals the run goroutine to remove the watch for the input filename -func RemoveWatch(fname string) { - remove(&watchInfo{ - fname: fname, - }) -} - -// RemoveWatch create signals the run goroutine to remove the watch for the input filename -func RemoveWatchCreate(fname string) { - remove(&watchInfo{ - op: fsnotify.Create, - fname: fname, - }) -} - -func remove(winfo *watchInfo) { - // start running the shared InotifyTracker if not already running - once.Do(goRun) - - winfo.fname = filepath.Clean(winfo.fname) - shared.mux.Lock() - done := shared.done[winfo.fname] - if done != nil { - delete(shared.done, winfo.fname) - close(done) - } - - fname := winfo.fname - if winfo.isCreate() { - // Watch for new files to be created in the parent directory. - fname = filepath.Dir(fname) - } - shared.watchNums[fname]-- - watchNum := shared.watchNums[fname] - if watchNum == 0 { - delete(shared.watchNums, fname) - } - shared.mux.Unlock() - - // If we were the last ones to watch this file, unsubscribe from inotify. - // This needs to happen after releasing the lock because fsnotify waits - // synchronously for the kernel to acknowledge the removal of the watch - // for this file, which causes us to deadlock if we still held the lock. - if watchNum == 0 { - shared.watcher.Remove(fname) - } - shared.remove <- winfo -} - -// Events returns a channel to which FileEvents corresponding to the input filename -// will be sent. This channel will be closed when removeWatch is called on this -// filename. -func Events(fname string) <-chan fsnotify.Event { - shared.mux.Lock() - defer shared.mux.Unlock() - - return shared.chans[fname] -} - -// Cleanup removes the watch for the input filename if necessary. -func Cleanup(fname string) { - RemoveWatch(fname) -} - -// watchFlags calls fsnotify.WatchFlags for the input filename and flags, creating -// a new Watcher if the previous Watcher was closed. -func (shared *InotifyTracker) addWatch(winfo *watchInfo) error { - shared.mux.Lock() - defer shared.mux.Unlock() - - if shared.chans[winfo.fname] == nil { - shared.chans[winfo.fname] = make(chan fsnotify.Event) - shared.done[winfo.fname] = make(chan bool) - } - - fname := winfo.fname - if winfo.isCreate() { - // Watch for new files to be created in the parent directory. - fname = filepath.Dir(fname) - } - - // already in inotify watch - if shared.watchNums[fname] > 0 { - shared.watchNums[fname]++ - if winfo.isCreate() { - shared.watchNums[winfo.fname]++ - } - return nil - } - - err := shared.watcher.Add(fname) - if err == nil { - shared.watchNums[fname]++ - if winfo.isCreate() { - shared.watchNums[winfo.fname]++ - } - } - return err -} - -// removeWatch calls fsnotify.RemoveWatch for the input filename and closes the -// corresponding events channel. -func (shared *InotifyTracker) removeWatch(winfo *watchInfo) { - shared.mux.Lock() - defer shared.mux.Unlock() - - ch := shared.chans[winfo.fname] - if ch == nil { - return - } - - delete(shared.chans, winfo.fname) - close(ch) - - if !winfo.isCreate() { - return - } - - shared.watchNums[winfo.fname]-- - if shared.watchNums[winfo.fname] == 0 { - delete(shared.watchNums, winfo.fname) - } -} - -// sendEvent sends the input event to the appropriate Tail. -func (shared *InotifyTracker) sendEvent(event fsnotify.Event) { - name := filepath.Clean(event.Name) - - shared.mux.Lock() - ch := shared.chans[name] - done := shared.done[name] - shared.mux.Unlock() - - if ch != nil && done != nil { - select { - case ch <- event: - case <-done: - } - } -} - -// run starts the goroutine in which the shared struct reads events from its -// Watcher's Event channel and sends the events to the appropriate Tail. -func (shared *InotifyTracker) run() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - util.Fatal("failed to create Watcher") - } - shared.watcher = watcher - - for { - select { - case winfo := <-shared.watch: - shared.error <- shared.addWatch(winfo) - - case winfo := <-shared.remove: - shared.removeWatch(winfo) - - case event, open := <-shared.watcher.Events: - if !open { - return - } - shared.sendEvent(event) - - case err, open := <-shared.watcher.Errors: - if !open { - return - } else if err != nil { - sysErr, ok := err.(*os.SyscallError) - if !ok || sysErr.Err != syscall.EINTR { - logger.Printf("Error in Watcher Error channel: %s", err) - } - } - } - } -} diff --git a/vendor/github.com/hpcloud/tail/watch/polling.go b/vendor/github.com/hpcloud/tail/watch/polling.go deleted file mode 100644 index 49491f21..00000000 --- a/vendor/github.com/hpcloud/tail/watch/polling.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package watch - -import ( - "os" - "runtime" - "time" - - "github.com/hpcloud/tail/util" - "gopkg.in/tomb.v1" -) - -// PollingFileWatcher polls the file for changes. -type PollingFileWatcher struct { - Filename string - Size int64 -} - -func NewPollingFileWatcher(filename string) *PollingFileWatcher { - fw := &PollingFileWatcher{filename, 0} - return fw -} - -var POLL_DURATION time.Duration - -func (fw *PollingFileWatcher) BlockUntilExists(t *tomb.Tomb) error { - for { - if _, err := os.Stat(fw.Filename); err == nil { - return nil - } else if !os.IsNotExist(err) { - return err - } - select { - case <-time.After(POLL_DURATION): - continue - case <-t.Dying(): - return tomb.ErrDying - } - } - panic("unreachable") -} - -func (fw *PollingFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { - origFi, err := os.Stat(fw.Filename) - if err != nil { - return nil, err - } - - changes := NewFileChanges() - var prevModTime time.Time - - // XXX: use tomb.Tomb to cleanly manage these goroutines. replace - // the fatal (below) with tomb's Kill. - - fw.Size = pos - - go func() { - prevSize := fw.Size - for { - select { - case <-t.Dying(): - return - default: - } - - time.Sleep(POLL_DURATION) - fi, err := os.Stat(fw.Filename) - if err != nil { - // Windows cannot delete a file if a handle is still open (tail keeps one open) - // so it gives access denied to anything trying to read it until all handles are released. - if os.IsNotExist(err) || (runtime.GOOS == "windows" && os.IsPermission(err)) { - // File does not exist (has been deleted). - changes.NotifyDeleted() - return - } - - // XXX: report this error back to the user - util.Fatal("Failed to stat file %v: %v", fw.Filename, err) - } - - // File got moved/renamed? - if !os.SameFile(origFi, fi) { - changes.NotifyDeleted() - return - } - - // File got truncated? - fw.Size = fi.Size() - if prevSize > 0 && prevSize > fw.Size { - changes.NotifyTruncated() - prevSize = fw.Size - continue - } - // File got bigger? - if prevSize > 0 && prevSize < fw.Size { - changes.NotifyModified() - prevSize = fw.Size - continue - } - prevSize = fw.Size - - // File was appended to (changed)? - modTime := fi.ModTime() - if modTime != prevModTime { - prevModTime = modTime - changes.NotifyModified() - } - } - }() - - return changes, nil -} - -func init() { - POLL_DURATION = 250 * time.Millisecond -} diff --git a/vendor/github.com/hpcloud/tail/watch/watch.go b/vendor/github.com/hpcloud/tail/watch/watch.go deleted file mode 100644 index 2e1783ef..00000000 --- a/vendor/github.com/hpcloud/tail/watch/watch.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2015 HPE Software Inc. All rights reserved. -// Copyright (c) 2013 ActiveState Software Inc. All rights reserved. - -package watch - -import "gopkg.in/tomb.v1" - -// FileWatcher monitors file-level events. -type FileWatcher interface { - // BlockUntilExists blocks until the file comes into existence. - BlockUntilExists(*tomb.Tomb) error - - // ChangeEvents reports on changes to a file, be it modification, - // deletion, renames or truncations. Returned FileChanges group of - // channels will be closed, thus become unusable, after a deletion - // or truncation event. - // In order to properly report truncations, ChangeEvents requires - // the caller to pass their current offset in the file. - ChangeEvents(*tomb.Tomb, int64) (*FileChanges, error) -} diff --git a/vendor/github.com/hpcloud/tail/winfile/winfile.go b/vendor/github.com/hpcloud/tail/winfile/winfile.go deleted file mode 100644 index aa7e7bc5..00000000 --- a/vendor/github.com/hpcloud/tail/winfile/winfile.go +++ /dev/null @@ -1,92 +0,0 @@ -// +build windows - -package winfile - -import ( - "os" - "syscall" - "unsafe" -) - -// issue also described here -//https://codereview.appspot.com/8203043/ - -// https://github.com/jnwhiteh/golang/blob/master/src/pkg/syscall/syscall_windows.go#L218 -func Open(path string, mode int, perm uint32) (fd syscall.Handle, err error) { - if len(path) == 0 { - return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND - } - pathp, err := syscall.UTF16PtrFromString(path) - if err != nil { - return syscall.InvalidHandle, err - } - var access uint32 - switch mode & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) { - case syscall.O_RDONLY: - access = syscall.GENERIC_READ - case syscall.O_WRONLY: - access = syscall.GENERIC_WRITE - case syscall.O_RDWR: - access = syscall.GENERIC_READ | syscall.GENERIC_WRITE - } - if mode&syscall.O_CREAT != 0 { - access |= syscall.GENERIC_WRITE - } - if mode&syscall.O_APPEND != 0 { - access &^= syscall.GENERIC_WRITE - access |= syscall.FILE_APPEND_DATA - } - sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE) - var sa *syscall.SecurityAttributes - if mode&syscall.O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL): - createmode = syscall.CREATE_NEW - case mode&(syscall.O_CREAT|syscall.O_TRUNC) == (syscall.O_CREAT | syscall.O_TRUNC): - createmode = syscall.CREATE_ALWAYS - case mode&syscall.O_CREAT == syscall.O_CREAT: - createmode = syscall.OPEN_ALWAYS - case mode&syscall.O_TRUNC == syscall.O_TRUNC: - createmode = syscall.TRUNCATE_EXISTING - default: - createmode = syscall.OPEN_EXISTING - } - h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0) - return h, e -} - -// https://github.com/jnwhiteh/golang/blob/master/src/pkg/syscall/syscall_windows.go#L211 -func makeInheritSa() *syscall.SecurityAttributes { - var sa syscall.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -// https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_windows.go#L133 -func OpenFile(name string, flag int, perm os.FileMode) (file *os.File, err error) { - r, e := Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm)) - if e != nil { - return nil, e - } - return os.NewFile(uintptr(r), name), nil -} - -// https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_posix.go#L61 -func syscallMode(i os.FileMode) (o uint32) { - o |= uint32(i.Perm()) - if i&os.ModeSetuid != 0 { - o |= syscall.S_ISUID - } - if i&os.ModeSetgid != 0 { - o |= syscall.S_ISGID - } - if i&os.ModeSticky != 0 { - o |= syscall.S_ISVTX - } - // No mapping for Go's ModeTemporary (plan9 only). - return -} diff --git a/vendor/github.com/jefferai/jsonx/LICENSE b/vendor/github.com/jefferai/jsonx/LICENSE deleted file mode 100644 index a612ad98..00000000 --- a/vendor/github.com/jefferai/jsonx/LICENSE +++ /dev/null @@ -1,373 +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/jefferai/jsonx/README.md b/vendor/github.com/jefferai/jsonx/README.md deleted file mode 100644 index a7bb5bac..00000000 --- a/vendor/github.com/jefferai/jsonx/README.md +++ /dev/null @@ -1,12 +0,0 @@ -JSONx -======== - -[![GoDoc](https://godoc.org/github.com/jefferai/jsonx?status.svg)](https://godoc.org/github.com/jefferai/jsonx) - -A Go (Golang) library to transform an object or existing JSON bytes into -[JSONx](https://www.ibm.com/support/knowledgecenter/SS9H2Y_7.5.0/com.ibm.dp.doc/json_jsonxconversionrules.html). -Because sometimes your luck runs out. - -This follows the "standard" except for the handling of special and escaped -characters. Names and values are properly XML-escaped but there is no special -handling of values already escaped in JSON if they are valid in XML. diff --git a/vendor/github.com/jefferai/jsonx/go.mod b/vendor/github.com/jefferai/jsonx/go.mod deleted file mode 100644 index eaf7062a..00000000 --- a/vendor/github.com/jefferai/jsonx/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/jefferai/jsonx - -require github.com/Jeffail/gabs v1.1.1 diff --git a/vendor/github.com/jefferai/jsonx/go.sum b/vendor/github.com/jefferai/jsonx/go.sum deleted file mode 100644 index 4169e3d0..00000000 --- a/vendor/github.com/jefferai/jsonx/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/Jeffail/gabs v1.1.1 h1:V0uzR08Hj22EX8+8QMhyI9sX2hwRu+/RJhJUmnwda/E= -github.com/Jeffail/gabs v1.1.1/go.mod h1:6xMvQMK4k33lb7GUUpaAPh6nKMmemQeg5d4gn7/bOXc= diff --git a/vendor/github.com/jefferai/jsonx/jsonx.go b/vendor/github.com/jefferai/jsonx/jsonx.go deleted file mode 100644 index 93d24a9b..00000000 --- a/vendor/github.com/jefferai/jsonx/jsonx.go +++ /dev/null @@ -1,132 +0,0 @@ -package jsonx - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "sort" - - "github.com/Jeffail/gabs" -) - -const ( - XMLHeader = `` - Header = `` - Footer = `` -) - -// namedContainer wraps a gabs.Container to carry name information with it -type namedContainer struct { - name string - *gabs.Container -} - -// Marshal marshals the input data into JSONx. -func Marshal(input interface{}) (string, error) { - jsonBytes, err := json.Marshal(input) - if err != nil { - return "", err - } - xmlBytes, err := EncodeJSONBytes(jsonBytes) - if err != nil { - return "", err - } - return fmt.Sprintf("%s%s%s%s", XMLHeader, Header, string(xmlBytes), Footer), nil -} - -// EncodeJSONBytes encodes JSON-formatted bytes into JSONx. It is designed to -// be used for multiple entries so does not prepend the JSONx header tag or -// append the JSONx footer tag. You can use jsonx.Header and jsonx.Footer to -// easily add these when necessary. -func EncodeJSONBytes(input []byte) ([]byte, error) { - o := bytes.NewBuffer(nil) - reader := bytes.NewReader(input) - dec := json.NewDecoder(reader) - dec.UseNumber() - - cont, err := gabs.ParseJSONDecoder(dec) - if err != nil { - return nil, err - } - - if err := sortAndTransformObject(o, &namedContainer{Container: cont}); err != nil { - return nil, err - } - - return o.Bytes(), nil -} - -func transformContainer(o *bytes.Buffer, cont *namedContainer) error { - var printName string - - if cont.name != "" { - escapedNameBuf := bytes.NewBuffer(nil) - err := xml.EscapeText(escapedNameBuf, []byte(cont.name)) - if err != nil { - return err - } - printName = fmt.Sprintf(" name=\"%s\"", escapedNameBuf.String()) - } - - data := cont.Data() - switch data.(type) { - case nil: - o.WriteString(fmt.Sprintf("", printName)) - - case bool: - o.WriteString(fmt.Sprintf("%t", printName, data)) - - case json.Number: - o.WriteString(fmt.Sprintf("%v", printName, data)) - - case string: - o.WriteString(fmt.Sprintf("%v", printName, data)) - - case []interface{}: - o.WriteString(fmt.Sprintf("", printName)) - arrayChildren, err := cont.Children() - if err != nil { - return err - } - for _, child := range arrayChildren { - if err := transformContainer(o, &namedContainer{Container: child}); err != nil { - return err - } - } - o.WriteString("") - - case map[string]interface{}: - o.WriteString(fmt.Sprintf("", printName)) - - if err := sortAndTransformObject(o, cont); err != nil { - return err - } - - o.WriteString("") - } - - return nil -} - -// sortAndTransformObject sorts object keys to make the output predictable so -// the package can be tested; logic is here to prevent code duplication -func sortAndTransformObject(o *bytes.Buffer, cont *namedContainer) error { - objectChildren, err := cont.ChildrenMap() - if err != nil { - return err - } - - sortedNames := make([]string, 0, len(objectChildren)) - for name, _ := range objectChildren { - sortedNames = append(sortedNames, name) - } - sort.Strings(sortedNames) - for _, name := range sortedNames { - if err := transformContainer(o, &namedContainer{name: name, Container: objectChildren[name]}); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/keybase/go-crypto/AUTHORS b/vendor/github.com/keybase/go-crypto/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/vendor/github.com/keybase/go-crypto/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/keybase/go-crypto/CONTRIBUTORS b/vendor/github.com/keybase/go-crypto/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/vendor/github.com/keybase/go-crypto/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/keybase/go-crypto/LICENSE b/vendor/github.com/keybase/go-crypto/LICENSE deleted file mode 100644 index 6a66aea5..00000000 --- a/vendor/github.com/keybase/go-crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/keybase/go-crypto/PATENTS b/vendor/github.com/keybase/go-crypto/PATENTS deleted file mode 100644 index 73309904..00000000 --- a/vendor/github.com/keybase/go-crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/github.com/keybase/go-crypto/brainpool/brainpool.go b/vendor/github.com/keybase/go-crypto/brainpool/brainpool.go deleted file mode 100644 index 77fb8b9a..00000000 --- a/vendor/github.com/keybase/go-crypto/brainpool/brainpool.go +++ /dev/null @@ -1,134 +0,0 @@ -// Package brainpool implements Brainpool elliptic curves. -// Implementation of rcurves is from github.com/ebfe/brainpool -// Note that these curves are implemented with naive, non-constant time operations -// and are likely not suitable for enviroments where timing attacks are a concern. -package brainpool - -import ( - "crypto/elliptic" - "math/big" - "sync" -) - -var ( - once sync.Once - p256t1, p384t1, p512t1 *elliptic.CurveParams - p256r1, p384r1, p512r1 *rcurve -) - -func initAll() { - initP256t1() - initP384t1() - initP512t1() - initP256r1() - initP384r1() - initP512r1() -} - -func initP256t1() { - p256t1 = &elliptic.CurveParams{Name: "brainpoolP256t1"} - p256t1.P, _ = new(big.Int).SetString("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16) - p256t1.N, _ = new(big.Int).SetString("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16) - p256t1.B, _ = new(big.Int).SetString("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16) - p256t1.Gx, _ = new(big.Int).SetString("A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F4", 16) - p256t1.Gy, _ = new(big.Int).SetString("2D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE", 16) - p256t1.BitSize = 256 -} - -func initP256r1() { - twisted := p256t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP256r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", 16) - params.Gy, _ = new(big.Int).SetString("547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", 16) - z, _ := new(big.Int).SetString("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0", 16) - p256r1 = newrcurve(twisted, params, z) -} - -func initP384t1() { - p384t1 = &elliptic.CurveParams{Name: "brainpoolP384t1"} - p384t1.P, _ = new(big.Int).SetString("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16) - p384t1.N, _ = new(big.Int).SetString("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16) - p384t1.B, _ = new(big.Int).SetString("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16) - p384t1.Gx, _ = new(big.Int).SetString("18DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC", 16) - p384t1.Gy, _ = new(big.Int).SetString("25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928", 16) - p384t1.BitSize = 384 -} - -func initP384r1() { - twisted := p384t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP384r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", 16) - params.Gy, _ = new(big.Int).SetString("8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", 16) - z, _ := new(big.Int).SetString("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C", 16) - p384r1 = newrcurve(twisted, params, z) -} - -func initP512t1() { - p512t1 = &elliptic.CurveParams{Name: "brainpoolP512t1"} - p512t1.P, _ = new(big.Int).SetString("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16) - p512t1.N, _ = new(big.Int).SetString("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16) - p512t1.B, _ = new(big.Int).SetString("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16) - p512t1.Gx, _ = new(big.Int).SetString("640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA", 16) - p512t1.Gy, _ = new(big.Int).SetString("5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332", 16) - p512t1.BitSize = 512 -} - -func initP512r1() { - twisted := p512t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP512r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", 16) - params.Gy, _ = new(big.Int).SetString("7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", 16) - z, _ := new(big.Int).SetString("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB", 16) - p512r1 = newrcurve(twisted, params, z) -} - -// P256t1 returns a Curve which implements Brainpool P256t1 (see RFC 5639, section 3.4) -func P256t1() elliptic.Curve { - once.Do(initAll) - return p256t1 -} - -// P256r1 returns a Curve which implements Brainpool P256r1 (see RFC 5639, section 3.4) -func P256r1() elliptic.Curve { - once.Do(initAll) - return p256r1 -} - -// P384t1 returns a Curve which implements Brainpool P384t1 (see RFC 5639, section 3.6) -func P384t1() elliptic.Curve { - once.Do(initAll) - return p384t1 -} - -// P384r1 returns a Curve which implements Brainpool P384r1 (see RFC 5639, section 3.6) -func P384r1() elliptic.Curve { - once.Do(initAll) - return p384r1 -} - -// P512t1 returns a Curve which implements Brainpool P512t1 (see RFC 5639, section 3.7) -func P512t1() elliptic.Curve { - once.Do(initAll) - return p512t1 -} - -// P512r1 returns a Curve which implements Brainpool P512r1 (see RFC 5639, section 3.7) -func P512r1() elliptic.Curve { - once.Do(initAll) - return p512r1 -} diff --git a/vendor/github.com/keybase/go-crypto/brainpool/rcurve.go b/vendor/github.com/keybase/go-crypto/brainpool/rcurve.go deleted file mode 100644 index 7e291d6a..00000000 --- a/vendor/github.com/keybase/go-crypto/brainpool/rcurve.go +++ /dev/null @@ -1,83 +0,0 @@ -package brainpool - -import ( - "crypto/elliptic" - "math/big" -) - -var _ elliptic.Curve = (*rcurve)(nil) - -type rcurve struct { - twisted elliptic.Curve - params *elliptic.CurveParams - z *big.Int - zinv *big.Int - z2 *big.Int - z3 *big.Int - zinv2 *big.Int - zinv3 *big.Int -} - -var ( - two = big.NewInt(2) - three = big.NewInt(3) -) - -func newrcurve(twisted elliptic.Curve, params *elliptic.CurveParams, z *big.Int) *rcurve { - zinv := new(big.Int).ModInverse(z, params.P) - return &rcurve{ - twisted: twisted, - params: params, - z: z, - zinv: zinv, - z2: new(big.Int).Exp(z, two, params.P), - z3: new(big.Int).Exp(z, three, params.P), - zinv2: new(big.Int).Exp(zinv, two, params.P), - zinv3: new(big.Int).Exp(zinv, three, params.P), - } -} - -func (curve *rcurve) toTwisted(x, y *big.Int) (*big.Int, *big.Int) { - var tx, ty big.Int - tx.Mul(x, curve.z2) - tx.Mod(&tx, curve.params.P) - ty.Mul(y, curve.z3) - ty.Mod(&ty, curve.params.P) - return &tx, &ty -} - -func (curve *rcurve) fromTwisted(tx, ty *big.Int) (*big.Int, *big.Int) { - var x, y big.Int - x.Mul(tx, curve.zinv2) - x.Mod(&x, curve.params.P) - y.Mul(ty, curve.zinv3) - y.Mod(&y, curve.params.P) - return &x, &y -} - -func (curve *rcurve) Params() *elliptic.CurveParams { - return curve.params -} - -func (curve *rcurve) IsOnCurve(x, y *big.Int) bool { - return curve.twisted.IsOnCurve(curve.toTwisted(x, y)) -} - -func (curve *rcurve) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) { - tx1, ty1 := curve.toTwisted(x1, y1) - tx2, ty2 := curve.toTwisted(x2, y2) - return curve.fromTwisted(curve.twisted.Add(tx1, ty1, tx2, ty2)) -} - -func (curve *rcurve) Double(x1, y1 *big.Int) (x, y *big.Int) { - return curve.fromTwisted(curve.twisted.Double(curve.toTwisted(x1, y1))) -} - -func (curve *rcurve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) { - tx1, ty1 := curve.toTwisted(x1, y1) - return curve.fromTwisted(curve.twisted.ScalarMult(tx1, ty1, scalar)) -} - -func (curve *rcurve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { - return curve.fromTwisted(curve.twisted.ScalarBaseMult(scalar)) -} diff --git a/vendor/github.com/keybase/go-crypto/cast5/cast5.go b/vendor/github.com/keybase/go-crypto/cast5/cast5.go deleted file mode 100644 index e0207352..00000000 --- a/vendor/github.com/keybase/go-crypto/cast5/cast5.go +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright 2010 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 cast5 implements CAST5, as defined in RFC 2144. CAST5 is a common -// OpenPGP cipher. -package cast5 // import "github.com/keybase/go-crypto/cast5" - -import "errors" - -const BlockSize = 8 -const KeySize = 16 - -type Cipher struct { - masking [16]uint32 - rotate [16]uint8 -} - -func NewCipher(key []byte) (c *Cipher, err error) { - if len(key) != KeySize { - return nil, errors.New("CAST5: keys must be 16 bytes") - } - - c = new(Cipher) - c.keySchedule(key) - return -} - -func (c *Cipher) BlockSize() int { - return BlockSize -} - -func (c *Cipher) Encrypt(dst, src []byte) { - l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) - r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) - - l, r = r, l^f1(r, c.masking[0], c.rotate[0]) - l, r = r, l^f2(r, c.masking[1], c.rotate[1]) - l, r = r, l^f3(r, c.masking[2], c.rotate[2]) - l, r = r, l^f1(r, c.masking[3], c.rotate[3]) - - l, r = r, l^f2(r, c.masking[4], c.rotate[4]) - l, r = r, l^f3(r, c.masking[5], c.rotate[5]) - l, r = r, l^f1(r, c.masking[6], c.rotate[6]) - l, r = r, l^f2(r, c.masking[7], c.rotate[7]) - - l, r = r, l^f3(r, c.masking[8], c.rotate[8]) - l, r = r, l^f1(r, c.masking[9], c.rotate[9]) - l, r = r, l^f2(r, c.masking[10], c.rotate[10]) - l, r = r, l^f3(r, c.masking[11], c.rotate[11]) - - l, r = r, l^f1(r, c.masking[12], c.rotate[12]) - l, r = r, l^f2(r, c.masking[13], c.rotate[13]) - l, r = r, l^f3(r, c.masking[14], c.rotate[14]) - l, r = r, l^f1(r, c.masking[15], c.rotate[15]) - - dst[0] = uint8(r >> 24) - dst[1] = uint8(r >> 16) - dst[2] = uint8(r >> 8) - dst[3] = uint8(r) - dst[4] = uint8(l >> 24) - dst[5] = uint8(l >> 16) - dst[6] = uint8(l >> 8) - dst[7] = uint8(l) -} - -func (c *Cipher) Decrypt(dst, src []byte) { - l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) - r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) - - l, r = r, l^f1(r, c.masking[15], c.rotate[15]) - l, r = r, l^f3(r, c.masking[14], c.rotate[14]) - l, r = r, l^f2(r, c.masking[13], c.rotate[13]) - l, r = r, l^f1(r, c.masking[12], c.rotate[12]) - - l, r = r, l^f3(r, c.masking[11], c.rotate[11]) - l, r = r, l^f2(r, c.masking[10], c.rotate[10]) - l, r = r, l^f1(r, c.masking[9], c.rotate[9]) - l, r = r, l^f3(r, c.masking[8], c.rotate[8]) - - l, r = r, l^f2(r, c.masking[7], c.rotate[7]) - l, r = r, l^f1(r, c.masking[6], c.rotate[6]) - l, r = r, l^f3(r, c.masking[5], c.rotate[5]) - l, r = r, l^f2(r, c.masking[4], c.rotate[4]) - - l, r = r, l^f1(r, c.masking[3], c.rotate[3]) - l, r = r, l^f3(r, c.masking[2], c.rotate[2]) - l, r = r, l^f2(r, c.masking[1], c.rotate[1]) - l, r = r, l^f1(r, c.masking[0], c.rotate[0]) - - dst[0] = uint8(r >> 24) - dst[1] = uint8(r >> 16) - dst[2] = uint8(r >> 8) - dst[3] = uint8(r) - dst[4] = uint8(l >> 24) - dst[5] = uint8(l >> 16) - dst[6] = uint8(l >> 8) - dst[7] = uint8(l) -} - -type keyScheduleA [4][7]uint8 -type keyScheduleB [4][5]uint8 - -// keyScheduleRound contains the magic values for a round of the key schedule. -// The keyScheduleA deals with the lines like: -// z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8] -// Conceptually, both x and z are in the same array, x first. The first -// element describes which word of this array gets written to and the -// second, which word gets read. So, for the line above, it's "4, 0", because -// it's writing to the first word of z, which, being after x, is word 4, and -// reading from the first word of x: word 0. -// -// Next are the indexes into the S-boxes. Now the array is treated as bytes. So -// "xD" is 0xd. The first byte of z is written as "16 + 0", just to be clear -// that it's z that we're indexing. -// -// keyScheduleB deals with lines like: -// K1 = S5[z8] ^ S6[z9] ^ S7[z7] ^ S8[z6] ^ S5[z2] -// "K1" is ignored because key words are always written in order. So the five -// elements are the S-box indexes. They use the same form as in keyScheduleA, -// above. - -type keyScheduleRound struct{} -type keySchedule []keyScheduleRound - -var schedule = []struct { - a keyScheduleA - b keyScheduleB -}{ - { - keyScheduleA{ - {4, 0, 0xd, 0xf, 0xc, 0xe, 0x8}, - {5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa}, - {6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9}, - {7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb}, - }, - keyScheduleB{ - {16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2}, - {16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6}, - {16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9}, - {16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc}, - }, - }, - { - keyScheduleA{ - {0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0}, - {1, 4, 0, 2, 1, 3, 16 + 2}, - {2, 5, 7, 6, 5, 4, 16 + 1}, - {3, 7, 0xa, 9, 0xb, 8, 16 + 3}, - }, - keyScheduleB{ - {3, 2, 0xc, 0xd, 8}, - {1, 0, 0xe, 0xf, 0xd}, - {7, 6, 8, 9, 3}, - {5, 4, 0xa, 0xb, 7}, - }, - }, - { - keyScheduleA{ - {4, 0, 0xd, 0xf, 0xc, 0xe, 8}, - {5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa}, - {6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9}, - {7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb}, - }, - keyScheduleB{ - {16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9}, - {16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc}, - {16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2}, - {16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6}, - }, - }, - { - keyScheduleA{ - {0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0}, - {1, 4, 0, 2, 1, 3, 16 + 2}, - {2, 5, 7, 6, 5, 4, 16 + 1}, - {3, 7, 0xa, 9, 0xb, 8, 16 + 3}, - }, - keyScheduleB{ - {8, 9, 7, 6, 3}, - {0xa, 0xb, 5, 4, 7}, - {0xc, 0xd, 3, 2, 8}, - {0xe, 0xf, 1, 0, 0xd}, - }, - }, -} - -func (c *Cipher) keySchedule(in []byte) { - var t [8]uint32 - var k [32]uint32 - - for i := 0; i < 4; i++ { - j := i * 4 - t[i] = uint32(in[j])<<24 | uint32(in[j+1])<<16 | uint32(in[j+2])<<8 | uint32(in[j+3]) - } - - x := []byte{6, 7, 4, 5} - ki := 0 - - for half := 0; half < 2; half++ { - for _, round := range schedule { - for j := 0; j < 4; j++ { - var a [7]uint8 - copy(a[:], round.a[j][:]) - w := t[a[1]] - w ^= sBox[4][(t[a[2]>>2]>>(24-8*(a[2]&3)))&0xff] - w ^= sBox[5][(t[a[3]>>2]>>(24-8*(a[3]&3)))&0xff] - w ^= sBox[6][(t[a[4]>>2]>>(24-8*(a[4]&3)))&0xff] - w ^= sBox[7][(t[a[5]>>2]>>(24-8*(a[5]&3)))&0xff] - w ^= sBox[x[j]][(t[a[6]>>2]>>(24-8*(a[6]&3)))&0xff] - t[a[0]] = w - } - - for j := 0; j < 4; j++ { - var b [5]uint8 - copy(b[:], round.b[j][:]) - w := sBox[4][(t[b[0]>>2]>>(24-8*(b[0]&3)))&0xff] - w ^= sBox[5][(t[b[1]>>2]>>(24-8*(b[1]&3)))&0xff] - w ^= sBox[6][(t[b[2]>>2]>>(24-8*(b[2]&3)))&0xff] - w ^= sBox[7][(t[b[3]>>2]>>(24-8*(b[3]&3)))&0xff] - w ^= sBox[4+j][(t[b[4]>>2]>>(24-8*(b[4]&3)))&0xff] - k[ki] = w - ki++ - } - } - } - - for i := 0; i < 16; i++ { - c.masking[i] = k[i] - c.rotate[i] = uint8(k[16+i] & 0x1f) - } -} - -// These are the three 'f' functions. See RFC 2144, section 2.2. -func f1(d, m uint32, r uint8) uint32 { - t := m + d - I := (t << r) | (t >> (32 - r)) - return ((sBox[0][I>>24] ^ sBox[1][(I>>16)&0xff]) - sBox[2][(I>>8)&0xff]) + sBox[3][I&0xff] -} - -func f2(d, m uint32, r uint8) uint32 { - t := m ^ d - I := (t << r) | (t >> (32 - r)) - return ((sBox[0][I>>24] - sBox[1][(I>>16)&0xff]) + sBox[2][(I>>8)&0xff]) ^ sBox[3][I&0xff] -} - -func f3(d, m uint32, r uint8) uint32 { - t := m - d - I := (t << r) | (t >> (32 - r)) - return ((sBox[0][I>>24] + sBox[1][(I>>16)&0xff]) ^ sBox[2][(I>>8)&0xff]) - sBox[3][I&0xff] -} - -var sBox = [8][256]uint32{ - { - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf, - }, - { - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1, - }, - { - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783, - }, - { - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2, - }, - { - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4, - }, - { - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, - }, - { - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3, - }, - { - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e, - }, -} diff --git a/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.h b/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.h deleted file mode 100644 index b3f74162..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.h +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -#define REDMASK51 0x0007FFFFFFFFFFFF diff --git a/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.s deleted file mode 100644 index ee7b4bd5..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/const_amd64.s +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// These constants cannot be encoded in non-MOVQ immediates. -// We access them directly from memory instead. - -DATA ·_121666_213(SB)/8, $996687872 -GLOBL ·_121666_213(SB), 8, $8 - -DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA -GLOBL ·_2P0(SB), 8, $8 - -DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE -GLOBL ·_2P1234(SB), 8, $8 diff --git a/vendor/github.com/keybase/go-crypto/curve25519/cswap_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/cswap_amd64.s deleted file mode 100644 index cd793a5b..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/cswap_amd64.s +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -// func cswap(inout *[4][5]uint64, v uint64) -TEXT ·cswap(SB),7,$0 - MOVQ inout+0(FP),DI - MOVQ v+8(FP),SI - - SUBQ $1, SI - NOTQ SI - MOVQ SI, X15 - PSHUFD $0x44, X15, X15 - - MOVOU 0(DI), X0 - MOVOU 16(DI), X2 - MOVOU 32(DI), X4 - MOVOU 48(DI), X6 - MOVOU 64(DI), X8 - MOVOU 80(DI), X1 - MOVOU 96(DI), X3 - MOVOU 112(DI), X5 - MOVOU 128(DI), X7 - MOVOU 144(DI), X9 - - MOVO X1, X10 - MOVO X3, X11 - MOVO X5, X12 - MOVO X7, X13 - MOVO X9, X14 - - PXOR X0, X10 - PXOR X2, X11 - PXOR X4, X12 - PXOR X6, X13 - PXOR X8, X14 - PAND X15, X10 - PAND X15, X11 - PAND X15, X12 - PAND X15, X13 - PAND X15, X14 - PXOR X10, X0 - PXOR X10, X1 - PXOR X11, X2 - PXOR X11, X3 - PXOR X12, X4 - PXOR X12, X5 - PXOR X13, X6 - PXOR X13, X7 - PXOR X14, X8 - PXOR X14, X9 - - MOVOU X0, 0(DI) - MOVOU X2, 16(DI) - MOVOU X4, 32(DI) - MOVOU X6, 48(DI) - MOVOU X8, 64(DI) - MOVOU X1, 80(DI) - MOVOU X3, 96(DI) - MOVOU X5, 112(DI) - MOVOU X7, 128(DI) - MOVOU X9, 144(DI) - RET diff --git a/vendor/github.com/keybase/go-crypto/curve25519/curve25519.go b/vendor/github.com/keybase/go-crypto/curve25519/curve25519.go deleted file mode 100644 index cb8fbc57..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/curve25519.go +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright 2013 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. - -// We have an implementation in amd64 assembly so this code is only run on -// non-amd64 platforms. The amd64 assembly does not support gccgo. -// +build !amd64 gccgo appengine - -package curve25519 - -import ( - "encoding/binary" -) - -// This code is a port of the public domain, "ref10" implementation of -// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. - -// fieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type fieldElement [10]int32 - -func feZero(fe *fieldElement) { - for i := range fe { - fe[i] = 0 - } -} - -func feOne(fe *fieldElement) { - feZero(fe) - fe[0] = 1 -} - -func feAdd(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] + b[i] - } -} - -func feSub(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] - b[i] - } -} - -func feCopy(dst, src *fieldElement) { - for i := range dst { - dst[i] = src[i] - } -} - -// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func feCSwap(f, g *fieldElement, b int32) { - b = -b - for i := range f { - t := b & (f[i] ^ g[i]) - f[i] ^= t - g[i] ^= t - } -} - -// load3 reads a 24-bit, little-endian value from in. -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -// load4 reads a 32-bit, little-endian value from in. -func load4(in []byte) int64 { - return int64(binary.LittleEndian.Uint32(in)) -} - -func feFromBytes(dst *fieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := load3(src[29:]) << 2 - - var carry [10]int64 - carry[9] = (h9 + 1<<24) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + 1<<24) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + 1<<24) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + 1<<24) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + 1<<24) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + 1<<25) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + 1<<25) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + 1<<25) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + 1<<25) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + 1<<25) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - dst[0] = int32(h0) - dst[1] = int32(h1) - dst[2] = int32(h2) - dst[3] = int32(h3) - dst[4] = int32(h4) - dst[5] = int32(h5) - dst[6] = int32(h6) - dst[7] = int32(h7) - dst[8] = int32(h8) - dst[9] = int32(h9) -} - -// feToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -// feMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs can squeeze carries into int32. -func feMul(h, f, g *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - g0 := g[0] - g1 := g[1] - g2 := g[2] - g3 := g[3] - g4 := g[4] - g5 := g[5] - g6 := g[6] - g7 := g[7] - g8 := g[8] - g9 := g[9] - g1_19 := 19 * g1 // 1.4*2^29 - g2_19 := 19 * g2 // 1.4*2^30; still ok - g3_19 := 19 * g3 - g4_19 := 19 * g4 - g5_19 := 19 * g5 - g6_19 := 19 * g6 - g7_19 := 19 * g7 - g8_19 := 19 * g8 - g9_19 := 19 * g9 - f1_2 := 2 * f1 - f3_2 := 2 * f3 - f5_2 := 2 * f5 - f7_2 := 2 * f7 - f9_2 := 2 * f9 - f0g0 := int64(f0) * int64(g0) - f0g1 := int64(f0) * int64(g1) - f0g2 := int64(f0) * int64(g2) - f0g3 := int64(f0) * int64(g3) - f0g4 := int64(f0) * int64(g4) - f0g5 := int64(f0) * int64(g5) - f0g6 := int64(f0) * int64(g6) - f0g7 := int64(f0) * int64(g7) - f0g8 := int64(f0) * int64(g8) - f0g9 := int64(f0) * int64(g9) - f1g0 := int64(f1) * int64(g0) - f1g1_2 := int64(f1_2) * int64(g1) - f1g2 := int64(f1) * int64(g2) - f1g3_2 := int64(f1_2) * int64(g3) - f1g4 := int64(f1) * int64(g4) - f1g5_2 := int64(f1_2) * int64(g5) - f1g6 := int64(f1) * int64(g6) - f1g7_2 := int64(f1_2) * int64(g7) - f1g8 := int64(f1) * int64(g8) - f1g9_38 := int64(f1_2) * int64(g9_19) - f2g0 := int64(f2) * int64(g0) - f2g1 := int64(f2) * int64(g1) - f2g2 := int64(f2) * int64(g2) - f2g3 := int64(f2) * int64(g3) - f2g4 := int64(f2) * int64(g4) - f2g5 := int64(f2) * int64(g5) - f2g6 := int64(f2) * int64(g6) - f2g7 := int64(f2) * int64(g7) - f2g8_19 := int64(f2) * int64(g8_19) - f2g9_19 := int64(f2) * int64(g9_19) - f3g0 := int64(f3) * int64(g0) - f3g1_2 := int64(f3_2) * int64(g1) - f3g2 := int64(f3) * int64(g2) - f3g3_2 := int64(f3_2) * int64(g3) - f3g4 := int64(f3) * int64(g4) - f3g5_2 := int64(f3_2) * int64(g5) - f3g6 := int64(f3) * int64(g6) - f3g7_38 := int64(f3_2) * int64(g7_19) - f3g8_19 := int64(f3) * int64(g8_19) - f3g9_38 := int64(f3_2) * int64(g9_19) - f4g0 := int64(f4) * int64(g0) - f4g1 := int64(f4) * int64(g1) - f4g2 := int64(f4) * int64(g2) - f4g3 := int64(f4) * int64(g3) - f4g4 := int64(f4) * int64(g4) - f4g5 := int64(f4) * int64(g5) - f4g6_19 := int64(f4) * int64(g6_19) - f4g7_19 := int64(f4) * int64(g7_19) - f4g8_19 := int64(f4) * int64(g8_19) - f4g9_19 := int64(f4) * int64(g9_19) - f5g0 := int64(f5) * int64(g0) - f5g1_2 := int64(f5_2) * int64(g1) - f5g2 := int64(f5) * int64(g2) - f5g3_2 := int64(f5_2) * int64(g3) - f5g4 := int64(f5) * int64(g4) - f5g5_38 := int64(f5_2) * int64(g5_19) - f5g6_19 := int64(f5) * int64(g6_19) - f5g7_38 := int64(f5_2) * int64(g7_19) - f5g8_19 := int64(f5) * int64(g8_19) - f5g9_38 := int64(f5_2) * int64(g9_19) - f6g0 := int64(f6) * int64(g0) - f6g1 := int64(f6) * int64(g1) - f6g2 := int64(f6) * int64(g2) - f6g3 := int64(f6) * int64(g3) - f6g4_19 := int64(f6) * int64(g4_19) - f6g5_19 := int64(f6) * int64(g5_19) - f6g6_19 := int64(f6) * int64(g6_19) - f6g7_19 := int64(f6) * int64(g7_19) - f6g8_19 := int64(f6) * int64(g8_19) - f6g9_19 := int64(f6) * int64(g9_19) - f7g0 := int64(f7) * int64(g0) - f7g1_2 := int64(f7_2) * int64(g1) - f7g2 := int64(f7) * int64(g2) - f7g3_38 := int64(f7_2) * int64(g3_19) - f7g4_19 := int64(f7) * int64(g4_19) - f7g5_38 := int64(f7_2) * int64(g5_19) - f7g6_19 := int64(f7) * int64(g6_19) - f7g7_38 := int64(f7_2) * int64(g7_19) - f7g8_19 := int64(f7) * int64(g8_19) - f7g9_38 := int64(f7_2) * int64(g9_19) - f8g0 := int64(f8) * int64(g0) - f8g1 := int64(f8) * int64(g1) - f8g2_19 := int64(f8) * int64(g2_19) - f8g3_19 := int64(f8) * int64(g3_19) - f8g4_19 := int64(f8) * int64(g4_19) - f8g5_19 := int64(f8) * int64(g5_19) - f8g6_19 := int64(f8) * int64(g6_19) - f8g7_19 := int64(f8) * int64(g7_19) - f8g8_19 := int64(f8) * int64(g8_19) - f8g9_19 := int64(f8) * int64(g9_19) - f9g0 := int64(f9) * int64(g0) - f9g1_38 := int64(f9_2) * int64(g1_19) - f9g2_19 := int64(f9) * int64(g2_19) - f9g3_38 := int64(f9_2) * int64(g3_19) - f9g4_19 := int64(f9) * int64(g4_19) - f9g5_38 := int64(f9_2) * int64(g5_19) - f9g6_19 := int64(f9) * int64(g6_19) - f9g7_38 := int64(f9_2) * int64(g7_19) - f9g8_19 := int64(f9) * int64(g8_19) - f9g9_38 := int64(f9_2) * int64(g9_19) - h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 - h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 - h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 - h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 - h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 - h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 - h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 - h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 - h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 - h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 - var carry [10]int64 - - // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - // |h0| <= 2^25 - // |h4| <= 2^25 - // |h1| <= 1.51*2^58 - // |h5| <= 1.51*2^58 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - // |h1| <= 2^24; from now on fits into int32 - // |h5| <= 2^24; from now on fits into int32 - // |h2| <= 1.21*2^59 - // |h6| <= 1.21*2^59 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - // |h2| <= 2^25; from now on fits into int32 unchanged - // |h6| <= 2^25; from now on fits into int32 unchanged - // |h3| <= 1.51*2^58 - // |h7| <= 1.51*2^58 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - // |h3| <= 2^24; from now on fits into int32 unchanged - // |h7| <= 2^24; from now on fits into int32 unchanged - // |h4| <= 1.52*2^33 - // |h8| <= 1.52*2^33 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - // |h4| <= 2^25; from now on fits into int32 unchanged - // |h8| <= 2^25; from now on fits into int32 unchanged - // |h5| <= 1.01*2^24 - // |h9| <= 1.51*2^58 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - // |h9| <= 2^24; from now on fits into int32 unchanged - // |h0| <= 1.8*2^37 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - // |h0| <= 2^25; from now on fits into int32 unchanged - // |h1| <= 1.01*2^24 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feSquare(h, f *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feMul121666 calculates h = f * 121666. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feMul121666(h, f *fieldElement) { - h0 := int64(f[0]) * 121666 - h1 := int64(f[1]) * 121666 - h2 := int64(f[2]) * 121666 - h3 := int64(f[3]) * 121666 - h4 := int64(f[4]) * 121666 - h5 := int64(f[5]) * 121666 - h6 := int64(f[6]) * 121666 - h7 := int64(f[7]) * 121666 - h8 := int64(f[8]) * 121666 - h9 := int64(f[9]) * 121666 - var carry [10]int64 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feInvert sets out = z^-1. -func feInvert(out, z *fieldElement) { - var t0, t1, t2, t3 fieldElement - var i int - - feSquare(&t0, z) - for i = 1; i < 1; i++ { - feSquare(&t0, &t0) - } - feSquare(&t1, &t0) - for i = 1; i < 2; i++ { - feSquare(&t1, &t1) - } - feMul(&t1, z, &t1) - feMul(&t0, &t0, &t1) - feSquare(&t2, &t0) - for i = 1; i < 1; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t1, &t2) - feSquare(&t2, &t1) - for i = 1; i < 5; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 20; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 100; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t1, &t1) - for i = 1; i < 5; i++ { - feSquare(&t1, &t1) - } - feMul(out, &t1, &t0) -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - - copy(e[:], in[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement - feFromBytes(&x1, base) - feOne(&x2) - feCopy(&x3, &x1) - feOne(&z3) - - swap := int32(0) - for pos := 254; pos >= 0; pos-- { - b := e[pos/8] >> uint(pos&7) - b &= 1 - swap ^= int32(b) - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - swap = int32(b) - - feSub(&tmp0, &x3, &z3) - feSub(&tmp1, &x2, &z2) - feAdd(&x2, &x2, &z2) - feAdd(&z2, &x3, &z3) - feMul(&z3, &tmp0, &x2) - feMul(&z2, &z2, &tmp1) - feSquare(&tmp0, &tmp1) - feSquare(&tmp1, &x2) - feAdd(&x3, &z3, &z2) - feSub(&z2, &z3, &z2) - feMul(&x2, &tmp1, &tmp0) - feSub(&tmp1, &tmp1, &tmp0) - feSquare(&z2, &z2) - feMul121666(&z3, &tmp1) - feSquare(&x3, &x3) - feAdd(&tmp0, &tmp0, &z3) - feMul(&z3, &x1, &z2) - feMul(&z2, &tmp1, &tmp0) - } - - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - - feInvert(&z2, &z2) - feMul(&x2, &x2, &z2) - feToBytes(out, &x2) -} diff --git a/vendor/github.com/keybase/go-crypto/curve25519/curve_impl.go b/vendor/github.com/keybase/go-crypto/curve25519/curve_impl.go deleted file mode 100644 index a3d3a3d9..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/curve_impl.go +++ /dev/null @@ -1,124 +0,0 @@ -package curve25519 - -import ( - "crypto/elliptic" - "math/big" - "sync" -) - -var cv25519 cv25519Curve - -type cv25519Curve struct { - *elliptic.CurveParams -} - -func copyReverse(dst []byte, src []byte) { - // Curve 25519 multiplication functions expect scalars in reverse - // order than PGP. To keep the curve25519Curve type consistent - // with other curves, we reverse it here. - for i, j := 0, len(src)-1; j >= 0 && i < len(dst); i, j = i+1, j-1 { - dst[i] = src[j] - } -} - -func copyTruncate(dst []byte, src []byte) { - lenDst, lenSrc := len(dst), len(src) - if lenDst == lenSrc { - copy(dst, src) - } else if lenDst > lenSrc { - copy(dst[lenDst-lenSrc:lenDst], src) - } else if lenDst < lenSrc { - copy(dst, src[:lenDst]) - } -} - -func (cv25519Curve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) { - // Assume y1 is 0 with cv25519. - var dst [32]byte - var x1Bytes [32]byte - var scalarBytes [32]byte - - copyTruncate(x1Bytes[:], x1.Bytes()) - copyReverse(scalarBytes[:], scalar) - - scalarMult(&dst, &scalarBytes, &x1Bytes) - - x = new(big.Int).SetBytes(dst[:]) - y = new(big.Int) - return x, y -} - -func (cv25519Curve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { - var dst [32]byte - var scalarBytes [32]byte - copyReverse(scalarBytes[:], scalar[:32]) - scalarMult(&dst, &scalarBytes, &basePoint) - x = new(big.Int).SetBytes(dst[:]) - y = new(big.Int) - return x, y -} - -func (cv25519Curve) IsOnCurve(bigX, bigY *big.Int) bool { - return bigY.Sign() == 0 // bigY == 0 ? -} - -// More information about 0x40 point format: -// https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-00#section-3 -// In addition to uncompressed point format described here: -// https://tools.ietf.org/html/rfc6637#section-6 - -func (cv25519Curve) MarshalType40(x, y *big.Int) []byte { - byteLen := 32 - - ret := make([]byte, 1+byteLen) - ret[0] = 0x40 - - xBytes := x.Bytes() - copyTruncate(ret[1:], xBytes) - return ret -} - -func (cv25519Curve) UnmarshalType40(data []byte) (x, y *big.Int) { - if len(data) != 1+32 { - return nil, nil - } - if data[0] != 0x40 { - return nil, nil - } - x = new(big.Int).SetBytes(data[1:]) - // Any x is a valid curve point. - return x, new(big.Int) -} - -// ToCurve25519 casts given elliptic.Curve type to Curve25519 type, or -// returns nil, false if cast was unsuccessful. -func ToCurve25519(cv elliptic.Curve) (cv25519Curve, bool) { - cv2, ok := cv.(cv25519Curve) - return cv2, ok -} - -func initCv25519() { - cv25519.CurveParams = &elliptic.CurveParams{Name: "Curve 25519"} - // Some code relies on these parameters being available for - // checking Curve coordinate length. They should not be used - // directly for any calculations. - cv25519.P, _ = new(big.Int).SetString("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed", 16) - cv25519.N, _ = new(big.Int).SetString("1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed", 16) - cv25519.Gx, _ = new(big.Int).SetString("9", 16) - cv25519.Gy, _ = new(big.Int).SetString("20ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9", 16) - cv25519.BitSize = 256 -} - -var initonce sync.Once - -// Cv25519 returns a Curve which (partially) implements Cv25519. Only -// ScalarMult and ScalarBaseMult are valid for this curve. Add and -// Double should not be used. -func Cv25519() elliptic.Curve { - initonce.Do(initCv25519) - return cv25519 -} - -func (curve cv25519Curve) Params() *elliptic.CurveParams { - return curve.CurveParams -} diff --git a/vendor/github.com/keybase/go-crypto/curve25519/doc.go b/vendor/github.com/keybase/go-crypto/curve25519/doc.go deleted file mode 100644 index 78bd9fc0..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 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 curve25519 provides an implementation of scalar multiplication on -// the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html -package curve25519 // import "github.com/keybase/go-crypto/curve25519" - -// basePoint is the x coordinate of the generator of the curve. -var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - -// ScalarMult sets dst to the product in*base where dst and base are the x -// coordinates of group points and all values are in little-endian form. -func ScalarMult(dst, in, base *[32]byte) { - scalarMult(dst, in, base) -} - -// ScalarBaseMult sets dst to the product in*base where dst and base are the x -// coordinates of group points, base is the standard generator and all values -// are in little-endian form. -func ScalarBaseMult(dst, in *[32]byte) { - ScalarMult(dst, in, &basePoint) -} diff --git a/vendor/github.com/keybase/go-crypto/curve25519/freeze_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/freeze_amd64.s deleted file mode 100644 index 39081610..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/freeze_amd64.s +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func freeze(inout *[5]uint64) -TEXT ·freeze(SB),7,$0-8 - MOVQ inout+0(FP), DI - - MOVQ 0(DI),SI - MOVQ 8(DI),DX - MOVQ 16(DI),CX - MOVQ 24(DI),R8 - MOVQ 32(DI),R9 - MOVQ $REDMASK51,AX - MOVQ AX,R10 - SUBQ $18,R10 - MOVQ $3,R11 -REDUCELOOP: - MOVQ SI,R12 - SHRQ $51,R12 - ANDQ AX,SI - ADDQ R12,DX - MOVQ DX,R12 - SHRQ $51,R12 - ANDQ AX,DX - ADDQ R12,CX - MOVQ CX,R12 - SHRQ $51,R12 - ANDQ AX,CX - ADDQ R12,R8 - MOVQ R8,R12 - SHRQ $51,R12 - ANDQ AX,R8 - ADDQ R12,R9 - MOVQ R9,R12 - SHRQ $51,R12 - ANDQ AX,R9 - IMUL3Q $19,R12,R12 - ADDQ R12,SI - SUBQ $1,R11 - JA REDUCELOOP - MOVQ $1,R12 - CMPQ R10,SI - CMOVQLT R11,R12 - CMPQ AX,DX - CMOVQNE R11,R12 - CMPQ AX,CX - CMOVQNE R11,R12 - CMPQ AX,R8 - CMOVQNE R11,R12 - CMPQ AX,R9 - CMOVQNE R11,R12 - NEGQ R12 - ANDQ R12,AX - ANDQ R12,R10 - SUBQ R10,SI - SUBQ AX,DX - SUBQ AX,CX - SUBQ AX,R8 - SUBQ AX,R9 - MOVQ SI,0(DI) - MOVQ DX,8(DI) - MOVQ CX,16(DI) - MOVQ R8,24(DI) - MOVQ R9,32(DI) - RET diff --git a/vendor/github.com/keybase/go-crypto/curve25519/ladderstep_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/ladderstep_amd64.s deleted file mode 100644 index 9e9040b2..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/ladderstep_amd64.s +++ /dev/null @@ -1,1377 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func ladderstep(inout *[5][5]uint64) -TEXT ·ladderstep(SB),0,$296-8 - MOVQ inout+0(FP),DI - - MOVQ 40(DI),SI - MOVQ 48(DI),DX - MOVQ 56(DI),CX - MOVQ 64(DI),R8 - MOVQ 72(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 80(DI),SI - ADDQ 88(DI),DX - ADDQ 96(DI),CX - ADDQ 104(DI),R8 - ADDQ 112(DI),R9 - SUBQ 80(DI),AX - SUBQ 88(DI),R10 - SUBQ 96(DI),R11 - SUBQ 104(DI),R12 - SUBQ 112(DI),R13 - MOVQ SI,0(SP) - MOVQ DX,8(SP) - MOVQ CX,16(SP) - MOVQ R8,24(SP) - MOVQ R9,32(SP) - MOVQ AX,40(SP) - MOVQ R10,48(SP) - MOVQ R11,56(SP) - MOVQ R12,64(SP) - MOVQ R13,72(SP) - MOVQ 40(SP),AX - MULQ 40(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 48(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 48(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 72(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(SP) - MOVQ R8,88(SP) - MOVQ R9,96(SP) - MOVQ AX,104(SP) - MOVQ R10,112(SP) - MOVQ 0(SP),AX - MULQ 0(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 8(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 32(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(SP) - MOVQ R8,128(SP) - MOVQ R9,136(SP) - MOVQ AX,144(SP) - MOVQ R10,152(SP) - MOVQ SI,SI - MOVQ R8,DX - MOVQ R9,CX - MOVQ AX,R8 - MOVQ R10,R9 - ADDQ ·_2P0(SB),SI - ADDQ ·_2P1234(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R8 - ADDQ ·_2P1234(SB),R9 - SUBQ 80(SP),SI - SUBQ 88(SP),DX - SUBQ 96(SP),CX - SUBQ 104(SP),R8 - SUBQ 112(SP),R9 - MOVQ SI,160(SP) - MOVQ DX,168(SP) - MOVQ CX,176(SP) - MOVQ R8,184(SP) - MOVQ R9,192(SP) - MOVQ 120(DI),SI - MOVQ 128(DI),DX - MOVQ 136(DI),CX - MOVQ 144(DI),R8 - MOVQ 152(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 160(DI),SI - ADDQ 168(DI),DX - ADDQ 176(DI),CX - ADDQ 184(DI),R8 - ADDQ 192(DI),R9 - SUBQ 160(DI),AX - SUBQ 168(DI),R10 - SUBQ 176(DI),R11 - SUBQ 184(DI),R12 - SUBQ 192(DI),R13 - MOVQ SI,200(SP) - MOVQ DX,208(SP) - MOVQ CX,216(SP) - MOVQ R8,224(SP) - MOVQ R9,232(SP) - MOVQ AX,240(SP) - MOVQ R10,248(SP) - MOVQ R11,256(SP) - MOVQ R12,264(SP) - MOVQ R13,272(SP) - MOVQ 224(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,280(SP) - MULQ 56(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 232(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,288(SP) - MULQ 48(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 40(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 200(SP),AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 200(SP),AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 200(SP),AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 208(SP),AX - MULQ 40(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 208(SP),AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),AX - MULQ 40(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 216(SP),AX - MULQ 48(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 216(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 224(SP),AX - MULQ 40(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 224(SP),AX - MULQ 48(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 280(SP),AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 280(SP),AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 232(SP),AX - MULQ 40(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 288(SP),AX - MULQ 56(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 288(SP),AX - MULQ 64(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 288(SP),AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(SP) - MOVQ R8,48(SP) - MOVQ R9,56(SP) - MOVQ AX,64(SP) - MOVQ R10,72(SP) - MOVQ 264(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,200(SP) - MULQ 16(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 272(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,208(SP) - MULQ 8(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 0(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 240(SP),AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 240(SP),AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 240(SP),AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 248(SP),AX - MULQ 0(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 248(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 248(SP),AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 248(SP),AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 248(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),AX - MULQ 0(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 256(SP),AX - MULQ 8(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 256(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 264(SP),AX - MULQ 0(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 264(SP),AX - MULQ 8(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 200(SP),AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 200(SP),AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 272(SP),AX - MULQ 0(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),AX - MULQ 16(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 24(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,DX - MOVQ R8,CX - MOVQ R9,R11 - MOVQ AX,R12 - MOVQ R10,R13 - ADDQ ·_2P0(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 40(SP),SI - ADDQ 48(SP),R8 - ADDQ 56(SP),R9 - ADDQ 64(SP),AX - ADDQ 72(SP),R10 - SUBQ 40(SP),DX - SUBQ 48(SP),CX - SUBQ 56(SP),R11 - SUBQ 64(SP),R12 - SUBQ 72(SP),R13 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ DX,160(DI) - MOVQ CX,168(DI) - MOVQ R11,176(DI) - MOVQ R12,184(DI) - MOVQ R13,192(DI) - MOVQ 120(DI),AX - MULQ 120(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 128(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 136(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 144(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 152(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(DI),AX - MULQ 128(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 136(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 144(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),AX - MULQ 136(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 144(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $19,DX,AX - MULQ 144(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(DI),DX - IMUL3Q $19,DX,AX - MULQ 152(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ 160(DI),AX - MULQ 160(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 168(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 176(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 184(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 192(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 168(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 176(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 184(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 176(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 184(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 184(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 16(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 0(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 8(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - MULQ 16(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - MULQ 24(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - MULQ 32(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 0(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 168(DI),AX - MULQ 8(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - MULQ 16(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - MULQ 24(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 0(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 176(DI),AX - MULQ 8(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 176(DI),AX - MULQ 16(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 24(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),AX - MULQ 0(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 184(DI),AX - MULQ 8(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 24(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 32(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),AX - MULQ 0(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 16(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 24(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 32(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 144(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 96(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 152(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 88(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 80(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 88(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(SP),AX - MULQ 96(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(SP),AX - MULQ 104(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(SP),AX - MULQ 112(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(SP),AX - MULQ 80(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 128(SP),AX - MULQ 88(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(SP),AX - MULQ 96(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(SP),AX - MULQ 104(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),AX - MULQ 80(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 136(SP),AX - MULQ 88(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 136(SP),AX - MULQ 96(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 104(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(SP),AX - MULQ 80(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 144(SP),AX - MULQ 88(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 104(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 112(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(SP),AX - MULQ 80(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 96(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 104(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 112(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(DI) - MOVQ R8,48(DI) - MOVQ R9,56(DI) - MOVQ AX,64(DI) - MOVQ R10,72(DI) - MOVQ 160(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - MOVQ AX,SI - MOVQ DX,CX - MOVQ 168(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,CX - MOVQ DX,R8 - MOVQ 176(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R8 - MOVQ DX,R9 - MOVQ 184(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R9 - MOVQ DX,R10 - MOVQ 192(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R10 - IMUL3Q $19,DX,DX - ADDQ DX,SI - ADDQ 80(SP),SI - ADDQ 88(SP),CX - ADDQ 96(SP),R8 - ADDQ 104(SP),R9 - ADDQ 112(SP),R10 - MOVQ SI,80(DI) - MOVQ CX,88(DI) - MOVQ R8,96(DI) - MOVQ R9,104(DI) - MOVQ R10,112(DI) - MOVQ 104(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 176(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 112(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 168(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 160(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 168(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 80(DI),AX - MULQ 176(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 80(DI),AX - MULQ 184(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 80(DI),AX - MULQ 192(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 88(DI),AX - MULQ 160(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 88(DI),AX - MULQ 168(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 88(DI),AX - MULQ 176(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 88(DI),AX - MULQ 184(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 88(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),AX - MULQ 160(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 96(DI),AX - MULQ 168(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 96(DI),AX - MULQ 176(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 104(DI),AX - MULQ 160(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 104(DI),AX - MULQ 168(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 184(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 192(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 112(DI),AX - MULQ 160(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 176(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 184(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 192(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(DI) - MOVQ R8,88(DI) - MOVQ R9,96(DI) - MOVQ AX,104(DI) - MOVQ R10,112(DI) - RET diff --git a/vendor/github.com/keybase/go-crypto/curve25519/mont25519_amd64.go b/vendor/github.com/keybase/go-crypto/curve25519/mont25519_amd64.go deleted file mode 100644 index 5822bd53..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/mont25519_amd64.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -package curve25519 - -// These functions are implemented in the .s files. The names of the functions -// in the rest of the file are also taken from the SUPERCOP sources to help -// people following along. - -//go:noescape - -func cswap(inout *[5]uint64, v uint64) - -//go:noescape - -func ladderstep(inout *[5][5]uint64) - -//go:noescape - -func freeze(inout *[5]uint64) - -//go:noescape - -func mul(dest, a, b *[5]uint64) - -//go:noescape - -func square(out, in *[5]uint64) - -// mladder uses a Montgomery ladder to calculate (xr/zr) *= s. -func mladder(xr, zr *[5]uint64, s *[32]byte) { - var work [5][5]uint64 - - work[0] = *xr - setint(&work[1], 1) - setint(&work[2], 0) - work[3] = *xr - setint(&work[4], 1) - - j := uint(6) - var prevbit byte - - for i := 31; i >= 0; i-- { - for j < 8 { - bit := ((*s)[i] >> j) & 1 - swap := bit ^ prevbit - prevbit = bit - cswap(&work[1], uint64(swap)) - ladderstep(&work) - j-- - } - j = 7 - } - - *xr = work[1] - *zr = work[2] -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - copy(e[:], (*in)[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var t, z [5]uint64 - unpack(&t, base) - mladder(&t, &z, &e) - invert(&z, &z) - mul(&t, &t, &z) - pack(out, &t) -} - -func setint(r *[5]uint64, v uint64) { - r[0] = v - r[1] = 0 - r[2] = 0 - r[3] = 0 - r[4] = 0 -} - -// unpack sets r = x where r consists of 5, 51-bit limbs in little-endian -// order. -func unpack(r *[5]uint64, x *[32]byte) { - r[0] = uint64(x[0]) | - uint64(x[1])<<8 | - uint64(x[2])<<16 | - uint64(x[3])<<24 | - uint64(x[4])<<32 | - uint64(x[5])<<40 | - uint64(x[6]&7)<<48 - - r[1] = uint64(x[6])>>3 | - uint64(x[7])<<5 | - uint64(x[8])<<13 | - uint64(x[9])<<21 | - uint64(x[10])<<29 | - uint64(x[11])<<37 | - uint64(x[12]&63)<<45 - - r[2] = uint64(x[12])>>6 | - uint64(x[13])<<2 | - uint64(x[14])<<10 | - uint64(x[15])<<18 | - uint64(x[16])<<26 | - uint64(x[17])<<34 | - uint64(x[18])<<42 | - uint64(x[19]&1)<<50 - - r[3] = uint64(x[19])>>1 | - uint64(x[20])<<7 | - uint64(x[21])<<15 | - uint64(x[22])<<23 | - uint64(x[23])<<31 | - uint64(x[24])<<39 | - uint64(x[25]&15)<<47 - - r[4] = uint64(x[25])>>4 | - uint64(x[26])<<4 | - uint64(x[27])<<12 | - uint64(x[28])<<20 | - uint64(x[29])<<28 | - uint64(x[30])<<36 | - uint64(x[31]&127)<<44 -} - -// pack sets out = x where out is the usual, little-endian form of the 5, -// 51-bit limbs in x. -func pack(out *[32]byte, x *[5]uint64) { - t := *x - freeze(&t) - - out[0] = byte(t[0]) - out[1] = byte(t[0] >> 8) - out[2] = byte(t[0] >> 16) - out[3] = byte(t[0] >> 24) - out[4] = byte(t[0] >> 32) - out[5] = byte(t[0] >> 40) - out[6] = byte(t[0] >> 48) - - out[6] ^= byte(t[1]<<3) & 0xf8 - out[7] = byte(t[1] >> 5) - out[8] = byte(t[1] >> 13) - out[9] = byte(t[1] >> 21) - out[10] = byte(t[1] >> 29) - out[11] = byte(t[1] >> 37) - out[12] = byte(t[1] >> 45) - - out[12] ^= byte(t[2]<<6) & 0xc0 - out[13] = byte(t[2] >> 2) - out[14] = byte(t[2] >> 10) - out[15] = byte(t[2] >> 18) - out[16] = byte(t[2] >> 26) - out[17] = byte(t[2] >> 34) - out[18] = byte(t[2] >> 42) - out[19] = byte(t[2] >> 50) - - out[19] ^= byte(t[3]<<1) & 0xfe - out[20] = byte(t[3] >> 7) - out[21] = byte(t[3] >> 15) - out[22] = byte(t[3] >> 23) - out[23] = byte(t[3] >> 31) - out[24] = byte(t[3] >> 39) - out[25] = byte(t[3] >> 47) - - out[25] ^= byte(t[4]<<4) & 0xf0 - out[26] = byte(t[4] >> 4) - out[27] = byte(t[4] >> 12) - out[28] = byte(t[4] >> 20) - out[29] = byte(t[4] >> 28) - out[30] = byte(t[4] >> 36) - out[31] = byte(t[4] >> 44) -} - -// invert calculates r = x^-1 mod p using Fermat's little theorem. -func invert(r *[5]uint64, x *[5]uint64) { - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 - - square(&z2, x) /* 2 */ - square(&t, &z2) /* 4 */ - square(&t, &t) /* 8 */ - mul(&z9, &t, x) /* 9 */ - mul(&z11, &z9, &z2) /* 11 */ - square(&t, &z11) /* 22 */ - mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ - - square(&t, &z2_5_0) /* 2^6 - 2^1 */ - for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ - - square(&t, &z2_10_0) /* 2^11 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ - - square(&t, &z2_20_0) /* 2^21 - 2^1 */ - for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ - square(&t, &t) - } - mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ - - square(&t, &t) /* 2^41 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ - square(&t, &t) - } - mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ - - square(&t, &z2_50_0) /* 2^51 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ - square(&t, &t) - } - mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ - - square(&t, &z2_100_0) /* 2^101 - 2^1 */ - for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ - square(&t, &t) - } - mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ - - square(&t, &t) /* 2^201 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ - square(&t, &t) - } - mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ - - square(&t, &t) /* 2^251 - 2^1 */ - square(&t, &t) /* 2^252 - 2^2 */ - square(&t, &t) /* 2^253 - 2^3 */ - - square(&t, &t) /* 2^254 - 2^4 */ - - square(&t, &t) /* 2^255 - 2^5 */ - mul(r, &t, &z11) /* 2^255 - 21 */ -} diff --git a/vendor/github.com/keybase/go-crypto/curve25519/mul_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/mul_amd64.s deleted file mode 100644 index 5ce80a2e..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/mul_amd64.s +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func mul(dest, a, b *[5]uint64) -TEXT ·mul(SB),0,$16-24 - MOVQ dest+0(FP), DI - MOVQ a+8(FP), SI - MOVQ b+16(FP), DX - - MOVQ DX,CX - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,0(SP) - MULQ 16(CX) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 0(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 8(CX) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SI),AX - MULQ 16(CX) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SI),AX - MULQ 24(CX) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 0(SI),AX - MULQ 32(CX) - MOVQ AX,BX - MOVQ DX,BP - MOVQ 8(SI),AX - MULQ 0(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SI),AX - MULQ 8(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SI),AX - MULQ 16(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SI),AX - MULQ 24(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),AX - MULQ 0(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 16(SI),AX - MULQ 8(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SI),AX - MULQ 16(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 24(SI),AX - MULQ 0(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 24(SI),AX - MULQ 8(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 0(SP),AX - MULQ 24(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 0(SP),AX - MULQ 32(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 32(SI),AX - MULQ 0(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SP),AX - MULQ 16(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 24(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - MULQ 32(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ $REDMASK51,SI - SHLQ $13,R9:R8 - ANDQ SI,R8 - SHLQ $13,R11:R10 - ANDQ SI,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ SI,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ SI,R14 - ADDQ R13,R14 - SHLQ $13,BP:BX - ANDQ SI,BX - ADDQ R15,BX - IMUL3Q $19,BP,DX - ADDQ DX,R8 - MOVQ R8,DX - SHRQ $51,DX - ADDQ R10,DX - MOVQ DX,CX - SHRQ $51,DX - ANDQ SI,R8 - ADDQ R12,DX - MOVQ DX,R9 - SHRQ $51,DX - ANDQ SI,CX - ADDQ R14,DX - MOVQ DX,AX - SHRQ $51,DX - ANDQ SI,R9 - ADDQ BX,DX - MOVQ DX,R10 - SHRQ $51,DX - ANDQ SI,AX - IMUL3Q $19,DX,DX - ADDQ DX,R8 - ANDQ SI,R10 - MOVQ R8,0(DI) - MOVQ CX,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/github.com/keybase/go-crypto/curve25519/square_amd64.s b/vendor/github.com/keybase/go-crypto/curve25519/square_amd64.s deleted file mode 100644 index 12f73734..00000000 --- a/vendor/github.com/keybase/go-crypto/curve25519/square_amd64.s +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func square(out, in *[5]uint64) -TEXT ·square(SB),7,$0-16 - MOVQ out+0(FP), DI - MOVQ in+8(FP), SI - - MOVQ 0(SI),AX - MULQ 0(SI) - MOVQ AX,CX - MOVQ DX,R8 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 8(SI) - MOVQ AX,R9 - MOVQ DX,R10 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 16(SI) - MOVQ AX,R11 - MOVQ DX,R12 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 24(SI) - MOVQ AX,R13 - MOVQ DX,R14 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 32(SI) - MOVQ AX,R15 - MOVQ DX,BX - MOVQ 8(SI),AX - MULQ 8(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 16(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 24(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 8(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),AX - MULQ 16(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 24(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ $REDMASK51,SI - SHLQ $13,R8:CX - ANDQ SI,CX - SHLQ $13,R10:R9 - ANDQ SI,R9 - ADDQ R8,R9 - SHLQ $13,R12:R11 - ANDQ SI,R11 - ADDQ R10,R11 - SHLQ $13,R14:R13 - ANDQ SI,R13 - ADDQ R12,R13 - SHLQ $13,BX:R15 - ANDQ SI,R15 - ADDQ R14,R15 - IMUL3Q $19,BX,DX - ADDQ DX,CX - MOVQ CX,DX - SHRQ $51,DX - ADDQ R9,DX - ANDQ SI,CX - MOVQ DX,R8 - SHRQ $51,DX - ADDQ R11,DX - ANDQ SI,R8 - MOVQ DX,R9 - SHRQ $51,DX - ADDQ R13,DX - ANDQ SI,R9 - MOVQ DX,AX - SHRQ $51,DX - ADDQ R15,DX - ANDQ SI,AX - MOVQ DX,R10 - SHRQ $51,DX - IMUL3Q $19,DX,DX - ADDQ DX,CX - ANDQ SI,R10 - MOVQ CX,0(DI) - MOVQ R8,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/github.com/keybase/go-crypto/ed25519/ed25519.go b/vendor/github.com/keybase/go-crypto/ed25519/ed25519.go deleted file mode 100644 index 5ba434b8..00000000 --- a/vendor/github.com/keybase/go-crypto/ed25519/ed25519.go +++ /dev/null @@ -1,217 +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 ed25519 implements the Ed25519 signature algorithm. See -// https://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the “seed”. -package ed25519 - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -import ( - "bytes" - "crypto" - cryptorand "crypto/rand" - "crypto/sha512" - "errors" - "io" - "strconv" - - "github.com/keybase/go-crypto/ed25519/internal/edwards25519" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[32:]) - return PublicKey(publicKey) -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:32]) - return seed -} - -// Sign signs the given message with priv. -// Ed25519 performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to -// indicate the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, errors.New("ed25519: cannot sign hashed message") - } - - return Sign(priv, message), nil -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptorand.Reader - } - - seed := make([]byte, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey := NewKeyFromSeed(seed) - publicKey := make([]byte, PublicKeySize) - copy(publicKey, privateKey[32:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - if l := len(seed); l != SeedSize { - panic("ed25519: bad seed length: " + strconv.Itoa(l)) - } - - digest := sha512.Sum512(seed) - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - var A edwards25519.ExtendedGroupElement - var hBytes [32]byte - copy(hBytes[:], digest[:]) - edwards25519.GeScalarMultBase(&A, &hBytes) - var publicKeyBytes [32]byte - A.ToBytes(&publicKeyBytes) - - privateKey := make([]byte, PrivateKeySize) - copy(privateKey, seed) - copy(privateKey[32:], publicKeyBytes[:]) - - return privateKey -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) []byte { - if l := len(privateKey); l != PrivateKeySize { - panic("ed25519: bad private key length: " + strconv.Itoa(l)) - } - - h := sha512.New() - h.Write(privateKey[:32]) - - var digest1, messageDigest, hramDigest [64]byte - var expandedSecretKey [32]byte - h.Sum(digest1[:0]) - copy(expandedSecretKey[:], digest1[:]) - expandedSecretKey[0] &= 248 - expandedSecretKey[31] &= 63 - expandedSecretKey[31] |= 64 - - h.Reset() - h.Write(digest1[32:]) - h.Write(message) - h.Sum(messageDigest[:0]) - - var messageDigestReduced [32]byte - edwards25519.ScReduce(&messageDigestReduced, &messageDigest) - var R edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&R, &messageDigestReduced) - - var encodedR [32]byte - R.ToBytes(&encodedR) - - h.Reset() - h.Write(encodedR[:]) - h.Write(privateKey[32:]) - h.Write(message) - h.Sum(hramDigest[:0]) - var hramDigestReduced [32]byte - edwards25519.ScReduce(&hramDigestReduced, &hramDigest) - - var s [32]byte - edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) - - signature := make([]byte, SignatureSize) - copy(signature[:], encodedR[:]) - copy(signature[32:], s[:]) - - return signature -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -func Verify(publicKey PublicKey, message, sig []byte) bool { - if l := len(publicKey); l != PublicKeySize { - panic("ed25519: bad public key length: " + strconv.Itoa(l)) - } - - if len(sig) != SignatureSize || sig[63]&224 != 0 { - return false - } - - var A edwards25519.ExtendedGroupElement - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], publicKey) - if !A.FromBytes(&publicKeyBytes) { - return false - } - edwards25519.FeNeg(&A.X, &A.X) - edwards25519.FeNeg(&A.T, &A.T) - - h := sha512.New() - h.Write(sig[:32]) - h.Write(publicKey[:]) - h.Write(message) - var digest [64]byte - h.Sum(digest[:0]) - - var hReduced [32]byte - edwards25519.ScReduce(&hReduced, &digest) - - var R edwards25519.ProjectiveGroupElement - var s [32]byte - copy(s[:], sig[32:]) - - // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in - // the range [0, order) in order to prevent signature malleability. - if !edwards25519.ScMinimal(&s) { - return false - } - - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) - - var checkR [32]byte - R.ToBytes(&checkR) - return bytes.Equal(sig[:32], checkR[:]) -} diff --git a/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/const.go b/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/const.go deleted file mode 100644 index e39f086c..00000000 --- a/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/const.go +++ /dev/null @@ -1,1422 +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 edwards25519 - -// These values are from the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// d is a constant in the Edwards curve equation. -var d = FieldElement{ - -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, -} - -// d2 is 2*d. -var d2 = FieldElement{ - -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, -} - -// SqrtM1 is the square-root of -1 in the field. -var SqrtM1 = FieldElement{ - -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, -} - -// A is a constant in the Montgomery-form of curve25519. -var A = FieldElement{ - 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, -} - -// bi contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var bi = [8]PreComputedGroupElement{ - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877}, - FieldElement{-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951}, - FieldElement{4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784}, - }, - { - FieldElement{-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436}, - FieldElement{25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918}, - FieldElement{23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877}, - }, - { - FieldElement{-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800}, - FieldElement{-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305}, - FieldElement{-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300}, - }, - { - FieldElement{-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876}, - FieldElement{-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619}, - FieldElement{-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683}, - }, -} - -// base contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var base = [32][8]PreComputedGroupElement{ - { - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303}, - FieldElement{-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081}, - FieldElement{26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540}, - FieldElement{23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397}, - FieldElement{7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777}, - FieldElement{-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737}, - FieldElement{-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726}, - FieldElement{-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955}, - FieldElement{27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425}, - }, - }, - { - { - FieldElement{-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171}, - FieldElement{27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510}, - FieldElement{17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660}, - }, - { - FieldElement{-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639}, - FieldElement{29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963}, - FieldElement{5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950}, - }, - { - FieldElement{-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568}, - FieldElement{12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335}, - FieldElement{25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628}, - }, - { - FieldElement{-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007}, - FieldElement{-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772}, - FieldElement{-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653}, - }, - { - FieldElement{2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567}, - FieldElement{13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686}, - FieldElement{21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372}, - }, - { - FieldElement{-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887}, - FieldElement{-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954}, - FieldElement{-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953}, - }, - { - FieldElement{24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833}, - FieldElement{-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532}, - FieldElement{-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876}, - }, - { - FieldElement{2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268}, - FieldElement{33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214}, - FieldElement{1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038}, - }, - }, - { - { - FieldElement{6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800}, - FieldElement{4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645}, - FieldElement{-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664}, - }, - { - FieldElement{1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933}, - FieldElement{-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182}, - FieldElement{-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222}, - }, - { - FieldElement{-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991}, - FieldElement{20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880}, - FieldElement{9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092}, - }, - { - FieldElement{-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295}, - FieldElement{19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788}, - FieldElement{8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553}, - }, - { - FieldElement{-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026}, - FieldElement{11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347}, - FieldElement{-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033}, - }, - { - FieldElement{-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395}, - FieldElement{-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278}, - FieldElement{1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890}, - }, - { - FieldElement{32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995}, - FieldElement{-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596}, - FieldElement{-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891}, - }, - { - FieldElement{31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060}, - FieldElement{11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608}, - FieldElement{-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606}, - }, - }, - { - { - FieldElement{7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389}, - FieldElement{-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016}, - FieldElement{-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341}, - }, - { - FieldElement{-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505}, - FieldElement{14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553}, - FieldElement{-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655}, - }, - { - FieldElement{15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220}, - FieldElement{12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631}, - FieldElement{-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099}, - }, - { - FieldElement{26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556}, - FieldElement{14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749}, - FieldElement{236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930}, - }, - { - FieldElement{1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391}, - FieldElement{5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253}, - FieldElement{20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066}, - }, - { - FieldElement{24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958}, - FieldElement{-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082}, - FieldElement{-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383}, - }, - { - FieldElement{-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521}, - FieldElement{-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807}, - FieldElement{23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948}, - }, - { - FieldElement{9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134}, - FieldElement{-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455}, - FieldElement{27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629}, - }, - }, - { - { - FieldElement{-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069}, - FieldElement{-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746}, - FieldElement{24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919}, - }, - { - FieldElement{11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837}, - FieldElement{8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906}, - FieldElement{-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771}, - }, - { - FieldElement{-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817}, - FieldElement{10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098}, - FieldElement{10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409}, - }, - { - FieldElement{-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504}, - FieldElement{-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727}, - FieldElement{28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420}, - }, - { - FieldElement{-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003}, - FieldElement{-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605}, - FieldElement{-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384}, - }, - { - FieldElement{-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701}, - FieldElement{-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683}, - FieldElement{29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708}, - }, - { - FieldElement{-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563}, - FieldElement{-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260}, - FieldElement{-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387}, - }, - { - FieldElement{-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672}, - FieldElement{23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686}, - FieldElement{-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665}, - }, - }, - { - { - FieldElement{11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182}, - FieldElement{-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277}, - FieldElement{14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628}, - }, - { - FieldElement{-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474}, - FieldElement{-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539}, - FieldElement{-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822}, - }, - { - FieldElement{-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970}, - FieldElement{19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756}, - FieldElement{-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508}, - }, - { - FieldElement{-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683}, - FieldElement{-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655}, - FieldElement{-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158}, - }, - { - FieldElement{-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125}, - FieldElement{-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839}, - FieldElement{-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664}, - }, - { - FieldElement{27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294}, - FieldElement{-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899}, - FieldElement{-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070}, - }, - { - FieldElement{3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294}, - FieldElement{-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949}, - FieldElement{-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083}, - }, - { - FieldElement{31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420}, - FieldElement{-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940}, - FieldElement{29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396}, - }, - }, - { - { - FieldElement{-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567}, - FieldElement{20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127}, - FieldElement{-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294}, - }, - { - FieldElement{-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887}, - FieldElement{22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964}, - FieldElement{16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195}, - }, - { - FieldElement{9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244}, - FieldElement{24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999}, - FieldElement{-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762}, - }, - { - FieldElement{-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274}, - FieldElement{-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236}, - FieldElement{-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605}, - }, - { - FieldElement{-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761}, - FieldElement{-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884}, - FieldElement{-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482}, - }, - { - FieldElement{-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638}, - FieldElement{-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490}, - FieldElement{-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170}, - }, - { - FieldElement{5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736}, - FieldElement{10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124}, - FieldElement{-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392}, - }, - { - FieldElement{8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029}, - FieldElement{6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048}, - FieldElement{28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958}, - }, - }, - { - { - FieldElement{24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593}, - FieldElement{26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071}, - FieldElement{-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692}, - }, - { - FieldElement{11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687}, - FieldElement{-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441}, - FieldElement{-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001}, - }, - { - FieldElement{-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460}, - FieldElement{-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007}, - FieldElement{-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762}, - }, - { - FieldElement{15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005}, - FieldElement{-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674}, - FieldElement{4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035}, - }, - { - FieldElement{7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590}, - FieldElement{-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957}, - FieldElement{-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812}, - }, - { - FieldElement{33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740}, - FieldElement{-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122}, - FieldElement{-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158}, - }, - { - FieldElement{8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885}, - FieldElement{26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140}, - FieldElement{19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857}, - }, - { - FieldElement{801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155}, - FieldElement{19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260}, - FieldElement{19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483}, - }, - }, - { - { - FieldElement{-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677}, - FieldElement{32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815}, - FieldElement{22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751}, - }, - { - FieldElement{-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203}, - FieldElement{-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208}, - FieldElement{1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230}, - }, - { - FieldElement{16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850}, - FieldElement{-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389}, - FieldElement{-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968}, - }, - { - FieldElement{-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689}, - FieldElement{14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880}, - FieldElement{5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304}, - }, - { - FieldElement{30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632}, - FieldElement{-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412}, - FieldElement{20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566}, - }, - { - FieldElement{-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038}, - FieldElement{-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232}, - FieldElement{-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943}, - }, - { - FieldElement{17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856}, - FieldElement{23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738}, - FieldElement{15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971}, - }, - { - FieldElement{-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718}, - FieldElement{-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697}, - FieldElement{-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883}, - }, - }, - { - { - FieldElement{5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912}, - FieldElement{-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358}, - FieldElement{3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849}, - }, - { - FieldElement{29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307}, - FieldElement{-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977}, - FieldElement{-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335}, - }, - { - FieldElement{-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644}, - FieldElement{-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616}, - FieldElement{-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735}, - }, - { - FieldElement{-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099}, - FieldElement{29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341}, - FieldElement{-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336}, - }, - { - FieldElement{-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646}, - FieldElement{31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425}, - FieldElement{-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388}, - }, - { - FieldElement{-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743}, - FieldElement{-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822}, - FieldElement{-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462}, - }, - { - FieldElement{18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985}, - FieldElement{9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702}, - FieldElement{-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797}, - }, - { - FieldElement{21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293}, - FieldElement{27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100}, - FieldElement{19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688}, - }, - }, - { - { - FieldElement{12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186}, - FieldElement{2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610}, - FieldElement{-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707}, - }, - { - FieldElement{7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220}, - FieldElement{915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025}, - FieldElement{32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044}, - }, - { - FieldElement{32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992}, - FieldElement{-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027}, - FieldElement{21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197}, - }, - { - FieldElement{8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901}, - FieldElement{31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952}, - FieldElement{19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878}, - }, - { - FieldElement{-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390}, - FieldElement{32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730}, - FieldElement{2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730}, - }, - { - FieldElement{-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180}, - FieldElement{-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272}, - FieldElement{-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715}, - }, - { - FieldElement{-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970}, - FieldElement{-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772}, - FieldElement{-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865}, - }, - { - FieldElement{15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750}, - FieldElement{20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373}, - FieldElement{32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348}, - }, - }, - { - { - FieldElement{9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144}, - FieldElement{-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195}, - FieldElement{5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086}, - }, - { - FieldElement{-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684}, - FieldElement{-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518}, - FieldElement{-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233}, - }, - { - FieldElement{-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793}, - FieldElement{-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794}, - FieldElement{580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435}, - }, - { - FieldElement{23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921}, - FieldElement{13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518}, - FieldElement{2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563}, - }, - { - FieldElement{14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278}, - FieldElement{-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024}, - FieldElement{4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030}, - }, - { - FieldElement{10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783}, - FieldElement{27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717}, - FieldElement{6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844}, - }, - { - FieldElement{14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333}, - FieldElement{16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048}, - FieldElement{22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760}, - }, - { - FieldElement{-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760}, - FieldElement{-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757}, - FieldElement{-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112}, - }, - }, - { - { - FieldElement{-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468}, - FieldElement{3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184}, - FieldElement{10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289}, - }, - { - FieldElement{15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066}, - FieldElement{24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882}, - FieldElement{13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226}, - }, - { - FieldElement{16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101}, - FieldElement{29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279}, - FieldElement{-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811}, - }, - { - FieldElement{27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709}, - FieldElement{20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714}, - FieldElement{-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121}, - }, - { - FieldElement{9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464}, - FieldElement{12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847}, - FieldElement{13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400}, - }, - { - FieldElement{4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414}, - FieldElement{-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158}, - FieldElement{17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045}, - }, - { - FieldElement{-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415}, - FieldElement{-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459}, - FieldElement{-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079}, - }, - { - FieldElement{21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412}, - FieldElement{-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743}, - FieldElement{-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836}, - }, - }, - { - { - FieldElement{12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022}, - FieldElement{18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429}, - FieldElement{-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065}, - }, - { - FieldElement{30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861}, - FieldElement{10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000}, - FieldElement{-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101}, - }, - { - FieldElement{32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815}, - FieldElement{29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642}, - FieldElement{10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966}, - }, - { - FieldElement{25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574}, - FieldElement{-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742}, - FieldElement{-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689}, - }, - { - FieldElement{12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020}, - FieldElement{-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772}, - FieldElement{3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982}, - }, - { - FieldElement{-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953}, - FieldElement{-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218}, - FieldElement{-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265}, - }, - { - FieldElement{29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073}, - FieldElement{-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325}, - FieldElement{-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798}, - }, - { - FieldElement{-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870}, - FieldElement{-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863}, - FieldElement{-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927}, - }, - }, - { - { - FieldElement{-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267}, - FieldElement{-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663}, - FieldElement{22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862}, - }, - { - FieldElement{-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673}, - FieldElement{15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943}, - FieldElement{15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020}, - }, - { - FieldElement{-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238}, - FieldElement{11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064}, - FieldElement{14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795}, - }, - { - FieldElement{15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052}, - FieldElement{-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904}, - FieldElement{29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531}, - }, - { - FieldElement{-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979}, - FieldElement{-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841}, - FieldElement{10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431}, - }, - { - FieldElement{10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324}, - FieldElement{-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940}, - FieldElement{10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320}, - }, - { - FieldElement{-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184}, - FieldElement{14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114}, - FieldElement{30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878}, - }, - { - FieldElement{12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784}, - FieldElement{-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091}, - FieldElement{-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585}, - }, - }, - { - { - FieldElement{-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208}, - FieldElement{10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864}, - FieldElement{17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661}, - }, - { - FieldElement{7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233}, - FieldElement{26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212}, - FieldElement{-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525}, - }, - { - FieldElement{-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068}, - FieldElement{9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397}, - FieldElement{-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988}, - }, - { - FieldElement{5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889}, - FieldElement{32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038}, - FieldElement{14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697}, - }, - { - FieldElement{20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875}, - FieldElement{-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905}, - FieldElement{-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656}, - }, - { - FieldElement{11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818}, - FieldElement{27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714}, - FieldElement{10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203}, - }, - { - FieldElement{20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931}, - FieldElement{-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024}, - FieldElement{-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084}, - }, - { - FieldElement{-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204}, - FieldElement{20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817}, - FieldElement{27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667}, - }, - }, - { - { - FieldElement{11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504}, - FieldElement{-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768}, - FieldElement{-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255}, - }, - { - FieldElement{6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790}, - FieldElement{1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438}, - FieldElement{-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333}, - }, - { - FieldElement{17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971}, - FieldElement{31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905}, - FieldElement{29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409}, - }, - { - FieldElement{12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409}, - FieldElement{6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499}, - FieldElement{-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363}, - }, - { - FieldElement{28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664}, - FieldElement{-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324}, - FieldElement{-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940}, - }, - { - FieldElement{13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990}, - FieldElement{-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914}, - FieldElement{-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290}, - }, - { - FieldElement{24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257}, - FieldElement{-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433}, - FieldElement{-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236}, - }, - { - FieldElement{-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045}, - FieldElement{11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093}, - FieldElement{-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347}, - }, - }, - { - { - FieldElement{-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191}, - FieldElement{-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507}, - FieldElement{-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906}, - }, - { - FieldElement{3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018}, - FieldElement{-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109}, - FieldElement{-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926}, - }, - { - FieldElement{-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528}, - FieldElement{8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625}, - FieldElement{-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286}, - }, - { - FieldElement{2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033}, - FieldElement{27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866}, - FieldElement{21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896}, - }, - { - FieldElement{30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075}, - FieldElement{26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347}, - FieldElement{-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437}, - }, - { - FieldElement{-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165}, - FieldElement{-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588}, - FieldElement{-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193}, - }, - { - FieldElement{-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017}, - FieldElement{-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883}, - FieldElement{21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961}, - }, - { - FieldElement{8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043}, - FieldElement{29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663}, - FieldElement{-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362}, - }, - }, - { - { - FieldElement{-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860}, - FieldElement{2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466}, - FieldElement{-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063}, - }, - { - FieldElement{-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997}, - FieldElement{-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295}, - FieldElement{-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369}, - }, - { - FieldElement{9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385}, - FieldElement{18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109}, - FieldElement{2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906}, - }, - { - FieldElement{4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424}, - FieldElement{-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185}, - FieldElement{7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962}, - }, - { - FieldElement{-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325}, - FieldElement{10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593}, - FieldElement{696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404}, - }, - { - FieldElement{-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644}, - FieldElement{17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801}, - FieldElement{26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804}, - }, - { - FieldElement{-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884}, - FieldElement{-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577}, - FieldElement{-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849}, - }, - { - FieldElement{32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473}, - FieldElement{-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644}, - FieldElement{-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319}, - }, - }, - { - { - FieldElement{-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599}, - FieldElement{-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768}, - FieldElement{-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084}, - }, - { - FieldElement{-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328}, - FieldElement{-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369}, - FieldElement{20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920}, - }, - { - FieldElement{12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815}, - FieldElement{-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025}, - FieldElement{-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397}, - }, - { - FieldElement{-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448}, - FieldElement{6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981}, - FieldElement{30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165}, - }, - { - FieldElement{32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501}, - FieldElement{17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073}, - FieldElement{-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861}, - }, - { - FieldElement{14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845}, - FieldElement{-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211}, - FieldElement{18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870}, - }, - { - FieldElement{10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096}, - FieldElement{33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803}, - FieldElement{-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168}, - }, - { - FieldElement{30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965}, - FieldElement{-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505}, - FieldElement{18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598}, - }, - }, - { - { - FieldElement{5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782}, - FieldElement{5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900}, - FieldElement{-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479}, - }, - { - FieldElement{-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208}, - FieldElement{8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232}, - FieldElement{17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719}, - }, - { - FieldElement{16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271}, - FieldElement{-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326}, - FieldElement{-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132}, - }, - { - FieldElement{14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300}, - FieldElement{8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570}, - FieldElement{15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670}, - }, - { - FieldElement{-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994}, - FieldElement{-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913}, - FieldElement{31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317}, - }, - { - FieldElement{-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730}, - FieldElement{842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096}, - FieldElement{-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078}, - }, - { - FieldElement{-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411}, - FieldElement{-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905}, - FieldElement{-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654}, - }, - { - FieldElement{-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870}, - FieldElement{-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498}, - FieldElement{12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579}, - }, - }, - { - { - FieldElement{14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677}, - FieldElement{10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647}, - FieldElement{-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743}, - }, - { - FieldElement{-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468}, - FieldElement{21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375}, - FieldElement{-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155}, - }, - { - FieldElement{6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725}, - FieldElement{-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612}, - FieldElement{-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943}, - }, - { - FieldElement{-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944}, - FieldElement{30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928}, - FieldElement{9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406}, - }, - { - FieldElement{22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139}, - FieldElement{-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963}, - FieldElement{-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693}, - }, - { - FieldElement{1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734}, - FieldElement{-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680}, - FieldElement{-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410}, - }, - { - FieldElement{-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931}, - FieldElement{-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654}, - FieldElement{22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710}, - }, - { - FieldElement{29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180}, - FieldElement{-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684}, - FieldElement{-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895}, - }, - }, - { - { - FieldElement{22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501}, - FieldElement{-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413}, - FieldElement{6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880}, - }, - { - FieldElement{-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874}, - FieldElement{22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962}, - FieldElement{-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899}, - }, - { - FieldElement{21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152}, - FieldElement{9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063}, - FieldElement{7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080}, - }, - { - FieldElement{-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146}, - FieldElement{-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183}, - FieldElement{-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133}, - }, - { - FieldElement{-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421}, - FieldElement{-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622}, - FieldElement{-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197}, - }, - { - FieldElement{2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663}, - FieldElement{31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753}, - FieldElement{4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755}, - }, - { - FieldElement{-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862}, - FieldElement{-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118}, - FieldElement{26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171}, - }, - { - FieldElement{15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380}, - FieldElement{16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824}, - FieldElement{28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270}, - }, - }, - { - { - FieldElement{-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438}, - FieldElement{-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584}, - FieldElement{-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562}, - }, - { - FieldElement{30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471}, - FieldElement{18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610}, - FieldElement{19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269}, - }, - { - FieldElement{-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650}, - FieldElement{14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369}, - FieldElement{19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461}, - }, - { - FieldElement{30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462}, - FieldElement{-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793}, - FieldElement{-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218}, - }, - { - FieldElement{-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226}, - FieldElement{18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019}, - FieldElement{-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037}, - }, - { - FieldElement{31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171}, - FieldElement{-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132}, - FieldElement{-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841}, - }, - { - FieldElement{21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181}, - FieldElement{-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210}, - FieldElement{-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040}, - }, - { - FieldElement{3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935}, - FieldElement{24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105}, - FieldElement{-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814}, - }, - }, - { - { - FieldElement{793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852}, - FieldElement{5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581}, - FieldElement{-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646}, - }, - { - FieldElement{10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844}, - FieldElement{10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025}, - FieldElement{27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453}, - }, - { - FieldElement{-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068}, - FieldElement{4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192}, - FieldElement{-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921}, - }, - { - FieldElement{-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259}, - FieldElement{-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426}, - FieldElement{-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072}, - }, - { - FieldElement{-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305}, - FieldElement{13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832}, - FieldElement{28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943}, - }, - { - FieldElement{-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011}, - FieldElement{24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447}, - FieldElement{17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494}, - }, - { - FieldElement{-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245}, - FieldElement{-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859}, - FieldElement{28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915}, - }, - { - FieldElement{16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707}, - FieldElement{10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848}, - FieldElement{-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224}, - }, - }, - { - { - FieldElement{-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391}, - FieldElement{15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215}, - FieldElement{-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101}, - }, - { - FieldElement{23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713}, - FieldElement{21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849}, - FieldElement{-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930}, - }, - { - FieldElement{-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940}, - FieldElement{-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031}, - FieldElement{-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404}, - }, - { - FieldElement{-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243}, - FieldElement{-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116}, - FieldElement{-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525}, - }, - { - FieldElement{-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509}, - FieldElement{-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883}, - FieldElement{15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865}, - }, - { - FieldElement{-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660}, - FieldElement{4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273}, - FieldElement{-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138}, - }, - { - FieldElement{-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560}, - FieldElement{-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135}, - FieldElement{2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941}, - }, - { - FieldElement{-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739}, - FieldElement{18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756}, - FieldElement{-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819}, - }, - }, - { - { - FieldElement{-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347}, - FieldElement{-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028}, - FieldElement{21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075}, - }, - { - FieldElement{16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799}, - FieldElement{-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609}, - FieldElement{-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817}, - }, - { - FieldElement{-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989}, - FieldElement{-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523}, - FieldElement{4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278}, - }, - { - FieldElement{31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045}, - FieldElement{19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377}, - FieldElement{24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480}, - }, - { - FieldElement{17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016}, - FieldElement{510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426}, - FieldElement{18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525}, - }, - { - FieldElement{13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396}, - FieldElement{9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080}, - FieldElement{12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892}, - }, - { - FieldElement{15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275}, - FieldElement{11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074}, - FieldElement{20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140}, - }, - { - FieldElement{-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717}, - FieldElement{-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101}, - FieldElement{24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127}, - }, - }, - { - { - FieldElement{-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632}, - FieldElement{-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415}, - FieldElement{-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160}, - }, - { - FieldElement{31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876}, - FieldElement{22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625}, - FieldElement{-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478}, - }, - { - FieldElement{27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164}, - FieldElement{26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595}, - FieldElement{-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248}, - }, - { - FieldElement{-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858}, - FieldElement{15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193}, - FieldElement{8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184}, - }, - { - FieldElement{-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942}, - FieldElement{-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635}, - FieldElement{21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948}, - }, - { - FieldElement{11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935}, - FieldElement{-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415}, - FieldElement{-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416}, - }, - { - FieldElement{-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018}, - FieldElement{4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778}, - FieldElement{366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659}, - }, - { - FieldElement{-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385}, - FieldElement{18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503}, - FieldElement{476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329}, - }, - }, - { - { - FieldElement{20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056}, - FieldElement{-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838}, - FieldElement{24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948}, - }, - { - FieldElement{-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691}, - FieldElement{-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118}, - FieldElement{-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517}, - }, - { - FieldElement{-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269}, - FieldElement{-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904}, - FieldElement{-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589}, - }, - { - FieldElement{-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193}, - FieldElement{-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910}, - FieldElement{-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930}, - }, - { - FieldElement{-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667}, - FieldElement{25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481}, - FieldElement{-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876}, - }, - { - FieldElement{22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640}, - FieldElement{-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278}, - FieldElement{-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112}, - }, - { - FieldElement{26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272}, - FieldElement{17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012}, - FieldElement{-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221}, - }, - { - FieldElement{30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046}, - FieldElement{13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345}, - FieldElement{-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310}, - }, - }, - { - { - FieldElement{19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937}, - FieldElement{31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636}, - FieldElement{-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008}, - }, - { - FieldElement{-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429}, - FieldElement{-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576}, - FieldElement{31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066}, - }, - { - FieldElement{-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490}, - FieldElement{-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104}, - FieldElement{33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053}, - }, - { - FieldElement{31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275}, - FieldElement{-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511}, - FieldElement{22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095}, - }, - { - FieldElement{-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439}, - FieldElement{23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939}, - FieldElement{-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424}, - }, - { - FieldElement{2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310}, - FieldElement{3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608}, - FieldElement{-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079}, - }, - { - FieldElement{-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101}, - FieldElement{21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418}, - FieldElement{18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576}, - }, - { - FieldElement{30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356}, - FieldElement{9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996}, - FieldElement{-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099}, - }, - }, - { - { - FieldElement{-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728}, - FieldElement{-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658}, - FieldElement{-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242}, - }, - { - FieldElement{-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001}, - FieldElement{-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766}, - FieldElement{18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373}, - }, - { - FieldElement{26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458}, - FieldElement{-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628}, - FieldElement{-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657}, - }, - { - FieldElement{-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062}, - FieldElement{25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616}, - FieldElement{31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014}, - }, - { - FieldElement{24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383}, - FieldElement{-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814}, - FieldElement{-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718}, - }, - { - FieldElement{30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417}, - FieldElement{2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222}, - FieldElement{33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444}, - }, - { - FieldElement{-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597}, - FieldElement{23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970}, - FieldElement{1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799}, - }, - { - FieldElement{-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647}, - FieldElement{13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511}, - FieldElement{-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032}, - }, - }, - { - { - FieldElement{9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834}, - FieldElement{-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461}, - FieldElement{29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062}, - }, - { - FieldElement{-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516}, - FieldElement{-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547}, - FieldElement{-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240}, - }, - { - FieldElement{-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038}, - FieldElement{-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741}, - FieldElement{16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103}, - }, - { - FieldElement{-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747}, - FieldElement{-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323}, - FieldElement{31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016}, - }, - { - FieldElement{-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373}, - FieldElement{15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228}, - FieldElement{-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141}, - }, - { - FieldElement{16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399}, - FieldElement{11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831}, - FieldElement{-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376}, - }, - { - FieldElement{-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313}, - FieldElement{-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958}, - FieldElement{-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577}, - }, - { - FieldElement{-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743}, - FieldElement{29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684}, - FieldElement{-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476}, - }, - }, -} diff --git a/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/edwards25519.go b/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/edwards25519.go deleted file mode 100644 index fd03c252..00000000 --- a/vendor/github.com/keybase/go-crypto/ed25519/internal/edwards25519/edwards25519.go +++ /dev/null @@ -1,1793 +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 edwards25519 - -import "encoding/binary" - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// FieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type FieldElement [10]int32 - -var zero FieldElement - -func FeZero(fe *FieldElement) { - copy(fe[:], zero[:]) -} - -func FeOne(fe *FieldElement) { - FeZero(fe) - fe[0] = 1 -} - -func FeAdd(dst, a, b *FieldElement) { - dst[0] = a[0] + b[0] - dst[1] = a[1] + b[1] - dst[2] = a[2] + b[2] - dst[3] = a[3] + b[3] - dst[4] = a[4] + b[4] - dst[5] = a[5] + b[5] - dst[6] = a[6] + b[6] - dst[7] = a[7] + b[7] - dst[8] = a[8] + b[8] - dst[9] = a[9] + b[9] -} - -func FeSub(dst, a, b *FieldElement) { - dst[0] = a[0] - b[0] - dst[1] = a[1] - b[1] - dst[2] = a[2] - b[2] - dst[3] = a[3] - b[3] - dst[4] = a[4] - b[4] - dst[5] = a[5] - b[5] - dst[6] = a[6] - b[6] - dst[7] = a[7] - b[7] - dst[8] = a[8] - b[8] - dst[9] = a[9] - b[9] -} - -func FeCopy(dst, src *FieldElement) { - copy(dst[:], src[:]) -} - -// Replace (f,g) with (g,g) if b == 1; -// replace (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func FeCMove(f, g *FieldElement, b int32) { - b = -b - f[0] ^= b & (f[0] ^ g[0]) - f[1] ^= b & (f[1] ^ g[1]) - f[2] ^= b & (f[2] ^ g[2]) - f[3] ^= b & (f[3] ^ g[3]) - f[4] ^= b & (f[4] ^ g[4]) - f[5] ^= b & (f[5] ^ g[5]) - f[6] ^= b & (f[6] ^ g[6]) - f[7] ^= b & (f[7] ^ g[7]) - f[8] ^= b & (f[8] ^ g[8]) - f[9] ^= b & (f[9] ^ g[9]) -} - -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -func load4(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -func FeFromBytes(dst *FieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 8388607) << 2 - - FeCombine(dst, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -func FeIsNegative(f *FieldElement) byte { - var s [32]byte - FeToBytes(&s, f) - return s[0] & 1 -} - -func FeIsNonZero(f *FieldElement) int32 { - var s [32]byte - FeToBytes(&s, f) - var x uint8 - for _, b := range s { - x |= b - } - x |= x >> 4 - x |= x >> 2 - x |= x >> 1 - return int32(x & 1) -} - -// FeNeg sets h = -f -// -// Preconditions: -// |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeNeg(h, f *FieldElement) { - h[0] = -f[0] - h[1] = -f[1] - h[2] = -f[2] - h[3] = -f[3] - h[4] = -f[4] - h[5] = -f[5] - h[6] = -f[6] - h[7] = -f[7] - h[8] = -f[8] - h[9] = -f[9] -} - -func FeCombine(h *FieldElement, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - var c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 int64 - - /* - |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - /* |h0| <= 2^25 */ - /* |h4| <= 2^25 */ - /* |h1| <= 1.51*2^58 */ - /* |h5| <= 1.51*2^58 */ - - c1 = (h1 + (1 << 24)) >> 25 - h2 += c1 - h1 -= c1 << 25 - c5 = (h5 + (1 << 24)) >> 25 - h6 += c5 - h5 -= c5 << 25 - /* |h1| <= 2^24; from now on fits into int32 */ - /* |h5| <= 2^24; from now on fits into int32 */ - /* |h2| <= 1.21*2^59 */ - /* |h6| <= 1.21*2^59 */ - - c2 = (h2 + (1 << 25)) >> 26 - h3 += c2 - h2 -= c2 << 26 - c6 = (h6 + (1 << 25)) >> 26 - h7 += c6 - h6 -= c6 << 26 - /* |h2| <= 2^25; from now on fits into int32 unchanged */ - /* |h6| <= 2^25; from now on fits into int32 unchanged */ - /* |h3| <= 1.51*2^58 */ - /* |h7| <= 1.51*2^58 */ - - c3 = (h3 + (1 << 24)) >> 25 - h4 += c3 - h3 -= c3 << 25 - c7 = (h7 + (1 << 24)) >> 25 - h8 += c7 - h7 -= c7 << 25 - /* |h3| <= 2^24; from now on fits into int32 unchanged */ - /* |h7| <= 2^24; from now on fits into int32 unchanged */ - /* |h4| <= 1.52*2^33 */ - /* |h8| <= 1.52*2^33 */ - - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - c8 = (h8 + (1 << 25)) >> 26 - h9 += c8 - h8 -= c8 << 26 - /* |h4| <= 2^25; from now on fits into int32 unchanged */ - /* |h8| <= 2^25; from now on fits into int32 unchanged */ - /* |h5| <= 1.01*2^24 */ - /* |h9| <= 1.51*2^58 */ - - c9 = (h9 + (1 << 24)) >> 25 - h0 += c9 * 19 - h9 -= c9 << 25 - /* |h9| <= 2^24; from now on fits into int32 unchanged */ - /* |h0| <= 1.8*2^37 */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - /* |h0| <= 2^25; from now on fits into int32 unchanged */ - /* |h1| <= 1.01*2^24 */ - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// FeMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs, can squeeze carries into int32. -func FeMul(h, f, g *FieldElement) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - - f1_2 := int64(2 * f[1]) - f3_2 := int64(2 * f[3]) - f5_2 := int64(2 * f[5]) - f7_2 := int64(2 * f[7]) - f9_2 := int64(2 * f[9]) - - g0 := int64(g[0]) - g1 := int64(g[1]) - g2 := int64(g[2]) - g3 := int64(g[3]) - g4 := int64(g[4]) - g5 := int64(g[5]) - g6 := int64(g[6]) - g7 := int64(g[7]) - g8 := int64(g[8]) - g9 := int64(g[9]) - - g1_19 := int64(19 * g[1]) /* 1.4*2^29 */ - g2_19 := int64(19 * g[2]) /* 1.4*2^30; still ok */ - g3_19 := int64(19 * g[3]) - g4_19 := int64(19 * g[4]) - g5_19 := int64(19 * g[5]) - g6_19 := int64(19 * g[6]) - g7_19 := int64(19 * g[7]) - g8_19 := int64(19 * g[8]) - g9_19 := int64(19 * g[9]) - - h0 := f0*g0 + f1_2*g9_19 + f2*g8_19 + f3_2*g7_19 + f4*g6_19 + f5_2*g5_19 + f6*g4_19 + f7_2*g3_19 + f8*g2_19 + f9_2*g1_19 - h1 := f0*g1 + f1*g0 + f2*g9_19 + f3*g8_19 + f4*g7_19 + f5*g6_19 + f6*g5_19 + f7*g4_19 + f8*g3_19 + f9*g2_19 - h2 := f0*g2 + f1_2*g1 + f2*g0 + f3_2*g9_19 + f4*g8_19 + f5_2*g7_19 + f6*g6_19 + f7_2*g5_19 + f8*g4_19 + f9_2*g3_19 - h3 := f0*g3 + f1*g2 + f2*g1 + f3*g0 + f4*g9_19 + f5*g8_19 + f6*g7_19 + f7*g6_19 + f8*g5_19 + f9*g4_19 - h4 := f0*g4 + f1_2*g3 + f2*g2 + f3_2*g1 + f4*g0 + f5_2*g9_19 + f6*g8_19 + f7_2*g7_19 + f8*g6_19 + f9_2*g5_19 - h5 := f0*g5 + f1*g4 + f2*g3 + f3*g2 + f4*g1 + f5*g0 + f6*g9_19 + f7*g8_19 + f8*g7_19 + f9*g6_19 - h6 := f0*g6 + f1_2*g5 + f2*g4 + f3_2*g3 + f4*g2 + f5_2*g1 + f6*g0 + f7_2*g9_19 + f8*g8_19 + f9_2*g7_19 - h7 := f0*g7 + f1*g6 + f2*g5 + f3*g4 + f4*g3 + f5*g2 + f6*g1 + f7*g0 + f8*g9_19 + f9*g8_19 - h8 := f0*g8 + f1_2*g7 + f2*g6 + f3_2*g5 + f4*g4 + f5_2*g3 + f6*g2 + f7_2*g1 + f8*g0 + f9_2*g9_19 - h9 := f0*g9 + f1*g8 + f2*g7 + f3*g6 + f4*g5 + f5*g4 + f6*g3 + f7*g2 + f8*g1 + f9*g0 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func feSquare(f *FieldElement) (h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - f0_2 := int64(2 * f[0]) - f1_2 := int64(2 * f[1]) - f2_2 := int64(2 * f[2]) - f3_2 := int64(2 * f[3]) - f4_2 := int64(2 * f[4]) - f5_2 := int64(2 * f[5]) - f6_2 := int64(2 * f[6]) - f7_2 := int64(2 * f[7]) - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - - h0 = f0*f0 + f1_2*f9_38 + f2_2*f8_19 + f3_2*f7_38 + f4_2*f6_19 + f5*f5_38 - h1 = f0_2*f1 + f2*f9_38 + f3_2*f8_19 + f4*f7_38 + f5_2*f6_19 - h2 = f0_2*f2 + f1_2*f1 + f3_2*f9_38 + f4_2*f8_19 + f5_2*f7_38 + f6*f6_19 - h3 = f0_2*f3 + f1_2*f2 + f4*f9_38 + f5_2*f8_19 + f6*f7_38 - h4 = f0_2*f4 + f1_2*f3_2 + f2*f2 + f5_2*f9_38 + f6_2*f8_19 + f7*f7_38 - h5 = f0_2*f5 + f1_2*f4 + f2_2*f3 + f6*f9_38 + f7_2*f8_19 - h6 = f0_2*f6 + f1_2*f5_2 + f2_2*f4 + f3_2*f3 + f7_2*f9_38 + f8*f8_19 - h7 = f0_2*f7 + f1_2*f6 + f2_2*f5 + f3_2*f4 + f8*f9_38 - h8 = f0_2*f8 + f1_2*f7_2 + f2_2*f6 + f3_2*f5_2 + f4*f4 + f9*f9_38 - h9 = f0_2*f9 + f1_2*f8 + f2_2*f7 + f3_2*f6 + f4_2*f5 - - return -} - -// FeSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeSquare(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeSquare2 sets h = 2 * f * f -// -// Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. -// See fe_mul.c for discussion of implementation strategy. -func FeSquare2(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - - h0 += h0 - h1 += h1 - h2 += h2 - h3 += h3 - h4 += h4 - h5 += h5 - h6 += h6 - h7 += h7 - h8 += h8 - h9 += h9 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func FeInvert(out, z *FieldElement) { - var t0, t1, t2, t3 FieldElement - var i int - - FeSquare(&t0, z) // 2^1 - FeSquare(&t1, &t0) // 2^2 - for i = 1; i < 2; i++ { // 2^3 - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) // 2^3 + 2^0 - FeMul(&t0, &t0, &t1) // 2^3 + 2^1 + 2^0 - FeSquare(&t2, &t0) // 2^4 + 2^2 + 2^1 - FeMul(&t1, &t1, &t2) // 2^4 + 2^3 + 2^2 + 2^1 + 2^0 - FeSquare(&t2, &t1) // 5,4,3,2,1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 19..0 - FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 39..0 - FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 49..0 - FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 99..0 - FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 199..0 - FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 249..0 - FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 5; i++ { // 254..5 - FeSquare(&t1, &t1) - } - FeMul(out, &t1, &t0) // 254..5,3,1,0 -} - -func fePow22523(out, z *FieldElement) { - var t0, t1, t2 FieldElement - var i int - - FeSquare(&t0, z) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeSquare(&t1, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) - FeMul(&t0, &t0, &t1) - FeSquare(&t0, &t0) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 5; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 20; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 100; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t0, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t0, &t0) - } - FeMul(out, &t0, z) -} - -// Group elements are members of the elliptic curve -x^2 + y^2 = 1 + d * x^2 * -// y^2 where d = -121665/121666. -// -// Several representations are used: -// ProjectiveGroupElement: (X:Y:Z) satisfying x=X/Z, y=Y/Z -// ExtendedGroupElement: (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT -// CompletedGroupElement: ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T -// PreComputedGroupElement: (y+x,y-x,2dxy) - -type ProjectiveGroupElement struct { - X, Y, Z FieldElement -} - -type ExtendedGroupElement struct { - X, Y, Z, T FieldElement -} - -type CompletedGroupElement struct { - X, Y, Z, T FieldElement -} - -type PreComputedGroupElement struct { - yPlusX, yMinusX, xy2d FieldElement -} - -type CachedGroupElement struct { - yPlusX, yMinusX, Z, T2d FieldElement -} - -func (p *ProjectiveGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) -} - -func (p *ProjectiveGroupElement) Double(r *CompletedGroupElement) { - var t0 FieldElement - - FeSquare(&r.X, &p.X) - FeSquare(&r.Z, &p.Y) - FeSquare2(&r.T, &p.Z) - FeAdd(&r.Y, &p.X, &p.Y) - FeSquare(&t0, &r.Y) - FeAdd(&r.Y, &r.Z, &r.X) - FeSub(&r.Z, &r.Z, &r.X) - FeSub(&r.X, &t0, &r.Y) - FeSub(&r.T, &r.T, &r.Z) -} - -func (p *ProjectiveGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) - FeZero(&p.T) -} - -func (p *ExtendedGroupElement) Double(r *CompletedGroupElement) { - var q ProjectiveGroupElement - p.ToProjective(&q) - q.Double(r) -} - -func (p *ExtendedGroupElement) ToCached(r *CachedGroupElement) { - FeAdd(&r.yPlusX, &p.Y, &p.X) - FeSub(&r.yMinusX, &p.Y, &p.X) - FeCopy(&r.Z, &p.Z) - FeMul(&r.T2d, &p.T, &d2) -} - -func (p *ExtendedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeCopy(&r.X, &p.X) - FeCopy(&r.Y, &p.Y) - FeCopy(&r.Z, &p.Z) -} - -func (p *ExtendedGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) FromBytes(s *[32]byte) bool { - var u, v, v3, vxx, check FieldElement - - FeFromBytes(&p.Y, s) - FeOne(&p.Z) - FeSquare(&u, &p.Y) - FeMul(&v, &u, &d) - FeSub(&u, &u, &p.Z) // y = y^2-1 - FeAdd(&v, &v, &p.Z) // v = dy^2+1 - - FeSquare(&v3, &v) - FeMul(&v3, &v3, &v) // v3 = v^3 - FeSquare(&p.X, &v3) - FeMul(&p.X, &p.X, &v) - FeMul(&p.X, &p.X, &u) // x = uv^7 - - fePow22523(&p.X, &p.X) // x = (uv^7)^((q-5)/8) - FeMul(&p.X, &p.X, &v3) - FeMul(&p.X, &p.X, &u) // x = uv^3(uv^7)^((q-5)/8) - - var tmpX, tmp2 [32]byte - - FeSquare(&vxx, &p.X) - FeMul(&vxx, &vxx, &v) - FeSub(&check, &vxx, &u) // vx^2-u - if FeIsNonZero(&check) == 1 { - FeAdd(&check, &vxx, &u) // vx^2+u - if FeIsNonZero(&check) == 1 { - return false - } - FeMul(&p.X, &p.X, &SqrtM1) - - FeToBytes(&tmpX, &p.X) - for i, v := range tmpX { - tmp2[31-i] = v - } - } - - if FeIsNegative(&p.X) != (s[31] >> 7) { - FeNeg(&p.X, &p.X) - } - - FeMul(&p.T, &p.X, &p.Y) - return true -} - -func (p *CompletedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) -} - -func (p *CompletedGroupElement) ToExtended(r *ExtendedGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) - FeMul(&r.T, &p.X, &p.Y) -} - -func (p *PreComputedGroupElement) Zero() { - FeOne(&p.yPlusX) - FeOne(&p.yMinusX) - FeZero(&p.xy2d) -} - -func geAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func geMixedAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geMixedSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func slide(r *[256]int8, a *[32]byte) { - for i := range r { - r[i] = int8(1 & (a[i>>3] >> uint(i&7))) - } - - for i := range r { - if r[i] != 0 { - for b := 1; b <= 6 && i+b < 256; b++ { - if r[i+b] != 0 { - if r[i]+(r[i+b]<= -15 { - r[i] -= r[i+b] << uint(b) - for k := i + b; k < 256; k++ { - if r[k] == 0 { - r[k] = 1 - break - } - r[k] = 0 - } - } else { - break - } - } - } - } - } -} - -// GeDoubleScalarMultVartime sets r = a*A + b*B -// where a = a[0]+256*a[1]+...+256^31 a[31]. -// and b = b[0]+256*b[1]+...+256^31 b[31]. -// B is the Ed25519 base point (x,4/5) with x positive. -func GeDoubleScalarMultVartime(r *ProjectiveGroupElement, a *[32]byte, A *ExtendedGroupElement, b *[32]byte) { - var aSlide, bSlide [256]int8 - var Ai [8]CachedGroupElement // A,3A,5A,7A,9A,11A,13A,15A - var t CompletedGroupElement - var u, A2 ExtendedGroupElement - var i int - - slide(&aSlide, a) - slide(&bSlide, b) - - A.ToCached(&Ai[0]) - A.Double(&t) - t.ToExtended(&A2) - - for i := 0; i < 7; i++ { - geAdd(&t, &A2, &Ai[i]) - t.ToExtended(&u) - u.ToCached(&Ai[i+1]) - } - - r.Zero() - - for i = 255; i >= 0; i-- { - if aSlide[i] != 0 || bSlide[i] != 0 { - break - } - } - - for ; i >= 0; i-- { - r.Double(&t) - - if aSlide[i] > 0 { - t.ToExtended(&u) - geAdd(&t, &u, &Ai[aSlide[i]/2]) - } else if aSlide[i] < 0 { - t.ToExtended(&u) - geSub(&t, &u, &Ai[(-aSlide[i])/2]) - } - - if bSlide[i] > 0 { - t.ToExtended(&u) - geMixedAdd(&t, &u, &bi[bSlide[i]/2]) - } else if bSlide[i] < 0 { - t.ToExtended(&u) - geMixedSub(&t, &u, &bi[(-bSlide[i])/2]) - } - - t.ToProjective(r) - } -} - -// equal returns 1 if b == c and 0 otherwise, assuming that b and c are -// non-negative. -func equal(b, c int32) int32 { - x := uint32(b ^ c) - x-- - return int32(x >> 31) -} - -// negative returns 1 if b < 0 and 0 otherwise. -func negative(b int32) int32 { - return (b >> 31) & 1 -} - -func PreComputedGroupElementCMove(t, u *PreComputedGroupElement, b int32) { - FeCMove(&t.yPlusX, &u.yPlusX, b) - FeCMove(&t.yMinusX, &u.yMinusX, b) - FeCMove(&t.xy2d, &u.xy2d, b) -} - -func selectPoint(t *PreComputedGroupElement, pos int32, b int32) { - var minusT PreComputedGroupElement - bNegative := negative(b) - bAbs := b - (((-bNegative) & b) << 1) - - t.Zero() - for i := int32(0); i < 8; i++ { - PreComputedGroupElementCMove(t, &base[pos][i], equal(bAbs, i+1)) - } - FeCopy(&minusT.yPlusX, &t.yMinusX) - FeCopy(&minusT.yMinusX, &t.yPlusX) - FeNeg(&minusT.xy2d, &t.xy2d) - PreComputedGroupElementCMove(t, &minusT, bNegative) -} - -// GeScalarMultBase computes h = a*B, where -// a = a[0]+256*a[1]+...+256^31 a[31] -// B is the Ed25519 base point (x,4/5) with x positive. -// -// Preconditions: -// a[31] <= 127 -func GeScalarMultBase(h *ExtendedGroupElement, a *[32]byte) { - var e [64]int8 - - for i, v := range a { - e[2*i] = int8(v & 15) - e[2*i+1] = int8((v >> 4) & 15) - } - - // each e[i] is between 0 and 15 and e[63] is between 0 and 7. - - carry := int8(0) - for i := 0; i < 63; i++ { - e[i] += carry - carry = (e[i] + 8) >> 4 - e[i] -= carry << 4 - } - e[63] += carry - // each e[i] is between -8 and 8. - - h.Zero() - var t PreComputedGroupElement - var r CompletedGroupElement - for i := int32(1); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } - - var s ProjectiveGroupElement - - h.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToExtended(h) - - for i := int32(0); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } -} - -// The scalars are GF(2^252 + 27742317777372353535851937790883648493). - -// Input: -// a[0]+256*a[1]+...+256^31*a[31] = a -// b[0]+256*b[1]+...+256^31*b[31] = b -// c[0]+256*c[1]+...+256^31*c[31] = c -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScMulAdd(s, a, b, c *[32]byte) { - a0 := 2097151 & load3(a[:]) - a1 := 2097151 & (load4(a[2:]) >> 5) - a2 := 2097151 & (load3(a[5:]) >> 2) - a3 := 2097151 & (load4(a[7:]) >> 7) - a4 := 2097151 & (load4(a[10:]) >> 4) - a5 := 2097151 & (load3(a[13:]) >> 1) - a6 := 2097151 & (load4(a[15:]) >> 6) - a7 := 2097151 & (load3(a[18:]) >> 3) - a8 := 2097151 & load3(a[21:]) - a9 := 2097151 & (load4(a[23:]) >> 5) - a10 := 2097151 & (load3(a[26:]) >> 2) - a11 := (load4(a[28:]) >> 7) - b0 := 2097151 & load3(b[:]) - b1 := 2097151 & (load4(b[2:]) >> 5) - b2 := 2097151 & (load3(b[5:]) >> 2) - b3 := 2097151 & (load4(b[7:]) >> 7) - b4 := 2097151 & (load4(b[10:]) >> 4) - b5 := 2097151 & (load3(b[13:]) >> 1) - b6 := 2097151 & (load4(b[15:]) >> 6) - b7 := 2097151 & (load3(b[18:]) >> 3) - b8 := 2097151 & load3(b[21:]) - b9 := 2097151 & (load4(b[23:]) >> 5) - b10 := 2097151 & (load3(b[26:]) >> 2) - b11 := (load4(b[28:]) >> 7) - c0 := 2097151 & load3(c[:]) - c1 := 2097151 & (load4(c[2:]) >> 5) - c2 := 2097151 & (load3(c[5:]) >> 2) - c3 := 2097151 & (load4(c[7:]) >> 7) - c4 := 2097151 & (load4(c[10:]) >> 4) - c5 := 2097151 & (load3(c[13:]) >> 1) - c6 := 2097151 & (load4(c[15:]) >> 6) - c7 := 2097151 & (load3(c[18:]) >> 3) - c8 := 2097151 & load3(c[21:]) - c9 := 2097151 & (load4(c[23:]) >> 5) - c10 := 2097151 & (load3(c[26:]) >> 2) - c11 := (load4(c[28:]) >> 7) - var carry [23]int64 - - s0 := c0 + a0*b0 - s1 := c1 + a0*b1 + a1*b0 - s2 := c2 + a0*b2 + a1*b1 + a2*b0 - s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 - s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 - s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 - s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 - s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 - s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 - s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 - s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 - s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 - s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 - s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 - s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 - s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 - s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 - s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 - s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 - s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 - s20 := a9*b11 + a10*b10 + a11*b9 - s21 := a10*b11 + a11*b10 - s22 := a11 * b11 - s23 := int64(0) - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - carry[18] = (s18 + (1 << 20)) >> 21 - s19 += carry[18] - s18 -= carry[18] << 21 - carry[20] = (s20 + (1 << 20)) >> 21 - s21 += carry[20] - s20 -= carry[20] << 21 - carry[22] = (s22 + (1 << 20)) >> 21 - s23 += carry[22] - s22 -= carry[22] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - carry[17] = (s17 + (1 << 20)) >> 21 - s18 += carry[17] - s17 -= carry[17] << 21 - carry[19] = (s19 + (1 << 20)) >> 21 - s20 += carry[19] - s19 -= carry[19] << 21 - carry[21] = (s21 + (1 << 20)) >> 21 - s22 += carry[21] - s21 -= carry[21] << 21 - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - s[0] = byte(s0 >> 0) - s[1] = byte(s0 >> 8) - s[2] = byte((s0 >> 16) | (s1 << 5)) - s[3] = byte(s1 >> 3) - s[4] = byte(s1 >> 11) - s[5] = byte((s1 >> 19) | (s2 << 2)) - s[6] = byte(s2 >> 6) - s[7] = byte((s2 >> 14) | (s3 << 7)) - s[8] = byte(s3 >> 1) - s[9] = byte(s3 >> 9) - s[10] = byte((s3 >> 17) | (s4 << 4)) - s[11] = byte(s4 >> 4) - s[12] = byte(s4 >> 12) - s[13] = byte((s4 >> 20) | (s5 << 1)) - s[14] = byte(s5 >> 7) - s[15] = byte((s5 >> 15) | (s6 << 6)) - s[16] = byte(s6 >> 2) - s[17] = byte(s6 >> 10) - s[18] = byte((s6 >> 18) | (s7 << 3)) - s[19] = byte(s7 >> 5) - s[20] = byte(s7 >> 13) - s[21] = byte(s8 >> 0) - s[22] = byte(s8 >> 8) - s[23] = byte((s8 >> 16) | (s9 << 5)) - s[24] = byte(s9 >> 3) - s[25] = byte(s9 >> 11) - s[26] = byte((s9 >> 19) | (s10 << 2)) - s[27] = byte(s10 >> 6) - s[28] = byte((s10 >> 14) | (s11 << 7)) - s[29] = byte(s11 >> 1) - s[30] = byte(s11 >> 9) - s[31] = byte(s11 >> 17) -} - -// Input: -// s[0]+256*s[1]+...+256^63*s[63] = s -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = s mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScReduce(out *[32]byte, s *[64]byte) { - s0 := 2097151 & load3(s[:]) - s1 := 2097151 & (load4(s[2:]) >> 5) - s2 := 2097151 & (load3(s[5:]) >> 2) - s3 := 2097151 & (load4(s[7:]) >> 7) - s4 := 2097151 & (load4(s[10:]) >> 4) - s5 := 2097151 & (load3(s[13:]) >> 1) - s6 := 2097151 & (load4(s[15:]) >> 6) - s7 := 2097151 & (load3(s[18:]) >> 3) - s8 := 2097151 & load3(s[21:]) - s9 := 2097151 & (load4(s[23:]) >> 5) - s10 := 2097151 & (load3(s[26:]) >> 2) - s11 := 2097151 & (load4(s[28:]) >> 7) - s12 := 2097151 & (load4(s[31:]) >> 4) - s13 := 2097151 & (load3(s[34:]) >> 1) - s14 := 2097151 & (load4(s[36:]) >> 6) - s15 := 2097151 & (load3(s[39:]) >> 3) - s16 := 2097151 & load3(s[42:]) - s17 := 2097151 & (load4(s[44:]) >> 5) - s18 := 2097151 & (load3(s[47:]) >> 2) - s19 := 2097151 & (load4(s[49:]) >> 7) - s20 := 2097151 & (load4(s[52:]) >> 4) - s21 := 2097151 & (load3(s[55:]) >> 1) - s22 := 2097151 & (load4(s[57:]) >> 6) - s23 := (load4(s[60:]) >> 3) - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - var carry [17]int64 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - out[0] = byte(s0 >> 0) - out[1] = byte(s0 >> 8) - out[2] = byte((s0 >> 16) | (s1 << 5)) - out[3] = byte(s1 >> 3) - out[4] = byte(s1 >> 11) - out[5] = byte((s1 >> 19) | (s2 << 2)) - out[6] = byte(s2 >> 6) - out[7] = byte((s2 >> 14) | (s3 << 7)) - out[8] = byte(s3 >> 1) - out[9] = byte(s3 >> 9) - out[10] = byte((s3 >> 17) | (s4 << 4)) - out[11] = byte(s4 >> 4) - out[12] = byte(s4 >> 12) - out[13] = byte((s4 >> 20) | (s5 << 1)) - out[14] = byte(s5 >> 7) - out[15] = byte((s5 >> 15) | (s6 << 6)) - out[16] = byte(s6 >> 2) - out[17] = byte(s6 >> 10) - out[18] = byte((s6 >> 18) | (s7 << 3)) - out[19] = byte(s7 >> 5) - out[20] = byte(s7 >> 13) - out[21] = byte(s8 >> 0) - out[22] = byte(s8 >> 8) - out[23] = byte((s8 >> 16) | (s9 << 5)) - out[24] = byte(s9 >> 3) - out[25] = byte(s9 >> 11) - out[26] = byte((s9 >> 19) | (s10 << 2)) - out[27] = byte(s10 >> 6) - out[28] = byte((s10 >> 14) | (s11 << 7)) - out[29] = byte(s11 >> 1) - out[30] = byte(s11 >> 9) - out[31] = byte(s11 >> 17) -} - -// order is the order of Curve25519 in little-endian form. -var order = [4]uint64{0x5812631a5cf5d3ed, 0x14def9dea2f79cd6, 0, 0x1000000000000000} - -// ScMinimal returns true if the given scalar is less than the order of the -// curve. -func ScMinimal(scalar *[32]byte) bool { - for i := 3; ; i-- { - v := binary.LittleEndian.Uint64(scalar[i*8:]) - if v > order[i] { - return false - } else if v < order[i] { - break - } else if i == 0 { - return false - } - } - - return true -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/armor/armor.go b/vendor/github.com/keybase/go-crypto/openpgp/armor/armor.go deleted file mode 100644 index b65b58bc..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/armor/armor.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2010 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 armor implements OpenPGP ASCII Armor, see RFC 4880. OpenPGP Armor is -// very similar to PEM except that it has an additional CRC checksum. -package armor // import "github.com/keybase/go-crypto/openpgp/armor" - -import ( - "bufio" - "bytes" - "encoding/base64" - "io" - "strings" - "unicode" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// A Block represents an OpenPGP armored structure. -// -// The encoded form is: -// -----BEGIN Type----- -// Headers -// -// base64-encoded Bytes -// '=' base64 encoded checksum -// -----END Type----- -// where Headers is a possibly empty sequence of Key: Value lines. -// -// Since the armored data can be very large, this package presents a streaming -// interface. -type Block struct { - Type string // The type, taken from the preamble (i.e. "PGP SIGNATURE"). - Header map[string]string // Optional headers. - Body io.Reader // A Reader from which the contents can be read - lReader lineReader - oReader openpgpReader -} - -var ArmorCorrupt error = errors.StructuralError("armor invalid") - -const crc24Init = 0xb704ce -const crc24Poly = 0x1864cfb -const crc24Mask = 0xffffff - -// crc24 calculates the OpenPGP checksum as specified in RFC 4880, section 6.1 -func crc24(crc uint32, d []byte) uint32 { - for _, b := range d { - crc ^= uint32(b) << 16 - for i := 0; i < 8; i++ { - crc <<= 1 - if crc&0x1000000 != 0 { - crc ^= crc24Poly - } - } - } - return crc -} - -var armorStart = []byte("-----BEGIN ") -var armorEnd = []byte("-----END ") -var armorEndOfLine = []byte("-----") - -// lineReader wraps a line based reader. It watches for the end of an armor -// block and records the expected CRC value. -type lineReader struct { - in *bufio.Reader - buf []byte - eof bool - crc *uint32 -} - -// ourIsSpace checks if a rune is either space according to unicode -// package, or ZeroWidthSpace (which is not a space according to -// unicode module). Used to trim lines during header reading. -func ourIsSpace(r rune) bool { - return r == '\u200b' || unicode.IsSpace(r) -} - -func (l *lineReader) Read(p []byte) (n int, err error) { - if l.eof { - return 0, io.EOF - } - - if len(l.buf) > 0 { - n = copy(p, l.buf) - l.buf = l.buf[n:] - return - } - - line, _, err := l.in.ReadLine() - if err != nil { - return - } - - // Entry-level cleanup, just trim spaces. - line = bytes.TrimFunc(line, ourIsSpace) - - if len(line) == 5 && line[0] == '=' { - // This is the checksum line - var expectedBytes [3]byte - var m int - m, err = base64.StdEncoding.Decode(expectedBytes[0:], line[1:]) - if m != 3 || err != nil { - return - } - crc := uint32(expectedBytes[0])<<16 | - uint32(expectedBytes[1])<<8 | - uint32(expectedBytes[2]) - l.crc = &crc - - for { - line, _, err = l.in.ReadLine() - if err == io.EOF { - break - } - if err != nil { - return - } - if len(strings.TrimSpace(string(line))) > 0 { - break - } - } - if !bytes.HasPrefix(line, armorEnd) { - return 0, ArmorCorrupt - } - - l.eof = true - return 0, io.EOF - } - - if bytes.HasPrefix(line, armorEnd) { - // Unexpected ending, there was no checksum. - l.eof = true - l.crc = nil - return 0, io.EOF - } - - // Clean-up line from whitespace to pass it further (to base64 - // decoder). This is done after test for CRC and test for - // armorEnd. Keys that have whitespace in CRC will have CRC - // treated as part of the payload and probably fail in base64 - // reading. - line = bytes.Map(func(r rune) rune { - if ourIsSpace(r) { - return -1 - } - return r - }, line) - - n = copy(p, line) - bytesToSave := len(line) - n - if bytesToSave > 0 { - if cap(l.buf) < bytesToSave { - l.buf = make([]byte, 0, bytesToSave) - } - l.buf = l.buf[0:bytesToSave] - copy(l.buf, line[n:]) - } - - return -} - -// openpgpReader passes Read calls to the underlying base64 decoder, but keeps -// a running CRC of the resulting data and checks the CRC against the value -// found by the lineReader at EOF. -type openpgpReader struct { - lReader *lineReader - b64Reader io.Reader - currentCRC uint32 -} - -func (r *openpgpReader) Read(p []byte) (n int, err error) { - n, err = r.b64Reader.Read(p) - r.currentCRC = crc24(r.currentCRC, p[:n]) - - if err == io.EOF { - if r.lReader.crc != nil && *r.lReader.crc != uint32(r.currentCRC&crc24Mask) { - return 0, ArmorCorrupt - } - } - - return -} - -// Decode reads a PGP armored block from the given Reader. It will ignore -// leading garbage. If it doesn't find a block, it will return nil, io.EOF. The -// given Reader is not usable after calling this function: an arbitrary amount -// of data may have been read past the end of the block. -func Decode(in io.Reader) (p *Block, err error) { - r := bufio.NewReaderSize(in, 100) - var line []byte - ignoreNext := false - -TryNextBlock: - p = nil - - // Skip leading garbage - for { - ignoreThis := ignoreNext - line, ignoreNext, err = r.ReadLine() - if err != nil { - return - } - if ignoreNext || ignoreThis { - continue - } - line = bytes.TrimSpace(line) - if len(line) > len(armorStart)+len(armorEndOfLine) && bytes.HasPrefix(line, armorStart) { - break - } - } - - p = new(Block) - p.Type = string(line[len(armorStart) : len(line)-len(armorEndOfLine)]) - p.Header = make(map[string]string) - nextIsContinuation := false - var lastKey string - - // Read headers - for { - isContinuation := nextIsContinuation - line, nextIsContinuation, err = r.ReadLine() - if err != nil { - p = nil - return - } - if isContinuation { - p.Header[lastKey] += string(line) - continue - } - line = bytes.TrimFunc(line, ourIsSpace) - if len(line) == 0 { - break - } - - i := bytes.Index(line, []byte(": ")) - if i == -1 { - goto TryNextBlock - } - lastKey = string(line[:i]) - p.Header[lastKey] = string(line[i+2:]) - } - - p.lReader.in = r - p.oReader.currentCRC = crc24Init - p.oReader.lReader = &p.lReader - p.oReader.b64Reader = base64.NewDecoder(base64.StdEncoding, &p.lReader) - p.Body = &p.oReader - - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/armor/encode.go b/vendor/github.com/keybase/go-crypto/openpgp/armor/encode.go deleted file mode 100644 index 075a1978..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/armor/encode.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2010 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 armor - -import ( - "encoding/base64" - "io" -) - -var armorHeaderSep = []byte(": ") -var blockEnd = []byte("\n=") -var newline = []byte("\n") -var armorEndOfLineOut = []byte("-----\n") - -// writeSlices writes its arguments to the given Writer. -func writeSlices(out io.Writer, slices ...[]byte) (err error) { - for _, s := range slices { - _, err = out.Write(s) - if err != nil { - return err - } - } - return -} - -// lineBreaker breaks data across several lines, all of the same byte length -// (except possibly the last). Lines are broken with a single '\n'. -type lineBreaker struct { - lineLength int - line []byte - used int - out io.Writer - haveWritten bool -} - -func newLineBreaker(out io.Writer, lineLength int) *lineBreaker { - return &lineBreaker{ - lineLength: lineLength, - line: make([]byte, lineLength), - used: 0, - out: out, - } -} - -func (l *lineBreaker) Write(b []byte) (n int, err error) { - n = len(b) - - if n == 0 { - return - } - - if l.used == 0 && l.haveWritten { - _, err = l.out.Write([]byte{'\n'}) - if err != nil { - return - } - } - - if l.used+len(b) < l.lineLength { - l.used += copy(l.line[l.used:], b) - return - } - - l.haveWritten = true - _, err = l.out.Write(l.line[0:l.used]) - if err != nil { - return - } - excess := l.lineLength - l.used - l.used = 0 - - _, err = l.out.Write(b[0:excess]) - if err != nil { - return - } - - _, err = l.Write(b[excess:]) - return -} - -func (l *lineBreaker) Close() (err error) { - if l.used > 0 { - _, err = l.out.Write(l.line[0:l.used]) - if err != nil { - return - } - } - - return -} - -// encoding keeps track of a running CRC24 over the data which has been written -// to it and outputs a OpenPGP checksum when closed, followed by an armor -// trailer. -// -// It's built into a stack of io.Writers: -// encoding -> base64 encoder -> lineBreaker -> out -type encoding struct { - out io.Writer - breaker *lineBreaker - b64 io.WriteCloser - crc uint32 - blockType []byte -} - -func (e *encoding) Write(data []byte) (n int, err error) { - e.crc = crc24(e.crc, data) - return e.b64.Write(data) -} - -func (e *encoding) Close() (err error) { - err = e.b64.Close() - if err != nil { - return - } - e.breaker.Close() - - var checksumBytes [3]byte - checksumBytes[0] = byte(e.crc >> 16) - checksumBytes[1] = byte(e.crc >> 8) - checksumBytes[2] = byte(e.crc) - - var b64ChecksumBytes [4]byte - base64.StdEncoding.Encode(b64ChecksumBytes[:], checksumBytes[:]) - - return writeSlices(e.out, blockEnd, b64ChecksumBytes[:], newline, armorEnd, e.blockType, armorEndOfLine, []byte{'\n'}) -} - -// Encode returns a WriteCloser which will encode the data written to it in -// OpenPGP armor. -func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) { - bType := []byte(blockType) - err = writeSlices(out, armorStart, bType, armorEndOfLineOut) - if err != nil { - return - } - - for k, v := range headers { - err = writeSlices(out, []byte(k), armorHeaderSep, []byte(v), newline) - if err != nil { - return - } - } - - _, err = out.Write(newline) - if err != nil { - return - } - - e := &encoding{ - out: out, - breaker: newLineBreaker(out, 64), - crc: crc24Init, - blockType: bType, - } - e.b64 = base64.NewEncoder(base64.StdEncoding, e.breaker) - return e, nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go b/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go deleted file mode 100644 index e601e389..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2011 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 openpgp - -import "hash" - -// NewCanonicalTextHash reformats text written to it into the canonical -// form and then applies the hash h. See RFC 4880, section 5.2.1. -func NewCanonicalTextHash(h hash.Hash) hash.Hash { - return &canonicalTextHash{h, 0} -} - -type canonicalTextHash struct { - h hash.Hash - s int -} - -var newline = []byte{'\r', '\n'} - -func (cth *canonicalTextHash) Write(buf []byte) (int, error) { - start := 0 - - for i, c := range buf { - switch cth.s { - case 0: - if c == '\r' { - cth.s = 1 - } else if c == '\n' { - cth.h.Write(buf[start:i]) - cth.h.Write(newline) - start = i + 1 - } - case 1: - cth.s = 0 - } - } - - cth.h.Write(buf[start:]) - return len(buf), nil -} - -func (cth *canonicalTextHash) Sum(in []byte) []byte { - return cth.h.Sum(in) -} - -func (cth *canonicalTextHash) Reset() { - cth.h.Reset() - cth.s = 0 -} - -func (cth *canonicalTextHash) Size() int { - return cth.h.Size() -} - -func (cth *canonicalTextHash) BlockSize() int { - return cth.h.BlockSize() -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/ecdh/ecdh.go b/vendor/github.com/keybase/go-crypto/openpgp/ecdh/ecdh.go deleted file mode 100644 index 1a87b275..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/ecdh/ecdh.go +++ /dev/null @@ -1,316 +0,0 @@ -package ecdh - -import ( - "bytes" - "crypto" - "crypto/aes" - "crypto/elliptic" - "encoding/binary" - "errors" - "github.com/keybase/go-crypto/curve25519" - "io" - "math/big" -) - -type PublicKey struct { - elliptic.Curve - X, Y *big.Int -} - -type PrivateKey struct { - PublicKey - X *big.Int -} - -// KDF implements Key Derivation Function as described in -// https://tools.ietf.org/html/rfc6637#section-7 -func (e *PublicKey) KDF(S []byte, kdfParams []byte, hash crypto.Hash) []byte { - sLen := (e.Curve.Params().P.BitLen() + 7) / 8 - buf := new(bytes.Buffer) - buf.Write([]byte{0, 0, 0, 1}) - if sLen > len(S) { - // zero-pad the S. If we got invalid S (bigger than curve's - // P), we are going to produce invalid key. Garbage in, - // garbage out. - buf.Write(make([]byte, sLen-len(S))) - } - buf.Write(S) - buf.Write(kdfParams) - - hashw := hash.New() - - hashw.Write(buf.Bytes()) - key := hashw.Sum(nil) - - return key -} - -// AESKeyUnwrap implements RFC 3394 Key Unwrapping. See -// http://tools.ietf.org/html/rfc3394#section-2.2.1 -// Note: The second described algorithm ("index-based") is implemented -// here. -func AESKeyUnwrap(key, cipherText []byte) ([]byte, error) { - if len(cipherText)%8 != 0 { - return nil, errors.New("cipherText must by a multiple of 64 bits") - } - - cipher, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - nblocks := len(cipherText)/8 - 1 - - // 1) Initialize variables. - // - Set A = C[0] - var A [aes.BlockSize]byte - copy(A[:8], cipherText[:8]) - - // For i = 1 to n - // Set R[i] = C[i] - R := make([]byte, len(cipherText)-8) - copy(R, cipherText[8:]) - - // 2) Compute intermediate values. - for j := 5; j >= 0; j-- { - for i := nblocks - 1; i >= 0; i-- { - // B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i - // A = MSB(64, B) - t := uint64(nblocks*j + i + 1) - At := binary.BigEndian.Uint64(A[:8]) ^ t - binary.BigEndian.PutUint64(A[:8], At) - - copy(A[8:], R[i*8:i*8+8]) - cipher.Decrypt(A[:], A[:]) - - // R[i] = LSB(B, 64) - copy(R[i*8:i*8+8], A[8:]) - } - } - - // 3) Output results. - // If A is an appropriate initial value (see 2.2.3), - for i := 0; i < 8; i++ { - if A[i] != 0xA6 { - return nil, errors.New("Failed to unwrap key (A is not IV)") - } - } - - return R, nil -} - -// AESKeyWrap implements RFC 3394 Key Wrapping. See -// https://tools.ietf.org/html/rfc3394#section-2.2.2 -// Note: The second described algorithm ("index-based") is implemented -// here. -func AESKeyWrap(key, plainText []byte) ([]byte, error) { - if len(plainText)%8 != 0 { - return nil, errors.New("plainText must be a multiple of 64 bits") - } - - cipher, err := aes.NewCipher(key) // NewCipher checks key size - if err != nil { - return nil, err - } - - nblocks := len(plainText) / 8 - - // 1) Initialize variables. - var A [aes.BlockSize]byte - // Section 2.2.3.1 -- Initial Value - // http://tools.ietf.org/html/rfc3394#section-2.2.3.1 - for i := 0; i < 8; i++ { - A[i] = 0xA6 - } - - // For i = 1 to n - // Set R[i] = P[i] - R := make([]byte, len(plainText)) - copy(R, plainText) - - // 2) Calculate intermediate values. - for j := 0; j <= 5; j++ { - for i := 0; i < nblocks; i++ { - // B = AES(K, A | R[i]) - copy(A[8:], R[i*8:i*8+8]) - cipher.Encrypt(A[:], A[:]) - - // (Assume B = A) - // A = MSB(64, B) ^ t where t = (n*j)+1 - t := uint64(j*nblocks + i + 1) - At := binary.BigEndian.Uint64(A[:8]) ^ t - binary.BigEndian.PutUint64(A[:8], At) - - // R[i] = LSB(64, B) - copy(R[i*8:i*8+8], A[8:]) - } - } - - // 3) Output results. - // Set C[0] = A - // For i = 1 to n - // C[i] = R[i] - return append(A[:8], R...), nil -} - -// PadBuffer pads byte buffer buf to a length being multiple of -// blockLen. Additional bytes appended to the buffer have value of the -// number padded bytes. E.g. if the buffer is 3 bytes short of being -// 40 bytes total, the appended bytes will be [03, 03, 03]. -func PadBuffer(buf []byte, blockLen int) []byte { - padding := blockLen - (len(buf) % blockLen) - if padding == 0 { - return buf - } - - padBuf := make([]byte, padding) - for i := 0; i < padding; i++ { - padBuf[i] = byte(padding) - } - - return append(buf, padBuf...) -} - -// UnpadBuffer verifies that buffer contains proper padding and -// returns buffer without the padding, or nil if the padding was -// invalid. -func UnpadBuffer(buf []byte, dataLen int) []byte { - padding := len(buf) - dataLen - outBuf := buf[:dataLen] - - for i := dataLen; i < len(buf); i++ { - if buf[i] != byte(padding) { - // Invalid padding - bail out - return nil - } - } - - return outBuf -} - -func (e *PublicKey) Encrypt(random io.Reader, kdfParams []byte, plain []byte, hash crypto.Hash, kdfKeySize int) (Vx *big.Int, Vy *big.Int, C []byte, err error) { - // Vx, Vy - encryption key - - // Note for Curve 25519 - curve25519 library already does key - // clamping in scalarMult, so we can use generic random scalar - // generation from elliptic. - priv, Vx, Vy, err := elliptic.GenerateKey(e.Curve, random) - if err != nil { - return nil, nil, nil, err - } - - // Sx, Sy - shared secret - Sx, _ := e.Curve.ScalarMult(e.X, e.Y, priv) - - // Encrypt the payload with KDF-ed S as the encryption key. Pass - // the ciphertext along with V to the recipient. Recipient can - // generate S using V and their priv key, and then KDF(S), on - // their own, to get encryption key and decrypt the ciphertext, - // revealing encryption key for symmetric encryption later. - - plain = PadBuffer(plain, 8) - key := e.KDF(Sx.Bytes(), kdfParams, hash) - - // Take only as many bytes from key as the key length (the hash - // result might be bigger) - encrypted, err := AESKeyWrap(key[:kdfKeySize], plain) - - return Vx, Vy, encrypted, nil -} - -func (e *PrivateKey) DecryptShared(X, Y *big.Int) []byte { - Sx, _ := e.Curve.ScalarMult(X, Y, e.X.Bytes()) - return Sx.Bytes() -} - -func countBits(buffer []byte) int { - var headerLen int - switch buffer[0] { - case 0x4: - headerLen = 3 - case 0x40: - headerLen = 7 - default: - // Unexpected header - but we can still count the bits. - val := buffer[0] - headerLen = 0 - for val > 0 { - val = val / 2 - headerLen++ - } - } - - return headerLen + (len(buffer)-1)*8 -} - -// elliptic.Marshal and elliptic.Unmarshal only marshals uncompressed -// 0x4 MPI types. These functions will check if the curve is cv25519, -// and if so, use 0x40 compressed type to (un)marshal. Otherwise, -// elliptic.(Un)marshal will be called. - -// Marshal encodes point into either 0x4 uncompressed point form, or -// 0x40 compressed point for Curve 25519. -func Marshal(curve elliptic.Curve, x, y *big.Int) (buf []byte, bitSize int) { - // NOTE: Read more about MPI encoding in the RFC: - // https://tools.ietf.org/html/rfc4880#section-3.2 - - // We are required to encode size in bits, counting from the most- - // significant non-zero bit. So assuming that the buffer never - // starts with 0x00, we only need to count bits in the first byte - // - and in current implentation it will always be 0x4 or 0x40. - - cv, ok := curve25519.ToCurve25519(curve) - if ok { - buf = cv.MarshalType40(x, y) - } else { - buf = elliptic.Marshal(curve, x, y) - } - - return buf, countBits(buf) -} - -// Unmarshal converts point, serialized by Marshal, into x, y pair. -// For 0x40 compressed points (for Curve 25519), y will always be 0. -// It is an error if point is not on the curve, On error, x = nil. -func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) { - cv, ok := curve25519.ToCurve25519(curve) - if ok { - return cv.UnmarshalType40(data) - } - - return elliptic.Unmarshal(curve, data) -} - -func GenerateKey(curve elliptic.Curve, random io.Reader) (priv *PrivateKey, err error) { - var privBytes []byte - var Vx, Vy *big.Int - - if _, ok := curve25519.ToCurve25519(curve); ok { - privBytes = make([]byte, 32) - _, err = io.ReadFull(random, privBytes) - if err != nil { - return nil, err - } - - // NOTE: PGP expect scalars in reverse order than Curve 25519 - // go library. That's why this trimming is backwards compared - // to curve25519.go - privBytes[31] &= 248 - privBytes[0] &= 127 - privBytes[0] |= 64 - - Vx,Vy = curve.ScalarBaseMult(privBytes) - } else { - privBytes, Vx, Vy, err = elliptic.GenerateKey(curve, random) - if err != nil { - return nil, err - } - } - - priv = &PrivateKey{} - priv.X = new(big.Int).SetBytes(privBytes) - priv.PublicKey.Curve = curve - priv.PublicKey.X = Vx - priv.PublicKey.Y = Vy - return priv, nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/elgamal/elgamal.go b/vendor/github.com/keybase/go-crypto/openpgp/elgamal/elgamal.go deleted file mode 100644 index 15dafc55..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/elgamal/elgamal.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2011 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 elgamal implements ElGamal encryption, suitable for OpenPGP, -// as specified in "A Public-Key Cryptosystem and a Signature Scheme Based on -// Discrete Logarithms," IEEE Transactions on Information Theory, v. IT-31, -// n. 4, 1985, pp. 469-472. -// -// This form of ElGamal embeds PKCS#1 v1.5 padding, which may make it -// unsuitable for other protocols. RSA should be used in preference in any -// case. -package elgamal // import "github.com/keybase/go-crypto/openpgp/elgamal" - -import ( - "crypto/rand" - "crypto/subtle" - "errors" - "io" - "math/big" -) - -// PublicKey represents an ElGamal public key. -type PublicKey struct { - G, P, Y *big.Int -} - -// PrivateKey represents an ElGamal private key. -type PrivateKey struct { - PublicKey - X *big.Int -} - -// Encrypt encrypts the given message to the given public key. The result is a -// pair of integers. Errors can result from reading random, or because msg is -// too large to be encrypted to the public key. -func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) { - pLen := (pub.P.BitLen() + 7) / 8 - if len(msg) > pLen-11 { - err = errors.New("elgamal: message too long") - return - } - - // EM = 0x02 || PS || 0x00 || M - em := make([]byte, pLen-1) - em[0] = 2 - ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):] - err = nonZeroRandomBytes(ps, random) - if err != nil { - return - } - em[len(em)-len(msg)-1] = 0 - copy(mm, msg) - - m := new(big.Int).SetBytes(em) - - k, err := rand.Int(random, pub.P) - if err != nil { - return - } - - c1 = new(big.Int).Exp(pub.G, k, pub.P) - s := new(big.Int).Exp(pub.Y, k, pub.P) - c2 = s.Mul(s, m) - c2.Mod(c2, pub.P) - - return -} - -// Decrypt takes two integers, resulting from an ElGamal encryption, and -// returns the plaintext of the message. An error can result only if the -// ciphertext is invalid. Users should keep in mind that this is a padding -// oracle and thus, if exposed to an adaptive chosen ciphertext attack, can -// be used to break the cryptosystem. See ``Chosen Ciphertext Attacks -// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel -// Bleichenbacher, Advances in Cryptology (Crypto '98), -func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) { - s := new(big.Int).Exp(c1, priv.X, priv.P) - s.ModInverse(s, priv.P) - s.Mul(s, c2) - s.Mod(s, priv.P) - em := s.Bytes() - - firstByteIsTwo := subtle.ConstantTimeByteEq(em[0], 2) - - // The remainder of the plaintext must be a string of non-zero random - // octets, followed by a 0, followed by the message. - // lookingForIndex: 1 iff we are still looking for the zero. - // index: the offset of the first zero byte. - var lookingForIndex, index int - lookingForIndex = 1 - - for i := 1; i < len(em); i++ { - equals0 := subtle.ConstantTimeByteEq(em[i], 0) - index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) - } - - if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { - return nil, errors.New("elgamal: decryption error") - } - return em[index+1:], nil -} - -// nonZeroRandomBytes fills the given slice with non-zero random octets. -func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { - _, err = io.ReadFull(rand, s) - if err != nil { - return - } - - for i := 0; i < len(s); i++ { - for s[i] == 0 { - _, err = io.ReadFull(rand, s[i:i+1]) - if err != nil { - return - } - } - } - - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/errors/errors.go b/vendor/github.com/keybase/go-crypto/openpgp/errors/errors.go deleted file mode 100644 index 855fa89c..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/errors/errors.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2010 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 errors contains common error types for the OpenPGP packages. -package errors // import "github.com/keybase/go-crypto/openpgp/errors" - -import ( - "strconv" -) - -// A StructuralError is returned when OpenPGP data is found to be syntactically -// invalid. -type StructuralError string - -func (s StructuralError) Error() string { - return "openpgp: invalid data: " + string(s) -} - -// UnsupportedError indicates that, although the OpenPGP data is valid, it -// makes use of currently unimplemented features. -type UnsupportedError string - -func (s UnsupportedError) Error() string { - return "openpgp: unsupported feature: " + string(s) -} - -// InvalidArgumentError indicates that the caller is in error and passed an -// incorrect value. -type InvalidArgumentError string - -func (i InvalidArgumentError) Error() string { - return "openpgp: invalid argument: " + string(i) -} - -// SignatureError indicates that a syntactically valid signature failed to -// validate. -type SignatureError string - -func (b SignatureError) Error() string { - return "openpgp: invalid signature: " + string(b) -} - -type keyIncorrectError int - -func (ki keyIncorrectError) Error() string { - return "openpgp: incorrect key" -} - -var ErrKeyIncorrect error = keyIncorrectError(0) - -type unknownIssuerError int - -func (unknownIssuerError) Error() string { - return "openpgp: signature made by unknown entity" -} - -var ErrUnknownIssuer error = unknownIssuerError(0) - -type keyRevokedError int - -func (keyRevokedError) Error() string { - return "openpgp: signature made by revoked key" -} - -var ErrKeyRevoked error = keyRevokedError(0) - -type UnknownPacketTypeError uint8 - -func (upte UnknownPacketTypeError) Error() string { - return "openpgp: unknown packet type: " + strconv.Itoa(int(upte)) -} - -// DeprecatedKeyError indicates that the key was read and verified -// properly, but uses a deprecated algorithm and can't be used. -type DeprecatedKeyError string - -func (d DeprecatedKeyError) Error() string { - return "openpgp: key is deprecated: " + string(d) -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/keys.go b/vendor/github.com/keybase/go-crypto/openpgp/keys.go deleted file mode 100644 index b30315c4..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/keys.go +++ /dev/null @@ -1,934 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - "crypto/hmac" - "encoding/binary" - "io" - "time" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" - "github.com/keybase/go-crypto/rsa" -) - -// PublicKeyType is the armor type for a PGP public key. -var PublicKeyType = "PGP PUBLIC KEY BLOCK" - -// PrivateKeyType is the armor type for a PGP private key. -var PrivateKeyType = "PGP PRIVATE KEY BLOCK" - -// An Entity represents the components of an OpenPGP key: a primary public key -// (which must be a signing key), one or more identities claimed by that key, -// and zero or more subkeys, which may be encryption keys. -type Entity struct { - PrimaryKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Identities map[string]*Identity // indexed by Identity.Name - Revocations []*packet.Signature - // Revocations that are signed by designated revokers. Reading keys - // will not verify these revocations, because it won't have access to - // issuers' public keys, API consumers should do this instead (or - // not, and just assume that the key is probably revoked). - UnverifiedRevocations []*packet.Signature - Subkeys []Subkey - BadSubkeys []BadSubkey -} - -// An Identity represents an identity claimed by an Entity and zero or more -// assertions by other entities about that claim. -type Identity struct { - Name string // by convention, has the form "Full Name (comment) " - UserId *packet.UserId - SelfSignature *packet.Signature - Signatures []*packet.Signature - Revocation *packet.Signature -} - -// A Subkey is an additional public key in an Entity. Subkeys can be used for -// encryption. -type Subkey struct { - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Sig *packet.Signature - Revocation *packet.Signature -} - -// BadSubkey is one that failed reconstruction, but we'll keep it around for -// informational purposes. -type BadSubkey struct { - Subkey - Err error -} - -// A Key identifies a specific public key in an Entity. This is either the -// Entity's primary key or a subkey. -type Key struct { - Entity *Entity - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - SelfSignature *packet.Signature - KeyFlags packet.KeyFlagBits -} - -// A KeyRing provides access to public and private keys. -type KeyRing interface { - - // KeysById returns the set of keys that have the given key id. - // fp can be optionally supplied, which is the full key fingerprint. - // If it's provided, then it must match. This comes up in the case - // of GPG subpacket 33. - KeysById(id uint64, fp []byte) []Key - - // KeysByIdAndUsage returns the set of keys with the given id - // that also meet the key usage given by requiredUsage. - // The requiredUsage is expressed as the bitwise-OR of - // packet.KeyFlag* values. - // fp can be optionally supplied, which is the full key fingerprint. - // If it's provided, then it must match. This comes up in the case - // of GPG subpacket 33. - KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) []Key - - // DecryptionKeys returns all private keys that are valid for - // decryption. - DecryptionKeys() []Key -} - -// primaryIdentity returns the Identity marked as primary or the first identity -// if none are so marked. -func (e *Entity) primaryIdentity() *Identity { - var firstIdentity *Identity - for _, ident := range e.Identities { - if firstIdentity == nil { - firstIdentity = ident - } - if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { - return ident - } - } - return firstIdentity -} - -// encryptionKey returns the best candidate Key for encrypting a message to the -// given Entity. -func (e *Entity) encryptionKey(now time.Time) (Key, bool) { - candidateSubkey := -1 - - // Iterate the keys to find the newest, non-revoked key that can - // encrypt. - var maxTime time.Time - for i, subkey := range e.Subkeys { - - // NOTE(maxtaco) - // If there is a Flags subpacket, then we have to follow it, and only - // use keys that are marked for Encryption of Communication. If there - // isn't a Flags subpacket, and this is an Encrypt-Only key (right now only ElGamal - // suffices), then we implicitly use it. The check for primary below is a little - // more open-ended, but for now, let's be strict and potentially open up - // if we see bugs in the wild. - // - // One more note: old DSA/ElGamal keys tend not to have the Flags subpacket, - // so this sort of thing is pretty important for encrypting to older keys. - // - if ((subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications) || - (!subkey.Sig.FlagsValid && subkey.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal)) && - subkey.PublicKey.PubKeyAlgo.CanEncrypt() && - !subkey.Sig.KeyExpired(now) && - subkey.Revocation == nil && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { - candidateSubkey = i - maxTime = subkey.Sig.CreationTime - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true - } - - // If we don't have any candidate subkeys for encryption and - // the primary key doesn't have any usage metadata then we - // assume that the primary key is ok. Or, if the primary key is - // marked as ok to encrypt to, then we can obviously use it. - // - // NOTE(maxtaco) - see note above, how this policy is a little too open-ended - // for my liking, but leave it for now. - i := e.primaryIdentity() - if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications) && - e.PrimaryKey.PubKeyAlgo.CanEncrypt() && - !i.SelfSignature.KeyExpired(now) { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true - } - - // This Entity appears to be signing only. - return Key{}, false -} - -// signingKey return the best candidate Key for signing a message with this -// Entity. -func (e *Entity) signingKey(now time.Time) (Key, bool) { - candidateSubkey := -1 - - // Iterate the keys to find the newest, non-revoked key that can - // sign. - var maxTime time.Time - for i, subkey := range e.Subkeys { - if (!subkey.Sig.FlagsValid || subkey.Sig.FlagSign) && - subkey.PrivateKey.PrivateKey != nil && - subkey.PublicKey.PubKeyAlgo.CanSign() && - !subkey.Sig.KeyExpired(now) && - subkey.Revocation == nil && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { - candidateSubkey = i - maxTime = subkey.Sig.CreationTime - break - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true - } - - // If we have no candidate subkey then we assume that it's ok to sign - // with the primary key. - i := e.primaryIdentity() - if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign) && - e.PrimaryKey.PubKeyAlgo.CanSign() && - !i.SelfSignature.KeyExpired(now) && - e.PrivateKey.PrivateKey != nil { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true - } - - return Key{}, false -} - -// An EntityList contains one or more Entities. -type EntityList []*Entity - -func keyMatchesIdAndFingerprint(key *packet.PublicKey, id uint64, fp []byte) bool { - if key.KeyId != id { - return false - } - if fp == nil { - return true - } - return hmac.Equal(fp, key.Fingerprint[:]) -} - -// KeysById returns the set of keys that have the given key id. -// fp can be optionally supplied, which is the full key fingerprint. -// If it's provided, then it must match. This comes up in the case -// of GPG subpacket 33. -func (el EntityList) KeysById(id uint64, fp []byte) (keys []Key) { - for _, e := range el { - if keyMatchesIdAndFingerprint(e.PrimaryKey, id, fp) { - var selfSig *packet.Signature - for _, ident := range e.Identities { - if selfSig == nil { - selfSig = ident.SelfSignature - } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { - selfSig = ident.SelfSignature - break - } - } - - var keyFlags packet.KeyFlagBits - for _, ident := range e.Identities { - keyFlags.Merge(ident.SelfSignature.GetKeyFlags()) - } - - keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, keyFlags}) - } - - for _, subKey := range e.Subkeys { - if keyMatchesIdAndFingerprint(subKey.PublicKey, id, fp) { - - // If there's both a a revocation and a sig, then take the - // revocation. Otherwise, we can proceed with the sig. - sig := subKey.Revocation - if sig == nil { - sig = subKey.Sig - } - - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, sig, sig.GetKeyFlags()}) - } - } - } - return -} - -// KeysByIdAndUsage returns the set of keys with the given id that also meet -// the key usage given by requiredUsage. The requiredUsage is expressed as -// the bitwise-OR of packet.KeyFlag* values. -// fp can be optionally supplied, which is the full key fingerprint. -// If it's provided, then it must match. This comes up in the case -// of GPG subpacket 33. -func (el EntityList) KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) (keys []Key) { - for _, key := range el.KeysById(id, fp) { - if len(key.Entity.Revocations) > 0 { - continue - } - - if key.SelfSignature.RevocationReason != nil { - continue - } - - if requiredUsage != 0 { - var usage byte - - switch { - case key.KeyFlags.Valid: - usage = key.KeyFlags.BitField - - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal: - // We also need to handle the case where, although the sig's - // flags aren't valid, the key can is implicitly usable for - // encryption by virtue of being ElGamal. See also the comment - // in encryptionKey() above. - usage |= packet.KeyFlagEncryptCommunications - usage |= packet.KeyFlagEncryptStorage - - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoDSA || - key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoECDSA || - key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA: - usage |= packet.KeyFlagSign - - // For a primary RSA key without any key flags, be as permissiable - // as possible. - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoRSA && - keyMatchesIdAndFingerprint(key.Entity.PrimaryKey, id, fp): - usage = (packet.KeyFlagCertify | packet.KeyFlagSign | - packet.KeyFlagEncryptCommunications | packet.KeyFlagEncryptStorage) - } - - if usage&requiredUsage != requiredUsage { - continue - } - } - - keys = append(keys, key) - } - return -} - -// DecryptionKeys returns all private keys that are valid for decryption. -func (el EntityList) DecryptionKeys() (keys []Key) { - for _, e := range el { - for _, subKey := range e.Subkeys { - if subKey.PrivateKey != nil && subKey.PrivateKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Sig.GetKeyFlags()}) - } - } - } - return -} - -// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. -func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { - block, err := armor.Decode(r) - if err == io.EOF { - return nil, errors.InvalidArgumentError("no armored data found") - } - if err != nil { - return nil, err - } - if block.Type != PublicKeyType && block.Type != PrivateKeyType { - return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) - } - - return ReadKeyRing(block.Body) -} - -// ReadKeyRing reads one or more public/private keys. Unsupported keys are -// ignored as long as at least a single valid key is found. -func ReadKeyRing(r io.Reader) (el EntityList, err error) { - packets := packet.NewReader(r) - var lastUnsupportedError error - - for { - var e *Entity - e, err = ReadEntity(packets) - if err != nil { - // TODO: warn about skipped unsupported/unreadable keys - if _, ok := err.(errors.UnsupportedError); ok { - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } else if _, ok := err.(errors.StructuralError); ok { - // Skip unreadable, badly-formatted keys - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } - if err == io.EOF { - err = nil - break - } - if err != nil { - el = nil - break - } - } else { - el = append(el, e) - } - } - - if len(el) == 0 && err == nil { - err = lastUnsupportedError - } - return -} - -// readToNextPublicKey reads packets until the start of the entity and leaves -// the first packet of the new entity in the Reader. -func readToNextPublicKey(packets *packet.Reader) (err error) { - var p packet.Packet - for { - p, err = packets.Next() - if err == io.EOF { - return - } else if err != nil { - if _, ok := err.(errors.UnsupportedError); ok { - err = nil - continue - } - return - } - - if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { - packets.Unread(p) - return - } - } - - panic("unreachable") -} - -// ReadEntity reads an entity (public key, identities, subkeys etc) from the -// given Reader. -func ReadEntity(packets *packet.Reader) (*Entity, error) { - e := new(Entity) - e.Identities = make(map[string]*Identity) - - p, err := packets.Next() - if err != nil { - return nil, err - } - - var ok bool - if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { - if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { - packets.Unread(p) - return nil, errors.StructuralError("first packet was not a public/private key") - } else { - e.PrimaryKey = &e.PrivateKey.PublicKey - } - } - - if !e.PrimaryKey.PubKeyAlgo.CanSign() { - return nil, errors.StructuralError("primary key cannot be used for signatures") - } - - var current *Identity - var revocations []*packet.Signature - - designatedRevokers := make(map[uint64]bool) -EachPacket: - for { - p, err := packets.Next() - if err == io.EOF { - break - } else if err != nil { - return nil, err - } - switch pkt := p.(type) { - case *packet.UserId: - - // Make a new Identity object, that we might wind up throwing away. - // We'll only add it if we get a valid self-signature over this - // userID. - current = new(Identity) - current.Name = pkt.Id - current.UserId = pkt - case *packet.Signature: - if pkt.SigType == packet.SigTypeKeyRevocation { - // These revocations won't revoke UIDs (see - // SigTypeIdentityRevocation). Handle these first, - // because key might have revocation coming from - // another key (designated revoke). - revocations = append(revocations, pkt) - continue - } - - // These are signatures by other people on this key. Let's just ignore them - // from the beginning, since they shouldn't affect our key decoding one way - // or the other. - if pkt.IssuerKeyId != nil && *pkt.IssuerKeyId != e.PrimaryKey.KeyId { - continue - } - - // If this is a signature made by the keyholder, and the signature has stubbed out - // critical packets, then *now* we need to bail out. - if e := pkt.StubbedOutCriticalError; e != nil { - return nil, e - } - - // Next handle the case of a self-signature. According to RFC8440, - // Section 5.2.3.3, if there are several self-signatures, - // we should take the newer one. If they were both created - // at the same time, but one of them has keyflags specified and the - // other doesn't, keep the one with the keyflags. We have actually - // seen this in the wild (see the 'Yield' test in read_test.go). - // If there is a tie, and both have the same value for FlagsValid, - // then "last writer wins." - // - // HOWEVER! We have seen yet more keys in the wild (see the 'Spiros' - // test in read_test.go), in which the later self-signature is a bunch - // of junk, and doesn't even specify key flags. Does it really make - // sense to overwrite reasonable key flags with the empty set? I'm not - // sure what that would be trying to achieve, and plus GPG seems to be - // ok with this situation, and ignores the later (empty) keyflag set. - // So further tighten our overwrite rules, and only allow the later - // signature to overwrite the earlier signature if so doing won't - // trash the key flags. - if current != nil && - (current.SelfSignature == nil || - (!pkt.CreationTime.Before(current.SelfSignature.CreationTime) && - (pkt.FlagsValid || !current.SelfSignature.FlagsValid))) && - (pkt.SigType == packet.SigTypePositiveCert || pkt.SigType == packet.SigTypeGenericCert) && - pkt.IssuerKeyId != nil && - *pkt.IssuerKeyId == e.PrimaryKey.KeyId { - - if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil { - - current.SelfSignature = pkt - - // NOTE(maxtaco) 2016.01.11 - // Only register an identity once we've gotten a valid self-signature. - // It's possible therefore for us to throw away `current` in the case - // no valid self-signatures were found. That's OK as long as there are - // other identities that make sense. - // - // NOTE! We might later see a revocation for this very same UID, and it - // won't be undone. We've preserved this feature from the original - // Google OpenPGP we forked from. - e.Identities[current.Name] = current - } else { - // We really should warn that there was a failure here. Not raise an error - // since this really shouldn't be a fail-stop error. - } - } else if current != nil && pkt.SigType == packet.SigTypeIdentityRevocation { - if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil { - // Note: we are not removing the identity from - // e.Identities. Caller can always filter by Revocation - // field to ignore revoked identities. - current.Revocation = pkt - } - } else if pkt.SigType == packet.SigTypeDirectSignature { - if err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, pkt); err == nil { - if desig := pkt.DesignatedRevoker; desig != nil { - // If it's a designated revoker signature, take last 8 octects - // of fingerprint as Key ID and save it to designatedRevokers - // map. We consult this map later to see if a foreign - // revocation should be added to UnverifiedRevocations. - keyID := binary.BigEndian.Uint64(desig.Fingerprint[len(desig.Fingerprint)-8:]) - designatedRevokers[keyID] = true - } - } - } else if current == nil { - // NOTE(maxtaco) - // - // See https://github.com/keybase/client/issues/2666 - // - // There might have been a user attribute picture before this signature, - // in which case this is still a valid PGP key. In the future we might - // not ignore user attributes (like picture). But either way, it doesn't - // make sense to bail out here. Keep looking for other valid signatures. - // - // Used to be: - // return nil, errors.StructuralError("signature packet found before user id packet") - } else { - current.Signatures = append(current.Signatures, pkt) - } - case *packet.PrivateKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, &pkt.PublicKey, pkt) - if err != nil { - return nil, err - } - case *packet.PublicKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, pkt, nil) - if err != nil { - return nil, err - } - default: - // we ignore unknown packets - } - } - - if len(e.Identities) == 0 { - return nil, errors.StructuralError("entity without any identities") - } - - for _, revocation := range revocations { - if revocation.IssuerKeyId == nil || *revocation.IssuerKeyId == e.PrimaryKey.KeyId { - // Key revokes itself, something that we can verify. - err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, revocation) - if err == nil { - e.Revocations = append(e.Revocations, revocation) - } else { - return nil, errors.StructuralError("revocation signature signed by alternate key") - } - } else if revocation.IssuerKeyId != nil { - if _, ok := designatedRevokers[*revocation.IssuerKeyId]; ok { - // Revocation is done by certified designated revoker, - // but we can't verify the revocation. - e.UnverifiedRevocations = append(e.UnverifiedRevocations, revocation) - } - } - } - - return e, nil -} - -func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { - var subKey Subkey - subKey.PublicKey = pub - subKey.PrivateKey = priv - var lastErr error - for { - p, err := packets.Next() - if err == io.EOF { - break - } - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } - sig, ok := p.(*packet.Signature) - if !ok { - // Hit a non-signature packet, so assume we're up to the next key - packets.Unread(p) - break - } - if st := sig.SigType; st != packet.SigTypeSubkeyBinding && st != packet.SigTypeSubkeyRevocation { - - // Note(maxtaco): - // We used to error out here, but instead, let's fast-forward past - // packets that are in the wrong place (like misplaced 0x13 signatures) - // until we get to one that works. For a test case, - // see TestWithBadSubkeySignaturePackets. - - continue - } - err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig) - if err != nil { - // Non valid signature, so again, no need to abandon all hope, just continue; - // make a note of the error we hit. - lastErr = errors.StructuralError("subkey signature invalid: " + err.Error()) - continue - } - switch sig.SigType { - case packet.SigTypeSubkeyBinding: - // Does the "new" sig set expiration to later date than - // "previous" sig? - if subKey.Sig == nil || subKey.Sig.ExpiresBeforeOther(sig) { - subKey.Sig = sig - } - case packet.SigTypeSubkeyRevocation: - // First writer wins - if subKey.Revocation == nil { - subKey.Revocation = sig - } - } - } - - if subKey.Sig != nil { - if err := subKey.PublicKey.ErrorIfDeprecated(); err != nil { - // Key passed signature check but is deprecated. - subKey.Sig = nil - lastErr = err - } - } - - if subKey.Sig != nil { - e.Subkeys = append(e.Subkeys, subKey) - } else { - if lastErr == nil { - lastErr = errors.StructuralError("Subkey wasn't signed; expected a 'binding' signature") - } - e.BadSubkeys = append(e.BadSubkeys, BadSubkey{Subkey: subKey, Err: lastErr}) - } - return nil -} - -const defaultRSAKeyBits = 2048 - -// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a -// single identity composed of the given full name, comment and email, any of -// which may be empty but must not contain any of "()<>\x00". -// If config is nil, sensible defaults will be used. -func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { - currentTime := config.Now() - - bits := defaultRSAKeyBits - if config != nil && config.RSABits != 0 { - bits = config.RSABits - } - - uid := packet.NewUserId(name, comment, email) - if uid == nil { - return nil, errors.InvalidArgumentError("user id field contained invalid characters") - } - signingPriv, err := rsa.GenerateKey(config.Random(), bits) - if err != nil { - return nil, err - } - encryptingPriv, err := rsa.GenerateKey(config.Random(), bits) - if err != nil { - return nil, err - } - - e := &Entity{ - PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey), - PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv), - Identities: make(map[string]*Identity), - } - isPrimaryId := true - e.Identities[uid.Id] = &Identity{ - Name: uid.Id, - UserId: uid, - SelfSignature: &packet.Signature{ - CreationTime: currentTime, - SigType: packet.SigTypePositiveCert, - PubKeyAlgo: packet.PubKeyAlgoRSA, - Hash: config.Hash(), - IsPrimaryId: &isPrimaryId, - FlagsValid: true, - FlagSign: true, - FlagCertify: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - } - - // If the user passes in a DefaultHash via packet.Config, set the - // PreferredHash for the SelfSignature. - if config != nil && config.DefaultHash != 0 { - e.Identities[uid.Id].SelfSignature.PreferredHash = []uint8{hashToHashId(config.DefaultHash)} - } - - // Likewise for DefaultCipher. - if config != nil && config.DefaultCipher != 0 { - e.Identities[uid.Id].SelfSignature.PreferredSymmetric = []uint8{uint8(config.DefaultCipher)} - } - - e.Subkeys = make([]Subkey, 1) - e.Subkeys[0] = Subkey{ - PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), - PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv), - Sig: &packet.Signature{ - CreationTime: currentTime, - SigType: packet.SigTypeSubkeyBinding, - PubKeyAlgo: packet.PubKeyAlgoRSA, - Hash: config.Hash(), - FlagsValid: true, - FlagEncryptStorage: true, - FlagEncryptCommunications: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - } - e.Subkeys[0].PublicKey.IsSubkey = true - e.Subkeys[0].PrivateKey.IsSubkey = true - - return e, nil -} - -// SerializePrivate serializes an Entity, including private key material, to -// the given Writer. For now, it must only be used on an Entity returned from -// NewEntity. -// If config is nil, sensible defaults will be used. -func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { - err = e.PrivateKey.Serialize(w) - if err != nil { - return - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return - } - if e.PrivateKey.PrivateKey != nil { - err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config) - if err != nil { - return - } - } - err = ident.SelfSignature.Serialize(w) - if err != nil { - return - } - } - for _, subkey := range e.Subkeys { - err = subkey.PrivateKey.Serialize(w) - if err != nil { - return - } - if e.PrivateKey.PrivateKey != nil && !config.ReuseSignatures() { - // If not reusing existing signatures, sign subkey using private key - // (subkey binding), but also sign primary key using subkey (primary - // key binding) if subkey is used for signing. - if subkey.Sig.FlagSign { - err = subkey.Sig.CrossSignKey(e.PrimaryKey, subkey.PrivateKey, config) - if err != nil { - return err - } - } - err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) - if err != nil { - return - } - } - - if subkey.Revocation != nil { - err = subkey.Revocation.Serialize(w) - if err != nil { - return - } - } - - err = subkey.Sig.Serialize(w) - if err != nil { - return - } - } - return nil -} - -// Serialize writes the public part of the given Entity to w. (No private -// key material will be output). -func (e *Entity) Serialize(w io.Writer) error { - err := e.PrimaryKey.Serialize(w) - if err != nil { - return err - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return err - } - err = ident.SelfSignature.Serialize(w) - if err != nil { - return err - } - for _, sig := range ident.Signatures { - err = sig.Serialize(w) - if err != nil { - return err - } - } - } - for _, subkey := range e.Subkeys { - err = subkey.PublicKey.Serialize(w) - if err != nil { - return err - } - - if subkey.Revocation != nil { - err = subkey.Revocation.Serialize(w) - if err != nil { - return err - } - } - err = subkey.Sig.Serialize(w) - if err != nil { - return err - } - } - return nil -} - -// SignIdentity adds a signature to e, from signer, attesting that identity is -// associated with e. The provided identity must already be an element of -// e.Identities and the private key of signer must have been decrypted if -// necessary. -// If config is nil, sensible defaults will be used. -func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error { - if signer.PrivateKey == nil { - return errors.InvalidArgumentError("signing Entity must have a private key") - } - if signer.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing Entity's private key must be decrypted") - } - ident, ok := e.Identities[identity] - if !ok { - return errors.InvalidArgumentError("given identity string not found in Entity") - } - - sig := &packet.Signature{ - SigType: packet.SigTypeGenericCert, - PubKeyAlgo: signer.PrivateKey.PubKeyAlgo, - Hash: config.Hash(), - CreationTime: config.Now(), - IssuerKeyId: &signer.PrivateKey.KeyId, - } - if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil { - return err - } - ident.Signatures = append(ident.Signatures, sig) - return nil -} - -// CopySubkeyRevocations copies subkey revocations from the src Entity over -// to the receiver entity. We need this because `gpg --export-secret-key` does -// not appear to output subkey revocations. In this case we need to manually -// merge with the output of `gpg --export`. -func (e *Entity) CopySubkeyRevocations(src *Entity) { - m := make(map[[20]byte]*packet.Signature) - for _, subkey := range src.Subkeys { - if subkey.Revocation != nil { - m[subkey.PublicKey.Fingerprint] = subkey.Revocation - } - } - for i, subkey := range e.Subkeys { - if r := m[subkey.PublicKey.Fingerprint]; r != nil { - e.Subkeys[i].Revocation = r - } - } -} - -// CheckDesignatedRevokers will try to confirm any of designated -// revocation of entity. For this function to work, revocation -// issuer's key should be found in keyring. First successfully -// verified designated revocation is returned along with the key that -// verified it. -func FindVerifiedDesignatedRevoke(keyring KeyRing, entity *Entity) (*packet.Signature, *Key) { - for _, sig := range entity.UnverifiedRevocations { - if sig.IssuerKeyId == nil { - continue - } - - issuerKeyId := *sig.IssuerKeyId - issuerFingerprint := sig.IssuerFingerprint - keys := keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign) - if len(keys) == 0 { - continue - } - for _, key := range keys { - err := key.PublicKey.VerifyRevocationSignature(entity.PrimaryKey, sig) - if err == nil { - return sig, &key - } - } - } - - return nil, nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go deleted file mode 100644 index f023fe53..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "compress/bzip2" - "compress/flate" - "compress/zlib" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// Compressed represents a compressed OpenPGP packet. The decompressed contents -// will contain more OpenPGP packets. See RFC 4880, section 5.6. -type Compressed struct { - Body io.Reader -} - -const ( - NoCompression = flate.NoCompression - BestSpeed = flate.BestSpeed - BestCompression = flate.BestCompression - DefaultCompression = flate.DefaultCompression -) - -// CompressionConfig contains compressor configuration settings. -type CompressionConfig struct { - // Level is the compression level to use. It must be set to - // between -1 and 9, with -1 causing the compressor to use the - // default compression level, 0 causing the compressor to use - // no compression and 1 to 9 representing increasing (better, - // slower) compression levels. If Level is less than -1 or - // more then 9, a non-nil error will be returned during - // encryption. See the constants above for convenient common - // settings for Level. - Level int -} - -func (c *Compressed) parse(r io.Reader) error { - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - - switch buf[0] { - case 1: - c.Body = flate.NewReader(r) - case 2: - c.Body, err = zlib.NewReader(r) - case 3: - c.Body = bzip2.NewReader(r) - default: - err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) - } - - return err -} - -// compressedWriterCloser represents the serialized compression stream -// header and the compressor. Its Close() method ensures that both the -// compressor and serialized stream header are closed. Its Write() -// method writes to the compressor. -type compressedWriteCloser struct { - sh io.Closer // Stream Header - c io.WriteCloser // Compressor -} - -func (cwc compressedWriteCloser) Write(p []byte) (int, error) { - return cwc.c.Write(p) -} - -func (cwc compressedWriteCloser) Close() (err error) { - err = cwc.c.Close() - if err != nil { - return err - } - - return cwc.sh.Close() -} - -// SerializeCompressed serializes a compressed data packet to w and -// returns a WriteCloser to which the literal data packets themselves -// can be written and which MUST be closed on completion. If cc is -// nil, sensible defaults will be used to configure the compression -// algorithm. -func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) { - compressed, err := serializeStreamHeader(w, packetTypeCompressed) - if err != nil { - return - } - - _, err = compressed.Write([]byte{uint8(algo)}) - if err != nil { - return - } - - level := DefaultCompression - if cc != nil { - level = cc.Level - } - - var compressor io.WriteCloser - switch algo { - case CompressionZIP: - compressor, err = flate.NewWriter(compressed, level) - case CompressionZLIB: - compressor, err = zlib.NewWriterLevel(compressed, level) - default: - s := strconv.Itoa(int(algo)) - err = errors.UnsupportedError("Unsupported compression algorithm: " + s) - } - if err != nil { - return - } - - literaldata = compressedWriteCloser{compressed, compressor} - - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go deleted file mode 100644 index f4125e18..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2012 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 packet - -import ( - "crypto" - "crypto/rand" - "io" - "time" -) - -// Config collects a number of parameters along with sensible defaults. -// A nil *Config is valid and results in all default values. -type Config struct { - // Rand provides the source of entropy. - // If nil, the crypto/rand Reader is used. - Rand io.Reader - // DefaultHash is the default hash function to be used. - // If zero, SHA-256 is used. - DefaultHash crypto.Hash - // DefaultCipher is the cipher to be used. - // If zero, AES-128 is used. - DefaultCipher CipherFunction - // Time returns the current time as the number of seconds since the - // epoch. If Time is nil, time.Now is used. - Time func() time.Time - // DefaultCompressionAlgo is the compression algorithm to be - // applied to the plaintext before encryption. If zero, no - // compression is done. - DefaultCompressionAlgo CompressionAlgo - // CompressionConfig configures the compression settings. - CompressionConfig *CompressionConfig - // S2KCount is only used for symmetric encryption. It - // determines the strength of the passphrase stretching when - // the said passphrase is hashed to produce a key. S2KCount - // should be between 1024 and 65011712, inclusive. If Config - // is nil or S2KCount is 0, the value 65536 used. Not all - // values in the above range can be represented. S2KCount will - // be rounded up to the next representable value if it cannot - // be encoded exactly. When set, it is strongly encrouraged to - // use a value that is at least 65536. See RFC 4880 Section - // 3.7.1.3. - S2KCount int - // RSABits is the number of bits in new RSA keys made with NewEntity. - // If zero, then 2048 bit keys are created. - RSABits int - // ReuseSignatures tells us to reuse existing Signatures - // on serialized output. - ReuseSignaturesOnSerialize bool -} - -func (c *Config) Random() io.Reader { - if c == nil || c.Rand == nil { - return rand.Reader - } - return c.Rand -} - -func (c *Config) Hash() crypto.Hash { - if c == nil || uint(c.DefaultHash) == 0 { - return crypto.SHA256 - } - return c.DefaultHash -} - -func (c *Config) Cipher() CipherFunction { - if c == nil || uint8(c.DefaultCipher) == 0 { - return CipherAES128 - } - return c.DefaultCipher -} - -func (c *Config) Now() time.Time { - if c == nil || c.Time == nil { - return time.Now() - } - return c.Time() -} - -func (c *Config) Compression() CompressionAlgo { - if c == nil { - return CompressionNone - } - return c.DefaultCompressionAlgo -} - -func (c *Config) PasswordHashIterations() int { - if c == nil || c.S2KCount == 0 { - return 0 - } - return c.S2KCount -} - -func (c *Config) ReuseSignatures() bool { - return c != nil && c.ReuseSignaturesOnSerialize -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go deleted file mode 100644 index 41de661d..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go +++ /dev/null @@ -1,104 +0,0 @@ -package packet - -import ( - "bytes" - "io" - "math/big" - - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// ECDHKdfParams generates KDF parameters sequence for given -// PublicKey. See https://tools.ietf.org/html/rfc6637#section-8 -func ECDHKdfParams(pub *PublicKey) []byte { - buf := new(bytes.Buffer) - oid := pub.ec.oid - buf.WriteByte(byte(len(oid))) - buf.Write(oid) - buf.WriteByte(18) // ECDH TYPE - pub.ecdh.serialize(buf) - buf.WriteString("Anonymous Sender ") - buf.Write(pub.Fingerprint[:]) - return buf.Bytes() -} - -func decryptKeyECDH(priv *PrivateKey, X, Y *big.Int, C []byte) (out []byte, err error) { - ecdhpriv, ok := priv.PrivateKey.(*ecdh.PrivateKey) - if !ok { - return nil, errors.InvalidArgumentError("bad internal ECDH key") - } - - Sx := ecdhpriv.DecryptShared(X, Y) - - kdfParams := ECDHKdfParams(&priv.PublicKey) - hash, ok := s2k.HashIdToHash(byte(priv.ecdh.KdfHash)) - if !ok { - return nil, errors.InvalidArgumentError("invalid hash id in private key") - } - - key := ecdhpriv.KDF(Sx, kdfParams, hash) - keySize := CipherFunction(priv.ecdh.KdfAlgo).KeySize() - - decrypted, err := ecdh.AESKeyUnwrap(key[:keySize], C) - if err != nil { - return nil, err - } - - // We have to "read ahead" to discover real length of the - // encryption key and properly unpad buffer. - cipherFunc := CipherFunction(decrypted[0]) - // +3 bytes = 1-byte cipher id and checksum 2-byte checksum. - out = ecdh.UnpadBuffer(decrypted, cipherFunc.KeySize()+3) - if out == nil { - return nil, errors.InvalidArgumentError("invalid padding while ECDH") - } - return out, nil -} - -func serializeEncryptedKeyECDH(w io.Writer, rand io.Reader, header [10]byte, pub *PublicKey, keyBlock []byte) error { - ecdhpub := pub.PublicKey.(*ecdh.PublicKey) - kdfParams := ECDHKdfParams(pub) - - hash, ok := s2k.HashIdToHash(byte(pub.ecdh.KdfHash)) - if !ok { - return errors.InvalidArgumentError("invalid hash id in private key") - } - - kdfKeySize := CipherFunction(pub.ecdh.KdfAlgo).KeySize() - Vx, Vy, C, err := ecdhpub.Encrypt(rand, kdfParams, keyBlock, hash, kdfKeySize) - if err != nil { - return err - } - - mpis, mpiBitLen := ecdh.Marshal(ecdhpub.Curve, Vx, Vy) - - packetLen := len(header) /* header length in bytes */ - packetLen += 2 /* mpi length in bits */ + len(mpis) - packetLen += 1 /* ciphertext size in bytes */ + len(C) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - - _, err = w.Write(header[:]) - if err != nil { - return err - } - - _, err = w.Write([]byte{byte(mpiBitLen >> 8), byte(mpiBitLen)}) - if err != nil { - return err - } - - _, err = w.Write(mpis[:]) - if err != nil { - return err - } - - w.Write([]byte{byte(len(C))}) - w.Write(C[:]) - return nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go deleted file mode 100644 index c0b6c954..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "encoding/binary" - "io" - "math/big" - "strconv" - - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/rsa" -) - -const encryptedKeyVersion = 3 - -// EncryptedKey represents a public-key encrypted session key. See RFC 4880, -// section 5.1. -type EncryptedKey struct { - KeyId uint64 - Algo PublicKeyAlgorithm - CipherFunc CipherFunction // only valid after a successful Decrypt - Key []byte // only valid after a successful Decrypt - - encryptedMPI1, encryptedMPI2 parsedMPI - ecdh_C []byte -} - -func (e *EncryptedKey) parse(r io.Reader) (err error) { - var buf [10]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != encryptedKeyVersion { - return errors.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) - } - e.KeyId = binary.BigEndian.Uint64(buf[1:9]) - e.Algo = PublicKeyAlgorithm(buf[9]) - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - case PubKeyAlgoElGamal: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - if err != nil { - return - } - e.encryptedMPI2.bytes, e.encryptedMPI2.bitLength, err = readMPI(r) - case PubKeyAlgoECDH: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - if err != nil { - return err - } - _, err = readFull(r, buf[:1]) // read C len (1 byte) - if err != nil { - return err - } - e.ecdh_C = make([]byte, int(buf[0])) - _, err = readFull(r, e.ecdh_C) - } - - if err != nil { - return err - } - - _, err = consumeAll(r) - return err -} - -func checksumKeyMaterial(key []byte) uint16 { - var checksum uint16 - for _, v := range key { - checksum += uint16(v) - } - return checksum -} - -// Decrypt decrypts an encrypted session key with the given private key. The -// private key must have been decrypted first. -// If config is nil, sensible defaults will be used. -func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error { - var err error - var b []byte - - // TODO(agl): use session key decryption routines here to avoid - // padding oracle attacks. - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - k := priv.PrivateKey.(*rsa.PrivateKey) - b, err = rsa.DecryptPKCS1v15(config.Random(), k, padToKeySize(&k.PublicKey, e.encryptedMPI1.bytes)) - case PubKeyAlgoElGamal: - c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes) - c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes) - b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) - case PubKeyAlgoECDH: - // Note: Unmarshal checks if point is on the curve. - c1, c2 := ecdh.Unmarshal(priv.PrivateKey.(*ecdh.PrivateKey).Curve, e.encryptedMPI1.bytes) - if c1 == nil { - return errors.InvalidArgumentError("failed to parse EC point for encryption key") - } - b, err = decryptKeyECDH(priv, c1, c2, e.ecdh_C) - default: - err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - - if err != nil { - return err - } - - e.CipherFunc = CipherFunction(b[0]) - e.Key = b[1 : len(b)-2] - expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) - checksum := checksumKeyMaterial(e.Key) - if checksum != expectedChecksum { - return errors.StructuralError("EncryptedKey checksum incorrect") - } - - return nil -} - -// Serialize writes the encrypted key packet, e, to w. -func (e *EncryptedKey) Serialize(w io.Writer) error { - var mpiLen int - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - mpiLen = 2 + len(e.encryptedMPI1.bytes) - case PubKeyAlgoElGamal: - mpiLen = 2 + len(e.encryptedMPI1.bytes) + 2 + len(e.encryptedMPI2.bytes) - default: - return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo))) - } - - serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) - - w.Write([]byte{encryptedKeyVersion}) - binary.Write(w, binary.BigEndian, e.KeyId) - w.Write([]byte{byte(e.Algo)}) - - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - writeMPIs(w, e.encryptedMPI1) - case PubKeyAlgoElGamal: - writeMPIs(w, e.encryptedMPI1, e.encryptedMPI2) - default: - panic("internal error") - } - - return nil -} - -// SerializeEncryptedKey serializes an encrypted key packet to w that contains -// key, encrypted to pub. -// If config is nil, sensible defaults will be used. -func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error { - var buf [10]byte - buf[0] = encryptedKeyVersion - binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) - buf[9] = byte(pub.PubKeyAlgo) - - keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */) - keyBlock[0] = byte(cipherFunc) - copy(keyBlock[1:], key) - checksum := checksumKeyMaterial(key) - keyBlock[1+len(key)] = byte(checksum >> 8) - keyBlock[1+len(key)+1] = byte(checksum) - - switch pub.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock) - case PubKeyAlgoElGamal: - return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) - case PubKeyAlgoECDH: - return serializeEncryptedKeyECDH(w, config.Random(), buf, pub, keyBlock) - case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: - return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) - } - - return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) -} - -func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error { - cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("RSA encryption failed: " + err.Error()) - } - - packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - return writeMPI(w, 8*uint16(len(cipherText)), cipherText) -} - -func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error { - c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error()) - } - - packetLen := 10 /* header length */ - packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8 - packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8 - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - err = writeBig(w, c1) - if err != nil { - return err - } - return writeBig(w, c2) -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go deleted file mode 100644 index 1a9ec6e5..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "encoding/binary" - "io" -) - -// LiteralData represents an encrypted file. See RFC 4880, section 5.9. -type LiteralData struct { - IsBinary bool - FileName string - Time uint32 // Unix epoch time. Either creation time or modification time. 0 means undefined. - Body io.Reader -} - -// ForEyesOnly returns whether the contents of the LiteralData have been marked -// as especially sensitive. -func (l *LiteralData) ForEyesOnly() bool { - return l.FileName == "_CONSOLE" -} - -func (l *LiteralData) parse(r io.Reader) (err error) { - var buf [256]byte - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - - l.IsBinary = buf[0] == 'b' - fileNameLen := int(buf[1]) - - _, err = readFull(r, buf[:fileNameLen]) - if err != nil { - return - } - - l.FileName = string(buf[:fileNameLen]) - - _, err = readFull(r, buf[:4]) - if err != nil { - return - } - - l.Time = binary.BigEndian.Uint32(buf[:4]) - l.Body = r - return -} - -// SerializeLiteral serializes a literal data packet to w and returns a -// WriteCloser to which the data itself can be written and which MUST be closed -// on completion. The fileName is truncated to 255 bytes. -func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) { - var buf [4]byte - buf[0] = 't' - if isBinary { - buf[0] = 'b' - } - if len(fileName) > 255 { - fileName = fileName[:255] - } - buf[1] = byte(len(fileName)) - - inner, err := serializeStreamHeader(w, packetTypeLiteralData) - if err != nil { - return - } - - _, err = inner.Write(buf[:2]) - if err != nil { - return - } - _, err = inner.Write([]byte(fileName)) - if err != nil { - return - } - binary.BigEndian.PutUint32(buf[:], time) - _, err = inner.Write(buf[:]) - if err != nil { - return - } - - plaintext = inner - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go deleted file mode 100644 index ce2a33a5..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2010 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. - -// OpenPGP CFB Mode. http://tools.ietf.org/html/rfc4880#section-13.9 - -package packet - -import ( - "crypto/cipher" -) - -type ocfbEncrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// An OCFBResyncOption determines if the "resynchronization step" of OCFB is -// performed. -type OCFBResyncOption bool - -const ( - OCFBResync OCFBResyncOption = true - OCFBNoResync OCFBResyncOption = false -) - -// NewOCFBEncrypter returns a cipher.Stream which encrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block, and an initial amount of -// ciphertext. randData must be random bytes and be the same length as the -// cipher.Block's block size. Resync determines if the "resynchronization step" -// from RFC 4880, 13.9 step 7 is performed. Different parts of OpenPGP vary on -// this point. -func NewOCFBEncrypter(block cipher.Block, randData []byte, resync OCFBResyncOption) (cipher.Stream, []byte) { - blockSize := block.BlockSize() - if len(randData) != blockSize { - return nil, nil - } - - x := &ocfbEncrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefix := make([]byte, blockSize+2) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefix[i] = randData[i] ^ x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefix[blockSize] = x.fre[0] ^ randData[blockSize-2] - prefix[blockSize+1] = x.fre[1] ^ randData[blockSize-1] - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - return x, prefix -} - -func (x *ocfbEncrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - x.fre[x.outUsed] ^= src[i] - dst[i] = x.fre[x.outUsed] - x.outUsed++ - } -} - -type ocfbDecrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// NewOCFBDecrypter returns a cipher.Stream which decrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block. Prefix must be the first -// blockSize + 2 bytes of the ciphertext, where blockSize is the cipher.Block's -// block size. If an incorrect key is detected then nil is returned. On -// successful exit, blockSize+2 bytes of decrypted data are written into -// prefix. Resync determines if the "resynchronization step" from RFC 4880, -// 13.9 step 7 is performed. Different parts of OpenPGP vary on this point. -func NewOCFBDecrypter(block cipher.Block, prefix []byte, resync OCFBResyncOption) cipher.Stream { - blockSize := block.BlockSize() - if len(prefix) != blockSize+2 { - return nil - } - - x := &ocfbDecrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefixCopy := make([]byte, len(prefix)) - copy(prefixCopy, prefix) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefixCopy[i] ^= x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefixCopy[blockSize] ^= x.fre[0] - prefixCopy[blockSize+1] ^= x.fre[1] - - if prefixCopy[blockSize-2] != prefixCopy[blockSize] || - prefixCopy[blockSize-1] != prefixCopy[blockSize+1] { - return nil - } - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - copy(prefix, prefixCopy) - return x -} - -func (x *ocfbDecrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - c := src[i] - dst[i] = x.fre[x.outUsed] ^ src[i] - x.fre[x.outUsed] = c - x.outUsed++ - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go deleted file mode 100644 index af404bb1..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto" - "encoding/binary" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// OnePassSignature represents a one-pass signature packet. See RFC 4880, -// section 5.4. -type OnePassSignature struct { - SigType SignatureType - Hash crypto.Hash - PubKeyAlgo PublicKeyAlgorithm - KeyId uint64 - IsLast bool -} - -const onePassSignatureVersion = 3 - -func (ops *OnePassSignature) parse(r io.Reader) (err error) { - var buf [13]byte - - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != onePassSignatureVersion { - err = errors.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) - } - - var ok bool - ops.Hash, ok = s2k.HashIdToHash(buf[2]) - if !ok { - return errors.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) - } - - ops.SigType = SignatureType(buf[1]) - ops.PubKeyAlgo = PublicKeyAlgorithm(buf[3]) - ops.KeyId = binary.BigEndian.Uint64(buf[4:12]) - ops.IsLast = buf[12] != 0 - return -} - -// Serialize marshals the given OnePassSignature to w. -func (ops *OnePassSignature) Serialize(w io.Writer) error { - var buf [13]byte - buf[0] = onePassSignatureVersion - buf[1] = uint8(ops.SigType) - var ok bool - buf[2], ok = s2k.HashToHashId(ops.Hash) - if !ok { - return errors.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) - } - buf[3] = uint8(ops.PubKeyAlgo) - binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) - if ops.IsLast { - buf[12] = 1 - } - - if err := serializeHeader(w, packetTypeOnePassSignature, len(buf)); err != nil { - return err - } - _, err := w.Write(buf[:]) - return err -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go deleted file mode 100644 index cdeea012..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2012 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 packet - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// OpaquePacket represents an OpenPGP packet as raw, unparsed data. This is -// useful for splitting and storing the original packet contents separately, -// handling unsupported packet types or accessing parts of the packet not yet -// implemented by this package. -type OpaquePacket struct { - // Packet type - Tag uint8 - // Reason why the packet was parsed opaquely - Reason error - // Binary contents of the packet data - Contents []byte -} - -func (op *OpaquePacket) parse(r io.Reader) (err error) { - op.Contents, err = ioutil.ReadAll(r) - return -} - -// Serialize marshals the packet to a writer in its original form, including -// the packet header. -func (op *OpaquePacket) Serialize(w io.Writer) (err error) { - err = serializeHeader(w, packetType(op.Tag), len(op.Contents)) - if err == nil { - _, err = w.Write(op.Contents) - } - return -} - -// Parse attempts to parse the opaque contents into a structure supported by -// this package. If the packet is not known then the result will be another -// OpaquePacket. -func (op *OpaquePacket) Parse() (p Packet, err error) { - hdr := bytes.NewBuffer(nil) - err = serializeHeader(hdr, packetType(op.Tag), len(op.Contents)) - if err != nil { - op.Reason = err - return op, err - } - p, err = Read(io.MultiReader(hdr, bytes.NewBuffer(op.Contents))) - if err != nil { - op.Reason = err - p = op - } - return -} - -// OpaqueReader reads OpaquePackets from an io.Reader. -type OpaqueReader struct { - r io.Reader -} - -func NewOpaqueReader(r io.Reader) *OpaqueReader { - return &OpaqueReader{r: r} -} - -// Read the next OpaquePacket. -func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { - tag, _, contents, err := readHeader(or.r) - if err != nil { - return - } - op = &OpaquePacket{Tag: uint8(tag), Reason: err} - err = op.parse(contents) - if err != nil { - consumeAll(contents) - } - return -} - -// OpaqueSubpacket represents an unparsed OpenPGP subpacket, -// as found in signature and user attribute packets. -type OpaqueSubpacket struct { - SubType uint8 - Contents []byte -} - -// OpaqueSubpackets extracts opaque, unparsed OpenPGP subpackets from -// their byte representation. -func OpaqueSubpackets(contents []byte) (result []*OpaqueSubpacket, err error) { - var ( - subHeaderLen int - subPacket *OpaqueSubpacket - ) - for len(contents) > 0 { - subHeaderLen, subPacket, err = nextSubpacket(contents) - if err != nil { - break - } - result = append(result, subPacket) - contents = contents[subHeaderLen+len(subPacket.Contents):] - } - return -} - -func nextSubpacket(contents []byte) (subHeaderLen int, subPacket *OpaqueSubpacket, err error) { - // RFC 4880, section 5.2.3.1 - var subLen uint32 - if len(contents) < 1 { - goto Truncated - } - subPacket = &OpaqueSubpacket{} - switch { - case contents[0] < 192: - subHeaderLen = 2 // 1 length byte, 1 subtype byte - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[0]) - contents = contents[1:] - case contents[0] < 255: - subHeaderLen = 3 // 2 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[0]-192)<<8 + uint32(contents[1]) + 192 - contents = contents[2:] - default: - subHeaderLen = 6 // 5 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[1])<<24 | - uint32(contents[2])<<16 | - uint32(contents[3])<<8 | - uint32(contents[4]) - contents = contents[5:] - } - if subLen > uint32(len(contents)) || subLen == 0 { - goto Truncated - } - subPacket.SubType = contents[0] - subPacket.Contents = contents[1:subLen] - return -Truncated: - err = errors.StructuralError("subpacket truncated") - return -} - -func (osp *OpaqueSubpacket) Serialize(w io.Writer) (err error) { - buf := make([]byte, 6) - n := serializeSubpacketLength(buf, len(osp.Contents)+1) - buf[n] = osp.SubType - if _, err = w.Write(buf[:n+1]); err != nil { - return - } - _, err = w.Write(osp.Contents) - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go deleted file mode 100644 index eb61eda9..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go +++ /dev/null @@ -1,576 +0,0 @@ -// Copyright 2011 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 packet implements parsing and serialization of OpenPGP packets, as -// specified in RFC 4880. -package packet // import "github.com/keybase/go-crypto/openpgp/packet" - -import ( - "bufio" - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/elliptic" - "io" - "math/big" - - "github.com/keybase/go-crypto/cast5" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/rsa" -) - -// readFull is the same as io.ReadFull except that reading zero bytes returns -// ErrUnexpectedEOF rather than EOF. -func readFull(r io.Reader, buf []byte) (n int, err error) { - n, err = io.ReadFull(r, buf) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. -func readLength(r io.Reader) (length int64, isPartial bool, err error) { - var buf [4]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - switch { - case buf[0] < 192: - length = int64(buf[0]) - case buf[0] < 224: - length = int64(buf[0]-192) << 8 - _, err = readFull(r, buf[0:1]) - if err != nil { - return - } - length += int64(buf[0]) + 192 - case buf[0] < 255: - length = int64(1) << (buf[0] & 0x1f) - isPartial = true - default: - _, err = readFull(r, buf[0:4]) - if err != nil { - return - } - length = int64(buf[0])<<24 | - int64(buf[1])<<16 | - int64(buf[2])<<8 | - int64(buf[3]) - } - return -} - -// partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths. -// The continuation lengths are parsed and removed from the stream and EOF is -// returned at the end of the packet. See RFC 4880, section 4.2.2.4. -type partialLengthReader struct { - r io.Reader - remaining int64 - isPartial bool -} - -func (r *partialLengthReader) Read(p []byte) (n int, err error) { - for r.remaining == 0 { - if !r.isPartial { - return 0, io.EOF - } - r.remaining, r.isPartial, err = readLength(r.r) - if err != nil { - return 0, err - } - } - - toRead := int64(len(p)) - if toRead > r.remaining { - toRead = r.remaining - } - - n, err = r.r.Read(p[:int(toRead)]) - r.remaining -= int64(n) - if n < int(toRead) && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// partialLengthWriter writes a stream of data using OpenPGP partial lengths. -// See RFC 4880, section 4.2.2.4. -type partialLengthWriter struct { - w io.WriteCloser - lengthByte [1]byte -} - -func (w *partialLengthWriter) Write(p []byte) (n int, err error) { - for len(p) > 0 { - for power := uint(14); power < 32; power-- { - l := 1 << power - if len(p) >= l { - w.lengthByte[0] = 224 + uint8(power) - _, err = w.w.Write(w.lengthByte[:]) - if err != nil { - return - } - var m int - m, err = w.w.Write(p[:l]) - n += m - if err != nil { - return - } - p = p[l:] - break - } - } - } - return -} - -func (w *partialLengthWriter) Close() error { - w.lengthByte[0] = 0 - _, err := w.w.Write(w.lengthByte[:]) - if err != nil { - return err - } - return w.w.Close() -} - -// A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the -// underlying Reader returns EOF before the limit has been reached. -type spanReader struct { - r io.Reader - n int64 -} - -func (l *spanReader) Read(p []byte) (n int, err error) { - if l.n <= 0 { - return 0, io.EOF - } - if int64(len(p)) > l.n { - p = p[0:l.n] - } - n, err = l.r.Read(p) - l.n -= int64(n) - if l.n > 0 && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readHeader parses a packet header and returns an io.Reader which will return -// the contents of the packet. See RFC 4880, section 4.2. -func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) { - var buf [4]byte - _, err = io.ReadFull(r, buf[:1]) - if err != nil { - return - } - if buf[0]&0x80 == 0 { - err = errors.StructuralError("tag byte does not have MSB set") - return - } - if buf[0]&0x40 == 0 { - // Old format packet - tag = packetType((buf[0] & 0x3f) >> 2) - lengthType := buf[0] & 3 - if lengthType == 3 { - length = -1 - contents = r - return - } - lengthBytes := 1 << lengthType - _, err = readFull(r, buf[0:lengthBytes]) - if err != nil { - return - } - for i := 0; i < lengthBytes; i++ { - length <<= 8 - length |= int64(buf[i]) - } - contents = &spanReader{r, length} - return - } - - // New format packet - tag = packetType(buf[0] & 0x3f) - length, isPartial, err := readLength(r) - if err != nil { - return - } - if isPartial { - contents = &partialLengthReader{ - remaining: length, - isPartial: true, - r: r, - } - length = -1 - } else { - contents = &spanReader{r, length} - } - return -} - -// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section -// 4.2. -func serializeHeader(w io.Writer, ptype packetType, length int) (err error) { - var buf [6]byte - var n int - - buf[0] = 0x80 | 0x40 | byte(ptype) - if length < 192 { - buf[1] = byte(length) - n = 2 - } else if length < 8384 { - length -= 192 - buf[1] = 192 + byte(length>>8) - buf[2] = byte(length) - n = 3 - } else { - buf[1] = 255 - buf[2] = byte(length >> 24) - buf[3] = byte(length >> 16) - buf[4] = byte(length >> 8) - buf[5] = byte(length) - n = 6 - } - - _, err = w.Write(buf[:n]) - return -} - -// serializeStreamHeader writes an OpenPGP packet header to w where the -// length of the packet is unknown. It returns a io.WriteCloser which can be -// used to write the contents of the packet. See RFC 4880, section 4.2. -func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) { - var buf [1]byte - buf[0] = 0x80 | 0x40 | byte(ptype) - _, err = w.Write(buf[:]) - if err != nil { - return - } - out = &partialLengthWriter{w: w} - return -} - -// Packet represents an OpenPGP packet. Users are expected to try casting -// instances of this interface to specific packet types. -type Packet interface { - parse(io.Reader) error -} - -// consumeAll reads from the given Reader until error, returning the number of -// bytes read. -func consumeAll(r io.Reader) (n int64, err error) { - var m int - var buf [1024]byte - - for { - m, err = r.Read(buf[:]) - n += int64(m) - if err == io.EOF { - err = nil - return - } - if err != nil { - return - } - } - - panic("unreachable") -} - -// packetType represents the numeric ids of the different OpenPGP packet types. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2 -type packetType uint8 - -const ( - packetTypeEncryptedKey packetType = 1 - packetTypeSignature packetType = 2 - packetTypeSymmetricKeyEncrypted packetType = 3 - packetTypeOnePassSignature packetType = 4 - packetTypePrivateKey packetType = 5 - packetTypePublicKey packetType = 6 - packetTypePrivateSubkey packetType = 7 - packetTypeCompressed packetType = 8 - packetTypeSymmetricallyEncrypted packetType = 9 - packetTypeLiteralData packetType = 11 - packetTypeUserId packetType = 13 - packetTypePublicSubkey packetType = 14 - packetTypeUserAttribute packetType = 17 - packetTypeSymmetricallyEncryptedMDC packetType = 18 -) - -// peekVersion detects the version of a public key packet about to -// be read. A bufio.Reader at the original position of the io.Reader -// is returned. -func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) { - bufr = bufio.NewReader(r) - var verBuf []byte - if verBuf, err = bufr.Peek(1); err != nil { - return - } - ver = verBuf[0] - return -} - -// Read reads a single OpenPGP packet from the given io.Reader. If there is an -// error parsing a packet, the whole packet is consumed from the input. -func Read(r io.Reader) (p Packet, err error) { - tag, _, contents, err := readHeader(r) - if err != nil { - return - } - - switch tag { - case packetTypeEncryptedKey: - p = new(EncryptedKey) - case packetTypeSignature: - var version byte - // Detect signature version - if contents, version, err = peekVersion(contents); err != nil { - return - } - if version < 4 { - p = new(SignatureV3) - } else { - p = new(Signature) - } - case packetTypeSymmetricKeyEncrypted: - p = new(SymmetricKeyEncrypted) - case packetTypeOnePassSignature: - p = new(OnePassSignature) - case packetTypePrivateKey, packetTypePrivateSubkey: - pk := new(PrivateKey) - if tag == packetTypePrivateSubkey { - pk.IsSubkey = true - } - p = pk - case packetTypePublicKey, packetTypePublicSubkey: - var version byte - if contents, version, err = peekVersion(contents); err != nil { - return - } - isSubkey := tag == packetTypePublicSubkey - if version < 4 { - p = &PublicKeyV3{IsSubkey: isSubkey} - } else { - p = &PublicKey{IsSubkey: isSubkey} - } - case packetTypeCompressed: - p = new(Compressed) - case packetTypeSymmetricallyEncrypted: - p = new(SymmetricallyEncrypted) - case packetTypeLiteralData: - p = new(LiteralData) - case packetTypeUserId: - p = new(UserId) - case packetTypeUserAttribute: - p = new(UserAttribute) - case packetTypeSymmetricallyEncryptedMDC: - se := new(SymmetricallyEncrypted) - se.MDC = true - p = se - default: - err = errors.UnknownPacketTypeError(tag) - } - if p != nil { - err = p.parse(contents) - } - if err != nil { - consumeAll(contents) - } - return -} - -// SignatureType represents the different semantic meanings of an OpenPGP -// signature. See RFC 4880, section 5.2.1. -type SignatureType uint8 - -const ( - SigTypeBinary SignatureType = 0 - SigTypeText = 1 - SigTypeGenericCert = 0x10 - SigTypePersonaCert = 0x11 - SigTypeCasualCert = 0x12 - SigTypePositiveCert = 0x13 - SigTypeSubkeyBinding = 0x18 - SigTypePrimaryKeyBinding = 0x19 - SigTypeDirectSignature = 0x1F - SigTypeKeyRevocation = 0x20 - SigTypeSubkeyRevocation = 0x28 - SigTypeIdentityRevocation = 0x30 -) - -// PublicKeyAlgorithm represents the different public key system specified for -// OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12 -type PublicKeyAlgorithm uint8 - -const ( - PubKeyAlgoRSA PublicKeyAlgorithm = 1 - PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 - PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 - PubKeyAlgoElGamal PublicKeyAlgorithm = 16 - PubKeyAlgoDSA PublicKeyAlgorithm = 17 - // RFC 6637, Section 5. - PubKeyAlgoECDH PublicKeyAlgorithm = 18 - PubKeyAlgoECDSA PublicKeyAlgorithm = 19 - - PubKeyAlgoBadElGamal PublicKeyAlgorithm = 20 // Reserved (deprecated, formerly ElGamal Encrypt or Sign) - // RFC -1 - PubKeyAlgoEdDSA PublicKeyAlgorithm = 22 -) - -// CanEncrypt returns true if it's possible to encrypt a message to a public -// key of the given type. -func (pka PublicKeyAlgorithm) CanEncrypt() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal, PubKeyAlgoECDH: - return true - } - return false -} - -// CanSign returns true if it's possible for a public key of the given type to -// sign a message. -func (pka PublicKeyAlgorithm) CanSign() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - return true - } - return false -} - -// CipherFunction represents the different block ciphers specified for OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 -type CipherFunction uint8 - -const ( - Cipher3DES CipherFunction = 2 - CipherCAST5 CipherFunction = 3 - CipherAES128 CipherFunction = 7 - CipherAES192 CipherFunction = 8 - CipherAES256 CipherFunction = 9 -) - -// KeySize returns the key size, in bytes, of cipher. -func (cipher CipherFunction) KeySize() int { - switch cipher { - case Cipher3DES: - return 24 - case CipherCAST5: - return cast5.KeySize - case CipherAES128: - return 16 - case CipherAES192: - return 24 - case CipherAES256: - return 32 - } - return 0 -} - -// blockSize returns the block size, in bytes, of cipher. -func (cipher CipherFunction) blockSize() int { - switch cipher { - case Cipher3DES: - return des.BlockSize - case CipherCAST5: - return 8 - case CipherAES128, CipherAES192, CipherAES256: - return 16 - } - return 0 -} - -// new returns a fresh instance of the given cipher. -func (cipher CipherFunction) new(key []byte) (block cipher.Block) { - switch cipher { - case Cipher3DES: - block, _ = des.NewTripleDESCipher(key) - case CipherCAST5: - block, _ = cast5.NewCipher(key) - case CipherAES128, CipherAES192, CipherAES256: - block, _ = aes.NewCipher(key) - } - return -} - -// readMPI reads a big integer from r. The bit length returned is the bit -// length that was specified in r. This is preserved so that the integer can be -// reserialized exactly. -func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) { - var buf [2]byte - _, err = readFull(r, buf[0:]) - if err != nil { - return - } - bitLength = uint16(buf[0])<<8 | uint16(buf[1]) - numBytes := (int(bitLength) + 7) / 8 - mpi = make([]byte, numBytes) - _, err = readFull(r, mpi) - // According to RFC 4880 3.2. we should check that the MPI has no leading - // zeroes (at least when not an encrypted MPI?), but this implementation - // does generate leading zeroes, so we keep accepting them. - return -} - -// writeMPI serializes a big integer to w. -func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) { - // Note that we can produce leading zeroes, in violation of RFC 4880 3.2. - // Implementations seem to be tolerant of them, and stripping them would - // make it complex to guarantee matching re-serialization. - _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) - if err == nil { - _, err = w.Write(mpiBytes) - } - return -} - -func WritePaddedBigInt(w io.Writer, length int, X *big.Int) (n int, err error) { - bytes := X.Bytes() - n1, err := w.Write(make([]byte, length-len(bytes))) - if err != nil { - return n1, err - } - n2, err := w.Write(bytes) - if err != nil { - return n2, err - } - return (n1 + n2), err -} - -// Minimum number of bytes to fit the curve coordinates. All -// coordinates have to be 0-padded to this length. -func mpiPointByteLength(curve elliptic.Curve) int { - return (curve.Params().P.BitLen() + 7) / 8 -} - -// writeBig serializes a *big.Int to w. -func writeBig(w io.Writer, i *big.Int) error { - return writeMPI(w, uint16(i.BitLen()), i.Bytes()) -} - -// padToKeySize left-pads a MPI with zeroes to match the length of the -// specified RSA public. -func padToKeySize(pub *rsa.PublicKey, b []byte) []byte { - k := (pub.N.BitLen() + 7) / 8 - if len(b) >= k { - return b - } - bb := make([]byte, k) - copy(bb[len(bb)-len(b):], b) - return bb -} - -// CompressionAlgo Represents the different compression algorithms -// supported by OpenPGP (except for BZIP2, which is not currently -// supported). See Section 9.3 of RFC 4880. -type CompressionAlgo uint8 - -const ( - CompressionNone CompressionAlgo = 0 - CompressionZIP CompressionAlgo = 1 - CompressionZLIB CompressionAlgo = 2 -) diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go deleted file mode 100644 index 5305b1f6..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go +++ /dev/null @@ -1,557 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto/cipher" - "crypto/dsa" - "crypto/ecdsa" - "crypto/sha1" - "fmt" - "io" - "io/ioutil" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/ed25519" - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" - "github.com/keybase/go-crypto/rsa" -) - -// PrivateKey represents a possibly encrypted private key. See RFC 4880, -// section 5.5.3. -type PrivateKey struct { - PublicKey - Encrypted bool // if true then the private key is unavailable until Decrypt has been called. - encryptedData []byte - cipher CipherFunction - s2k func(out, in []byte) - PrivateKey interface{} // An *rsa.PrivateKey or *dsa.PrivateKey. - sha1Checksum bool - iv []byte - s2kHeader []byte -} - -type EdDSAPrivateKey struct { - PrivateKey - seed parsedMPI -} - -func (e *EdDSAPrivateKey) Sign(digest []byte) (R, S []byte, err error) { - r := bytes.NewReader(e.seed.bytes) - publicKey, privateKey, err := ed25519.GenerateKey(r) - if err != nil { - return nil, nil, err - } - - if !bytes.Equal(publicKey, e.PublicKey.edk.p.bytes[1:]) { // [1:] because [0] is 0x40 mpi header - return nil, nil, errors.UnsupportedError("EdDSA: Private key does not match public key.") - } - - sig := ed25519.Sign(privateKey, digest) - - sigLen := ed25519.SignatureSize / 2 - return sig[:sigLen], sig[sigLen:], nil -} - -func NewRSAPrivateKey(currentTime time.Time, priv *rsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewRSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewDSAPrivateKey(currentTime time.Time, priv *dsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewDSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewElGamalPrivateKey(currentTime time.Time, priv *elgamal.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewElGamalPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDSAPrivateKey(currentTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDHPrivateKey(currentTime time.Time, priv *ecdh.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDHPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func (pk *PrivateKey) parse(r io.Reader) (err error) { - err = (&pk.PublicKey).parse(r) - if err != nil { - return - } - var buf [1]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - - s2kType := buf[0] - - switch s2kType { - case 0: - pk.s2k = nil - pk.Encrypted = false - case 254, 255: - _, err = readFull(r, buf[:]) - if err != nil { - return - } - pk.cipher = CipherFunction(buf[0]) - pk.Encrypted = true - pk.s2k, err = s2k.Parse(r) - if err != nil { - return - } - if s2kType == 254 { - pk.sha1Checksum = true - } - // S2K == nil implies that we got a "GNU Dummy" S2K. For instance, - // because our master secret key is on a USB key in a vault somewhere. - // In that case, there is no further data to consume here. - if pk.s2k == nil { - pk.Encrypted = false - return - } - default: - return errors.UnsupportedError("deprecated s2k function in private key") - } - if pk.Encrypted { - blockSize := pk.cipher.blockSize() - if blockSize == 0 { - return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) - } - pk.iv = make([]byte, blockSize) - _, err = readFull(r, pk.iv) - if err != nil { - return - } - } - - pk.encryptedData, err = ioutil.ReadAll(r) - if err != nil { - return - } - - if !pk.Encrypted { - return pk.parsePrivateKey(pk.encryptedData) - } - - return -} - -func mod64kHash(d []byte) uint16 { - var h uint16 - for _, b := range d { - h += uint16(b) - } - return h -} - -// Encrypt is the counterpart to the Decrypt() method below. It encrypts -// the private key with the provided passphrase. If config is nil, then -// the standard, and sensible, defaults apply. -// -// A key will be derived from the given passphrase using S2K Specifier -// Type 3 (Iterated + Salted, see RFC-4880 Sec. 3.7.1.3). This choice -// is hardcoded in s2k.Serialize(). S2KCount is hardcoded to 0, which is -// equivalent to 65536. And the hash algorithm for key-derivation can be -// set with config. The encrypted PrivateKey, using the algorithm specified -// in config (if provided), is written out to the encryptedData member. -// When Serialize() is called, this encryptedData member will be -// serialized, using S2K Usage value of 254, and thus SHA1 checksum. -func (pk *PrivateKey) Encrypt(passphrase []byte, config *Config) (err error) { - if pk.PrivateKey == nil { - return errors.InvalidArgumentError("there is no private key to encrypt") - } - - pk.sha1Checksum = true - pk.cipher = config.Cipher() - s2kConfig := s2k.Config{ - Hash: config.Hash(), - S2KCount: 0, - } - s2kBuf := bytes.NewBuffer(nil) - derivedKey := make([]byte, pk.cipher.KeySize()) - err = s2k.Serialize(s2kBuf, derivedKey, config.Random(), passphrase, &s2kConfig) - if err != nil { - return err - } - - pk.s2kHeader = s2kBuf.Bytes() - // No good way to set pk.s2k but to call s2k.Parse(), - // even though we have all the information here, but - // most of the functions needed are private to s2k. - pk.s2k, err = s2k.Parse(s2kBuf) - pk.iv = make([]byte, pk.cipher.blockSize()) - if _, err = config.Random().Read(pk.iv); err != nil { - return err - } - - privateKeyBuf := bytes.NewBuffer(nil) - if err = pk.serializePrivateKey(privateKeyBuf); err != nil { - return err - } - - checksum := sha1.Sum(privateKeyBuf.Bytes()) - if _, err = privateKeyBuf.Write(checksum[:]); err != nil { - return err - } - - pkData := privateKeyBuf.Bytes() - block := pk.cipher.new(derivedKey) - pk.encryptedData = make([]byte, len(pkData)) - cfb := cipher.NewCFBEncrypter(block, pk.iv) - cfb.XORKeyStream(pk.encryptedData, pkData) - pk.Encrypted = true - return nil -} - -func (pk *PrivateKey) Serialize(w io.Writer) (err error) { - buf := bytes.NewBuffer(nil) - err = pk.PublicKey.serializeWithoutHeaders(buf) - if err != nil { - return - } - - privateKeyBuf := bytes.NewBuffer(nil) - - if pk.PrivateKey == nil { - _, err = buf.Write([]byte{ - 254, // SHA-1 Convention - 9, // Encryption scheme (AES256) - 101, // GNU Extensions - 2, // Hash value (SHA1) - 'G', 'N', 'U', // "GNU" as a string - 1, // Extension type 1001 (minus 1000) - }) - } else if pk.Encrypted { - _, err = buf.Write([]byte{ - 254, // SHA-1 Convention - byte(pk.cipher), // Encryption scheme - }) - if err != nil { - return err - } - if _, err = buf.Write(pk.s2kHeader); err != nil { - return err - } - if _, err = buf.Write(pk.iv); err != nil { - return err - } - if _, err = privateKeyBuf.Write(pk.encryptedData); err != nil { - return err - } - } else { - buf.WriteByte(0 /* no encryption */) - if err = pk.serializePrivateKey(privateKeyBuf); err != nil { - return err - } - } - - ptype := packetTypePrivateKey - contents := buf.Bytes() - privateKeyBytes := privateKeyBuf.Bytes() - if pk.IsSubkey { - ptype = packetTypePrivateSubkey - } - totalLen := len(contents) + len(privateKeyBytes) - if !pk.Encrypted { - totalLen += 2 - } - err = serializeHeader(w, ptype, totalLen) - if err != nil { - return - } - _, err = w.Write(contents) - if err != nil { - return - } - _, err = w.Write(privateKeyBytes) - if err != nil { - return - } - - if len(privateKeyBytes) > 0 && !pk.Encrypted { - checksum := mod64kHash(privateKeyBytes) - var checksumBytes [2]byte - checksumBytes[0] = byte(checksum >> 8) - checksumBytes[1] = byte(checksum) - _, err = w.Write(checksumBytes[:]) - } - - return -} - -func (pk *PrivateKey) serializePrivateKey(w io.Writer) (err error) { - switch priv := pk.PrivateKey.(type) { - case *rsa.PrivateKey: - err = serializeRSAPrivateKey(w, priv) - case *dsa.PrivateKey: - err = serializeDSAPrivateKey(w, priv) - case *elgamal.PrivateKey: - err = serializeElGamalPrivateKey(w, priv) - case *ecdsa.PrivateKey: - err = serializeECDSAPrivateKey(w, priv) - case *ecdh.PrivateKey: - err = serializeECDHPrivateKey(w, priv) - case *EdDSAPrivateKey: - err = serializeEdDSAPrivateKey(w, priv) - default: - err = errors.InvalidArgumentError("unknown private key type") - } - - return err -} - -func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error { - err := writeBig(w, priv.D) - if err != nil { - return err - } - err = writeBig(w, priv.Primes[1]) - if err != nil { - return err - } - err = writeBig(w, priv.Primes[0]) - if err != nil { - return err - } - return writeBig(w, priv.Precomputed.Qinv) -} - -func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error { - return writeBig(w, priv.D) -} - -func serializeECDHPrivateKey(w io.Writer, priv *ecdh.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeEdDSAPrivateKey(w io.Writer, priv *EdDSAPrivateKey) error { - return writeMPI(w, priv.seed.bitLength, priv.seed.bytes) -} - -// Decrypt decrypts an encrypted private key using a passphrase. -func (pk *PrivateKey) Decrypt(passphrase []byte) error { - if !pk.Encrypted { - return nil - } - // For GNU Dummy S2K, there's no key here, so don't do anything. - if pk.s2k == nil { - return nil - } - - key := make([]byte, pk.cipher.KeySize()) - pk.s2k(key, passphrase) - block := pk.cipher.new(key) - cfb := cipher.NewCFBDecrypter(block, pk.iv) - - data := make([]byte, len(pk.encryptedData)) - cfb.XORKeyStream(data, pk.encryptedData) - - if pk.sha1Checksum { - if len(data) < sha1.Size { - return errors.StructuralError("truncated private key data") - } - h := sha1.New() - h.Write(data[:len(data)-sha1.Size]) - sum := h.Sum(nil) - if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-sha1.Size] - } else { - if len(data) < 2 { - return errors.StructuralError("truncated private key data") - } - var sum uint16 - for i := 0; i < len(data)-2; i++ { - sum += uint16(data[i]) - } - if data[len(data)-2] != uint8(sum>>8) || - data[len(data)-1] != uint8(sum) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-2] - } - - return pk.parsePrivateKey(data) -} - -func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) { - switch pk.PublicKey.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: - return pk.parseRSAPrivateKey(data) - case PubKeyAlgoDSA: - return pk.parseDSAPrivateKey(data) - case PubKeyAlgoElGamal: - return pk.parseElGamalPrivateKey(data) - case PubKeyAlgoECDSA: - return pk.parseECDSAPrivateKey(data) - case PubKeyAlgoECDH: - return pk.parseECDHPrivateKey(data) - case PubKeyAlgoEdDSA: - return pk.parseEdDSAPrivateKey(data) - } - panic("impossible") -} - -func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) { - rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) - rsaPriv := new(rsa.PrivateKey) - rsaPriv.PublicKey = *rsaPub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - p, _, err := readMPI(buf) - if err != nil { - return - } - q, _, err := readMPI(buf) - if err != nil { - return - } - - rsaPriv.D = new(big.Int).SetBytes(d) - rsaPriv.Primes = make([]*big.Int, 2) - rsaPriv.Primes[0] = new(big.Int).SetBytes(p) - rsaPriv.Primes[1] = new(big.Int).SetBytes(q) - if err := rsaPriv.Validate(); err != nil { - return err - } - rsaPriv.Precompute() - pk.PrivateKey = rsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) { - dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) - dsaPriv := new(dsa.PrivateKey) - dsaPriv.PublicKey = *dsaPub - - buf := bytes.NewBuffer(data) - x, _, err := readMPI(buf) - if err != nil { - return - } - - dsaPriv.X = new(big.Int).SetBytes(x) - pk.PrivateKey = dsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) { - pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) - priv := new(elgamal.PrivateKey) - priv.PublicKey = *pub - - buf := bytes.NewBuffer(data) - x, _, err := readMPI(buf) - if err != nil { - return - } - - priv.X = new(big.Int).SetBytes(x) - pk.PrivateKey = priv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseECDHPrivateKey(data []byte) (err error) { - pub := pk.PublicKey.PublicKey.(*ecdh.PublicKey) - priv := new(ecdh.PrivateKey) - priv.PublicKey = *pub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - - priv.X = new(big.Int).SetBytes(d) - pk.PrivateKey = priv - pk.Encrypted = false - pk.encryptedData = nil - return nil -} - -func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) { - ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey) - ecdsaPriv := new(ecdsa.PrivateKey) - ecdsaPriv.PublicKey = *ecdsaPub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - - ecdsaPriv.D = new(big.Int).SetBytes(d) - pk.PrivateKey = ecdsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseEdDSAPrivateKey(data []byte) (err error) { - eddsaPriv := new(EdDSAPrivateKey) - eddsaPriv.PublicKey = pk.PublicKey - - buf := bytes.NewBuffer(data) - eddsaPriv.seed.bytes, eddsaPriv.seed.bitLength, err = readMPI(buf) - if err != nil { - return err - } - - if bLen := len(eddsaPriv.seed.bytes); bLen != 32 { // 32 bytes private part of ed25519 key. - return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA private key length: %d", bLen)) - } - - pk.PrivateKey = eddsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go deleted file mode 100644 index a46a008a..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go +++ /dev/null @@ -1,990 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" - "encoding/binary" - "fmt" - "hash" - "io" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/brainpool" - "github.com/keybase/go-crypto/curve25519" - "github.com/keybase/go-crypto/ed25519" - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" - "github.com/keybase/go-crypto/rsa" -) - -var ( - // NIST curve P-224 - oidCurveP224 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x21} - // NIST curve P-256 - oidCurveP256 []byte = []byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07} - // NIST curve P-384 - oidCurveP384 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x22} - // NIST curve P-521 - oidCurveP521 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x23} - // Brainpool curve P-256r1 - oidCurveP256r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07} - // Brainpool curve P-384r1 - oidCurveP384r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B} - // Brainpool curve P-512r1 - oidCurveP512r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D} - // EdDSA - oidEdDSA []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01} - // cv25519 - oidCurve25519 []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01} -) - -const maxOIDLength = 10 - -// ecdsaKey stores the algorithm-specific fields for ECDSA keys. -// as defined in RFC 6637, Section 9. -type ecdsaKey struct { - // oid contains the OID byte sequence identifying the elliptic curve used - oid []byte - // p contains the elliptic curve point that represents the public key - p parsedMPI -} - -type edDSAkey struct { - ecdsaKey -} - -func copyFrontFill(dst, src []byte, length int) int { - if srcLen := len(src); srcLen < length { - return copy(dst[length-srcLen:], src[:]) - } else { - return copy(dst[:], src[:]) - } -} - -func (e *edDSAkey) Verify(payload []byte, r parsedMPI, s parsedMPI) bool { - const halfSigSize = ed25519.SignatureSize / 2 - var sig [ed25519.SignatureSize]byte - - // NOTE: The first byte is 0x40 - MPI header - // TODO: Maybe clean the code up and use 0x40 as a header when - // reading and keep only actual number in p field. Find out how - // other MPIs are stored. - key := e.p.bytes[1:] - - // Note: it may happen that R + S do not form 64-byte signature buffer that - // ed25519 expects, but because we copy it over to an array of exact size, - // we will always pass correctly sized slice to Verify. Slice too short - // would make ed25519 panic(). - copyFrontFill(sig[:halfSigSize], r.bytes, halfSigSize) - copyFrontFill(sig[halfSigSize:], s.bytes, halfSigSize) - - return ed25519.Verify(key, payload, sig[:]) -} - -// parseOID reads the OID for the curve as defined in RFC 6637, Section 9. -func parseOID(r io.Reader) (oid []byte, err error) { - buf := make([]byte, maxOIDLength) - if _, err = readFull(r, buf[:1]); err != nil { - return - } - oidLen := buf[0] - if int(oidLen) > len(buf) { - err = errors.UnsupportedError("invalid oid length: " + strconv.Itoa(int(oidLen))) - return - } - oid = buf[:oidLen] - _, err = readFull(r, oid) - return -} - -func (f *ecdsaKey) parse(r io.Reader) (err error) { - if f.oid, err = parseOID(r); err != nil { - return err - } - f.p.bytes, f.p.bitLength, err = readMPI(r) - return err -} - -func (f *ecdsaKey) serialize(w io.Writer) (err error) { - buf := make([]byte, maxOIDLength+1) - buf[0] = byte(len(f.oid)) - copy(buf[1:], f.oid) - if _, err = w.Write(buf[:len(f.oid)+1]); err != nil { - return - } - return writeMPIs(w, f.p) -} - -func getCurveByOid(oid []byte) elliptic.Curve { - switch { - case bytes.Equal(oid, oidCurveP224): - return elliptic.P224() - case bytes.Equal(oid, oidCurveP256): - return elliptic.P256() - case bytes.Equal(oid, oidCurveP384): - return elliptic.P384() - case bytes.Equal(oid, oidCurveP521): - return elliptic.P521() - case bytes.Equal(oid, oidCurveP256r1): - return brainpool.P256r1() - case bytes.Equal(oid, oidCurveP384r1): - return brainpool.P384r1() - case bytes.Equal(oid, oidCurveP512r1): - return brainpool.P512r1() - case bytes.Equal(oid, oidCurve25519): - return curve25519.Cv25519() - default: - return nil - } -} - -func (f *ecdsaKey) newECDSA() (*ecdsa.PublicKey, error) { - var c = getCurveByOid(f.oid) - // Curve25519 should not be used in ECDSA. - if c == nil || bytes.Equal(f.oid, oidCurve25519) { - return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid)) - } - // Note: Unmarshal already checks if point is on curve. - x, y := elliptic.Unmarshal(c, f.p.bytes) - if x == nil { - return nil, errors.UnsupportedError("failed to parse EC point") - } - return &ecdsa.PublicKey{Curve: c, X: x, Y: y}, nil -} - -func (f *ecdsaKey) newECDH() (*ecdh.PublicKey, error) { - var c = getCurveByOid(f.oid) - if c == nil { - return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid)) - } - // ecdh.Unmarshal handles unmarshaling for all curve types. It - // also checks if point is on curve. - x, y := ecdh.Unmarshal(c, f.p.bytes) - if x == nil { - return nil, errors.UnsupportedError("failed to parse EC point") - } - return &ecdh.PublicKey{Curve: c, X: x, Y: y}, nil -} - -func (f *ecdsaKey) byteLen() int { - return 1 + len(f.oid) + 2 + len(f.p.bytes) -} - -type kdfHashFunction byte -type kdfAlgorithm byte - -// ecdhKdf stores key derivation function parameters -// used for ECDH encryption. See RFC 6637, Section 9. -type ecdhKdf struct { - KdfHash kdfHashFunction - KdfAlgo kdfAlgorithm -} - -func (f *ecdhKdf) parse(r io.Reader) (err error) { - buf := make([]byte, 1) - if _, err = readFull(r, buf); err != nil { - return - } - kdfLen := int(buf[0]) - if kdfLen < 3 { - return errors.UnsupportedError("Unsupported ECDH KDF length: " + strconv.Itoa(kdfLen)) - } - buf = make([]byte, kdfLen) - if _, err = readFull(r, buf); err != nil { - return - } - reserved := int(buf[0]) - f.KdfHash = kdfHashFunction(buf[1]) - f.KdfAlgo = kdfAlgorithm(buf[2]) - if reserved != 0x01 { - return errors.UnsupportedError("Unsupported KDF reserved field: " + strconv.Itoa(reserved)) - } - return -} - -func (f *ecdhKdf) serialize(w io.Writer) (err error) { - buf := make([]byte, 4) - // See RFC 6637, Section 9, Algorithm-Specific Fields for ECDH keys. - buf[0] = byte(0x03) // Length of the following fields - buf[1] = byte(0x01) // Reserved for future extensions, must be 1 for now - buf[2] = byte(f.KdfHash) - buf[3] = byte(f.KdfAlgo) - _, err = w.Write(buf[:]) - return -} - -func (f *ecdhKdf) byteLen() int { - return 4 -} - -// PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2. -type PublicKey struct { - CreationTime time.Time - PubKeyAlgo PublicKeyAlgorithm - PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey or *ecdsa.PublicKey - Fingerprint [20]byte - KeyId uint64 - IsSubkey bool - - n, e, p, q, g, y parsedMPI - - // RFC 6637 fields - ec *ecdsaKey - ecdh *ecdhKdf - - // EdDSA fields (no RFC available), uses ecdsa scaffolding - edk *edDSAkey -} - -// signingKey provides a convenient abstraction over signature verification -// for v3 and v4 public keys. -type signingKey interface { - SerializeSignaturePrefix(io.Writer) - serializeWithoutHeaders(io.Writer) error -} - -func FromBig(n *big.Int) parsedMPI { - return parsedMPI{ - bytes: n.Bytes(), - bitLength: uint16(n.BitLen()), - } -} - -func FromBytes(bytes []byte) parsedMPI { - return parsedMPI{ - bytes: bytes, - bitLength: uint16(8 * len(bytes)), - } -} - -// NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey. -func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoRSA, - PublicKey: pub, - n: FromBig(pub.N), - e: FromBig(big.NewInt(int64(pub.E))), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -// NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey. -func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoDSA, - PublicKey: pub, - p: FromBig(pub.P), - q: FromBig(pub.Q), - g: FromBig(pub.G), - y: FromBig(pub.Y), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -// check EdDSA public key material. -// There is currently no RFC for it, but it doesn't mean it's not -// implemented or in use. -func (e *edDSAkey) check() error { - if !bytes.Equal(e.oid, oidEdDSA) { - return errors.UnsupportedError(fmt.Sprintf("Bad OID for EdDSA key: %v", e.oid)) - } - if bLen := len(e.p.bytes); bLen != 33 { // 32 bytes for ed25519 key and 1 byte for 0x40 header - return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA public key length: %d", bLen)) - } - return nil -} - -// NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey. -func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoElGamal, - PublicKey: pub, - p: FromBig(pub.P), - g: FromBig(pub.G), - y: FromBig(pub.Y), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func getCurveOid(curve elliptic.Curve) (res []byte, err error) { - switch curve { - case elliptic.P224(): - res = oidCurveP224 - case elliptic.P256(): - res = oidCurveP256 - case elliptic.P384(): - res = oidCurveP384 - case elliptic.P521(): - res = oidCurveP521 - case brainpool.P256r1(): - res = oidCurveP256r1 - case brainpool.P384r1(): - res = oidCurveP384r1 - case brainpool.P512r1(): - res = oidCurveP512r1 - case curve25519.Cv25519(): - res = oidCurve25519 - default: - err = errors.UnsupportedError("unknown curve") - } - return -} - -func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDSA, - PublicKey: pub, - ec: new(ecdsaKey), - } - oid, _ := getCurveOid(pub.Curve) - pk.ec.oid = oid - bs, bitLen := ecdh.Marshal(pub.Curve, pub.X, pub.Y) - pk.ec.p.bytes = bs - pk.ec.p.bitLength = uint16(bitLen) - - pk.setFingerPrintAndKeyId() - return pk -} - -func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDH, - PublicKey: pub, - ec: new(ecdsaKey), - } - oid, _ := getCurveOid(pub.Curve) - pk.ec.oid = oid - bs, bitLen := ecdh.Marshal(pub.Curve, pub.X, pub.Y) - pk.ec.p.bytes = bs - pk.ec.p.bitLength = uint16(bitLen) - - hashbyte, _ := s2k.HashToHashId(crypto.SHA512) - pk.ecdh = &ecdhKdf{ - KdfHash: kdfHashFunction(hashbyte), - KdfAlgo: kdfAlgorithm(CipherAES256), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func (pk *PublicKey) parse(r io.Reader) (err error) { - // RFC 4880, section 5.5.2 - var buf [6]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != 4 { - return errors.UnsupportedError("public key version") - } - pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) - pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5]) - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - err = pk.parseRSA(r) - case PubKeyAlgoDSA: - err = pk.parseDSA(r) - case PubKeyAlgoElGamal: - err = pk.parseElGamal(r) - case PubKeyAlgoEdDSA: - pk.edk = new(edDSAkey) - if err = pk.edk.parse(r); err != nil { - return err - } - err = pk.edk.check() - case PubKeyAlgoECDSA: - pk.ec = new(ecdsaKey) - if err = pk.ec.parse(r); err != nil { - return err - } - pk.PublicKey, err = pk.ec.newECDSA() - case PubKeyAlgoECDH: - pk.ec = new(ecdsaKey) - if err = pk.ec.parse(r); err != nil { - return - } - pk.ecdh = new(ecdhKdf) - if err = pk.ecdh.parse(r); err != nil { - return - } - pk.PublicKey, err = pk.ec.newECDH() - case PubKeyAlgoBadElGamal: - // Key has ElGamal format but nil-implementation - it will - // load but it's not possible to do any operations using this - // key. - err = pk.parseElGamal(r) - if err != nil { - pk.PublicKey = nil - } - default: - err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) - } - if err != nil { - return - } - - pk.setFingerPrintAndKeyId() - return -} - -func (pk *PublicKey) setFingerPrintAndKeyId() { - // RFC 4880, section 12.2 - fingerPrint := sha1.New() - pk.SerializeSignaturePrefix(fingerPrint) - pk.serializeWithoutHeaders(fingerPrint) - copy(pk.Fingerprint[:], fingerPrint.Sum(nil)) - pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20]) -} - -// parseRSA parses RSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseRSA(r io.Reader) (err error) { - pk.n.bytes, pk.n.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.e.bytes, pk.e.bitLength, err = readMPI(r) - if err != nil { - return - } - - if len(pk.e.bytes) > 7 { - err = errors.UnsupportedError("large public exponent") - return - } - rsa := &rsa.PublicKey{ - N: new(big.Int).SetBytes(pk.n.bytes), - E: 0, - } - // Warning: incompatibility with crypto/rsa: keybase fork uses - // int64 public exponents instead of int32. - for i := 0; i < len(pk.e.bytes); i++ { - rsa.E <<= 8 - rsa.E |= int64(pk.e.bytes[i]) - } - pk.PublicKey = rsa - return -} - -// parseDSA parses DSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseDSA(r io.Reader) (err error) { - pk.p.bytes, pk.p.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.q.bytes, pk.q.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.g.bytes, pk.g.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.y.bytes, pk.y.bitLength, err = readMPI(r) - if err != nil { - return - } - - dsa := new(dsa.PublicKey) - dsa.P = new(big.Int).SetBytes(pk.p.bytes) - dsa.Q = new(big.Int).SetBytes(pk.q.bytes) - dsa.G = new(big.Int).SetBytes(pk.g.bytes) - dsa.Y = new(big.Int).SetBytes(pk.y.bytes) - pk.PublicKey = dsa - return -} - -// parseElGamal parses ElGamal public key material from the given Reader. See -// RFC 4880, section 5.5.2. -func (pk *PublicKey) parseElGamal(r io.Reader) (err error) { - pk.p.bytes, pk.p.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.g.bytes, pk.g.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.y.bytes, pk.y.bitLength, err = readMPI(r) - if err != nil { - return - } - - elgamal := new(elgamal.PublicKey) - elgamal.P = new(big.Int).SetBytes(pk.p.bytes) - elgamal.G = new(big.Int).SetBytes(pk.g.bytes) - elgamal.Y = new(big.Int).SetBytes(pk.y.bytes) - pk.PublicKey = elgamal - return -} - -// SerializeSignaturePrefix writes the prefix for this public key to the given Writer. -// The prefix is used when calculating a signature over this public key. See -// RFC 4880, section 5.2.4. -func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) { - var pLength uint16 - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - pLength += 2 + uint16(len(pk.n.bytes)) - pLength += 2 + uint16(len(pk.e.bytes)) - case PubKeyAlgoDSA: - pLength += 2 + uint16(len(pk.p.bytes)) - pLength += 2 + uint16(len(pk.q.bytes)) - pLength += 2 + uint16(len(pk.g.bytes)) - pLength += 2 + uint16(len(pk.y.bytes)) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - pLength += 2 + uint16(len(pk.p.bytes)) - pLength += 2 + uint16(len(pk.g.bytes)) - pLength += 2 + uint16(len(pk.y.bytes)) - case PubKeyAlgoECDSA: - pLength += uint16(pk.ec.byteLen()) - case PubKeyAlgoECDH: - pLength += uint16(pk.ec.byteLen()) - pLength += uint16(pk.ecdh.byteLen()) - case PubKeyAlgoEdDSA: - pLength += uint16(pk.edk.byteLen()) - default: - panic("unknown public key algorithm") - } - pLength += 6 - h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) - return -} - -func (pk *PublicKey) Serialize(w io.Writer) (err error) { - length := 6 // 6 byte header - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - length += 2 + len(pk.n.bytes) - length += 2 + len(pk.e.bytes) - case PubKeyAlgoDSA: - length += 2 + len(pk.p.bytes) - length += 2 + len(pk.q.bytes) - length += 2 + len(pk.g.bytes) - length += 2 + len(pk.y.bytes) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - length += 2 + len(pk.p.bytes) - length += 2 + len(pk.g.bytes) - length += 2 + len(pk.y.bytes) - case PubKeyAlgoECDSA: - length += pk.ec.byteLen() - case PubKeyAlgoECDH: - length += pk.ec.byteLen() - length += pk.ecdh.byteLen() - case PubKeyAlgoEdDSA: - length += pk.edk.byteLen() - default: - panic("unknown public key algorithm") - } - - packetType := packetTypePublicKey - if pk.IsSubkey { - packetType = packetTypePublicSubkey - } - err = serializeHeader(w, packetType, length) - if err != nil { - return - } - return pk.serializeWithoutHeaders(w) -} - -// serializeWithoutHeaders marshals the PublicKey to w in the form of an -// OpenPGP public key packet, not including the packet header. -func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) { - var buf [6]byte - buf[0] = 4 - t := uint32(pk.CreationTime.Unix()) - buf[1] = byte(t >> 24) - buf[2] = byte(t >> 16) - buf[3] = byte(t >> 8) - buf[4] = byte(t) - buf[5] = byte(pk.PubKeyAlgo) - - _, err = w.Write(buf[:]) - if err != nil { - return - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - return writeMPIs(w, pk.n, pk.e) - case PubKeyAlgoDSA: - return writeMPIs(w, pk.p, pk.q, pk.g, pk.y) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - return writeMPIs(w, pk.p, pk.g, pk.y) - case PubKeyAlgoECDSA: - return pk.ec.serialize(w) - case PubKeyAlgoEdDSA: - return pk.edk.serialize(w) - case PubKeyAlgoECDH: - if err = pk.ec.serialize(w); err != nil { - return - } - return pk.ecdh.serialize(w) - } - return errors.InvalidArgumentError("bad public-key algorithm") -} - -// CanSign returns true iff this public key can generate signatures -func (pk *PublicKey) CanSign() bool { - return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal -} - -// VerifySignature returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - signed.Write(sig.HashSuffix) - hashBytes := signed.Sum(nil) - - // NOTE(maxtaco) 2016-08-22 - // - // We used to do this: - // - // if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - // return errors.SignatureError("hash tag doesn't match") - // } - // - // But don't do anything in this case. Some GPGs generate bad - // 2-byte hash prefixes, but GPG also doesn't seem to care on - // import. See BrentMaxwell's key. I think it's safe to disable - // this check! - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) - err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)) - if err != nil { - return errors.SignatureError("RSA verification failure") - } - return nil - case PubKeyAlgoDSA: - dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey) - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 - if len(hashBytes) > subgroupSize { - hashBytes = hashBytes[:subgroupSize] - } - if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { - return errors.SignatureError("DSA verification failure") - } - return nil - case PubKeyAlgoECDSA: - ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) - if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) { - return errors.SignatureError("ECDSA verification failure") - } - return nil - case PubKeyAlgoEdDSA: - if !pk.edk.Verify(hashBytes, sig.EdDSASigR, sig.EdDSASigS) { - return errors.SignatureError("EdDSA verification failure") - } - return nil - default: - return errors.SignatureError("Unsupported public key algorithm used in signature") - } - panic("unreachable") -} - -// VerifySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - suffix := make([]byte, 5) - suffix[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) - signed.Write(suffix) - hashBytes := signed.Sum(nil) - - if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - return errors.SignatureError("hash tag doesn't match") - } - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - rsaPublicKey := pk.PublicKey.(*rsa.PublicKey) - if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)); err != nil { - return errors.SignatureError("RSA verification failure") - } - return - case PubKeyAlgoDSA: - dsaPublicKey := pk.PublicKey.(*dsa.PublicKey) - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 - if len(hashBytes) > subgroupSize { - hashBytes = hashBytes[:subgroupSize] - } - if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { - return errors.SignatureError("DSA verification failure") - } - return nil - default: - panic("shouldn't happen") - } - panic("unreachable") -} - -// keySignatureHash returns a Hash of the message that needs to be signed for -// pk to assert a subkey relationship to signed. -func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - updateKeySignatureHash(pk, signed, h) - - return -} - -// updateKeySignatureHash does the actual hash updates for keySignatureHash. -func updateKeySignatureHash(pk, signed signingKey, h hash.Hash) { - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - signed.SerializeSignaturePrefix(h) - signed.serializeWithoutHeaders(h) -} - -// VerifyKeySignature returns nil iff sig is a valid signature, made by this -// public key, of signed. -func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - if err = pk.VerifySignature(h, sig); err != nil { - return err - } - - if sig.FlagSign { - - // BUG(maxtaco) - // - // We should check for more than FlagsSign here, because if - // you read keys.go, we can sometimes use signing subkeys even if they're - // not explicitly flagged as such. However, so doing fails lots of currently - // working tests, so I'm not going to do much here. - // - // In other words, we should have this disjunction in the condition above: - // - // || (!sig.FlagsValid && pk.PubKeyAlgo.CanSign()) { - // - - // Signing subkeys must be cross-signed. See - // https://www.gnupg.org/faq/subkey-cross-certify.html. - if sig.EmbeddedSignature == nil { - return errors.StructuralError("signing subkey is missing cross-signature") - } - // Verify the cross-signature. This is calculated over the same - // data as the main signature, so we cannot just recursively - // call signed.VerifyKeySignature(...) - if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil { - return errors.StructuralError("error while hashing for cross-signature: " + err.Error()) - } - if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil { - return errors.StructuralError("error while verifying cross-signature: " + err.Error()) - } - } - - return nil -} - -func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - return -} - -// VerifyRevocationSignature returns nil iff sig is a valid signature, made by this -// public key. -func (pk *PublicKey) VerifyRevocationSignature(revokedKey *PublicKey, sig *Signature) (err error) { - h, err := keyRevocationHash(revokedKey, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -type teeHash struct { - h hash.Hash -} - -func (t teeHash) Write(b []byte) (n int, err error) { - fmt.Printf("hash -> %s %+v\n", string(b), b) - return t.h.Write(b) -} -func (t teeHash) Sum(b []byte) []byte { return t.h.Sum(b) } -func (t teeHash) Reset() { t.h.Reset() } -func (t teeHash) Size() int { return t.h.Size() } -func (t teeHash) BlockSize() int { return t.h.BlockSize() } - -// userIdSignatureHash returns a Hash of the message that needs to be signed -// to assert that pk is a valid key for id. -func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - updateUserIdSignatureHash(id, pk, h) - - return -} - -// updateUserIdSignatureHash does the actual hash updates for -// userIdSignatureHash. -func updateUserIdSignatureHash(id string, pk *PublicKey, h hash.Hash) { - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - var buf [5]byte - buf[0] = 0xb4 - buf[1] = byte(len(id) >> 24) - buf[2] = byte(len(id) >> 16) - buf[3] = byte(len(id) >> 8) - buf[4] = byte(len(id)) - h.Write(buf[:]) - h.Write([]byte(id)) - - return -} - -// VerifyUserIdSignature returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) { - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -// VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pub, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// KeyIdString returns the public key's fingerprint in capital hex -// (e.g. "6C7EE1B8621CC013"). -func (pk *PublicKey) KeyIdString() string { - return fmt.Sprintf("%X", pk.Fingerprint[12:20]) -} - -// KeyIdShortString returns the short form of public key's fingerprint -// in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). -func (pk *PublicKey) KeyIdShortString() string { - return fmt.Sprintf("%X", pk.Fingerprint[16:20]) -} - -// A parsedMPI is used to store the contents of a big integer, along with the -// bit length that was specified in the original input. This allows the MPI to -// be reserialized exactly. -type parsedMPI struct { - bytes []byte - bitLength uint16 -} - -// writeMPIs is a utility function for serializing several big integers to the -// given Writer. -func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) { - for _, mpi := range mpis { - err = writeMPI(w, mpi.bitLength, mpi.bytes) - if err != nil { - return - } - } - return -} - -// BitLength returns the bit length for the given public key. Used for -// displaying key information, actual buffers and BigInts inside may -// have non-matching different size if the key is invalid. -func (pk *PublicKey) BitLength() (bitLength uint16, err error) { - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - bitLength = pk.n.bitLength - case PubKeyAlgoDSA: - bitLength = pk.p.bitLength - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - bitLength = pk.p.bitLength - case PubKeyAlgoECDH: - ecdhPublicKey := pk.PublicKey.(*ecdh.PublicKey) - bitLength = uint16(ecdhPublicKey.Curve.Params().BitSize) - case PubKeyAlgoECDSA: - ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) - bitLength = uint16(ecdsaPublicKey.Curve.Params().BitSize) - case PubKeyAlgoEdDSA: - // EdDSA only support ed25519 curves right now, just return - // the length. Also, we don't have any PublicKey.Curve object - // to look the size up from. - bitLength = 256 - default: - err = errors.InvalidArgumentError("bad public-key algorithm") - } - return -} - -func (pk *PublicKey) ErrorIfDeprecated() error { - switch pk.PubKeyAlgo { - case PubKeyAlgoBadElGamal: - return errors.DeprecatedKeyError("ElGamal Encrypt or Sign (algo 20) is deprecated") - default: - return nil - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go deleted file mode 100644 index f75cbeab..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2013 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 packet - -import ( - "crypto" - "crypto/md5" - "encoding/binary" - "fmt" - "hash" - "io" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/rsa" -) - -// PublicKeyV3 represents older, version 3 public keys. These keys are less secure and -// should not be used for signing or encrypting. They are supported here only for -// parsing version 3 key material and validating signatures. -// See RFC 4880, section 5.5.2. -type PublicKeyV3 struct { - CreationTime time.Time - DaysToExpire uint16 - PubKeyAlgo PublicKeyAlgorithm - PublicKey *rsa.PublicKey - Fingerprint [16]byte - KeyId uint64 - IsSubkey bool - - n, e parsedMPI -} - -// newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey. -// Included here for testing purposes only. RFC 4880, section 5.5.2: -// "an implementation MUST NOT generate a V3 key, but MAY accept it." -func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 { - pk := &PublicKeyV3{ - CreationTime: creationTime, - PublicKey: pub, - n: FromBig(pub.N), - e: FromBig(big.NewInt(int64(pub.E))), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func (pk *PublicKeyV3) parse(r io.Reader) (err error) { - // RFC 4880, section 5.5.2 - var buf [8]byte - if _, err = readFull(r, buf[:]); err != nil { - return - } - if buf[0] < 2 || buf[0] > 3 { - return errors.UnsupportedError("public key version") - } - pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) - pk.DaysToExpire = binary.BigEndian.Uint16(buf[5:7]) - pk.PubKeyAlgo = PublicKeyAlgorithm(buf[7]) - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - err = pk.parseRSA(r) - default: - err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) - } - if err != nil { - return - } - - pk.setFingerPrintAndKeyId() - return -} - -func (pk *PublicKeyV3) setFingerPrintAndKeyId() { - // RFC 4880, section 12.2 - fingerPrint := md5.New() - fingerPrint.Write(pk.n.bytes) - fingerPrint.Write(pk.e.bytes) - fingerPrint.Sum(pk.Fingerprint[:0]) - pk.KeyId = binary.BigEndian.Uint64(pk.n.bytes[len(pk.n.bytes)-8:]) -} - -// parseRSA parses RSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKeyV3) parseRSA(r io.Reader) (err error) { - if pk.n.bytes, pk.n.bitLength, err = readMPI(r); err != nil { - return - } - if pk.e.bytes, pk.e.bitLength, err = readMPI(r); err != nil { - return - } - - // RFC 4880 Section 12.2 requires the low 8 bytes of the - // modulus to form the key id. - if len(pk.n.bytes) < 8 { - return errors.StructuralError("v3 public key modulus is too short") - } - if len(pk.e.bytes) > 7 { - err = errors.UnsupportedError("large public exponent") - return - } - rsa := &rsa.PublicKey{N: new(big.Int).SetBytes(pk.n.bytes)} - // Warning: incompatibility with crypto/rsa: keybase fork uses - // int64 public exponents instead of int32. - for i := 0; i < len(pk.e.bytes); i++ { - rsa.E <<= 8 - rsa.E |= int64(pk.e.bytes[i]) - } - pk.PublicKey = rsa - return -} - -// SerializeSignaturePrefix writes the prefix for this public key to the given Writer. -// The prefix is used when calculating a signature over this public key. See -// RFC 4880, section 5.2.4. -func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { - var pLength uint16 - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - pLength += 2 + uint16(len(pk.n.bytes)) - pLength += 2 + uint16(len(pk.e.bytes)) - default: - panic("unknown public key algorithm") - } - pLength += 6 - w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) - return -} - -func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) { - length := 8 // 8 byte header - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - length += 2 + len(pk.n.bytes) - length += 2 + len(pk.e.bytes) - default: - panic("unknown public key algorithm") - } - - packetType := packetTypePublicKey - if pk.IsSubkey { - packetType = packetTypePublicSubkey - } - if err = serializeHeader(w, packetType, length); err != nil { - return - } - return pk.serializeWithoutHeaders(w) -} - -// serializeWithoutHeaders marshals the PublicKey to w in the form of an -// OpenPGP public key packet, not including the packet header. -func (pk *PublicKeyV3) serializeWithoutHeaders(w io.Writer) (err error) { - var buf [8]byte - // Version 3 - buf[0] = 3 - // Creation time - t := uint32(pk.CreationTime.Unix()) - buf[1] = byte(t >> 24) - buf[2] = byte(t >> 16) - buf[3] = byte(t >> 8) - buf[4] = byte(t) - // Days to expire - buf[5] = byte(pk.DaysToExpire >> 8) - buf[6] = byte(pk.DaysToExpire) - // Public key algorithm - buf[7] = byte(pk.PubKeyAlgo) - - if _, err = w.Write(buf[:]); err != nil { - return - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - return writeMPIs(w, pk.n, pk.e) - } - return errors.InvalidArgumentError("bad public-key algorithm") -} - -// CanSign returns true iff this public key can generate signatures -func (pk *PublicKeyV3) CanSign() bool { - return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly -} - -// VerifySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - suffix := make([]byte, 5) - suffix[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) - signed.Write(suffix) - hashBytes := signed.Sum(nil) - - if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - return errors.SignatureError("hash tag doesn't match") - } - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { - return errors.SignatureError("RSA verification failure") - } - return - default: - // V3 public keys only support RSA. - panic("shouldn't happen") - } - panic("unreachable") -} - -// VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, pub *PublicKeyV3, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pk, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// VerifyKeySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of signed. -func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV3) (err error) { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// userIdSignatureV3Hash returns a Hash of the message that needs to be signed -// to assert that pk is a valid key for id. -func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { - if !hfn.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hfn.New() - - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - h.Write([]byte(id)) - - return -} - -// KeyIdString returns the public key's fingerprint in capital hex -// (e.g. "6C7EE1B8621CC013"). -func (pk *PublicKeyV3) KeyIdString() string { - return fmt.Sprintf("%X", pk.KeyId) -} - -// KeyIdShortString returns the short form of public key's fingerprint -// in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). -func (pk *PublicKeyV3) KeyIdShortString() string { - return fmt.Sprintf("%X", pk.KeyId&0xFFFFFFFF) -} - -// BitLength returns the bit length for the given public key. -func (pk *PublicKeyV3) BitLength() (bitLength uint16, err error) { - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - bitLength = pk.n.bitLength - default: - err = errors.InvalidArgumentError("bad public-key algorithm") - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go deleted file mode 100644 index 957b3b89..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "io" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// Reader reads packets from an io.Reader and allows packets to be 'unread' so -// that they result from the next call to Next. -type Reader struct { - q []Packet - readers []io.Reader -} - -// New io.Readers are pushed when a compressed or encrypted packet is processed -// and recursively treated as a new source of packets. However, a carefully -// crafted packet can trigger an infinite recursive sequence of packets. See -// http://mumble.net/~campbell/misc/pgp-quine -// https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-4402 -// This constant limits the number of recursive packets that may be pushed. -const maxReaders = 32 - -// Next returns the most recently unread Packet, or reads another packet from -// the top-most io.Reader. Unknown packet types are skipped. -func (r *Reader) Next() (p Packet, err error) { - if len(r.q) > 0 { - p = r.q[len(r.q)-1] - r.q = r.q[:len(r.q)-1] - return - } - - for len(r.readers) > 0 { - p, err = Read(r.readers[len(r.readers)-1]) - if err == nil { - return - } - if err == io.EOF { - r.readers = r.readers[:len(r.readers)-1] - continue - } - if _, ok := err.(errors.UnknownPacketTypeError); !ok { - return nil, err - } - } - return nil, io.EOF -} - -// Push causes the Reader to start reading from a new io.Reader. When an EOF -// error is seen from the new io.Reader, it is popped and the Reader continues -// to read from the next most recent io.Reader. Push returns a StructuralError -// if pushing the reader would exceed the maximum recursion level, otherwise it -// returns nil. -func (r *Reader) Push(reader io.Reader) (err error) { - if len(r.readers) >= maxReaders { - return errors.StructuralError("too many layers of packets") - } - r.readers = append(r.readers, reader) - return nil -} - -// Unread causes the given Packet to be returned from the next call to Next. -func (r *Reader) Unread(p Packet) { - r.q = append(r.q, p) -} - -func NewReader(r io.Reader) *Reader { - return &Reader{ - q: nil, - readers: []io.Reader{r}, - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go deleted file mode 100644 index 383a8a6a..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go +++ /dev/null @@ -1,923 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "encoding/binary" - "fmt" - "hash" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" - "github.com/keybase/go-crypto/rsa" -) - -const ( - // See RFC 4880, section 5.2.3.21 for details. - KeyFlagCertify = 1 << iota - KeyFlagSign - KeyFlagEncryptCommunications - KeyFlagEncryptStorage -) - -// Signer can be implemented by application code to do actual signing. -type Signer interface { - hash.Hash - Sign(sig *Signature) error - KeyId() uint64 - PublicKeyAlgo() PublicKeyAlgorithm -} - -// RevocationKey represents designated revoker packet. See RFC 4880 -// section 5.2.3.15 for details. -type RevocationKey struct { - Class byte - PublicKeyAlgo PublicKeyAlgorithm - Fingerprint []byte -} - -// KeyFlagBits holds boolean whether any usage flags were provided in -// the signature and BitField with KeyFlag* flags. -type KeyFlagBits struct { - Valid bool - BitField byte -} - -// Signature represents a signature. See RFC 4880, section 5.2. -type Signature struct { - SigType SignatureType - PubKeyAlgo PublicKeyAlgorithm - Hash crypto.Hash - - // HashSuffix is extra data that is hashed in after the signed data. - HashSuffix []byte - // HashTag contains the first two bytes of the hash for fast rejection - // of bad signed data. - HashTag [2]byte - CreationTime time.Time - - RSASignature parsedMPI - DSASigR, DSASigS parsedMPI - ECDSASigR, ECDSASigS parsedMPI - EdDSASigR, EdDSASigS parsedMPI - - // rawSubpackets contains the unparsed subpackets, in order. - rawSubpackets []outputSubpacket - - // The following are optional so are nil when not included in the - // signature. - - SigLifetimeSecs, KeyLifetimeSecs *uint32 - PreferredSymmetric, PreferredHash, PreferredCompression []uint8 - PreferredKeyServer string - IssuerKeyId *uint64 - IsPrimaryId *bool - IssuerFingerprint []byte - - // FlagsValid is set if any flags were given. See RFC 4880, section - // 5.2.3.21 for details. - FlagsValid bool - FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool - - // RevocationReason is set if this signature has been revoked. - // See RFC 4880, section 5.2.3.23 for details. - RevocationReason *uint8 - RevocationReasonText string - - // PolicyURI is optional. See RFC 4880, Section 5.2.3.20 for details - PolicyURI string - - // Regex is a regex that can match a PGP UID. See RFC 4880, 5.2.3.14 for details - Regex string - - // MDC is set if this signature has a feature packet that indicates - // support for MDC subpackets. - MDC bool - - // EmbeddedSignature, if non-nil, is a signature of the parent key, by - // this key. This prevents an attacker from claiming another's signing - // subkey as their own. - EmbeddedSignature *Signature - - // StubbedOutCriticalError is not fail-stop, since it shouldn't break key parsing - // when appearing in WoT-style cross signatures. But it should prevent a signature - // from being applied to a primary or subkey. - StubbedOutCriticalError error - - // DesignaterRevoker will be present if this signature certifies a - // designated revoking key id (3rd party key that can sign - // revocation for this key). - DesignatedRevoker *RevocationKey - - outSubpackets []outputSubpacket -} - -func (sig *Signature) parse(r io.Reader) (err error) { - // RFC 4880, section 5.2.3 - var buf [5]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - if buf[0] != 4 { - err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) - return - } - - _, err = readFull(r, buf[:5]) - if err != nil { - return - } - sig.SigType = SignatureType(buf[0]) - sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1]) - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - default: - err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) - return - } - - var ok bool - sig.Hash, ok = s2k.HashIdToHash(buf[2]) - if !ok { - return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) - } - - hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4]) - l := 6 + hashedSubpacketsLength - sig.HashSuffix = make([]byte, l+6) - sig.HashSuffix[0] = 4 - copy(sig.HashSuffix[1:], buf[:5]) - hashedSubpackets := sig.HashSuffix[6:l] - _, err = readFull(r, hashedSubpackets) - if err != nil { - return - } - // See RFC 4880, section 5.2.4 - trailer := sig.HashSuffix[l:] - trailer[0] = 4 - trailer[1] = 0xff - trailer[2] = uint8(l >> 24) - trailer[3] = uint8(l >> 16) - trailer[4] = uint8(l >> 8) - trailer[5] = uint8(l) - - err = parseSignatureSubpackets(sig, hashedSubpackets, true) - if err != nil { - return - } - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1]) - unhashedSubpackets := make([]byte, unhashedSubpacketsLength) - _, err = readFull(r, unhashedSubpackets) - if err != nil { - return - } - err = parseSignatureSubpackets(sig, unhashedSubpackets, false) - if err != nil { - return - } - - _, err = readFull(r, sig.HashTag[:2]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) - case PubKeyAlgoDSA: - sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) - } - case PubKeyAlgoEdDSA: - sig.EdDSASigR.bytes, sig.EdDSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.EdDSASigS.bytes, sig.EdDSASigS.bitLength, err = readMPI(r) - } - case PubKeyAlgoECDSA: - sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r) - } - default: - panic("unreachable") - } - return -} - -// parseSignatureSubpackets parses subpackets of the main signature packet. See -// RFC 4880, section 5.2.3.1. -func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) { - for len(subpackets) > 0 { - subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed) - if err != nil { - return - } - } - - if sig.CreationTime.IsZero() { - err = errors.StructuralError("no creation time in signature") - } - - return -} - -type signatureSubpacketType uint8 - -const ( - creationTimeSubpacket signatureSubpacketType = 2 - signatureExpirationSubpacket signatureSubpacketType = 3 - regularExpressionSubpacket signatureSubpacketType = 6 - keyExpirationSubpacket signatureSubpacketType = 9 - prefSymmetricAlgosSubpacket signatureSubpacketType = 11 - revocationKey signatureSubpacketType = 12 - issuerSubpacket signatureSubpacketType = 16 - prefHashAlgosSubpacket signatureSubpacketType = 21 - prefCompressionSubpacket signatureSubpacketType = 22 - prefKeyServerSubpacket signatureSubpacketType = 24 - primaryUserIdSubpacket signatureSubpacketType = 25 - policyURISubpacket signatureSubpacketType = 26 - keyFlagsSubpacket signatureSubpacketType = 27 - reasonForRevocationSubpacket signatureSubpacketType = 29 - featuresSubpacket signatureSubpacketType = 30 - embeddedSignatureSubpacket signatureSubpacketType = 32 - issuerFingerprint signatureSubpacketType = 33 -) - -// parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1. -func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) { - // RFC 4880, section 5.2.3.1 - var ( - length uint32 - packetType signatureSubpacketType - isCritical bool - ) - switch { - case subpacket[0] < 192: - length = uint32(subpacket[0]) - subpacket = subpacket[1:] - case subpacket[0] < 255: - if len(subpacket) < 2 { - goto Truncated - } - length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192 - subpacket = subpacket[2:] - default: - if len(subpacket) < 5 { - goto Truncated - } - length = uint32(subpacket[1])<<24 | - uint32(subpacket[2])<<16 | - uint32(subpacket[3])<<8 | - uint32(subpacket[4]) - subpacket = subpacket[5:] - } - if length > uint32(len(subpacket)) { - goto Truncated - } - rest = subpacket[length:] - subpacket = subpacket[:length] - if len(subpacket) == 0 { - err = errors.StructuralError("zero length signature subpacket") - return - } - packetType = signatureSubpacketType(subpacket[0] & 0x7f) - isCritical = subpacket[0]&0x80 == 0x80 - subpacket = subpacket[1:] - sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket}) - switch packetType { - case creationTimeSubpacket: - if !isHashed { - err = errors.StructuralError("signature creation time in non-hashed area") - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("signature creation time not four bytes") - return - } - t := binary.BigEndian.Uint32(subpacket) - sig.CreationTime = time.Unix(int64(t), 0) - case signatureExpirationSubpacket: - // Signature expiration time, section 5.2.3.10 - if !isHashed { - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("expiration subpacket with bad length") - return - } - sig.SigLifetimeSecs = new(uint32) - *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case keyExpirationSubpacket: - // Key expiration time, section 5.2.3.6 - if !isHashed { - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("key expiration subpacket with bad length") - return - } - sig.KeyLifetimeSecs = new(uint32) - *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case prefSymmetricAlgosSubpacket: - // Preferred symmetric algorithms, section 5.2.3.7 - if !isHashed { - return - } - sig.PreferredSymmetric = make([]byte, len(subpacket)) - copy(sig.PreferredSymmetric, subpacket) - case issuerSubpacket: - // Issuer, section 5.2.3.5 - if len(subpacket) != 8 { - err = errors.StructuralError("issuer subpacket with bad length") - return - } - sig.IssuerKeyId = new(uint64) - *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket) - case prefHashAlgosSubpacket: - // Preferred hash algorithms, section 5.2.3.8 - if !isHashed { - return - } - sig.PreferredHash = make([]byte, len(subpacket)) - copy(sig.PreferredHash, subpacket) - case prefCompressionSubpacket: - // Preferred compression algorithms, section 5.2.3.9 - if !isHashed { - return - } - sig.PreferredCompression = make([]byte, len(subpacket)) - copy(sig.PreferredCompression, subpacket) - case primaryUserIdSubpacket: - // Primary User ID, section 5.2.3.19 - if !isHashed { - return - } - if len(subpacket) != 1 { - err = errors.StructuralError("primary user id subpacket with bad length") - return - } - sig.IsPrimaryId = new(bool) - if subpacket[0] > 0 { - *sig.IsPrimaryId = true - } - case keyFlagsSubpacket: - // Key flags, section 5.2.3.21 - if !isHashed { - return - } - if len(subpacket) == 0 { - err = errors.StructuralError("empty key flags subpacket") - return - } - if subpacket[0] != 0 { - sig.FlagsValid = true - if subpacket[0]&KeyFlagCertify != 0 { - sig.FlagCertify = true - } - if subpacket[0]&KeyFlagSign != 0 { - sig.FlagSign = true - } - if subpacket[0]&KeyFlagEncryptCommunications != 0 { - sig.FlagEncryptCommunications = true - } - if subpacket[0]&KeyFlagEncryptStorage != 0 { - sig.FlagEncryptStorage = true - } - } - case reasonForRevocationSubpacket: - // Reason For Revocation, section 5.2.3.23 - if !isHashed { - return - } - if len(subpacket) == 0 { - err = errors.StructuralError("empty revocation reason subpacket") - return - } - sig.RevocationReason = new(uint8) - *sig.RevocationReason = subpacket[0] - sig.RevocationReasonText = string(subpacket[1:]) - case featuresSubpacket: - // Features subpacket, section 5.2.3.24 specifies a very general - // mechanism for OpenPGP implementations to signal support for new - // features. In practice, the subpacket is used exclusively to - // indicate support for MDC-protected encryption. - sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1 - case embeddedSignatureSubpacket: - // Only usage is in signatures that cross-certify - // signing subkeys. section 5.2.3.26 describes the - // format, with its usage described in section 11.1 - if sig.EmbeddedSignature != nil { - err = errors.StructuralError("Cannot have multiple embedded signatures") - return - } - sig.EmbeddedSignature = new(Signature) - // Embedded signatures are required to be v4 signatures see - // section 12.1. However, we only parse v4 signatures in this - // file anyway. - if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil { - return nil, err - } - if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding { - return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType))) - } - case policyURISubpacket: - // See RFC 4880, Section 5.2.3.20 - sig.PolicyURI = string(subpacket[:]) - case regularExpressionSubpacket: - sig.Regex = string(subpacket[:]) - if isCritical { - sig.StubbedOutCriticalError = errors.UnsupportedError("regex support is stubbed out") - } - case prefKeyServerSubpacket: - sig.PreferredKeyServer = string(subpacket[:]) - case issuerFingerprint: - // The first byte is how many bytes the fingerprint is, but we'll just - // read until the end of the subpacket, so we'll ignore it. - sig.IssuerFingerprint = append([]byte{}, subpacket[1:]...) - case revocationKey: - // Authorizes the specified key to issue revocation signatures - // for a key. - - // TODO: Class octet must have bit 0x80 set. If the bit 0x40 - // is set, then this means that the revocation information is - // sensitive. - sig.DesignatedRevoker = &RevocationKey{ - Class: subpacket[0], - PublicKeyAlgo: PublicKeyAlgorithm(subpacket[1]), - Fingerprint: append([]byte{}, subpacket[2:]...), - } - default: - if isCritical { - err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType))) - return - } - } - return - -Truncated: - err = errors.StructuralError("signature subpacket truncated") - return -} - -// subpacketLengthLength returns the length, in bytes, of an encoded length value. -func subpacketLengthLength(length int) int { - if length < 192 { - return 1 - } - if length < 16320 { - return 2 - } - return 5 -} - -// serializeSubpacketLength marshals the given length into to. -func serializeSubpacketLength(to []byte, length int) int { - // RFC 4880, Section 4.2.2. - if length < 192 { - to[0] = byte(length) - return 1 - } - if length < 16320 { - length -= 192 - to[0] = byte((length >> 8) + 192) - to[1] = byte(length) - return 2 - } - to[0] = 255 - to[1] = byte(length >> 24) - to[2] = byte(length >> 16) - to[3] = byte(length >> 8) - to[4] = byte(length) - return 5 -} - -// subpacketsLength returns the serialized length, in bytes, of the given -// subpackets. -func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - length += subpacketLengthLength(len(subpacket.contents) + 1) - length += 1 // type byte - length += len(subpacket.contents) - } - } - return -} - -// serializeSubpackets marshals the given subpackets into to. -func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - n := serializeSubpacketLength(to, len(subpacket.contents)+1) - to[n] = byte(subpacket.subpacketType) - to = to[1+n:] - n = copy(to, subpacket.contents) - to = to[n:] - } - } - return -} - -// KeyExpired returns whether sig is a self-signature of a key that has -// expired. -func (sig *Signature) KeyExpired(currentTime time.Time) bool { - if sig.KeyLifetimeSecs == nil { - return false - } - expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second) - return currentTime.After(expiry) -} - -// ExpiresBeforeOther checks if other signature has expiration at -// later date than sig. -func (sig *Signature) ExpiresBeforeOther(other *Signature) bool { - if sig.KeyLifetimeSecs == nil { - // This sig never expires, or has infinitely long expiration - // time. - return false - } else if other.KeyLifetimeSecs == nil { - // This sig expires at some non-infinite point, but the other - // sig never expires. - return true - } - - getExpiryDate := func(s *Signature) time.Time { - return s.CreationTime.Add(time.Duration(*s.KeyLifetimeSecs) * time.Second) - } - - return getExpiryDate(other).After(getExpiryDate(sig)) -} - -// buildHashSuffix constructs the HashSuffix member of sig in preparation for signing. -func (sig *Signature) buildHashSuffix() (err error) { - hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true) - - var ok bool - l := 6 + hashedSubpacketsLen - sig.HashSuffix = make([]byte, l+6) - sig.HashSuffix[0] = 4 - sig.HashSuffix[1] = uint8(sig.SigType) - sig.HashSuffix[2] = uint8(sig.PubKeyAlgo) - sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash) - if !ok { - sig.HashSuffix = nil - return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash))) - } - sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8) - sig.HashSuffix[5] = byte(hashedSubpacketsLen) - serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true) - trailer := sig.HashSuffix[l:] - trailer[0] = 4 - trailer[1] = 0xff - trailer[2] = byte(l >> 24) - trailer[3] = byte(l >> 16) - trailer[4] = byte(l >> 8) - trailer[5] = byte(l) - return -} - -func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) { - err = sig.buildHashSuffix() - if err != nil { - return - } - - h.Write(sig.HashSuffix) - digest = h.Sum(nil) - copy(sig.HashTag[:], digest) - return -} - -// Sign signs a message with a private key. The hash, h, must contain -// the hash of the message to be signed and will be mutated by this function. -// On success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) { - signer, hashIsSigner := h.(Signer) - - if !hashIsSigner && (priv == nil || priv.PrivateKey == nil) { - err = errors.InvalidArgumentError("attempting to sign with nil PrivateKey") - return - } - - sig.outSubpackets = sig.buildSubpackets() - digest, err := sig.signPrepareHash(h) - if err != nil { - return - } - - if hashIsSigner { - err = signer.Sign(sig) - return - } - - // Parameter check, if this is wrong we will make a signature but - // not serialize it later. - if sig.PubKeyAlgo != priv.PubKeyAlgo { - err = errors.InvalidArgumentError("signature pub key algo does not match priv key") - return - } - - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest) - sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes)) - case PubKeyAlgoDSA: - dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) - - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8 - if len(digest) > subgroupSize { - digest = digest[:subgroupSize] - } - r, s, err := dsa.Sign(config.Random(), dsaPriv, digest) - if err != nil { - return err - } - sig.DSASigR.bytes = r.Bytes() - sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes)) - sig.DSASigS.bytes = s.Bytes() - sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) - case PubKeyAlgoECDSA: - r, s, err := ecdsa.Sign(config.Random(), priv.PrivateKey.(*ecdsa.PrivateKey), digest) - if err != nil { - return err - } - sig.ECDSASigR = FromBig(r) - sig.ECDSASigS = FromBig(s) - case PubKeyAlgoEdDSA: - r, s, err := priv.PrivateKey.(*EdDSAPrivateKey).Sign(digest) - if err != nil { - return err - } - sig.EdDSASigR = FromBytes(r) - sig.EdDSASigS = FromBytes(s) - default: - err = errors.UnsupportedError("public key algorithm for signing: " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - - return -} - -// SignUserId computes a signature from priv, asserting that pub is a valid -// key for the identity id. On success, the signature is stored in sig. Call -// Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// SignUserIdWithSigner computes a signature from priv, asserting that pub is a -// valid key for the identity id. On success, the signature is stored in sig. -// Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignUserIdWithSigner(id string, pub *PublicKey, s Signer, config *Config) error { - updateUserIdSignatureHash(id, pub, s) - - return sig.Sign(s, nil, config) -} - -// SignKey computes a signature from priv, asserting that pub is a subkey. On -// success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// SignKeyWithSigner computes a signature using s, asserting that -// signeePubKey is a subkey. On success, the signature is stored in sig. Call -// Serialize to write it out. If config is nil, sensible defaults will be used. -func (sig *Signature) SignKeyWithSigner(signeePubKey *PublicKey, signerPubKey *PublicKey, s Signer, config *Config) error { - updateKeySignatureHash(signerPubKey, signeePubKey, s) - - return sig.Sign(s, nil, config) -} - -// CrossSignKey creates PrimaryKeyBinding signature in sig.EmbeddedSignature by -// signing `primary` key's hash using `priv` subkey private key. Primary public -// key is the `signee` here. -func (sig *Signature) CrossSignKey(primary *PublicKey, priv *PrivateKey, config *Config) error { - if len(sig.outSubpackets) > 0 { - return fmt.Errorf("outSubpackets already exists, looks like CrossSignKey was called after Sign") - } - - sig.EmbeddedSignature = &Signature{ - CreationTime: sig.CreationTime, - SigType: SigTypePrimaryKeyBinding, - PubKeyAlgo: priv.PubKeyAlgo, - Hash: sig.Hash, - } - - h, err := keySignatureHash(primary, &priv.PublicKey, sig.Hash) - if err != nil { - return err - } - return sig.EmbeddedSignature.Sign(h, priv, config) -} - -// Serialize marshals sig to w. Sign, SignUserId or SignKey must have been -// called first. -func (sig *Signature) Serialize(w io.Writer) (err error) { - if len(sig.outSubpackets) == 0 { - sig.outSubpackets = sig.rawSubpackets - } - if sig.RSASignature.bytes == nil && - sig.DSASigR.bytes == nil && - sig.ECDSASigR.bytes == nil && - sig.EdDSASigR.bytes == nil { - return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") - } - - sigLength := 0 - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sigLength = 2 + len(sig.RSASignature.bytes) - case PubKeyAlgoDSA: - sigLength = 2 + len(sig.DSASigR.bytes) - sigLength += 2 + len(sig.DSASigS.bytes) - case PubKeyAlgoEdDSA: - sigLength = 2 + len(sig.EdDSASigR.bytes) - sigLength += 2 + len(sig.EdDSASigS.bytes) - case PubKeyAlgoECDSA: - sigLength = 2 + len(sig.ECDSASigR.bytes) - sigLength += 2 + len(sig.ECDSASigS.bytes) - default: - panic("impossible") - } - - unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false) - length := len(sig.HashSuffix) - 6 /* trailer not included */ + - 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen + - 2 /* hash tag */ + sigLength - err = serializeHeader(w, packetTypeSignature, length) - if err != nil { - return - } - - _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6]) - if err != nil { - return - } - - unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen) - unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8) - unhashedSubpackets[1] = byte(unhashedSubpacketsLen) - serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false) - - _, err = w.Write(unhashedSubpackets) - if err != nil { - return - } - _, err = w.Write(sig.HashTag[:]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - err = writeMPIs(w, sig.RSASignature) - case PubKeyAlgoDSA: - err = writeMPIs(w, sig.DSASigR, sig.DSASigS) - case PubKeyAlgoEdDSA: - err = writeMPIs(w, sig.EdDSASigR, sig.EdDSASigS) - case PubKeyAlgoECDSA: - err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS) - default: - panic("impossible") - } - return -} - -// outputSubpacket represents a subpacket to be marshaled. -type outputSubpacket struct { - hashed bool // true if this subpacket is in the hashed area. - subpacketType signatureSubpacketType - isCritical bool - contents []byte -} - -func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { - creationTime := make([]byte, 4) - binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix())) - subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime}) - - if sig.IssuerKeyId != nil { - keyId := make([]byte, 8) - binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId) - subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId}) - } - - if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 { - sigLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime}) - } - - // Key flags may only appear in self-signatures or certification signatures. - - if sig.FlagsValid { - subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{sig.GetKeyFlags().BitField}}) - } - - // The following subpackets may only appear in self-signatures - - if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 { - keyLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime}) - } - - if sig.IsPrimaryId != nil && *sig.IsPrimaryId { - subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}}) - } - - if len(sig.PreferredSymmetric) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric}) - } - - if len(sig.PreferredHash) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash}) - } - - if len(sig.PreferredCompression) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression}) - } - - if sig.EmbeddedSignature != nil { - buf := bytes.NewBuffer(nil) - if err := sig.EmbeddedSignature.Serialize(buf); err == nil { - byteContent := buf.Bytes()[2:] // skip 2-byte length header - subpackets = append(subpackets, outputSubpacket{false, embeddedSignatureSubpacket, true, byteContent}) - } - } - - return -} - -func (sig *Signature) GetKeyFlags() (ret KeyFlagBits) { - if !sig.FlagsValid { - return ret - } - - ret.Valid = true - if sig.FlagCertify { - ret.BitField |= KeyFlagCertify - } - if sig.FlagSign { - ret.BitField |= KeyFlagSign - } - if sig.FlagEncryptCommunications { - ret.BitField |= KeyFlagEncryptCommunications - } - if sig.FlagEncryptStorage { - ret.BitField |= KeyFlagEncryptStorage - } - return ret -} - -func (f *KeyFlagBits) HasFlagCertify() bool { - return f.BitField&KeyFlagCertify != 0 -} - -func (f *KeyFlagBits) HasFlagSign() bool { - return f.BitField&KeyFlagSign != 0 -} - -func (f *KeyFlagBits) HasFlagEncryptCommunications() bool { - return f.BitField&KeyFlagEncryptCommunications != 0 -} - -func (f *KeyFlagBits) HasFlagEncryptStorage() bool { - return f.BitField&KeyFlagEncryptStorage != 0 -} - -func (f *KeyFlagBits) Merge(other KeyFlagBits) { - if other.Valid { - f.Valid = true - f.BitField |= other.BitField - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go deleted file mode 100644 index dfca651b..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2013 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 packet - -import ( - "crypto" - "encoding/binary" - "fmt" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// SignatureV3 represents older version 3 signatures. These signatures are less secure -// than version 4 and should not be used to create new signatures. They are included -// here for backwards compatibility to read and validate with older key material. -// See RFC 4880, section 5.2.2. -type SignatureV3 struct { - SigType SignatureType - CreationTime time.Time - IssuerKeyId uint64 - PubKeyAlgo PublicKeyAlgorithm - Hash crypto.Hash - HashTag [2]byte - - RSASignature parsedMPI - DSASigR, DSASigS parsedMPI -} - -func (sig *SignatureV3) parse(r io.Reader) (err error) { - // RFC 4880, section 5.2.2 - var buf [8]byte - if _, err = readFull(r, buf[:1]); err != nil { - return - } - if buf[0] < 2 || buf[0] > 3 { - err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) - return - } - if _, err = readFull(r, buf[:1]); err != nil { - return - } - if buf[0] != 5 { - err = errors.UnsupportedError( - "invalid hashed material length " + strconv.Itoa(int(buf[0]))) - return - } - - // Read hashed material: signature type + creation time - if _, err = readFull(r, buf[:5]); err != nil { - return - } - sig.SigType = SignatureType(buf[0]) - t := binary.BigEndian.Uint32(buf[1:5]) - sig.CreationTime = time.Unix(int64(t), 0) - - // Eight-octet Key ID of signer. - if _, err = readFull(r, buf[:8]); err != nil { - return - } - sig.IssuerKeyId = binary.BigEndian.Uint64(buf[:]) - - // Public-key and hash algorithm - if _, err = readFull(r, buf[:2]); err != nil { - return - } - sig.PubKeyAlgo = PublicKeyAlgorithm(buf[0]) - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA: - default: - err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) - return - } - var ok bool - if sig.Hash, ok = s2k.HashIdToHash(buf[1]); !ok { - return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) - } - - // Two-octet field holding left 16 bits of signed hash value. - if _, err = readFull(r, sig.HashTag[:2]); err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) - case PubKeyAlgoDSA: - if sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r); err != nil { - return - } - sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) - default: - panic("unreachable") - } - return -} - -// Serialize marshals sig to w. Sign, SignUserId or SignKey must have been -// called first. -func (sig *SignatureV3) Serialize(w io.Writer) (err error) { - buf := make([]byte, 8) - - // Write the sig type and creation time - buf[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(buf[1:5], uint32(sig.CreationTime.Unix())) - if _, err = w.Write(buf[:5]); err != nil { - return - } - - // Write the issuer long key ID - binary.BigEndian.PutUint64(buf[:8], sig.IssuerKeyId) - if _, err = w.Write(buf[:8]); err != nil { - return - } - - // Write public key algorithm, hash ID, and hash value - buf[0] = byte(sig.PubKeyAlgo) - hashId, ok := s2k.HashToHashId(sig.Hash) - if !ok { - return errors.UnsupportedError(fmt.Sprintf("hash function %v", sig.Hash)) - } - buf[1] = hashId - copy(buf[2:4], sig.HashTag[:]) - if _, err = w.Write(buf[:4]); err != nil { - return - } - - if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil { - return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - err = writeMPIs(w, sig.RSASignature) - case PubKeyAlgoDSA: - err = writeMPIs(w, sig.DSASigR, sig.DSASigS) - default: - panic("impossible") - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go deleted file mode 100644 index b92c1d77..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto/cipher" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// This is the largest session key that we'll support. Since no 512-bit cipher -// has even been seriously used, this is comfortably large. -const maxSessionKeySizeInBytes = 64 - -// SymmetricKeyEncrypted represents a passphrase protected session key. See RFC -// 4880, section 5.3. -type SymmetricKeyEncrypted struct { - CipherFunc CipherFunction - s2k func(out, in []byte) - encryptedKey []byte -} - -const symmetricKeyEncryptedVersion = 4 - -func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error { - // RFC 4880, section 5.3. - var buf [2]byte - if _, err := readFull(r, buf[:]); err != nil { - return err - } - if buf[0] != symmetricKeyEncryptedVersion { - return errors.UnsupportedError("SymmetricKeyEncrypted version") - } - ske.CipherFunc = CipherFunction(buf[1]) - - if ske.CipherFunc.KeySize() == 0 { - return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1]))) - } - - var err error - ske.s2k, err = s2k.Parse(r) - if err != nil { - return err - } - if ske.s2k == nil { - return errors.UnsupportedError("can't use dummy S2K for symmetric key encryption") - } - - encryptedKey := make([]byte, maxSessionKeySizeInBytes) - // The session key may follow. We just have to try and read to find - // out. If it exists then we limit it to maxSessionKeySizeInBytes. - n, err := readFull(r, encryptedKey) - if err != nil && err != io.ErrUnexpectedEOF { - return err - } - - if n != 0 { - if n == maxSessionKeySizeInBytes { - return errors.UnsupportedError("oversized encrypted session key") - } - ske.encryptedKey = encryptedKey[:n] - } - - return nil -} - -// Decrypt attempts to decrypt an encrypted session key and returns the key and -// the cipher to use when decrypting a subsequent Symmetrically Encrypted Data -// packet. -func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) { - key := make([]byte, ske.CipherFunc.KeySize()) - ske.s2k(key, passphrase) - - if len(ske.encryptedKey) == 0 { - return key, ske.CipherFunc, nil - } - - // the IV is all zeros - iv := make([]byte, ske.CipherFunc.blockSize()) - c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv) - plaintextKey := make([]byte, len(ske.encryptedKey)) - c.XORKeyStream(plaintextKey, ske.encryptedKey) - cipherFunc := CipherFunction(plaintextKey[0]) - if cipherFunc.blockSize() == 0 { - return nil, ske.CipherFunc, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) - } - plaintextKey = plaintextKey[1:] - if l, cipherKeySize := len(plaintextKey), cipherFunc.KeySize(); l != cipherFunc.KeySize() { - return nil, cipherFunc, errors.StructuralError("length of decrypted key (" + strconv.Itoa(l) + ") " + - "not equal to cipher keysize (" + strconv.Itoa(cipherKeySize) + ")") - } - return plaintextKey, cipherFunc, nil -} - -// SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The -// packet contains a random session key, encrypted by a key derived from the -// given passphrase. The session key is returned and must be passed to -// SerializeSymmetricallyEncrypted. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) { - cipherFunc := config.Cipher() - keySize := cipherFunc.KeySize() - if keySize == 0 { - return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) - } - - s2kBuf := new(bytes.Buffer) - keyEncryptingKey := make([]byte, keySize) - // s2k.Serialize salts and stretches the passphrase, and writes the - // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf. - err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()}) - if err != nil { - return - } - s2kBytes := s2kBuf.Bytes() - - packetLength := 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize - err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength) - if err != nil { - return - } - - var buf [2]byte - buf[0] = symmetricKeyEncryptedVersion - buf[1] = byte(cipherFunc) - _, err = w.Write(buf[:]) - if err != nil { - return - } - _, err = w.Write(s2kBytes) - if err != nil { - return - } - - sessionKey := make([]byte, keySize) - _, err = io.ReadFull(config.Random(), sessionKey) - if err != nil { - return - } - iv := make([]byte, cipherFunc.blockSize()) - c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv) - encryptedCipherAndKey := make([]byte, keySize+1) - c.XORKeyStream(encryptedCipherAndKey, buf[1:]) - c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey) - _, err = w.Write(encryptedCipherAndKey) - if err != nil { - return - } - - key = sessionKey - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go deleted file mode 100644 index fd4f8f01..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto/cipher" - "crypto/sha1" - "crypto/subtle" - "hash" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// SymmetricallyEncrypted represents a symmetrically encrypted byte string. The -// encrypted contents will consist of more OpenPGP packets. See RFC 4880, -// sections 5.7 and 5.13. -type SymmetricallyEncrypted struct { - MDC bool // true iff this is a type 18 packet and thus has an embedded MAC. - contents io.Reader - prefix []byte -} - -const symmetricallyEncryptedVersion = 1 - -func (se *SymmetricallyEncrypted) parse(r io.Reader) error { - if se.MDC { - // See RFC 4880, section 5.13. - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - if buf[0] != symmetricallyEncryptedVersion { - return errors.UnsupportedError("unknown SymmetricallyEncrypted version") - } - } - se.contents = r - return nil -} - -// Decrypt returns a ReadCloser, from which the decrypted contents of the -// packet can be read. An incorrect key can, with high probability, be detected -// immediately and this will result in a KeyIncorrect error being returned. -func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) { - keySize := c.KeySize() - if keySize == 0 { - return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c))) - } - if len(key) != keySize { - return nil, errors.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length") - } - - if se.prefix == nil { - se.prefix = make([]byte, c.blockSize()+2) - _, err := readFull(se.contents, se.prefix) - if err != nil { - return nil, err - } - } else if len(se.prefix) != c.blockSize()+2 { - return nil, errors.InvalidArgumentError("can't try ciphers with different block lengths") - } - - ocfbResync := OCFBResync - if se.MDC { - // MDC packets use a different form of OCFB mode. - ocfbResync = OCFBNoResync - } - - s := NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync) - if s == nil { - return nil, errors.ErrKeyIncorrect - } - - plaintext := cipher.StreamReader{S: s, R: se.contents} - - if se.MDC { - // MDC packets have an embedded hash that we need to check. - h := sha1.New() - h.Write(se.prefix) - return &seMDCReader{in: plaintext, h: h}, nil - } - - // Otherwise, we just need to wrap plaintext so that it's a valid ReadCloser. - return seReader{plaintext}, nil -} - -// seReader wraps an io.Reader with a no-op Close method. -type seReader struct { - in io.Reader -} - -func (ser seReader) Read(buf []byte) (int, error) { - return ser.in.Read(buf) -} - -func (ser seReader) Close() error { - return nil -} - -const mdcTrailerSize = 1 /* tag byte */ + 1 /* length byte */ + sha1.Size - -// An seMDCReader wraps an io.Reader, maintains a running hash and keeps hold -// of the most recent 22 bytes (mdcTrailerSize). Upon EOF, those bytes form an -// MDC packet containing a hash of the previous contents which is checked -// against the running hash. See RFC 4880, section 5.13. -type seMDCReader struct { - in io.Reader - h hash.Hash - trailer [mdcTrailerSize]byte - scratch [mdcTrailerSize]byte - trailerUsed int - error bool - eof bool -} - -func (ser *seMDCReader) Read(buf []byte) (n int, err error) { - if ser.error { - err = io.ErrUnexpectedEOF - return - } - if ser.eof { - err = io.EOF - return - } - - // If we haven't yet filled the trailer buffer then we must do that - // first. - for ser.trailerUsed < mdcTrailerSize { - n, err = ser.in.Read(ser.trailer[ser.trailerUsed:]) - ser.trailerUsed += n - if err == io.EOF { - if ser.trailerUsed != mdcTrailerSize { - n = 0 - err = io.ErrUnexpectedEOF - ser.error = true - return - } - ser.eof = true - n = 0 - return - } - - if err != nil { - n = 0 - return - } - } - - // If it's a short read then we read into a temporary buffer and shift - // the data into the caller's buffer. - if len(buf) <= mdcTrailerSize { - n, err = readFull(ser.in, ser.scratch[:len(buf)]) - copy(buf, ser.trailer[:n]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], ser.trailer[n:]) - copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:]) - if n < len(buf) { - ser.eof = true - err = io.EOF - } - return - } - - n, err = ser.in.Read(buf[mdcTrailerSize:]) - copy(buf, ser.trailer[:]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], buf[n:]) - - if err == io.EOF { - ser.eof = true - } - return -} - -// This is a new-format packet tag byte for a type 19 (MDC) packet. -const mdcPacketTagByte = byte(0x80) | 0x40 | 19 - -func (ser *seMDCReader) Close() error { - if ser.error { - return errors.SignatureError("error during reading") - } - - for !ser.eof { - // We haven't seen EOF so we need to read to the end - var buf [1024]byte - _, err := ser.Read(buf[:]) - if err == io.EOF { - break - } - if err != nil { - return errors.SignatureError("error during reading") - } - } - - if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size { - return errors.SignatureError("MDC packet not found") - } - ser.h.Write(ser.trailer[:2]) - - final := ser.h.Sum(nil) - if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 { - return errors.SignatureError("hash mismatch") - } - return nil -} - -// An seMDCWriter writes through to an io.WriteCloser while maintains a running -// hash of the data written. On close, it emits an MDC packet containing the -// running hash. -type seMDCWriter struct { - w io.WriteCloser - h hash.Hash -} - -func (w *seMDCWriter) Write(buf []byte) (n int, err error) { - w.h.Write(buf) - return w.w.Write(buf) -} - -func (w *seMDCWriter) Close() (err error) { - var buf [mdcTrailerSize]byte - - buf[0] = mdcPacketTagByte - buf[1] = sha1.Size - w.h.Write(buf[:2]) - digest := w.h.Sum(nil) - copy(buf[2:], digest) - - _, err = w.w.Write(buf[:]) - if err != nil { - return - } - return w.w.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -// SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet -// to w and returns a WriteCloser to which the to-be-encrypted packets can be -// written. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte, config *Config) (contents io.WriteCloser, err error) { - if c.KeySize() != len(key) { - return nil, errors.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length") - } - writeCloser := noOpCloser{w} - ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC) - if err != nil { - return - } - - _, err = ciphertext.Write([]byte{symmetricallyEncryptedVersion}) - if err != nil { - return - } - - block := c.new(key) - blockSize := block.BlockSize() - iv := make([]byte, blockSize) - _, err = config.Random().Read(iv) - if err != nil { - return - } - s, prefix := NewOCFBEncrypter(block, iv, OCFBNoResync) - _, err = ciphertext.Write(prefix) - if err != nil { - return - } - plaintext := cipher.StreamWriter{S: s, W: ciphertext} - - h := sha1.New() - h.Write(iv) - h.Write(iv[blockSize-2:]) - contents = &seMDCWriter{w: plaintext, h: h} - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go deleted file mode 100644 index 96a2b382..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 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 packet - -import ( - "bytes" - "image" - "image/jpeg" - "io" - "io/ioutil" -) - -const UserAttrImageSubpacket = 1 - -// UserAttribute is capable of storing other types of data about a user -// beyond name, email and a text comment. In practice, user attributes are typically used -// to store a signed thumbnail photo JPEG image of the user. -// See RFC 4880, section 5.12. -type UserAttribute struct { - Contents []*OpaqueSubpacket -} - -// NewUserAttributePhoto creates a user attribute packet -// containing the given images. -func NewUserAttributePhoto(photos ...image.Image) (uat *UserAttribute, err error) { - uat = new(UserAttribute) - for _, photo := range photos { - var buf bytes.Buffer - // RFC 4880, Section 5.12.1. - data := []byte{ - 0x10, 0x00, // Little-endian image header length (16 bytes) - 0x01, // Image header version 1 - 0x01, // JPEG - 0, 0, 0, 0, // 12 reserved octets, must be all zero. - 0, 0, 0, 0, - 0, 0, 0, 0} - if _, err = buf.Write(data); err != nil { - return - } - if err = jpeg.Encode(&buf, photo, nil); err != nil { - return - } - uat.Contents = append(uat.Contents, &OpaqueSubpacket{ - SubType: UserAttrImageSubpacket, - Contents: buf.Bytes()}) - } - return -} - -// NewUserAttribute creates a new user attribute packet containing the given subpackets. -func NewUserAttribute(contents ...*OpaqueSubpacket) *UserAttribute { - return &UserAttribute{Contents: contents} -} - -func (uat *UserAttribute) parse(r io.Reader) (err error) { - // RFC 4880, section 5.13 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uat.Contents, err = OpaqueSubpackets(b) - return -} - -// Serialize marshals the user attribute to w in the form of an OpenPGP packet, including -// header. -func (uat *UserAttribute) Serialize(w io.Writer) (err error) { - var buf bytes.Buffer - for _, sp := range uat.Contents { - sp.Serialize(&buf) - } - if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { - return err - } - _, err = w.Write(buf.Bytes()) - return -} - -// ImageData returns zero or more byte slices, each containing -// JPEG File Interchange Format (JFIF), for each photo in the -// the user attribute packet. -func (uat *UserAttribute) ImageData() (imageData [][]byte) { - for _, sp := range uat.Contents { - if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { - imageData = append(imageData, sp.Contents[16:]) - } - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go deleted file mode 100644 index d6bea7d4..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "io" - "io/ioutil" - "strings" -) - -// UserId contains text that is intended to represent the name and email -// address of the key holder. See RFC 4880, section 5.11. By convention, this -// takes the form "Full Name (Comment) " -type UserId struct { - Id string // By convention, this takes the form "Full Name (Comment) " which is split out in the fields below. - - Name, Comment, Email string -} - -func hasInvalidCharacters(s string) bool { - for _, c := range s { - switch c { - case '(', ')', '<', '>', 0: - return true - } - } - return false -} - -// NewUserId returns a UserId or nil if any of the arguments contain invalid -// characters. The invalid characters are '\x00', '(', ')', '<' and '>' -func NewUserId(name, comment, email string) *UserId { - // RFC 4880 doesn't deal with the structure of userid strings; the - // name, comment and email form is just a convention. However, there's - // no convention about escaping the metacharacters and GPG just refuses - // to create user ids where, say, the name contains a '('. We mirror - // this behaviour. - - if hasInvalidCharacters(name) || hasInvalidCharacters(comment) || hasInvalidCharacters(email) { - return nil - } - - uid := new(UserId) - uid.Name, uid.Comment, uid.Email = name, comment, email - uid.Id = name - if len(comment) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "(" - uid.Id += comment - uid.Id += ")" - } - if len(email) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "<" - uid.Id += email - uid.Id += ">" - } - return uid -} - -func (uid *UserId) parse(r io.Reader) (err error) { - // RFC 4880, section 5.11 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uid.Id = string(b) - uid.Name, uid.Comment, uid.Email = parseUserId(uid.Id) - return -} - -// Serialize marshals uid to w in the form of an OpenPGP packet, including -// header. -func (uid *UserId) Serialize(w io.Writer) error { - err := serializeHeader(w, packetTypeUserId, len(uid.Id)) - if err != nil { - return err - } - _, err = w.Write([]byte(uid.Id)) - return err -} - -// parseUserId extracts the name, comment and email from a user id string that -// is formatted as "Full Name (Comment) ". -func parseUserId(id string) (name, comment, email string) { - var n, c, e struct { - start, end int - } - var state int - - for offset, rune := range id { - switch state { - case 0: - // Entering name - n.start = offset - state = 1 - fallthrough - case 1: - // In name - if rune == '(' { - state = 2 - n.end = offset - } else if rune == '<' { - state = 5 - n.end = offset - } - case 2: - // Entering comment - c.start = offset - state = 3 - fallthrough - case 3: - // In comment - if rune == ')' { - state = 4 - c.end = offset - } - case 4: - // Between comment and email - if rune == '<' { - state = 5 - } - case 5: - // Entering email - e.start = offset - state = 6 - fallthrough - case 6: - // In email - if rune == '>' { - state = 7 - e.end = offset - } - default: - // After email - } - } - switch state { - case 1: - // ended in the name - n.end = len(id) - case 3: - // ended in comment - c.end = len(id) - case 6: - // ended in email - e.end = len(id) - } - - name = strings.TrimSpace(id[n.start:n.end]) - comment = strings.TrimSpace(id[c.start:c.end]) - email = strings.TrimSpace(id[e.start:e.end]) - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/patch.sh b/vendor/github.com/keybase/go-crypto/openpgp/patch.sh deleted file mode 100644 index 23cacc83..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/patch.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -patch < sig-v3.patch -patch < s2k-gnu-dummy.patch -find . -type f -name '*.go' -exec sed -i'' -e 's/golang.org\/x\/crypto\/openpgp/github.com\/keybase\/go-crypto\/openpgp/' {} \; -find . -type f -name '*.go-e' -exec rm {} \; -go test ./... diff --git a/vendor/github.com/keybase/go-crypto/openpgp/read.go b/vendor/github.com/keybase/go-crypto/openpgp/read.go deleted file mode 100644 index 790630e5..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/read.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright 2011 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 openpgp implements high level operations on OpenPGP messages. -package openpgp // import "github.com/keybase/go-crypto/openpgp" - -import ( - "crypto" - "crypto/hmac" - _ "crypto/sha256" - "hash" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// SignatureType is the armor type for a PGP signature. -var SignatureType = "PGP SIGNATURE" - -// readArmored reads an armored block with the given type. -func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { - block, err := armor.Decode(r) - if err != nil { - return - } - - if block.Type != expectedType { - return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) - } - - return block.Body, nil -} - -// MessageDetails contains the result of parsing an OpenPGP encrypted and/or -// signed message. -type MessageDetails struct { - IsEncrypted bool // true if the message was encrypted. - EncryptedToKeyIds []uint64 // the list of recipient key ids. - IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. - DecryptedWith Key // the private key used to decrypt the message, if any. - IsSigned bool // true if the message is signed. - SignedByKeyId uint64 // the key id of the signer, if any. - SignedBy *Key // the key of the signer, if available. - LiteralData *packet.LiteralData // the metadata of the contents - UnverifiedBody io.Reader // the contents of the message. - - // If IsSigned is true and SignedBy is non-zero then the signature will - // be verified as UnverifiedBody is read. The signature cannot be - // checked until the whole of UnverifiedBody is read so UnverifiedBody - // must be consumed until EOF before the data can trusted. Even if a - // message isn't signed (or the signer is unknown) the data may contain - // an authentication code that is only checked once UnverifiedBody has - // been consumed. Once EOF has been seen, the following fields are - // valid. (An authentication code failure is reported as a - // SignatureError error when reading from UnverifiedBody.) - SignatureError error // nil if the signature is good. - Signature *packet.Signature // the signature packet itself, if v4 (default) - SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature - - // Does the Message include multiple signatures? Also called "nested signatures". - MultiSig bool - - decrypted io.ReadCloser -} - -// A PromptFunction is used as a callback by functions that may need to decrypt -// a private key, or prompt for a passphrase. It is called with a list of -// acceptable, encrypted private keys and a boolean that indicates whether a -// passphrase is usable. It should either decrypt a private key or return a -// passphrase to try. If the decrypted private key or given passphrase isn't -// correct, the function will be called again, forever. Any error returned will -// be passed up. -type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) - -// A keyEnvelopePair is used to store a private key with the envelope that -// contains a symmetric key, encrypted with that key. -type keyEnvelopePair struct { - key Key - encryptedKey *packet.EncryptedKey -} - -// ReadMessage parses an OpenPGP message that may be signed and/or encrypted. -// The given KeyRing should contain both public keys (for signature -// verification) and, possibly encrypted, private keys for decrypting. -// If config is nil, sensible defaults will be used. -func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { - var p packet.Packet - - var symKeys []*packet.SymmetricKeyEncrypted - var pubKeys []keyEnvelopePair - var se *packet.SymmetricallyEncrypted - - packets := packet.NewReader(r) - md = new(MessageDetails) - md.IsEncrypted = true - - // The message, if encrypted, starts with a number of packets - // containing an encrypted decryption key. The decryption key is either - // encrypted to a public key, or with a passphrase. This loop - // collects these packets. -ParsePackets: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.SymmetricKeyEncrypted: - // This packet contains the decryption key encrypted with a passphrase. - md.IsSymmetricallyEncrypted = true - symKeys = append(symKeys, p) - case *packet.EncryptedKey: - // This packet contains the decryption key encrypted to a public key. - md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) - switch p.Algo { - case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH: - break - default: - continue - } - var keys []Key - if p.KeyId == 0 { - keys = keyring.DecryptionKeys() - } else { - keys = keyring.KeysById(p.KeyId, nil) - } - for _, k := range keys { - pubKeys = append(pubKeys, keyEnvelopePair{k, p}) - } - case *packet.SymmetricallyEncrypted: - se = p - break ParsePackets - case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: - // This message isn't encrypted. - if len(symKeys) != 0 || len(pubKeys) != 0 { - return nil, errors.StructuralError("key material not followed by encrypted message") - } - packets.Unread(p) - return readSignedMessage(packets, nil, keyring) - } - } - - var candidates []Key - var decrypted io.ReadCloser - - // Now that we have the list of encrypted keys we need to decrypt at - // least one of them or, if we cannot, we need to call the prompt - // function so that it can decrypt a key or give us a passphrase. -FindKey: - for { - // See if any of the keys already have a private key available - candidates = candidates[:0] - candidateFingerprints := make(map[string]bool) - - for _, pk := range pubKeys { - if pk.key.PrivateKey == nil { - continue - } - if !pk.key.PrivateKey.Encrypted { - if len(pk.encryptedKey.Key) == 0 { - pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) - } - if len(pk.encryptedKey.Key) == 0 { - continue - } - decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) - if err != nil && err != errors.ErrKeyIncorrect { - return nil, err - } - if decrypted != nil { - md.DecryptedWith = pk.key - break FindKey - } - } else { - fpr := string(pk.key.PublicKey.Fingerprint[:]) - if v := candidateFingerprints[fpr]; v { - continue - } - candidates = append(candidates, pk.key) - candidateFingerprints[fpr] = true - } - } - - if len(candidates) == 0 && len(symKeys) == 0 { - return nil, errors.ErrKeyIncorrect - } - - if prompt == nil { - return nil, errors.ErrKeyIncorrect - } - - passphrase, err := prompt(candidates, len(symKeys) != 0) - if err != nil { - return nil, err - } - - // Try the symmetric passphrase first - if len(symKeys) != 0 && passphrase != nil { - for _, s := range symKeys { - key, cipherFunc, err := s.Decrypt(passphrase) - if err == nil { - decrypted, err = se.Decrypt(cipherFunc, key) - if err != nil && err != errors.ErrKeyIncorrect { - return nil, err - } - if decrypted != nil { - break FindKey - } - } - - } - } - } - - md.decrypted = decrypted - if err := packets.Push(decrypted); err != nil { - return nil, err - } - return readSignedMessage(packets, md, keyring) -} - -// readSignedMessage reads a possibly signed message if mdin is non-zero then -// that structure is updated and returned. Otherwise a fresh MessageDetails is -// used. -func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) { - if mdin == nil { - mdin = new(MessageDetails) - } - md = mdin - - var p packet.Packet - var h hash.Hash - var wrappedHash hash.Hash -FindLiteralData: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.Compressed: - if err := packets.Push(p.Body); err != nil { - return nil, err - } - case *packet.OnePassSignature: - if md.IsSigned { - // If IsSigned is set, it means we have multiple - // OnePassSignature packets. - md.MultiSig = true - if md.SignedBy != nil { - // We've already found the signature we were looking - // for, made by key that we had in keyring and can - // check signature against. Continue with that instead - // of trying to find another. - continue FindLiteralData - } - } - - h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) - if err != nil { - md = nil - return - } - - md.IsSigned = true - md.SignedByKeyId = p.KeyId - keys := keyring.KeysByIdUsage(p.KeyId, nil, packet.KeyFlagSign) - if len(keys) > 0 { - md.SignedBy = &keys[0] - } - case *packet.LiteralData: - md.LiteralData = p - break FindLiteralData - } - } - - if md.SignedBy != nil { - md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md} - } else if md.decrypted != nil { - md.UnverifiedBody = checkReader{md} - } else { - md.UnverifiedBody = md.LiteralData.Body - } - - return md, nil -} - -// hashForSignature returns a pair of hashes that can be used to verify a -// signature. The signature may specify that the contents of the signed message -// should be preprocessed (i.e. to normalize line endings). Thus this function -// returns two hashes. The second should be used to hash the message itself and -// performs any needed preprocessing. -func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { - if !hashId.Available() { - return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) - } - h := hashId.New() - - switch sigType { - case packet.SigTypeBinary: - return h, h, nil - case packet.SigTypeText: - return h, NewCanonicalTextHash(h), nil - } - - return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) -} - -// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF -// it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger -// MDC checks. -type checkReader struct { - md *MessageDetails -} - -func (cr checkReader) Read(buf []byte) (n int, err error) { - n, err = cr.md.LiteralData.Body.Read(buf) - if err == io.EOF { - mdcErr := cr.md.decrypted.Close() - if mdcErr != nil { - err = mdcErr - } - } - return -} - -// signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes -// the data as it is read. When it sees an EOF from the underlying io.Reader -// it parses and checks a trailing Signature packet and triggers any MDC checks. -type signatureCheckReader struct { - packets *packet.Reader - h, wrappedHash hash.Hash - md *MessageDetails -} - -func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { - n, err = scr.md.LiteralData.Body.Read(buf) - scr.wrappedHash.Write(buf[:n]) - if err == io.EOF { - for { - var p packet.Packet - p, scr.md.SignatureError = scr.packets.Next() - if scr.md.SignatureError != nil { - if scr.md.MultiSig { - // If we are in MultiSig, we might have found other - // signature that cannot be verified using our key. - // Clear Signature field so it's clear for consumers - // that this message failed to verify. - scr.md.Signature = nil - } - return - } - - var ok bool - if scr.md.Signature, ok = p.(*packet.Signature); ok { - var err error - if keyID := scr.md.Signature.IssuerKeyId; keyID != nil { - if *keyID != scr.md.SignedBy.PublicKey.KeyId { - if scr.md.MultiSig { - continue // try again to find a sig we can verify - } - err = errors.StructuralError("bad key id") - } - } - if fingerprint := scr.md.Signature.IssuerFingerprint; fingerprint != nil { - if !hmac.Equal(fingerprint, scr.md.SignedBy.PublicKey.Fingerprint[:]) { - if scr.md.MultiSig { - continue // try again to find a sig we can verify - } - err = errors.StructuralError("bad key fingerprint") - } - } - if err == nil { - err = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) - } - scr.md.SignatureError = err - } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { - scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) - } else { - scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") - return - } - - // Parse only one packet by default, unless message is MultiSig. Then - // we ask for more packets after discovering non-matching signature, - // until we find one that we can verify. - break - } - - // The SymmetricallyEncrypted packet, if any, might have an - // unsigned hash of its own. In order to check this we need to - // close that Reader. - if scr.md.decrypted != nil { - mdcErr := scr.md.decrypted.Close() - if mdcErr != nil { - err = mdcErr - } - } - } - return -} - -// CheckDetachedSignature takes a signed file and a detached signature and -// returns the signer if the signature is valid. If the signer isn't known, -// ErrUnknownIssuer is returned. -func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { - signer, _, err = checkDetachedSignature(keyring, signed, signature) - return signer, err -} - -func checkDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) { - var issuerKeyId uint64 - var issuerFingerprint []byte - var hashFunc crypto.Hash - var sigType packet.SignatureType - var keys []Key - var p packet.Packet - - packets := packet.NewReader(signature) - for { - p, err = packets.Next() - if err == io.EOF { - return nil, nil, errors.ErrUnknownIssuer - } - if err != nil { - return nil, nil, err - } - - switch sig := p.(type) { - case *packet.Signature: - if sig.IssuerKeyId == nil { - return nil, nil, errors.StructuralError("signature doesn't have an issuer") - } - issuerKeyId = *sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - issuerFingerprint = sig.IssuerFingerprint - case *packet.SignatureV3: - issuerKeyId = sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - default: - return nil, nil, errors.StructuralError("non signature packet found") - } - - keys = keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign) - if len(keys) > 0 { - break - } - } - - if len(keys) == 0 { - panic("unreachable") - } - - h, wrappedHash, err := hashForSignature(hashFunc, sigType) - if err != nil { - return nil, nil, err - } - - if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { - return nil, nil, err - } - - for _, key := range keys { - switch sig := p.(type) { - case *packet.Signature: - err = key.PublicKey.VerifySignature(h, sig) - case *packet.SignatureV3: - err = key.PublicKey.VerifySignatureV3(h, sig) - default: - panic("unreachable") - } - - if err == nil { - return key.Entity, &issuerKeyId, nil - } - } - - return nil, nil, err -} - -// CheckArmoredDetachedSignature performs the same actions as -// CheckDetachedSignature but expects the signature to be armored. -func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { - signer, _, err = checkArmoredDetachedSignature(keyring, signed, signature) - return signer, err -} - -func checkArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) { - body, err := readArmored(signature, SignatureType) - if err != nil { - return - } - return checkDetachedSignature(keyring, signed, body) -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/s2k/s2k.go b/vendor/github.com/keybase/go-crypto/openpgp/s2k/s2k.go deleted file mode 100644 index 01bb6785..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/s2k/s2k.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2011 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 s2k implements the various OpenPGP string-to-key transforms as -// specified in RFC 4800 section 3.7.1. -package s2k // import "github.com/keybase/go-crypto/openpgp/s2k" - -import ( - "crypto" - "hash" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// Config collects configuration parameters for s2k key-stretching -// transformatioms. A nil *Config is valid and results in all default -// values. Currently, Config is used only by the Serialize function in -// this package. -type Config struct { - // Hash is the default hash function to be used. If - // nil, SHA1 is used. - Hash crypto.Hash - // S2KCount is only used for symmetric encryption. It - // determines the strength of the passphrase stretching when - // the said passphrase is hashed to produce a key. S2KCount - // should be between 1024 and 65011712, inclusive. If Config - // is nil or S2KCount is 0, the value 65536 used. Not all - // values in the above range can be represented. S2KCount will - // be rounded up to the next representable value if it cannot - // be encoded exactly. When set, it is strongly encrouraged to - // use a value that is at least 65536. See RFC 4880 Section - // 3.7.1.3. - S2KCount int -} - -func (c *Config) hash() crypto.Hash { - if c == nil || uint(c.Hash) == 0 { - // SHA1 is the historical default in this package. - return crypto.SHA1 - } - - return c.Hash -} - -func (c *Config) encodedCount() uint8 { - if c == nil || c.S2KCount == 0 { - return 96 // The common case. Correspoding to 65536 - } - - i := c.S2KCount - switch { - // Behave like GPG. Should we make 65536 the lowest value used? - case i < 1024: - i = 1024 - case i > 65011712: - i = 65011712 - } - - return encodeCount(i) -} - -// encodeCount converts an iterative "count" in the range 1024 to -// 65011712, inclusive, to an encoded count. The return value is the -// octet that is actually stored in the GPG file. encodeCount panics -// if i is not in the above range (encodedCount above takes care to -// pass i in the correct range). See RFC 4880 Section 3.7.7.1. -func encodeCount(i int) uint8 { - if i < 1024 || i > 65011712 { - panic("count arg i outside the required range") - } - - for encoded := 0; encoded < 256; encoded++ { - count := decodeCount(uint8(encoded)) - if count >= i { - return uint8(encoded) - } - } - - return 255 -} - -// decodeCount returns the s2k mode 3 iterative "count" corresponding to -// the encoded octet c. -func decodeCount(c uint8) int { - return (16 + int(c&15)) << (uint32(c>>4) + 6) -} - -// Simple writes to out the result of computing the Simple S2K function (RFC -// 4880, section 3.7.1.1) using the given hash and input passphrase. -func Simple(out []byte, h hash.Hash, in []byte) { - Salted(out, h, in, nil) -} - -var zero [1]byte - -// Salted writes to out the result of computing the Salted S2K function (RFC -// 4880, section 3.7.1.2) using the given hash, input passphrase and salt. -func Salted(out []byte, h hash.Hash, in []byte, salt []byte) { - done := 0 - var digest []byte - - for i := 0; done < len(out); i++ { - h.Reset() - for j := 0; j < i; j++ { - h.Write(zero[:]) - } - h.Write(salt) - h.Write(in) - digest = h.Sum(digest[:0]) - n := copy(out[done:], digest) - done += n - } -} - -// Iterated writes to out the result of computing the Iterated and Salted S2K -// function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase, -// salt and iteration count. -func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) { - combined := make([]byte, len(in)+len(salt)) - copy(combined, salt) - copy(combined[len(salt):], in) - - if count < len(combined) { - count = len(combined) - } - - done := 0 - var digest []byte - for i := 0; done < len(out); i++ { - h.Reset() - for j := 0; j < i; j++ { - h.Write(zero[:]) - } - written := 0 - for written < count { - if written+len(combined) > count { - todo := count - written - h.Write(combined[:todo]) - written = count - } else { - h.Write(combined) - written += len(combined) - } - } - digest = h.Sum(digest[:0]) - n := copy(out[done:], digest) - done += n - } -} - -func parseGNUExtensions(r io.Reader) (f func(out, in []byte), err error) { - var buf [9]byte - - // A three-byte string identifier - _, err = io.ReadFull(r, buf[:3]) - if err != nil { - return - } - gnuExt := string(buf[:3]) - - if gnuExt != "GNU" { - return nil, errors.UnsupportedError("Malformed GNU extension: " + gnuExt) - } - _, err = io.ReadFull(r, buf[:1]) - if err != nil { - return - } - gnuExtType := int(buf[0]) - switch gnuExtType { - case 1: - return nil, nil - case 2: - // Read a serial number, which is prefixed by a 1-byte length. - // The maximum length is 16. - var lenBuf [1]byte - _, err = io.ReadFull(r, lenBuf[:]) - if err != nil { - return - } - - maxLen := 16 - ivLen := int(lenBuf[0]) - if ivLen > maxLen { - ivLen = maxLen - } - ivBuf := make([]byte, ivLen) - // For now we simply discard the IV - _, err = io.ReadFull(r, ivBuf) - if err != nil { - return - } - return nil, nil - default: - return nil, errors.UnsupportedError("unknown S2K GNU protection mode: " + strconv.Itoa(int(gnuExtType))) - } -} - -// Parse reads a binary specification for a string-to-key transformation from r -// and returns a function which performs that transform. -func Parse(r io.Reader) (f func(out, in []byte), err error) { - var buf [9]byte - - _, err = io.ReadFull(r, buf[:2]) - if err != nil { - return - } - - // GNU Extensions; handle them before we try to look for a hash, which won't - // be needed in most cases anyway. - if buf[0] == 101 { - return parseGNUExtensions(r) - } - - hash, ok := HashIdToHash(buf[1]) - if !ok { - return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1]))) - } - if !hash.Available() { - return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash))) - } - h := hash.New() - - switch buf[0] { - case 0: - f := func(out, in []byte) { - Simple(out, h, in) - } - return f, nil - case 1: - _, err = io.ReadFull(r, buf[:8]) - if err != nil { - return - } - f := func(out, in []byte) { - Salted(out, h, in, buf[:8]) - } - return f, nil - case 3: - _, err = io.ReadFull(r, buf[:9]) - if err != nil { - return - } - count := decodeCount(buf[8]) - f := func(out, in []byte) { - Iterated(out, h, in, buf[:8], count) - } - return f, nil - } - - return nil, errors.UnsupportedError("S2K function") -} - -// Serialize salts and stretches the given passphrase and writes the -// resulting key into key. It also serializes an S2K descriptor to -// w. The key stretching can be configured with c, which may be -// nil. In that case, sensible defaults will be used. -func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error { - var buf [11]byte - buf[0] = 3 /* iterated and salted */ - buf[1], _ = HashToHashId(c.hash()) - salt := buf[2:10] - if _, err := io.ReadFull(rand, salt); err != nil { - return err - } - encodedCount := c.encodedCount() - count := decodeCount(encodedCount) - buf[10] = encodedCount - if _, err := w.Write(buf[:]); err != nil { - return err - } - - Iterated(key, c.hash().New(), passphrase, salt, count) - return nil -} - -// hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with -// Go's crypto.Hash type. See RFC 4880, section 9.4. -var hashToHashIdMapping = []struct { - id byte - hash crypto.Hash - name string -}{ - {1, crypto.MD5, "MD5"}, - {2, crypto.SHA1, "SHA1"}, - {3, crypto.RIPEMD160, "RIPEMD160"}, - {8, crypto.SHA256, "SHA256"}, - {9, crypto.SHA384, "SHA384"}, - {10, crypto.SHA512, "SHA512"}, - {11, crypto.SHA224, "SHA224"}, -} - -// HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP -// hash id. -func HashIdToHash(id byte) (h crypto.Hash, ok bool) { - for _, m := range hashToHashIdMapping { - if m.id == id { - return m.hash, true - } - } - return 0, false -} - -// HashIdToString returns the name of the hash function corresponding to the -// given OpenPGP hash id, or panics if id is unknown. -func HashIdToString(id byte) (name string, ok bool) { - for _, m := range hashToHashIdMapping { - if m.id == id { - return m.name, true - } - } - - return "", false -} - -// HashIdToHash returns an OpenPGP hash id which corresponds the given Hash. -func HashToHashId(h crypto.Hash) (id byte, ok bool) { - for _, m := range hashToHashIdMapping { - if m.hash == h { - return m.id, true - } - } - return 0, false -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch b/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch deleted file mode 100644 index bfd764af..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch +++ /dev/null @@ -1,135 +0,0 @@ -diff --git a/openpgp/read.go b/openpgp/read.go -index a6cecc5..0c9397b 100644 ---- a/openpgp/read.go -+++ b/openpgp/read.go -@@ -56,8 +56,9 @@ type MessageDetails struct { - // been consumed. Once EOF has been seen, the following fields are - // valid. (An authentication code failure is reported as a - // SignatureError error when reading from UnverifiedBody.) -- SignatureError error // nil if the signature is good. -- Signature *packet.Signature // the signature packet itself. -+ SignatureError error // nil if the signature is good. -+ Signature *packet.Signature // the signature packet itself, if v4 (default) -+ SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature - - decrypted io.ReadCloser - } -@@ -334,13 +335,15 @@ func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { - } - - var ok bool -- if scr.md.Signature, ok = p.(*packet.Signature); !ok { -+ if scr.md.Signature, ok = p.(*packet.Signature); ok { -+ scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) -+ } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { -+ scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) -+ } else { - scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") - return - } - -- scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) -- - // The SymmetricallyEncrypted packet, if any, might have an - // unsigned hash of its own. In order to check this we need to - // close that Reader. -diff --git a/openpgp/read_test.go b/openpgp/read_test.go -index 52f942c..abe8d7b 100644 ---- a/openpgp/read_test.go -+++ b/openpgp/read_test.go -@@ -13,6 +13,7 @@ import ( - "strings" - "testing" - -+ "golang.org/x/crypto/openpgp/armor" - "golang.org/x/crypto/openpgp/errors" - ) - -@@ -411,6 +412,50 @@ func TestIssue11504(t *testing.T) { - testReadMessageError(t, "9303000130303030303030303030983002303030303030030000000130") - } - -+// TestSignatureV3Message tests the verification of V3 signature, generated -+// with a modern V4-style key. Some people have their clients set to generate -+// V3 signatures, so it's useful to be able to verify them. -+func TestSignatureV3Message(t *testing.T) { -+ sig, err := armor.Decode(strings.NewReader(signedMessageV3)) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ key, err := ReadArmoredKeyRing(strings.NewReader(keyV4forVerifyingSignedMessageV3)) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ md, err := ReadMessage(sig.Body, key, nil, nil) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ -+ _, err = ioutil.ReadAll(md.UnverifiedBody) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ -+ // We'll see a sig error here after reading in the UnverifiedBody above, -+ // if there was one to see. -+ if err = md.SignatureError; err != nil { -+ t.Error(err) -+ return -+ } -+ -+ if md.SignatureV3 == nil { -+ t.Errorf("No available signature after checking signature") -+ return -+ } -+ if md.Signature != nil { -+ t.Errorf("Did not expect a signature V4 back") -+ return -+ } -+ return -+} -+ - const testKey1KeyId = 0xA34D7E18C20C31BB - const testKey3KeyId = 0x338934250CCC0360 - -@@ -504,3 +549,36 @@ const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6 - const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` - - const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` -+ -+const keyV4forVerifyingSignedMessageV3 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -+Comment: GPGTools - https://gpgtools.org -+ -+mI0EVfxoFQEEAMBIqmbDfYygcvP6Phr1wr1XI41IF7Qixqybs/foBF8qqblD9gIY -+BKpXjnBOtbkcVOJ0nljd3/sQIfH4E0vQwK5/4YRQSI59eKOqd6Fx+fWQOLG+uu6z -+tewpeCj9LLHvibx/Sc7VWRnrznia6ftrXxJ/wHMezSab3tnGC0YPVdGNABEBAAG0 -+JEdvY3J5cHRvIFRlc3QgS2V5IDx0aGVtYXhAZ21haWwuY29tPoi5BBMBCgAjBQJV -+/GgVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQeXnQmhdGW9PFVAP+ -+K7TU0qX5ArvIONIxh/WAweyOk884c5cE8f+3NOPOOCRGyVy0FId5A7MmD5GOQh4H -+JseOZVEVCqlmngEvtHZb3U1VYtVGE5WZ+6rQhGsMcWP5qaT4soYwMBlSYxgYwQcx -+YhN9qOr292f9j2Y//TTIJmZT4Oa+lMxhWdqTfX+qMgG4jQRV/GgVAQQArhFSiij1 -+b+hT3dnapbEU+23Z1yTu1DfF6zsxQ4XQWEV3eR8v+8mEDDNcz8oyyF56k6UQ3rXi -+UMTIwRDg4V6SbZmaFbZYCOwp/EmXJ3rfhm7z7yzXj2OFN22luuqbyVhuL7LRdB0M -+pxgmjXb4tTvfgKd26x34S+QqUJ7W6uprY4sAEQEAAYifBBgBCgAJBQJV/GgVAhsM -+AAoJEHl50JoXRlvT7y8D/02ckx4OMkKBZo7viyrBw0MLG92i+DC2bs35PooHR6zz -+786mitjOp5z2QWNLBvxC70S0qVfCIz8jKupO1J6rq6Z8CcbLF3qjm6h1omUBf8Nd -+EfXKD2/2HV6zMKVknnKzIEzauh+eCKS2CeJUSSSryap/QLVAjRnckaES/OsEWhNB -+=RZia -+-----END PGP PUBLIC KEY BLOCK----- -+` -+ -+const signedMessageV3 = `-----BEGIN PGP MESSAGE----- -+Comment: GPGTools - https://gpgtools.org -+ -+owGbwMvMwMVYWXlhlrhb9GXG03JJDKF/MtxDMjKLFYAoUaEktbhEITe1uDgxPVWP -+q5NhKjMrWAVcC9evD8z/bF/uWNjqtk/X3y5/38XGRQHm/57rrDRYuGnTw597Xqka -+uM3137/hH3Os+Jf2dc0fXOITKwJvXJvecPVs0ta+Vg7ZO1MLn8w58Xx+6L58mbka -+DGHyU9yTueZE8D+QF/Tz28Y78dqtF56R1VPn9Xw4uJqrWYdd7b3vIZ1V6R4Nh05d -+iT57d/OhWwA= -+=hG7R -+-----END PGP MESSAGE----- -+` diff --git a/vendor/github.com/keybase/go-crypto/openpgp/write.go b/vendor/github.com/keybase/go-crypto/openpgp/write.go deleted file mode 100644 index 89ef132b..00000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/write.go +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - "crypto" - "hash" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// DetachSign signs message with the private key from signer (which must -// already have been decrypted) and writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// ArmoredDetachSign signs message with the private key from signer (which -// must already have been decrypted) and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { - return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// DetachSignText signs message (after canonicalising the line endings) with -// the private key from signer (which must already have been decrypted) and -// writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeText, config) -} - -// ArmoredDetachSignText signs message (after canonicalising the line endings) -// with the private key from signer (which must already have been decrypted) -// and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return armoredDetachSign(w, signer, message, packet.SigTypeText, config) -} - -func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - out, err := armor.Encode(w, SignatureType, nil) - if err != nil { - return - } - err = detachSign(out, signer, message, sigType, config) - if err != nil { - return - } - return out.Close() -} - -// SignWithSigner signs the message of type sigType with s and writes the -// signature to w. -// If config is nil, sensible defaults will be used. -func SignWithSigner(s packet.Signer, w io.Writer, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - keyId := s.KeyId() - sig := new(packet.Signature) - sig.SigType = sigType - sig.PubKeyAlgo = s.PublicKeyAlgo() - sig.Hash = config.Hash() - sig.CreationTime = config.Now() - sig.IssuerKeyId = &keyId - - s.Reset() - - wrapped := s.(hash.Hash) - - if sigType == packet.SigTypeText { - wrapped = NewCanonicalTextHash(s) - } - - io.Copy(wrapped, message) - - err = sig.Sign(s, nil, config) - if err != nil { - return - } - - err = sig.Serialize(w) - - return -} - -func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - signerSubkey, ok := signer.signingKey(config.Now()) - if !ok { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - if signerSubkey.PrivateKey == nil { - return errors.InvalidArgumentError("signing key doesn't have a private key") - } - if signerSubkey.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing key is encrypted") - } - - sig := new(packet.Signature) - sig.SigType = sigType - sig.PubKeyAlgo = signerSubkey.PrivateKey.PubKeyAlgo - sig.Hash = config.Hash() - sig.CreationTime = config.Now() - sig.IssuerKeyId = &signerSubkey.PrivateKey.KeyId - - h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) - if err != nil { - return - } - io.Copy(wrappedHash, message) - - err = sig.Sign(h, signerSubkey.PrivateKey, config) - if err != nil { - return - } - - return sig.Serialize(w) -} - -// FileHints contains metadata about encrypted files. This metadata is, itself, -// encrypted. -type FileHints struct { - // IsBinary can be set to hint that the contents are binary data. - IsBinary bool - // FileName hints at the name of the file that should be written. It's - // truncated to 255 bytes if longer. It may be empty to suggest that the - // file should not be written to disk. It may be equal to "_CONSOLE" to - // suggest the data should not be written to disk. - FileName string - // ModTime contains the modification time of the file, or the zero time if not applicable. - ModTime time.Time -} - -// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. -// The resulting WriteCloser must be closed after the contents of the file have -// been written. -// If config is nil, sensible defaults will be used. -func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - if hints == nil { - hints = &FileHints{} - } - - key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) - if err != nil { - return - } - w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config) - if err != nil { - return - } - - literaldata := w - if algo := config.Compression(); algo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - literaldata, err = packet.SerializeCompressed(w, algo, compConfig) - if err != nil { - return - } - } - - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - return packet.SerializeLiteral(literaldata, hints.IsBinary, hints.FileName, epochSeconds) -} - -// intersectPreferences mutates and returns a prefix of a that contains only -// the values in the intersection of a and b. The order of a is preserved. -func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { - var j int - for _, v := range a { - for _, v2 := range b { - if v == v2 { - a[j] = v - j++ - break - } - } - } - - return a[:j] -} - -func hashToHashId(h crypto.Hash) uint8 { - v, ok := s2k.HashToHashId(h) - if !ok { - panic("tried to convert unknown hash") - } - return v -} - -// Encrypt encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - var signer *packet.PrivateKey - if signed != nil { - signKey, ok := signed.signingKey(config.Now()) - if !ok { - return nil, errors.InvalidArgumentError("no valid signing keys") - } - signer = signKey.PrivateKey - if signer == nil { - return nil, errors.InvalidArgumentError("no private key in signing key") - } - if signer.Encrypted { - return nil, errors.InvalidArgumentError("signing key must be decrypted") - } - } - - // These are the possible ciphers that we'll use for the message. - candidateCiphers := []uint8{ - uint8(packet.CipherAES128), - uint8(packet.CipherAES256), - uint8(packet.CipherCAST5), - } - // These are the possible hash functions that we'll use for the signature. - candidateHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.SHA1), - hashToHashId(crypto.RIPEMD160), - } - - // If no preferences were specified, assume something safe and reasonable. - defaultCiphers := []uint8{ - uint8(packet.CipherAES128), - uint8(packet.CipherAES192), - uint8(packet.CipherAES256), - uint8(packet.CipherCAST5), - } - - defaultHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.RIPEMD160), - } - - encryptKeys := make([]Key, len(to)) - for i := range to { - var ok bool - encryptKeys[i], ok = to[i].encryptionKey(config.Now()) - if !ok { - return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys") - } - - sig := to[i].primaryIdentity().SelfSignature - - preferredSymmetric := sig.PreferredSymmetric - if len(preferredSymmetric) == 0 { - preferredSymmetric = defaultCiphers - } - preferredHashes := sig.PreferredHash - if len(preferredHashes) == 0 { - preferredHashes = defaultHashes - } - candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric) - candidateHashes = intersectPreferences(candidateHashes, preferredHashes) - } - - if len(candidateCiphers) == 0 { - return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common ciphers") - } - if len(candidateHashes) == 0 { - return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common hashes") - } - - cipher := packet.CipherFunction(candidateCiphers[0]) - // If the cipher specifed by config is a candidate, we'll use that. - configuredCipher := config.Cipher() - for _, c := range candidateCiphers { - cipherFunc := packet.CipherFunction(c) - if cipherFunc == configuredCipher { - cipher = cipherFunc - break - } - } - - var hash crypto.Hash - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { - hash = h - break - } - } - - // If the hash specified by config is a candidate, we'll use that. - if configuredHash := config.Hash(); configuredHash.Available() { - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { - hash = h - break - } - } - } - - if hash == 0 { - hashId := candidateHashes[0] - name, ok := s2k.HashIdToString(hashId) - if !ok { - name = "#" + strconv.Itoa(int(hashId)) - } - return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") - } - - symKey := make([]byte, cipher.KeySize()) - if _, err := io.ReadFull(config.Random(), symKey); err != nil { - return nil, err - } - - for _, key := range encryptKeys { - if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil { - return nil, err - } - } - - encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config) - if err != nil { - return - } - - if signer != nil { - ops := &packet.OnePassSignature{ - SigType: packet.SigTypeBinary, - Hash: hash, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - if err := ops.Serialize(encryptedData); err != nil { - return nil, err - } - } - - if hints == nil { - hints = &FileHints{} - } - - w := encryptedData - if signer != nil { - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - w = noOpCloser{encryptedData} - - } - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) - if err != nil { - return nil, err - } - - if signer != nil { - return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil - } - return literalData, nil -} - -// signatureWriter hashes the contents of a message while passing it along to -// literalData. When closed, it closes literalData, writes a signature packet -// to encryptedData and then also closes encryptedData. -type signatureWriter struct { - encryptedData io.WriteCloser - literalData io.WriteCloser - hashType crypto.Hash - h hash.Hash - signer *packet.PrivateKey - config *packet.Config -} - -func (s signatureWriter) Write(data []byte) (int, error) { - s.h.Write(data) - return s.literalData.Write(data) -} - -func (s signatureWriter) Close() error { - sig := &packet.Signature{ - SigType: packet.SigTypeBinary, - PubKeyAlgo: s.signer.PubKeyAlgo, - Hash: s.hashType, - CreationTime: s.config.Now(), - IssuerKeyId: &s.signer.KeyId, - } - - if err := sig.Sign(s.h, s.signer, s.config); err != nil { - return err - } - if err := s.literalData.Close(); err != nil { - return err - } - if err := sig.Serialize(s.encryptedData); err != nil { - return err - } - return s.encryptedData.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -// TODO: we have two of these in OpenPGP packages alone. This probably needs -// to be promoted somewhere more common. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -// AttachedSign is like openpgp.Encrypt (as in p.crypto/openpgp/write.go), but -// don't encrypt at all, just sign the literal unencrypted data. -// Unfortunately we need to duplicate some code here that's already -// in write.go -func AttachedSign(out io.WriteCloser, signed Entity, hints *FileHints, - config *packet.Config) (in io.WriteCloser, err error) { - - if hints == nil { - hints = &FileHints{} - } - - if config == nil { - config = &packet.Config{} - } - - var signer *packet.PrivateKey - - signKey, ok := signed.signingKey(config.Now()) - if !ok { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - signer = signKey.PrivateKey - if signer == nil { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - if signer.Encrypted { - err = errors.InvalidArgumentError("signing key must be decrypted") - return - } - - if algo := config.Compression(); algo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - out, err = packet.SerializeCompressed(out, algo, compConfig) - if err != nil { - return - } - } - - hasher := crypto.SHA512 - - ops := &packet.OnePassSignature{ - SigType: packet.SigTypeBinary, - Hash: hasher, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - - if err = ops.Serialize(out); err != nil { - return - } - - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - - // We don't want the literal serializer to closer the output stream - // since we're going to need to write to it when we finish up the - // signature stuff. - in, err = packet.SerializeLiteral(noOpCloser{out}, hints.IsBinary, hints.FileName, epochSeconds) - - if err != nil { - return - } - - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - in = signatureWriter{out, in, hasher, hasher.New(), signer, config} - - return -} diff --git a/vendor/github.com/keybase/go-crypto/rsa/pkcs1v15.go b/vendor/github.com/keybase/go-crypto/rsa/pkcs1v15.go deleted file mode 100644 index 5c5f415c..00000000 --- a/vendor/github.com/keybase/go-crypto/rsa/pkcs1v15.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -import ( - "crypto" - "crypto/subtle" - "errors" - "io" - "math/big" -) - -// This file implements encryption and decryption using PKCS#1 v1.5 padding. - -// PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using -// the crypto.Decrypter interface. -type PKCS1v15DecryptOptions struct { - // SessionKeyLen is the length of the session key that is being - // decrypted. If not zero, then a padding error during decryption will - // cause a random plaintext of this length to be returned rather than - // an error. These alternatives happen in constant time. - SessionKeyLen int -} - -// EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS#1 v1.5. -// The message must be no longer than the length of the public modulus minus 11 bytes. -// -// The rand parameter is used as a source of entropy to ensure that encrypting -// the same message twice doesn't result in the same ciphertext. -// -// WARNING: use of this function to encrypt plaintexts other than session keys -// is dangerous. Use RSA OAEP in new protocols. -func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err error) { - if err := checkPub(pub); err != nil { - return nil, err - } - k := (pub.N.BitLen() + 7) / 8 - if len(msg) > k-11 { - err = ErrMessageTooLong - return - } - - // EM = 0x00 || 0x02 || PS || 0x00 || M - em := make([]byte, k) - em[1] = 2 - ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):] - err = nonZeroRandomBytes(ps, rand) - if err != nil { - return - } - em[len(em)-len(msg)-1] = 0 - copy(mm, msg) - - m := new(big.Int).SetBytes(em) - c := encrypt(new(big.Int), pub, m) - - copyWithLeftPad(em, c.Bytes()) - out = em - return -} - -// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5. -// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. -// -// Note that whether this function returns an error or not discloses secret -// information. If an attacker can cause this function to run repeatedly and -// learn whether each instance returned an error then they can decrypt and -// forge signatures as if they had the private key. See -// DecryptPKCS1v15SessionKey for a way of solving this problem. -func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return nil, err - } - valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext) - if err != nil { - return - } - if valid == 0 { - return nil, ErrDecryption - } - out = out[index:] - return -} - -// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5. -// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. -// It returns an error if the ciphertext is the wrong length or if the -// ciphertext is greater than the public modulus. Otherwise, no error is -// returned. If the padding is valid, the resulting plaintext message is copied -// into key. Otherwise, key is unchanged. These alternatives occur in constant -// time. It is intended that the user of this function generate a random -// session key beforehand and continue the protocol with the resulting value. -// This will remove any possibility that an attacker can learn any information -// about the plaintext. -// See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA -// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology -// (Crypto '98). -// -// Note that if the session key is too small then it may be possible for an -// attacker to brute-force it. If they can do that then they can learn whether -// a random value was used (because it'll be different for the same ciphertext) -// and thus whether the padding was correct. This defeats the point of this -// function. Using at least a 16-byte key will protect against this attack. -func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return err - } - k := (priv.N.BitLen() + 7) / 8 - if k-(len(key)+3+8) < 0 { - return ErrDecryption - } - - valid, em, index, err := decryptPKCS1v15(rand, priv, ciphertext) - if err != nil { - return - } - - if len(em) != k { - // This should be impossible because decryptPKCS1v15 always - // returns the full slice. - return ErrDecryption - } - - valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key))) - subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):]) - return -} - -// decryptPKCS1v15 decrypts ciphertext using priv and blinds the operation if -// rand is not nil. It returns one or zero in valid that indicates whether the -// plaintext was correctly structured. In either case, the plaintext is -// returned in em so that it may be read independently of whether it was valid -// in order to maintain constant memory access patterns. If the plaintext was -// valid then index contains the index of the original message in em. -func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) { - k := (priv.N.BitLen() + 7) / 8 - if k < 11 { - err = ErrDecryption - return - } - - c := new(big.Int).SetBytes(ciphertext) - m, err := decrypt(rand, priv, c) - if err != nil { - return - } - - em = leftPad(m.Bytes(), k) - firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0) - secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2) - - // The remainder of the plaintext must be a string of non-zero random - // octets, followed by a 0, followed by the message. - // lookingForIndex: 1 iff we are still looking for the zero. - // index: the offset of the first zero byte. - lookingForIndex := 1 - - for i := 2; i < len(em); i++ { - equals0 := subtle.ConstantTimeByteEq(em[i], 0) - index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) - } - - // The PS padding must be at least 8 bytes long, and it starts two - // bytes into em. - validPS := subtle.ConstantTimeLessOrEq(2+8, index) - - valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS - index = subtle.ConstantTimeSelect(valid, index+1, 0) - return valid, em, index, nil -} - -// nonZeroRandomBytes fills the given slice with non-zero random octets. -func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { - _, err = io.ReadFull(rand, s) - if err != nil { - return - } - - for i := 0; i < len(s); i++ { - for s[i] == 0 { - _, err = io.ReadFull(rand, s[i:i+1]) - if err != nil { - return - } - // In tests, the PRNG may return all zeros so we do - // this to break the loop. - s[i] ^= 0x42 - } - } - - return -} - -// These are ASN1 DER structures: -// DigestInfo ::= SEQUENCE { -// digestAlgorithm AlgorithmIdentifier, -// digest OCTET STRING -// } -// For performance, we don't use the generic ASN1 encoder. Rather, we -// precompute a prefix of the digest value that makes a valid ASN1 DER string -// with the correct contents. -var hashPrefixes = map[crypto.Hash][]byte{ - crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10}, - crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14}, - crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c}, - crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}, - crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}, - crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40}, - crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix. - crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14}, -} - -// SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. -// Note that hashed must be the result of hashing the input message using the -// given hash function. If hash is zero, hashed is signed directly. This isn't -// advisable except for interoperability. -// -// If rand is not nil then RSA blinding will be used to avoid timing side-channel attacks. -// -// This function is deterministic. Thus, if the set of possible messages is -// small, an attacker may be able to build a map from messages to signatures -// and identify the signed messages. As ever, signatures provide authenticity, -// not confidentiality. -func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error) { - hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) - if err != nil { - return - } - - tLen := len(prefix) + hashLen - k := (priv.N.BitLen() + 7) / 8 - if k < tLen+11 { - return nil, ErrMessageTooLong - } - - // EM = 0x00 || 0x01 || PS || 0x00 || T - em := make([]byte, k) - em[1] = 1 - for i := 2; i < k-tLen-1; i++ { - em[i] = 0xff - } - copy(em[k-tLen:k-hashLen], prefix) - copy(em[k-hashLen:k], hashed) - - m := new(big.Int).SetBytes(em) - c, err := decryptAndCheck(rand, priv, m) - if err != nil { - return - } - - copyWithLeftPad(em, c.Bytes()) - s = em - return -} - -// VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature. -// hashed is the result of hashing the input message using the given hash -// function and sig is the signature. A valid signature is indicated by -// returning a nil error. If hash is zero then hashed is used directly. This -// isn't advisable except for interoperability. -func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error) { - hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) - if err != nil { - return - } - - tLen := len(prefix) + hashLen - k := (pub.N.BitLen() + 7) / 8 - if k < tLen+11 { - err = ErrVerification - return - } - - c := new(big.Int).SetBytes(sig) - m := encrypt(new(big.Int), pub, c) - em := leftPad(m.Bytes(), k) - // EM = 0x00 || 0x01 || PS || 0x00 || T - - ok := subtle.ConstantTimeByteEq(em[0], 0) - ok &= subtle.ConstantTimeByteEq(em[1], 1) - ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed) - ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix) - ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0) - - for i := 2; i < k-tLen-1; i++ { - ok &= subtle.ConstantTimeByteEq(em[i], 0xff) - } - - if ok != 1 { - return ErrVerification - } - - return nil -} - -func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) { - // Special case: crypto.Hash(0) is used to indicate that the data is - // signed directly. - if hash == 0 { - return inLen, nil, nil - } - - hashLen = hash.Size() - if inLen != hashLen { - return 0, nil, errors.New("crypto/rsa: input must be hashed message") - } - prefix, ok := hashPrefixes[hash] - if !ok { - return 0, nil, errors.New("crypto/rsa: unsupported hash function") - } - return -} - -// copyWithLeftPad copies src to the end of dest, padding with zero bytes as -// needed. -func copyWithLeftPad(dest, src []byte) { - numPaddingBytes := len(dest) - len(src) - for i := 0; i < numPaddingBytes; i++ { - dest[i] = 0 - } - copy(dest[numPaddingBytes:], src) -} diff --git a/vendor/github.com/keybase/go-crypto/rsa/pss.go b/vendor/github.com/keybase/go-crypto/rsa/pss.go deleted file mode 100644 index 8a94589b..00000000 --- a/vendor/github.com/keybase/go-crypto/rsa/pss.go +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright 2013 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 rsa - -// This file implements the PSS signature scheme [1]. -// -// [1] http://www.rsa.com/rsalabs/pkcs/files/h11300-wp-pkcs-1v2-2-rsa-cryptography-standard.pdf - -import ( - "bytes" - "crypto" - "errors" - "hash" - "io" - "math/big" -) - -func emsaPSSEncode(mHash []byte, emBits int, salt []byte, hash hash.Hash) ([]byte, error) { - // See [1], section 9.1.1 - hLen := hash.Size() - sLen := len(salt) - emLen := (emBits + 7) / 8 - - // 1. If the length of M is greater than the input limitation for the - // hash function (2^61 - 1 octets for SHA-1), output "message too - // long" and stop. - // - // 2. Let mHash = Hash(M), an octet string of length hLen. - - if len(mHash) != hLen { - return nil, errors.New("crypto/rsa: input must be hashed message") - } - - // 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. - - if emLen < hLen+sLen+2 { - return nil, errors.New("crypto/rsa: encoding error") - } - - em := make([]byte, emLen) - db := em[:emLen-sLen-hLen-2+1+sLen] - h := em[emLen-sLen-hLen-2+1+sLen : emLen-1] - - // 4. Generate a random octet string salt of length sLen; if sLen = 0, - // then salt is the empty string. - // - // 5. Let - // M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; - // - // M' is an octet string of length 8 + hLen + sLen with eight - // initial zero octets. - // - // 6. Let H = Hash(M'), an octet string of length hLen. - - var prefix [8]byte - - hash.Write(prefix[:]) - hash.Write(mHash) - hash.Write(salt) - - h = hash.Sum(h[:0]) - hash.Reset() - - // 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 - // zero octets. The length of PS may be 0. - // - // 8. Let DB = PS || 0x01 || salt; DB is an octet string of length - // emLen - hLen - 1. - - db[emLen-sLen-hLen-2] = 0x01 - copy(db[emLen-sLen-hLen-1:], salt) - - // 9. Let dbMask = MGF(H, emLen - hLen - 1). - // - // 10. Let maskedDB = DB \xor dbMask. - - mgf1XOR(db, hash, h) - - // 11. Set the leftmost 8 * emLen - emBits bits of the leftmost octet in - // maskedDB to zero. - - db[0] &= (0xFF >> uint(8*emLen-emBits)) - - // 12. Let EM = maskedDB || H || 0xbc. - em[emLen-1] = 0xBC - - // 13. Output EM. - return em, nil -} - -func emsaPSSVerify(mHash, em []byte, emBits, sLen int, hash hash.Hash) error { - // 1. If the length of M is greater than the input limitation for the - // hash function (2^61 - 1 octets for SHA-1), output "inconsistent" - // and stop. - // - // 2. Let mHash = Hash(M), an octet string of length hLen. - hLen := hash.Size() - if hLen != len(mHash) { - return ErrVerification - } - - // 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. - emLen := (emBits + 7) / 8 - if emLen < hLen+sLen+2 { - return ErrVerification - } - - // 4. If the rightmost octet of EM does not have hexadecimal value - // 0xbc, output "inconsistent" and stop. - if em[len(em)-1] != 0xBC { - return ErrVerification - } - - // 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and - // let H be the next hLen octets. - db := em[:emLen-hLen-1] - h := em[emLen-hLen-1 : len(em)-1] - - // 6. If the leftmost 8 * emLen - emBits bits of the leftmost octet in - // maskedDB are not all equal to zero, output "inconsistent" and - // stop. - if em[0]&(0xFF<> uint(8*emLen-emBits)) - - if sLen == PSSSaltLengthAuto { - FindSaltLength: - for sLen = emLen - (hLen + 2); sLen >= 0; sLen-- { - switch db[emLen-hLen-sLen-2] { - case 1: - break FindSaltLength - case 0: - continue - default: - return ErrVerification - } - } - if sLen < 0 { - return ErrVerification - } - } else { - // 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero - // or if the octet at position emLen - hLen - sLen - 1 (the leftmost - // position is "position 1") does not have hexadecimal value 0x01, - // output "inconsistent" and stop. - for _, e := range db[:emLen-hLen-sLen-2] { - if e != 0x00 { - return ErrVerification - } - } - if db[emLen-hLen-sLen-2] != 0x01 { - return ErrVerification - } - } - - // 11. Let salt be the last sLen octets of DB. - salt := db[len(db)-sLen:] - - // 12. Let - // M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt ; - // M' is an octet string of length 8 + hLen + sLen with eight - // initial zero octets. - // - // 13. Let H' = Hash(M'), an octet string of length hLen. - var prefix [8]byte - hash.Write(prefix[:]) - hash.Write(mHash) - hash.Write(salt) - - h0 := hash.Sum(nil) - - // 14. If H = H', output "consistent." Otherwise, output "inconsistent." - if !bytes.Equal(h0, h) { - return ErrVerification - } - return nil -} - -// signPSSWithSalt calculates the signature of hashed using PSS [1] with specified salt. -// Note that hashed must be the result of hashing the input message using the -// given hash function. salt is a random sequence of bytes whose length will be -// later used to verify the signature. -func signPSSWithSalt(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed, salt []byte) (s []byte, err error) { - nBits := priv.N.BitLen() - em, err := emsaPSSEncode(hashed, nBits-1, salt, hash.New()) - if err != nil { - return - } - m := new(big.Int).SetBytes(em) - c, err := decryptAndCheck(rand, priv, m) - if err != nil { - return - } - s = make([]byte, (nBits+7)/8) - copyWithLeftPad(s, c.Bytes()) - return -} - -const ( - // PSSSaltLengthAuto causes the salt in a PSS signature to be as large - // as possible when signing, and to be auto-detected when verifying. - PSSSaltLengthAuto = 0 - // PSSSaltLengthEqualsHash causes the salt length to equal the length - // of the hash used in the signature. - PSSSaltLengthEqualsHash = -1 -) - -// PSSOptions contains options for creating and verifying PSS signatures. -type PSSOptions struct { - // SaltLength controls the length of the salt used in the PSS - // signature. It can either be a number of bytes, or one of the special - // PSSSaltLength constants. - SaltLength int - - // Hash, if not zero, overrides the hash function passed to SignPSS. - // This is the only way to specify the hash function when using the - // crypto.Signer interface. - Hash crypto.Hash -} - -// HashFunc returns pssOpts.Hash so that PSSOptions implements -// crypto.SignerOpts. -func (pssOpts *PSSOptions) HashFunc() crypto.Hash { - return pssOpts.Hash -} - -func (opts *PSSOptions) saltLength() int { - if opts == nil { - return PSSSaltLengthAuto - } - return opts.SaltLength -} - -// SignPSS calculates the signature of hashed using RSASSA-PSS [1]. -// Note that hashed must be the result of hashing the input message using the -// given hash function. The opts argument may be nil, in which case sensible -// defaults are used. -func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) (s []byte, err error) { - saltLength := opts.saltLength() - switch saltLength { - case PSSSaltLengthAuto: - saltLength = (priv.N.BitLen()+7)/8 - 2 - hash.Size() - case PSSSaltLengthEqualsHash: - saltLength = hash.Size() - } - - if opts != nil && opts.Hash != 0 { - hash = opts.Hash - } - - salt := make([]byte, saltLength) - if _, err = io.ReadFull(rand, salt); err != nil { - return - } - return signPSSWithSalt(rand, priv, hash, hashed, salt) -} - -// VerifyPSS verifies a PSS signature. -// hashed is the result of hashing the input message using the given hash -// function and sig is the signature. A valid signature is indicated by -// returning a nil error. The opts argument may be nil, in which case sensible -// defaults are used. -func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error { - return verifyPSS(pub, hash, hashed, sig, opts.saltLength()) -} - -// verifyPSS verifies a PSS signature with the given salt length. -func verifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, saltLen int) error { - nBits := pub.N.BitLen() - if len(sig) != (nBits+7)/8 { - return ErrVerification - } - s := new(big.Int).SetBytes(sig) - m := encrypt(new(big.Int), pub, s) - emBits := nBits - 1 - emLen := (emBits + 7) / 8 - if emLen < len(m.Bytes()) { - return ErrVerification - } - em := make([]byte, emLen) - copyWithLeftPad(em, m.Bytes()) - if saltLen == PSSSaltLengthEqualsHash { - saltLen = hash.Size() - } - return emsaPSSVerify(hashed, em, emBits, saltLen, hash.New()) -} diff --git a/vendor/github.com/keybase/go-crypto/rsa/rsa.go b/vendor/github.com/keybase/go-crypto/rsa/rsa.go deleted file mode 100644 index ff6b11b3..00000000 --- a/vendor/github.com/keybase/go-crypto/rsa/rsa.go +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package rsa implements RSA encryption as specified in PKCS#1. -// -// RSA is a single, fundamental operation that is used in this package to -// implement either public-key encryption or public-key signatures. -// -// The original specification for encryption and signatures with RSA is PKCS#1 -// and the terms "RSA encryption" and "RSA signatures" by default refer to -// PKCS#1 version 1.5. However, that specification has flaws and new designs -// should use version two, usually called by just OAEP and PSS, where -// possible. -// -// Two sets of interfaces are included in this package. When a more abstract -// interface isn't neccessary, there are functions for encrypting/decrypting -// with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract -// over the public-key primitive, the PrivateKey struct implements the -// Decrypter and Signer interfaces from the crypto package. -package rsa - -import ( - "crypto" - "crypto/rand" - "crypto/subtle" - "errors" - "hash" - "io" - "math/big" -) - -var bigZero = big.NewInt(0) -var bigOne = big.NewInt(1) - -// A PublicKey represents the public part of an RSA key. -type PublicKey struct { - N *big.Int // modulus - E int64 // public exponent -} - -// OAEPOptions is an interface for passing options to OAEP decryption using the -// crypto.Decrypter interface. -type OAEPOptions struct { - // Hash is the hash function that will be used when generating the mask. - Hash crypto.Hash - // Label is an arbitrary byte string that must be equal to the value - // used when encrypting. - Label []byte -} - -var ( - errPublicModulus = errors.New("crypto/rsa: missing public modulus") - errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small") - errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large") -) - -// checkPub sanity checks the public key before we use it. -// We require pub.E to fit into a 32-bit integer so that we -// do not have different behavior depending on whether -// int is 32 or 64 bits. See also -// http://www.imperialviolet.org/2012/03/16/rsae.html. -func checkPub(pub *PublicKey) error { - if pub.N == nil { - return errPublicModulus - } - if pub.E < 2 { - return errPublicExponentSmall - } - if pub.E > 1<<63-1 { - return errPublicExponentLarge - } - return nil -} - -// A PrivateKey represents an RSA key -type PrivateKey struct { - PublicKey // public part. - D *big.Int // private exponent - Primes []*big.Int // prime factors of N, has >= 2 elements. - - // Precomputed contains precomputed values that speed up private - // operations, if available. - Precomputed PrecomputedValues -} - -// Public returns the public key corresponding to priv. -func (priv *PrivateKey) Public() crypto.PublicKey { - return &priv.PublicKey -} - -// Sign signs msg with priv, reading randomness from rand. If opts is a -// *PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will -// be used. This method is intended to support keys where the private part is -// kept in, for example, a hardware module. Common uses should use the Sign* -// functions in this package. -func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { - if pssOpts, ok := opts.(*PSSOptions); ok { - return SignPSS(rand, priv, pssOpts.Hash, msg, pssOpts) - } - - return SignPKCS1v15(rand, priv, opts.HashFunc(), msg) -} - -// Decrypt decrypts ciphertext with priv. If opts is nil or of type -// *PKCS1v15DecryptOptions then PKCS#1 v1.5 decryption is performed. Otherwise -// opts must have type *OAEPOptions and OAEP decryption is done. -func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) { - if opts == nil { - return DecryptPKCS1v15(rand, priv, ciphertext) - } - - switch opts := opts.(type) { - case *OAEPOptions: - return DecryptOAEP(opts.Hash.New(), rand, priv, ciphertext, opts.Label) - - case *PKCS1v15DecryptOptions: - if l := opts.SessionKeyLen; l > 0 { - plaintext = make([]byte, l) - if _, err := io.ReadFull(rand, plaintext); err != nil { - return nil, err - } - if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil { - return nil, err - } - return plaintext, nil - } else { - return DecryptPKCS1v15(rand, priv, ciphertext) - } - - default: - return nil, errors.New("crypto/rsa: invalid options for Decrypt") - } -} - -type PrecomputedValues struct { - Dp, Dq *big.Int // D mod (P-1) (or mod Q-1) - Qinv *big.Int // Q^-1 mod P - - // CRTValues is used for the 3rd and subsequent primes. Due to a - // historical accident, the CRT for the first two primes is handled - // differently in PKCS#1 and interoperability is sufficiently - // important that we mirror this. - CRTValues []CRTValue -} - -// CRTValue contains the precomputed Chinese remainder theorem values. -type CRTValue struct { - Exp *big.Int // D mod (prime-1). - Coeff *big.Int // R·Coeff ≡ 1 mod Prime. - R *big.Int // product of primes prior to this (inc p and q). -} - -// Validate performs basic sanity checks on the key. -// It returns nil if the key is valid, or else an error describing a problem. -func (priv *PrivateKey) Validate() error { - if err := checkPub(&priv.PublicKey); err != nil { - return err - } - - // Check that Πprimes == n. - modulus := new(big.Int).Set(bigOne) - for _, prime := range priv.Primes { - // Any primes ≤ 1 will cause divide-by-zero panics later. - if prime.Cmp(bigOne) <= 0 { - return errors.New("crypto/rsa: invalid prime value") - } - modulus.Mul(modulus, prime) - } - if modulus.Cmp(priv.N) != 0 { - return errors.New("crypto/rsa: invalid modulus") - } - - // Check that de ≡ 1 mod p-1, for each prime. - // This implies that e is coprime to each p-1 as e has a multiplicative - // inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) = - // exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1 - // mod p. Thus a^de ≡ a mod n for all a coprime to n, as required. - congruence := new(big.Int) - de := new(big.Int).SetInt64(int64(priv.E)) - de.Mul(de, priv.D) - for _, prime := range priv.Primes { - pminus1 := new(big.Int).Sub(prime, bigOne) - congruence.Mod(de, pminus1) - if congruence.Cmp(bigOne) != 0 { - return errors.New("crypto/rsa: invalid exponents") - } - } - return nil -} - -// GenerateKey generates an RSA keypair of the given bit size using the -// random source random (for example, crypto/rand.Reader). -func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error) { - return GenerateMultiPrimeKey(random, 2, bits) -} - -// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit -// size and the given random source, as suggested in [1]. Although the public -// keys are compatible (actually, indistinguishable) from the 2-prime case, -// the private keys are not. Thus it may not be possible to export multi-prime -// private keys in certain formats or to subsequently import them into other -// code. -// -// Table 1 in [2] suggests maximum numbers of primes for a given size. -// -// [1] US patent 4405829 (1972, expired) -// [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf -func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) { - priv = new(PrivateKey) - priv.E = 65537 - - if nprimes < 2 { - return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") - } - - primes := make([]*big.Int, nprimes) - -NextSetOfPrimes: - for { - todo := bits - // crypto/rand should set the top two bits in each prime. - // Thus each prime has the form - // p_i = 2^bitlen(p_i) × 0.11... (in base 2). - // And the product is: - // P = 2^todo × α - // where α is the product of nprimes numbers of the form 0.11... - // - // If α < 1/2 (which can happen for nprimes > 2), we need to - // shift todo to compensate for lost bits: the mean value of 0.11... - // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 - // will give good results. - if nprimes >= 7 { - todo += (nprimes - 2) / 5 - } - for i := 0; i < nprimes; i++ { - primes[i], err = rand.Prime(random, todo/(nprimes-i)) - if err != nil { - return nil, err - } - todo -= primes[i].BitLen() - } - - // Make sure that primes is pairwise unequal. - for i, prime := range primes { - for j := 0; j < i; j++ { - if prime.Cmp(primes[j]) == 0 { - continue NextSetOfPrimes - } - } - } - - n := new(big.Int).Set(bigOne) - totient := new(big.Int).Set(bigOne) - pminus1 := new(big.Int) - for _, prime := range primes { - n.Mul(n, prime) - pminus1.Sub(prime, bigOne) - totient.Mul(totient, pminus1) - } - if n.BitLen() != bits { - // This should never happen for nprimes == 2 because - // crypto/rand should set the top two bits in each prime. - // For nprimes > 2 we hope it does not happen often. - continue NextSetOfPrimes - } - - g := new(big.Int) - priv.D = new(big.Int) - y := new(big.Int) - e := big.NewInt(int64(priv.E)) - g.GCD(priv.D, y, e, totient) - - if g.Cmp(bigOne) == 0 { - if priv.D.Sign() < 0 { - priv.D.Add(priv.D, totient) - } - priv.Primes = primes - priv.N = n - - break - } - } - - priv.Precompute() - return -} - -// incCounter increments a four byte, big-endian counter. -func incCounter(c *[4]byte) { - if c[3]++; c[3] != 0 { - return - } - if c[2]++; c[2] != 0 { - return - } - if c[1]++; c[1] != 0 { - return - } - c[0]++ -} - -// mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function -// specified in PKCS#1 v2.1. -func mgf1XOR(out []byte, hash hash.Hash, seed []byte) { - var counter [4]byte - var digest []byte - - done := 0 - for done < len(out) { - hash.Write(seed) - hash.Write(counter[0:4]) - digest = hash.Sum(digest[:0]) - hash.Reset() - - for i := 0; i < len(digest) && done < len(out); i++ { - out[done] ^= digest[i] - done++ - } - incCounter(&counter) - } -} - -// ErrMessageTooLong is returned when attempting to encrypt a message which is -// too large for the size of the public key. -var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size") - -func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int { - e := big.NewInt(int64(pub.E)) - c.Exp(m, e, pub.N) - return c -} - -// EncryptOAEP encrypts the given message with RSA-OAEP. -// -// OAEP is parameterised by a hash function that is used as a random oracle. -// Encryption and decryption of a given message must use the same hash function -// and sha256.New() is a reasonable choice. -// -// The random parameter is used as a source of entropy to ensure that -// encrypting the same message twice doesn't result in the same ciphertext. -// -// The label parameter may contain arbitrary data that will not be encrypted, -// but which gives important context to the message. For example, if a given -// public key is used to decrypt two types of messages then distinct label -// values could be used to ensure that a ciphertext for one purpose cannot be -// used for another by an attacker. If not required it can be empty. -// -// The message must be no longer than the length of the public modulus less -// twice the hash length plus 2. -func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error) { - if err := checkPub(pub); err != nil { - return nil, err - } - hash.Reset() - k := (pub.N.BitLen() + 7) / 8 - if len(msg) > k-2*hash.Size()-2 { - err = ErrMessageTooLong - return - } - - hash.Write(label) - lHash := hash.Sum(nil) - hash.Reset() - - em := make([]byte, k) - seed := em[1 : 1+hash.Size()] - db := em[1+hash.Size():] - - copy(db[0:hash.Size()], lHash) - db[len(db)-len(msg)-1] = 1 - copy(db[len(db)-len(msg):], msg) - - _, err = io.ReadFull(random, seed) - if err != nil { - return - } - - mgf1XOR(db, hash, seed) - mgf1XOR(seed, hash, db) - - m := new(big.Int) - m.SetBytes(em) - c := encrypt(new(big.Int), pub, m) - out = c.Bytes() - - if len(out) < k { - // If the output is too small, we need to left-pad with zeros. - t := make([]byte, k) - copy(t[k-len(out):], out) - out = t - } - - return -} - -// ErrDecryption represents a failure to decrypt a message. -// It is deliberately vague to avoid adaptive attacks. -var ErrDecryption = errors.New("crypto/rsa: decryption error") - -// ErrVerification represents a failure to verify a signature. -// It is deliberately vague to avoid adaptive attacks. -var ErrVerification = errors.New("crypto/rsa: verification error") - -// modInverse returns ia, the inverse of a in the multiplicative group of prime -// order n. It requires that a be a member of the group (i.e. less than n). -func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { - g := new(big.Int) - x := new(big.Int) - y := new(big.Int) - g.GCD(x, y, a, n) - if g.Cmp(bigOne) != 0 { - // In this case, a and n aren't coprime and we cannot calculate - // the inverse. This happens because the values of n are nearly - // prime (being the product of two primes) rather than truly - // prime. - return - } - - if x.Cmp(bigOne) < 0 { - // 0 is not the multiplicative inverse of any element so, if x - // < 1, then x is negative. - x.Add(x, n) - } - - return x, true -} - -// Precompute performs some calculations that speed up private key operations -// in the future. -func (priv *PrivateKey) Precompute() { - if priv.Precomputed.Dp != nil { - return - } - - priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne) - priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp) - - priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne) - priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq) - - priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0]) - - r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1]) - priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2) - for i := 2; i < len(priv.Primes); i++ { - prime := priv.Primes[i] - values := &priv.Precomputed.CRTValues[i-2] - - values.Exp = new(big.Int).Sub(prime, bigOne) - values.Exp.Mod(priv.D, values.Exp) - - values.R = new(big.Int).Set(r) - values.Coeff = new(big.Int).ModInverse(r, prime) - - r.Mul(r, prime) - } -} - -// decrypt performs an RSA decryption, resulting in a plaintext integer. If a -// random source is given, RSA blinding is used. -func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) { - // TODO(agl): can we get away with reusing blinds? - if c.Cmp(priv.N) > 0 { - err = ErrDecryption - return - } - - var ir *big.Int - if random != nil { - // Blinding enabled. Blinding involves multiplying c by r^e. - // Then the decryption operation performs (m^e * r^e)^d mod n - // which equals mr mod n. The factor of r can then be removed - // by multiplying by the multiplicative inverse of r. - - var r *big.Int - - for { - r, err = rand.Int(random, priv.N) - if err != nil { - return - } - if r.Cmp(bigZero) == 0 { - r = bigOne - } - var ok bool - ir, ok = modInverse(r, priv.N) - if ok { - break - } - } - bigE := big.NewInt(int64(priv.E)) - rpowe := new(big.Int).Exp(r, bigE, priv.N) - cCopy := new(big.Int).Set(c) - cCopy.Mul(cCopy, rpowe) - cCopy.Mod(cCopy, priv.N) - c = cCopy - } - - if priv.Precomputed.Dp == nil { - m = new(big.Int).Exp(c, priv.D, priv.N) - } else { - // We have the precalculated values needed for the CRT. - m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) - m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) - m.Sub(m, m2) - if m.Sign() < 0 { - m.Add(m, priv.Primes[0]) - } - m.Mul(m, priv.Precomputed.Qinv) - m.Mod(m, priv.Primes[0]) - m.Mul(m, priv.Primes[1]) - m.Add(m, m2) - - for i, values := range priv.Precomputed.CRTValues { - prime := priv.Primes[2+i] - m2.Exp(c, values.Exp, prime) - m2.Sub(m2, m) - m2.Mul(m2, values.Coeff) - m2.Mod(m2, prime) - if m2.Sign() < 0 { - m2.Add(m2, prime) - } - m2.Mul(m2, values.R) - m.Add(m, m2) - } - } - - if ir != nil { - // Unblind. - m.Mul(m, ir) - m.Mod(m, priv.N) - } - - return -} - -func decryptAndCheck(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) { - m, err = decrypt(random, priv, c) - if err != nil { - return nil, err - } - - // In order to defend against errors in the CRT computation, m^e is - // calculated, which should match the original ciphertext. - check := encrypt(new(big.Int), &priv.PublicKey, m) - if c.Cmp(check) != 0 { - return nil, errors.New("rsa: internal error") - } - return m, nil -} - -// DecryptOAEP decrypts ciphertext using RSA-OAEP. - -// OAEP is parameterised by a hash function that is used as a random oracle. -// Encryption and decryption of a given message must use the same hash function -// and sha256.New() is a reasonable choice. -// -// The random parameter, if not nil, is used to blind the private-key operation -// and avoid timing side-channel attacks. Blinding is purely internal to this -// function – the random data need not match that used when encrypting. -// -// The label parameter must match the value given when encrypting. See -// EncryptOAEP for details. -func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return nil, err - } - k := (priv.N.BitLen() + 7) / 8 - if len(ciphertext) > k || - k < hash.Size()*2+2 { - err = ErrDecryption - return - } - - c := new(big.Int).SetBytes(ciphertext) - - m, err := decrypt(random, priv, c) - if err != nil { - return - } - - hash.Write(label) - lHash := hash.Sum(nil) - hash.Reset() - - // Converting the plaintext number to bytes will strip any - // leading zeros so we may have to left pad. We do this unconditionally - // to avoid leaking timing information. (Although we still probably - // leak the number of leading zeros. It's not clear that we can do - // anything about this.) - em := leftPad(m.Bytes(), k) - - firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0) - - seed := em[1 : hash.Size()+1] - db := em[hash.Size()+1:] - - mgf1XOR(seed, hash, db) - mgf1XOR(db, hash, seed) - - lHash2 := db[0:hash.Size()] - - // We have to validate the plaintext in constant time in order to avoid - // attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal - // Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1 - // v2.0. In J. Kilian, editor, Advances in Cryptology. - lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2) - - // The remainder of the plaintext must be zero or more 0x00, followed - // by 0x01, followed by the message. - // lookingForIndex: 1 iff we are still looking for the 0x01 - // index: the offset of the first 0x01 byte - // invalid: 1 iff we saw a non-zero byte before the 0x01. - var lookingForIndex, index, invalid int - lookingForIndex = 1 - rest := db[hash.Size():] - - for i := 0; i < len(rest); i++ { - equals0 := subtle.ConstantTimeByteEq(rest[i], 0) - equals1 := subtle.ConstantTimeByteEq(rest[i], 1) - index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex) - invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid) - } - - if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 { - err = ErrDecryption - return - } - - msg = rest[index+1:] - return -} - -// leftPad returns a new slice of length size. The contents of input are right -// aligned in the new slice. -func leftPad(input []byte, size int) (out []byte) { - n := len(input) - if n > size { - n = size - } - out = make([]byte, size) - copy(out[len(out)-n:], input) - return -} diff --git a/vendor/github.com/lib/pq/.gitignore b/vendor/github.com/lib/pq/.gitignore deleted file mode 100644 index 0f1d00e1..00000000 --- a/vendor/github.com/lib/pq/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.db -*.test -*~ -*.swp diff --git a/vendor/github.com/lib/pq/.travis.sh b/vendor/github.com/lib/pq/.travis.sh deleted file mode 100644 index a297dc45..00000000 --- a/vendor/github.com/lib/pq/.travis.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/bash - -set -eu - -client_configure() { - sudo chmod 600 $PQSSLCERTTEST_PATH/postgresql.key -} - -pgdg_repository() { - local sourcelist='sources.list.d/postgresql.list' - - curl -sS 'https://www.postgresql.org/media/keys/ACCC4CF8.asc' | sudo apt-key add - - echo deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main $PGVERSION | sudo tee "/etc/apt/$sourcelist" - sudo apt-get -o Dir::Etc::sourcelist="$sourcelist" -o Dir::Etc::sourceparts='-' -o APT::Get::List-Cleanup='0' update -} - -postgresql_configure() { - sudo tee /etc/postgresql/$PGVERSION/main/pg_hba.conf > /dev/null <<-config - local all all trust - hostnossl all pqgossltest 127.0.0.1/32 reject - hostnossl all pqgosslcert 127.0.0.1/32 reject - hostssl all pqgossltest 127.0.0.1/32 trust - hostssl all pqgosslcert 127.0.0.1/32 cert - host all all 127.0.0.1/32 trust - hostnossl all pqgossltest ::1/128 reject - hostnossl all pqgosslcert ::1/128 reject - hostssl all pqgossltest ::1/128 trust - hostssl all pqgosslcert ::1/128 cert - host all all ::1/128 trust - config - - xargs sudo install -o postgres -g postgres -m 600 -t /var/lib/postgresql/$PGVERSION/main/ <<-certificates - certs/root.crt - certs/server.crt - certs/server.key - certificates - - sort -VCu <<-versions || - $PGVERSION - 9.2 - versions - sudo tee -a /etc/postgresql/$PGVERSION/main/postgresql.conf > /dev/null <<-config - ssl_ca_file = 'root.crt' - ssl_cert_file = 'server.crt' - ssl_key_file = 'server.key' - config - - echo 127.0.0.1 postgres | sudo tee -a /etc/hosts > /dev/null - - sudo service postgresql restart -} - -postgresql_install() { - xargs sudo apt-get -y -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::='--force-confnew' install <<-packages - postgresql-$PGVERSION - postgresql-server-dev-$PGVERSION - postgresql-contrib-$PGVERSION - packages -} - -postgresql_uninstall() { - sudo service postgresql stop - xargs sudo apt-get -y --purge remove <<-packages - libpq-dev - libpq5 - postgresql - postgresql-client-common - postgresql-common - packages - sudo rm -rf /var/lib/postgresql -} - -megacheck_install() { - # Lock megacheck version at $MEGACHECK_VERSION to prevent spontaneous - # new error messages in old code. - go get -d honnef.co/go/tools/... - git -C $GOPATH/src/honnef.co/go/tools/ checkout $MEGACHECK_VERSION - go install honnef.co/go/tools/cmd/megacheck - megacheck --version -} - -golint_install() { - go get github.com/golang/lint/golint -} - -$1 diff --git a/vendor/github.com/lib/pq/.travis.yml b/vendor/github.com/lib/pq/.travis.yml deleted file mode 100644 index 18556e08..00000000 --- a/vendor/github.com/lib/pq/.travis.yml +++ /dev/null @@ -1,50 +0,0 @@ -language: go - -go: - - 1.8.x - - 1.9.x - - 1.10.x - - master - -sudo: true - -env: - global: - - PGUSER=postgres - - PQGOSSLTESTS=1 - - PQSSLCERTTEST_PATH=$PWD/certs - - PGHOST=127.0.0.1 - - MEGACHECK_VERSION=2017.2.2 - matrix: - - PGVERSION=10 - - PGVERSION=9.6 - - PGVERSION=9.5 - - PGVERSION=9.4 - - PGVERSION=9.3 - - PGVERSION=9.2 - - PGVERSION=9.1 - - PGVERSION=9.0 - -before_install: - - ./.travis.sh postgresql_uninstall - - ./.travis.sh pgdg_repository - - ./.travis.sh postgresql_install - - ./.travis.sh postgresql_configure - - ./.travis.sh client_configure - - ./.travis.sh megacheck_install - - ./.travis.sh golint_install - - go get golang.org/x/tools/cmd/goimports - -before_script: - - createdb pqgotest - - createuser -DRS pqgossltest - - createuser -DRS pqgosslcert - -script: - - > - goimports -d -e $(find -name '*.go') | awk '{ print } END { exit NR == 0 ? 0 : 1 }' - - go vet ./... - - megacheck -go 1.8 ./... - - golint ./... - - PQTEST_BINARY_PARAMETERS=no go test -race -v ./... - - PQTEST_BINARY_PARAMETERS=yes go test -race -v ./... diff --git a/vendor/github.com/lib/pq/CONTRIBUTING.md b/vendor/github.com/lib/pq/CONTRIBUTING.md deleted file mode 100644 index 84c937f1..00000000 --- a/vendor/github.com/lib/pq/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -## Contributing to pq - -`pq` has a backlog of pull requests, but contributions are still very -much welcome. You can help with patch review, submitting bug reports, -or adding new functionality. There is no formal style guide, but -please conform to the style of existing code and general Go formatting -conventions when submitting patches. - -### Patch review - -Help review existing open pull requests by commenting on the code or -proposed functionality. - -### Bug reports - -We appreciate any bug reports, but especially ones with self-contained -(doesn't depend on code outside of pq), minimal (can't be simplified -further) test cases. It's especially helpful if you can submit a pull -request with just the failing test case (you'll probably want to -pattern it after the tests in -[conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go). - -### New functionality - -There are a number of pending patches for new functionality, so -additional feature patches will take a while to merge. Still, patches -are generally reviewed based on usefulness and complexity in addition -to time-in-queue, so if you have a knockout idea, take a shot. Feel -free to open an issue discussion your proposed patch beforehand. diff --git a/vendor/github.com/lib/pq/LICENSE.md b/vendor/github.com/lib/pq/LICENSE.md deleted file mode 100644 index 5773904a..00000000 --- a/vendor/github.com/lib/pq/LICENSE.md +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2011-2013, 'pq' Contributors -Portions Copyright (C) 2011 Blake Mizerany - -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/lib/pq/README.md b/vendor/github.com/lib/pq/README.md deleted file mode 100644 index d71f3c2c..00000000 --- a/vendor/github.com/lib/pq/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# pq - A pure Go postgres driver for Go's database/sql package - -[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://godoc.org/github.com/lib/pq) -[![Build Status](https://travis-ci.org/lib/pq.svg?branch=master)](https://travis-ci.org/lib/pq) - -## Install - - go get github.com/lib/pq - -## Docs - -For detailed documentation and basic usage examples, please see the package -documentation at . - -## Tests - -`go test` is used for testing. See [TESTS.md](TESTS.md) for more details. - -## Features - -* SSL -* Handles bad connections for `database/sql` -* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`) -* Scan binary blobs correctly (i.e. `bytea`) -* Package for `hstore` support -* COPY FROM support -* pq.ParseURL for converting urls to connection strings for sql.Open. -* Many libpq compatible environment variables -* Unix socket support -* Notifications: `LISTEN`/`NOTIFY` -* pgpass support - -## Future / Things you can help with - -* Better COPY FROM / COPY TO (see discussion in #181) - -## Thank you (alphabetical) - -Some of these contributors are from the original library `bmizerany/pq.go` whose -code still exists in here. - -* Andy Balholm (andybalholm) -* Ben Berkert (benburkert) -* Benjamin Heatwole (bheatwole) -* Bill Mill (llimllib) -* Bjørn Madsen (aeons) -* Blake Gentry (bgentry) -* Brad Fitzpatrick (bradfitz) -* Charlie Melbye (cmelbye) -* Chris Bandy (cbandy) -* Chris Gilling (cgilling) -* Chris Walsh (cwds) -* Dan Sosedoff (sosedoff) -* Daniel Farina (fdr) -* Eric Chlebek (echlebek) -* Eric Garrido (minusnine) -* Eric Urban (hydrogen18) -* Everyone at The Go Team -* Evan Shaw (edsrzf) -* Ewan Chou (coocood) -* Fazal Majid (fazalmajid) -* Federico Romero (federomero) -* Fumin (fumin) -* Gary Burd (garyburd) -* Heroku (heroku) -* James Pozdena (jpoz) -* Jason McVetta (jmcvetta) -* Jeremy Jay (pbnjay) -* Joakim Sernbrant (serbaut) -* John Gallagher (jgallagher) -* Jonathan Rudenberg (titanous) -* Joël Stemmer (jstemmer) -* Kamil Kisiel (kisielk) -* Kelly Dunn (kellydunn) -* Keith Rarick (kr) -* Kir Shatrov (kirs) -* Lann Martin (lann) -* Maciek Sakrejda (uhoh-itsmaciek) -* Marc Brinkmann (mbr) -* Marko Tiikkaja (johto) -* Matt Newberry (MattNewberry) -* Matt Robenolt (mattrobenolt) -* Martin Olsen (martinolsen) -* Mike Lewis (mikelikespie) -* Nicolas Patry (Narsil) -* Oliver Tonnhofer (olt) -* Patrick Hayes (phayes) -* Paul Hammond (paulhammond) -* Ryan Smith (ryandotsmith) -* Samuel Stauffer (samuel) -* Timothée Peignier (cyberdelia) -* Travis Cline (tmc) -* TruongSinh Tran-Nguyen (truongsinh) -* Yaismel Miranda (ympons) -* notedit (notedit) diff --git a/vendor/github.com/lib/pq/TESTS.md b/vendor/github.com/lib/pq/TESTS.md deleted file mode 100644 index f0502111..00000000 --- a/vendor/github.com/lib/pq/TESTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# Tests - -## Running Tests - -`go test` is used for testing. A running PostgreSQL -server is required, with the ability to log in. The -database to connect to test with is "pqgotest," on -"localhost" but these can be overridden using [environment -variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html). - -Example: - - PGHOST=/run/postgresql go test - -## Benchmarks - -A benchmark suite can be run as part of the tests: - - go test -bench . - -## Example setup (Docker) - -Run a postgres container: - -``` -docker run --expose 5432:5432 postgres -``` - -Run tests: - -``` -PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test -``` diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go deleted file mode 100644 index e4933e22..00000000 --- a/vendor/github.com/lib/pq/array.go +++ /dev/null @@ -1,756 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql" - "database/sql/driver" - "encoding/hex" - "fmt" - "reflect" - "strconv" - "strings" -) - -var typeByteSlice = reflect.TypeOf([]byte{}) -var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() -var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() - -// Array returns the optimal driver.Valuer and sql.Scanner for an array or -// slice of any dimension. -// -// For example: -// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401})) -// -// var x []sql.NullInt64 -// db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x)) -// -// Scanning multi-dimensional arrays is not supported. Arrays where the lower -// bound is not one (such as `[0:0]={1}') are not supported. -func Array(a interface{}) interface { - driver.Valuer - sql.Scanner -} { - switch a := a.(type) { - case []bool: - return (*BoolArray)(&a) - case []float64: - return (*Float64Array)(&a) - case []int64: - return (*Int64Array)(&a) - case []string: - return (*StringArray)(&a) - - case *[]bool: - return (*BoolArray)(a) - case *[]float64: - return (*Float64Array)(a) - case *[]int64: - return (*Int64Array)(a) - case *[]string: - return (*StringArray)(a) - } - - return GenericArray{a} -} - -// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner -// to override the array delimiter used by GenericArray. -type ArrayDelimiter interface { - // ArrayDelimiter returns the delimiter character(s) for this element's type. - ArrayDelimiter() string -} - -// BoolArray represents a one-dimensional array of the PostgreSQL boolean type. -type BoolArray []bool - -// Scan implements the sql.Scanner interface. -func (a *BoolArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to BoolArray", src) -} - -func (a *BoolArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "BoolArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(BoolArray, len(elems)) - for i, v := range elems { - if len(v) != 1 { - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - switch v[0] { - case 't': - b[i] = true - case 'f': - b[i] = false - default: - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a BoolArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be exactly two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1+2*n) - - for i := 0; i < n; i++ { - b[2*i] = ',' - if a[i] { - b[1+2*i] = 't' - } else { - b[1+2*i] = 'f' - } - } - - b[0] = '{' - b[2*n] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type. -type ByteaArray [][]byte - -// Scan implements the sql.Scanner interface. -func (a *ByteaArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to ByteaArray", src) -} - -func (a *ByteaArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "ByteaArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(ByteaArray, len(elems)) - for i, v := range elems { - b[i], err = parseBytea(v) - if err != nil { - return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error()) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. It uses the "hex" format which -// is only supported on PostgreSQL 9.0 or newer. -func (a ByteaArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // 3*N bytes of hex formatting, and N-1 bytes of delimiters. - size := 1 + 6*n - for _, x := range a { - size += hex.EncodedLen(len(x)) - } - - b := make([]byte, size) - - for i, s := 0, b; i < n; i++ { - o := copy(s, `,"\\x`) - o += hex.Encode(s[o:], a[i]) - s[o] = '"' - s = s[o+1:] - } - - b[0] = '{' - b[size-1] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// Float64Array represents a one-dimensional array of the PostgreSQL double -// precision type. -type Float64Array []float64 - -// Scan implements the sql.Scanner interface. -func (a *Float64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Float64Array", src) -} - -func (a *Float64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Float64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Float64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseFloat(string(v), 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Float64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendFloat(b, a[0], 'f', -1, 64) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendFloat(b, a[i], 'f', -1, 64) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// GenericArray implements the driver.Valuer and sql.Scanner interfaces for -// an array or slice of any dimension. -type GenericArray struct{ A interface{} } - -func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { - var assign func([]byte, reflect.Value) error - var del = "," - - // TODO calculate the assign function for other types - // TODO repeat this section on the element type of arrays or slices (multidimensional) - { - if reflect.PtrTo(rt).Implements(typeSQLScanner) { - // dest is always addressable because it is an element of a slice. - assign = func(src []byte, dest reflect.Value) (err error) { - ss := dest.Addr().Interface().(sql.Scanner) - if src == nil { - err = ss.Scan(nil) - } else { - err = ss.Scan(src) - } - return - } - goto FoundType - } - - assign = func([]byte, reflect.Value) error { - return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt) - } - } - -FoundType: - - if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - return rt, assign, del -} - -// Scan implements the sql.Scanner interface. -func (a GenericArray) Scan(src interface{}) error { - dpv := reflect.ValueOf(a.A) - switch { - case dpv.Kind() != reflect.Ptr: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - case dpv.IsNil(): - return fmt.Errorf("pq: destination %T is nil", a.A) - } - - dv := dpv.Elem() - switch dv.Kind() { - case reflect.Slice: - case reflect.Array: - default: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - } - - switch src := src.(type) { - case []byte: - return a.scanBytes(src, dv) - case string: - return a.scanBytes([]byte(src), dv) - case nil: - if dv.Kind() == reflect.Slice { - dv.Set(reflect.Zero(dv.Type())) - return nil - } - } - - return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type()) -} - -func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error { - dtype, assign, del := a.evaluateDestination(dv.Type().Elem()) - dims, elems, err := parseArray(src, []byte(del)) - if err != nil { - return err - } - - // TODO allow multidimensional - - if len(dims) > 1 { - return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented", - strings.Replace(fmt.Sprint(dims), " ", "][", -1)) - } - - // Treat a zero-dimensional array like an array with a single dimension of zero. - if len(dims) == 0 { - dims = append(dims, 0) - } - - for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() { - switch rt.Kind() { - case reflect.Slice: - case reflect.Array: - if rt.Len() != dims[i] { - return fmt.Errorf("pq: cannot convert ARRAY%s to %s", - strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type()) - } - default: - // TODO handle multidimensional - } - } - - values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems)) - for i, e := range elems { - if err := assign(e, values.Index(i)); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - - // TODO handle multidimensional - - switch dv.Kind() { - case reflect.Slice: - dv.Set(values.Slice(0, dims[0])) - case reflect.Array: - for i := 0; i < dims[0]; i++ { - dv.Index(i).Set(values.Index(i)) - } - } - - return nil -} - -// Value implements the driver.Valuer interface. -func (a GenericArray) Value() (driver.Value, error) { - if a.A == nil { - return nil, nil - } - - rv := reflect.ValueOf(a.A) - - switch rv.Kind() { - case reflect.Slice: - if rv.IsNil() { - return nil, nil - } - case reflect.Array: - default: - return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A) - } - - if n := rv.Len(); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 0, 1+2*n) - - b, _, err := appendArray(b, rv, n) - return string(b), err - } - - return "{}", nil -} - -// Int64Array represents a one-dimensional array of the PostgreSQL integer types. -type Int64Array []int64 - -// Scan implements the sql.Scanner interface. -func (a *Int64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Int64Array", src) -} - -func (a *Int64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Int64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Int64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Int64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendInt(b, a[0], 10) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendInt(b, a[i], 10) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// StringArray represents a one-dimensional array of the PostgreSQL character types. -type StringArray []string - -// Scan implements the sql.Scanner interface. -func (a *StringArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to StringArray", src) -} - -func (a *StringArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "StringArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(StringArray, len(elems)) - for i, v := range elems { - if b[i] = string(v); v == nil { - return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a StringArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+3*n) - b[0] = '{' - - b = appendArrayQuotedBytes(b, []byte(a[0])) - for i := 1; i < n; i++ { - b = append(b, ',') - b = appendArrayQuotedBytes(b, []byte(a[i])) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// appendArray appends rv to the buffer, returning the extended buffer and -// the delimiter used between elements. -// -// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice. -func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) { - var del string - var err error - - b = append(b, '{') - - if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil { - return b, del, err - } - - for i := 1; i < n; i++ { - b = append(b, del...) - if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil { - return b, del, err - } - } - - return append(b, '}'), del, nil -} - -// appendArrayElement appends rv to the buffer, returning the extended buffer -// and the delimiter to use before the next element. -// -// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted -// using driver.DefaultParameterConverter and the resulting []byte or string -// is double-quoted. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { - if k := rv.Kind(); k == reflect.Array || k == reflect.Slice { - if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) { - if n := rv.Len(); n > 0 { - return appendArray(b, rv, n) - } - - return b, "", nil - } - } - - var del = "," - var err error - var iv interface{} = rv.Interface() - - if ad, ok := iv.(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil { - return b, del, err - } - - switch v := iv.(type) { - case nil: - return append(b, "NULL"...), del, nil - case []byte: - return appendArrayQuotedBytes(b, v), del, nil - case string: - return appendArrayQuotedBytes(b, []byte(v)), del, nil - } - - b, err = appendValue(b, iv) - return b, del, err -} - -func appendArrayQuotedBytes(b, v []byte) []byte { - b = append(b, '"') - for { - i := bytes.IndexAny(v, `"\`) - if i < 0 { - b = append(b, v...) - break - } - if i > 0 { - b = append(b, v[:i]...) - } - b = append(b, '\\', v[i]) - v = v[i+1:] - } - return append(b, '"') -} - -func appendValue(b []byte, v driver.Value) ([]byte, error) { - return append(b, encode(nil, v, 0)...), nil -} - -// parseArray extracts the dimensions and elements of an array represented in -// text format. Only representations emitted by the backend are supported. -// Notably, whitespace around brackets and delimiters is significant, and NULL -// is case-sensitive. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) { - var depth, i int - - if len(src) < 1 || src[0] != '{' { - return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0) - } - -Open: - for i < len(src) { - switch src[i] { - case '{': - depth++ - i++ - case '}': - elems = make([][]byte, 0) - goto Close - default: - break Open - } - } - dims = make([]int, i) - -Element: - for i < len(src) { - switch src[i] { - case '{': - if depth == len(dims) { - break Element - } - depth++ - dims[depth-1] = 0 - i++ - case '"': - var elem = []byte{} - var escape bool - for i++; i < len(src); i++ { - if escape { - elem = append(elem, src[i]) - escape = false - } else { - switch src[i] { - default: - elem = append(elem, src[i]) - case '\\': - escape = true - case '"': - elems = append(elems, elem) - i++ - break Element - } - } - } - default: - for start := i; i < len(src); i++ { - if bytes.HasPrefix(src[i:], del) || src[i] == '}' { - elem := src[start:i] - if len(elem) == 0 { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - if bytes.Equal(elem, []byte("NULL")) { - elem = nil - } - elems = append(elems, elem) - break Element - } - } - } - } - - for i < len(src) { - if bytes.HasPrefix(src[i:], del) && depth > 0 { - dims[depth-1]++ - i += len(del) - goto Element - } else if src[i] == '}' && depth > 0 { - dims[depth-1]++ - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - -Close: - for i < len(src) { - if src[i] == '}' && depth > 0 { - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - if depth > 0 { - err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i) - } - if err == nil { - for _, d := range dims { - if (len(elems) % d) != 0 { - err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions") - } - } - } - return -} - -func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) { - dims, elems, err := parseArray(src, del) - if err != nil { - return nil, err - } - if len(dims) > 1 { - return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ) - } - return elems, err -} diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go deleted file mode 100644 index 666b0012..00000000 --- a/vendor/github.com/lib/pq/buf.go +++ /dev/null @@ -1,91 +0,0 @@ -package pq - -import ( - "bytes" - "encoding/binary" - - "github.com/lib/pq/oid" -) - -type readBuf []byte - -func (b *readBuf) int32() (n int) { - n = int(int32(binary.BigEndian.Uint32(*b))) - *b = (*b)[4:] - return -} - -func (b *readBuf) oid() (n oid.Oid) { - n = oid.Oid(binary.BigEndian.Uint32(*b)) - *b = (*b)[4:] - return -} - -// N.B: this is actually an unsigned 16-bit integer, unlike int32 -func (b *readBuf) int16() (n int) { - n = int(binary.BigEndian.Uint16(*b)) - *b = (*b)[2:] - return -} - -func (b *readBuf) string() string { - i := bytes.IndexByte(*b, 0) - if i < 0 { - errorf("invalid message format; expected string terminator") - } - s := (*b)[:i] - *b = (*b)[i+1:] - return string(s) -} - -func (b *readBuf) next(n int) (v []byte) { - v = (*b)[:n] - *b = (*b)[n:] - return -} - -func (b *readBuf) byte() byte { - return b.next(1)[0] -} - -type writeBuf struct { - buf []byte - pos int -} - -func (b *writeBuf) int32(n int) { - x := make([]byte, 4) - binary.BigEndian.PutUint32(x, uint32(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) int16(n int) { - x := make([]byte, 2) - binary.BigEndian.PutUint16(x, uint16(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) string(s string) { - b.buf = append(b.buf, (s + "\000")...) -} - -func (b *writeBuf) byte(c byte) { - b.buf = append(b.buf, c) -} - -func (b *writeBuf) bytes(v []byte) { - b.buf = append(b.buf, v...) -} - -func (b *writeBuf) wrap() []byte { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - return b.buf -} - -func (b *writeBuf) next(c byte) { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - b.pos = len(b.buf) + 1 - b.buf = append(b.buf, c, 0, 0, 0, 0) -} diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go deleted file mode 100644 index 43c8df29..00000000 --- a/vendor/github.com/lib/pq/conn.go +++ /dev/null @@ -1,1854 +0,0 @@ -package pq - -import ( - "bufio" - "crypto/md5" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "os" - "os/user" - "path" - "path/filepath" - "strconv" - "strings" - "time" - "unicode" - - "github.com/lib/pq/oid" -) - -// Common error types -var ( - ErrNotSupported = errors.New("pq: Unsupported command") - ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") - ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") - ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less") - ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly") - - errUnexpectedReady = errors.New("unexpected ReadyForQuery") - errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") - errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") -) - -// Driver is the Postgres database driver. -type Driver struct{} - -// Open opens a new connection to the database. name is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func (d *Driver) Open(name string) (driver.Conn, error) { - return Open(name) -} - -func init() { - sql.Register("postgres", &Driver{}) -} - -type parameterStatus struct { - // server version in the same format as server_version_num, or 0 if - // unavailable - serverVersion int - - // the current location based on the TimeZone value of the session, if - // available - currentLocation *time.Location -} - -type transactionStatus byte - -const ( - txnStatusIdle transactionStatus = 'I' - txnStatusIdleInTransaction transactionStatus = 'T' - txnStatusInFailedTransaction transactionStatus = 'E' -) - -func (s transactionStatus) String() string { - switch s { - case txnStatusIdle: - return "idle" - case txnStatusIdleInTransaction: - return "idle in transaction" - case txnStatusInFailedTransaction: - return "in a failed transaction" - default: - errorf("unknown transactionStatus %d", s) - } - - panic("not reached") -} - -// Dialer is the dialer interface. It can be used to obtain more control over -// how pq creates network connections. -type Dialer interface { - Dial(network, address string) (net.Conn, error) - DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) -} - -type defaultDialer struct{} - -func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) { - return net.Dial(ntw, addr) -} -func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) { - return net.DialTimeout(ntw, addr, timeout) -} - -type conn struct { - c net.Conn - buf *bufio.Reader - namei int - scratch [512]byte - txnStatus transactionStatus - txnFinish func() - - // Save connection arguments to use during CancelRequest. - dialer Dialer - opts values - - // Cancellation key data for use with CancelRequest messages. - processID int - secretKey int - - parameterStatus parameterStatus - - saveMessageType byte - saveMessageBuffer []byte - - // If true, this connection is bad and all public-facing functions should - // return ErrBadConn. - bad bool - - // If set, this connection should never use the binary format when - // receiving query results from prepared statements. Only provided for - // debugging. - disablePreparedBinaryResult bool - - // Whether to always send []byte parameters over as binary. Enables single - // round-trip mode for non-prepared Query calls. - binaryParameters bool - - // If true this connection is in the middle of a COPY - inCopy bool -} - -// Handle driver-side settings in parsed connection string. -func (cn *conn) handleDriverSettings(o values) (err error) { - boolSetting := func(key string, val *bool) error { - if value, ok := o[key]; ok { - if value == "yes" { - *val = true - } else if value == "no" { - *val = false - } else { - return fmt.Errorf("unrecognized value %q for %s", value, key) - } - } - return nil - } - - err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult) - if err != nil { - return err - } - return boolSetting("binary_parameters", &cn.binaryParameters) -} - -func (cn *conn) handlePgpass(o values) { - // if a password was supplied, do not process .pgpass - if _, ok := o["password"]; ok { - return - } - filename := os.Getenv("PGPASSFILE") - if filename == "" { - // XXX this code doesn't work on Windows where the default filename is - // XXX %APPDATA%\postgresql\pgpass.conf - // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 - userHome := os.Getenv("HOME") - if userHome == "" { - user, err := user.Current() - if err != nil { - return - } - userHome = user.HomeDir - } - filename = filepath.Join(userHome, ".pgpass") - } - fileinfo, err := os.Stat(filename) - if err != nil { - return - } - mode := fileinfo.Mode() - if mode&(0x77) != 0 { - // XXX should warn about incorrect .pgpass permissions as psql does - return - } - file, err := os.Open(filename) - if err != nil { - return - } - defer file.Close() - scanner := bufio.NewScanner(io.Reader(file)) - hostname := o["host"] - ntw, _ := network(o) - port := o["port"] - db := o["dbname"] - username := o["user"] - // From: https://github.com/tg/pgpass/blob/master/reader.go - getFields := func(s string) []string { - fs := make([]string, 0, 5) - f := make([]rune, 0, len(s)) - - var esc bool - for _, c := range s { - switch { - case esc: - f = append(f, c) - esc = false - case c == '\\': - esc = true - case c == ':': - fs = append(fs, string(f)) - f = f[:0] - default: - f = append(f, c) - } - } - return append(fs, string(f)) - } - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 || line[0] == '#' { - continue - } - split := getFields(line) - if len(split) != 5 { - continue - } - if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) { - o["password"] = split[4] - return - } - } -} - -func (cn *conn) writeBuf(b byte) *writeBuf { - cn.scratch[0] = b - return &writeBuf{ - buf: cn.scratch[:5], - pos: 1, - } -} - -// Open opens a new connection to the database. name is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func Open(name string) (_ driver.Conn, err error) { - return DialOpen(defaultDialer{}, name) -} - -// DialOpen opens a new connection to the database using a dialer. -func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { - // Handle any panics during connection initialization. Note that we - // specifically do *not* want to use errRecover(), as that would turn any - // connection errors into ErrBadConns, hiding the real error message from - // the user. - defer errRecoverNoErrBadConn(&err) - - o := make(values) - - // A number of defaults are applied here, in this order: - // - // * Very low precedence defaults applied in every situation - // * Environment variables - // * Explicitly passed connection information - o["host"] = "localhost" - o["port"] = "5432" - // N.B.: Extra float digits should be set to 3, but that breaks - // Postgres 8.4 and older, where the max is 2. - o["extra_float_digits"] = "2" - for k, v := range parseEnviron(os.Environ()) { - o[k] = v - } - - if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") { - name, err = ParseURL(name) - if err != nil { - return nil, err - } - } - - if err := parseOpts(name, o); err != nil { - return nil, err - } - - // Use the "fallback" application name if necessary - if fallback, ok := o["fallback_application_name"]; ok { - if _, ok := o["application_name"]; !ok { - o["application_name"] = fallback - } - } - - // We can't work with any client_encoding other than UTF-8 currently. - // However, we have historically allowed the user to set it to UTF-8 - // explicitly, and there's no reason to break such programs, so allow that. - // Note that the "options" setting could also set client_encoding, but - // parsing its value is not worth it. Instead, we always explicitly send - // client_encoding as a separate run-time parameter, which should override - // anything set in options. - if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) { - return nil, errors.New("client_encoding must be absent or 'UTF8'") - } - o["client_encoding"] = "UTF8" - // DateStyle needs a similar treatment. - if datestyle, ok := o["datestyle"]; ok { - if datestyle != "ISO, MDY" { - panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v", - "ISO, MDY", datestyle)) - } - } else { - o["datestyle"] = "ISO, MDY" - } - - // If a user is not provided by any other means, the last - // resort is to use the current operating system provided user - // name. - if _, ok := o["user"]; !ok { - u, err := userCurrent() - if err != nil { - return nil, err - } - o["user"] = u - } - - cn := &conn{ - opts: o, - dialer: d, - } - err = cn.handleDriverSettings(o) - if err != nil { - return nil, err - } - cn.handlePgpass(o) - - cn.c, err = dial(d, o) - if err != nil { - return nil, err - } - - err = cn.ssl(o) - if err != nil { - return nil, err - } - - // cn.startup panics on error. Make sure we don't leak cn.c. - panicking := true - defer func() { - if panicking { - cn.c.Close() - } - }() - - cn.buf = bufio.NewReader(cn.c) - cn.startup(o) - - // reset the deadline, in case one was set (see dial) - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - err = cn.c.SetDeadline(time.Time{}) - } - panicking = false - return cn, err -} - -func dial(d Dialer, o values) (net.Conn, error) { - ntw, addr := network(o) - // SSL is not necessary or supported over UNIX domain sockets - if ntw == "unix" { - o["sslmode"] = "disable" - } - - // Zero or not specified means wait indefinitely. - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - seconds, err := strconv.ParseInt(timeout, 10, 0) - if err != nil { - return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) - } - duration := time.Duration(seconds) * time.Second - // connect_timeout should apply to the entire connection establishment - // procedure, so we both use a timeout for the TCP connection - // establishment and set a deadline for doing the initial handshake. - // The deadline is then reset after startup() is done. - deadline := time.Now().Add(duration) - conn, err := d.DialTimeout(ntw, addr, duration) - if err != nil { - return nil, err - } - err = conn.SetDeadline(deadline) - return conn, err - } - return d.Dial(ntw, addr) -} - -func network(o values) (string, string) { - host := o["host"] - - if strings.HasPrefix(host, "/") { - sockPath := path.Join(host, ".s.PGSQL."+o["port"]) - return "unix", sockPath - } - - return "tcp", net.JoinHostPort(host, o["port"]) -} - -type values map[string]string - -// scanner implements a tokenizer for libpq-style option strings. -type scanner struct { - s []rune - i int -} - -// newScanner returns a new scanner initialized with the option string s. -func newScanner(s string) *scanner { - return &scanner{[]rune(s), 0} -} - -// Next returns the next rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) Next() (rune, bool) { - if s.i >= len(s.s) { - return 0, false - } - r := s.s[s.i] - s.i++ - return r, true -} - -// SkipSpaces returns the next non-whitespace rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) SkipSpaces() (rune, bool) { - r, ok := s.Next() - for unicode.IsSpace(r) && ok { - r, ok = s.Next() - } - return r, ok -} - -// parseOpts parses the options from name and adds them to the values. -// -// The parsing code is based on conninfo_parse from libpq's fe-connect.c -func parseOpts(name string, o values) error { - s := newScanner(name) - - for { - var ( - keyRunes, valRunes []rune - r rune - ok bool - ) - - if r, ok = s.SkipSpaces(); !ok { - break - } - - // Scan the key - for !unicode.IsSpace(r) && r != '=' { - keyRunes = append(keyRunes, r) - if r, ok = s.Next(); !ok { - break - } - } - - // Skip any whitespace if we're not at the = yet - if r != '=' { - r, ok = s.SkipSpaces() - } - - // The current character should be = - if r != '=' || !ok { - return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) - } - - // Skip any whitespace after the = - if r, ok = s.SkipSpaces(); !ok { - // If we reach the end here, the last value is just an empty string as per libpq. - o[string(keyRunes)] = "" - break - } - - if r != '\'' { - for !unicode.IsSpace(r) { - if r == '\\' { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`missing character after backslash`) - } - } - valRunes = append(valRunes, r) - - if r, ok = s.Next(); !ok { - break - } - } - } else { - quote: - for { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`unterminated quoted string literal in connection string`) - } - switch r { - case '\'': - break quote - case '\\': - r, _ = s.Next() - fallthrough - default: - valRunes = append(valRunes, r) - } - } - } - - o[string(keyRunes)] = string(valRunes) - } - - return nil -} - -func (cn *conn) isInTransaction() bool { - return cn.txnStatus == txnStatusIdleInTransaction || - cn.txnStatus == txnStatusInFailedTransaction -} - -func (cn *conn) checkIsInTransaction(intxn bool) { - if cn.isInTransaction() != intxn { - cn.bad = true - errorf("unexpected transaction status %v", cn.txnStatus) - } -} - -func (cn *conn) Begin() (_ driver.Tx, err error) { - return cn.begin("") -} - -func (cn *conn) begin(mode string) (_ driver.Tx, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(false) - _, commandTag, err := cn.simpleExec("BEGIN" + mode) - if err != nil { - return nil, err - } - if commandTag != "BEGIN" { - cn.bad = true - return nil, fmt.Errorf("unexpected command tag %s", commandTag) - } - if cn.txnStatus != txnStatusIdleInTransaction { - cn.bad = true - return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) - } - return cn, nil -} - -func (cn *conn) closeTxn() { - if finish := cn.txnFinish; finish != nil { - finish() - } -} - -func (cn *conn) Commit() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(true) - // We don't want the client to think that everything is okay if it tries - // to commit a failed transaction. However, no matter what we return, - // database/sql will release this connection back into the free connection - // pool so we have to abort the current transaction here. Note that you - // would get the same behaviour if you issued a COMMIT in a failed - // transaction, so it's also the least surprising thing to do here. - if cn.txnStatus == txnStatusInFailedTransaction { - if err := cn.Rollback(); err != nil { - return err - } - return ErrInFailedTransaction - } - - _, commandTag, err := cn.simpleExec("COMMIT") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "COMMIT" { - cn.bad = true - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) Rollback() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(true) - _, commandTag, err := cn.simpleExec("ROLLBACK") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "ROLLBACK" { - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) gname() string { - cn.namei++ - return strconv.FormatInt(int64(cn.namei), 10) -} - -func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C': - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - // done - return - case 'E': - err = parseError(r) - case 'I': - res = emptyRows - case 'T', 'D': - // ignore any results - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -func (cn *conn) simpleQuery(q string) (res *rows, err error) { - defer cn.errRecover(&err) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C', 'I': - // We allow queries which don't return any results through Query as - // well as Exec. We still have to give database/sql a rows object - // the user can close, though, to avoid connections from being - // leaked. A "rows" with done=true works fine for that purpose. - if err != nil { - cn.bad = true - errorf("unexpected message %q in simple query execution", t) - } - if res == nil { - res = &rows{ - cn: cn, - } - } - // Set the result and tag to the last command complete if there wasn't a - // query already run. Although queries usually return from here and cede - // control to Next, a query with zero results does not. - if t == 'C' && res.colNames == nil { - res.result, res.tag = cn.parseComplete(r.string()) - } - res.done = true - case 'Z': - cn.processReadyForQuery(r) - // done - return - case 'E': - res = nil - err = parseError(r) - case 'D': - if res == nil { - cn.bad = true - errorf("unexpected DataRow in simple query execution") - } - // the query didn't fail; kick off to Next - cn.saveMessage(t, r) - return - case 'T': - // res might be non-nil here if we received a previous - // CommandComplete, but that's fine; just overwrite it - res = &rows{cn: cn} - res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r) - - // To work around a bug in QueryRow in Go 1.2 and earlier, wait - // until the first DataRow has been received. - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -type noRows struct{} - -var emptyRows noRows - -var _ driver.Result = noRows{} - -func (noRows) LastInsertId() (int64, error) { - return 0, errNoLastInsertID -} - -func (noRows) RowsAffected() (int64, error) { - return 0, errNoRowsAffected -} - -// Decides which column formats to use for a prepared statement. The input is -// an array of type oids, one element per result column. -func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) { - if len(colTyps) == 0 { - return nil, colFmtDataAllText - } - - colFmts = make([]format, len(colTyps)) - if forceText { - return colFmts, colFmtDataAllText - } - - allBinary := true - allText := true - for i, t := range colTyps { - switch t.OID { - // This is the list of types to use binary mode for when receiving them - // through a prepared statement. If a type appears in this list, it - // must also be implemented in binaryDecode in encode.go. - case oid.T_bytea: - fallthrough - case oid.T_int8: - fallthrough - case oid.T_int4: - fallthrough - case oid.T_int2: - fallthrough - case oid.T_uuid: - colFmts[i] = formatBinary - allText = false - - default: - allBinary = false - } - } - - if allBinary { - return colFmts, colFmtDataAllBinary - } else if allText { - return colFmts, colFmtDataAllText - } else { - colFmtData = make([]byte, 2+len(colFmts)*2) - binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) - for i, v := range colFmts { - binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) - } - return colFmts, colFmtData - } -} - -func (cn *conn) prepareTo(q, stmtName string) *stmt { - st := &stmt{cn: cn, name: stmtName} - - b := cn.writeBuf('P') - b.string(st.name) - b.string(q) - b.int16(0) - - b.next('D') - b.byte('S') - b.string(st.name) - - b.next('S') - cn.send(b) - - cn.readParseResponse() - st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() - st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) - cn.readReadyForQuery() - return st -} - -func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { - s, err := cn.prepareCopyIn(q) - if err == nil { - cn.inCopy = true - } - return s, err - } - return cn.prepareTo(q, cn.gname()), nil -} - -func (cn *conn) Close() (err error) { - // Skip cn.bad return here because we always want to close a connection. - defer cn.errRecover(&err) - - // Ensure that cn.c.Close is always run. Since error handling is done with - // panics and cn.errRecover, the Close must be in a defer. - defer func() { - cerr := cn.c.Close() - if err == nil { - err = cerr - } - }() - - // Don't go through send(); ListenerConn relies on us not scribbling on the - // scratch buffer of this connection. - return cn.sendSimpleMessage('X') -} - -// Implement the "Queryer" interface -func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { - return cn.query(query, args) -} - -func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - if cn.inCopy { - return nil, errCopyInProgress - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleQuery" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - return cn.simpleQuery(query) - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - rows := &rows{cn: cn} - rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - return rows, nil - } - st := cn.prepareTo(query, "") - st.exec(args) - return &rows{ - cn: cn, - colNames: st.colNames, - colTyps: st.colTyps, - colFmts: st.colFmts, - }, nil -} - -// Implement the optional "Execer" interface for one-shot queries -func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleExec" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - // ignore commandTag, our caller doesn't care - r, _, err := cn.simpleExec(query) - return r, err - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - res, _, err = cn.readExecuteResponse("Execute") - return res, err - } - // Use the unnamed statement to defer planning until bind - // time, or else value-based selectivity estimates cannot be - // used. - st := cn.prepareTo(query, "") - r, err := st.Exec(args) - if err != nil { - panic(err) - } - return r, err -} - -func (cn *conn) send(m *writeBuf) { - _, err := cn.c.Write(m.wrap()) - if err != nil { - panic(err) - } -} - -func (cn *conn) sendStartupPacket(m *writeBuf) error { - _, err := cn.c.Write((m.wrap())[1:]) - return err -} - -// Send a message of type typ to the server on the other end of cn. The -// message should have no payload. This method does not use the scratch -// buffer. -func (cn *conn) sendSimpleMessage(typ byte) (err error) { - _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) - return err -} - -// saveMessage memorizes a message and its buffer in the conn struct. -// recvMessage will then return these values on the next call to it. This -// method is useful in cases where you have to see what the next message is -// going to be (e.g. to see whether it's an error or not) but you can't handle -// the message yourself. -func (cn *conn) saveMessage(typ byte, buf *readBuf) { - if cn.saveMessageType != 0 { - cn.bad = true - errorf("unexpected saveMessageType %d", cn.saveMessageType) - } - cn.saveMessageType = typ - cn.saveMessageBuffer = *buf -} - -// recvMessage receives any message from the backend, or returns an error if -// a problem occurred while reading the message. -func (cn *conn) recvMessage(r *readBuf) (byte, error) { - // workaround for a QueryRow bug, see exec - if cn.saveMessageType != 0 { - t := cn.saveMessageType - *r = cn.saveMessageBuffer - cn.saveMessageType = 0 - cn.saveMessageBuffer = nil - return t, nil - } - - x := cn.scratch[:5] - _, err := io.ReadFull(cn.buf, x) - if err != nil { - return 0, err - } - - // read the type and length of the message that follows - t := x[0] - n := int(binary.BigEndian.Uint32(x[1:])) - 4 - var y []byte - if n <= len(cn.scratch) { - y = cn.scratch[:n] - } else { - y = make([]byte, n) - } - _, err = io.ReadFull(cn.buf, y) - if err != nil { - return 0, err - } - *r = y - return t, nil -} - -// recv receives a message from the backend, but if an error happened while -// reading the message or the received message was an ErrorResponse, it panics. -// NoticeResponses are ignored. This function should generally be used only -// during the startup sequence. -func (cn *conn) recv() (t byte, r *readBuf) { - for { - var err error - r = &readBuf{} - t, err = cn.recvMessage(r) - if err != nil { - panic(err) - } - - switch t { - case 'E': - panic(parseError(r)) - case 'N': - // ignore - default: - return - } - } -} - -// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by -// the caller to avoid an allocation. -func (cn *conn) recv1Buf(r *readBuf) byte { - for { - t, err := cn.recvMessage(r) - if err != nil { - panic(err) - } - - switch t { - case 'A', 'N': - // ignore - case 'S': - cn.processParameterStatus(r) - default: - return t - } - } -} - -// recv1 receives a message from the backend, panicking if an error occurs -// while attempting to read it. All asynchronous messages are ignored, with -// the exception of ErrorResponse. -func (cn *conn) recv1() (t byte, r *readBuf) { - r = &readBuf{} - t = cn.recv1Buf(r) - return t, r -} - -func (cn *conn) ssl(o values) error { - upgrade, err := ssl(o) - if err != nil { - return err - } - - if upgrade == nil { - // Nothing to do - return nil - } - - w := cn.writeBuf(0) - w.int32(80877103) - if err = cn.sendStartupPacket(w); err != nil { - return err - } - - b := cn.scratch[:1] - _, err = io.ReadFull(cn.c, b) - if err != nil { - return err - } - - if b[0] != 'S' { - return ErrSSLNotSupported - } - - cn.c, err = upgrade(cn.c) - return err -} - -// isDriverSetting returns true iff a setting is purely for configuring the -// driver's options and should not be sent to the server in the connection -// startup packet. -func isDriverSetting(key string) bool { - switch key { - case "host", "port": - return true - case "password": - return true - case "sslmode", "sslcert", "sslkey", "sslrootcert": - return true - case "fallback_application_name": - return true - case "connect_timeout": - return true - case "disable_prepared_binary_result": - return true - case "binary_parameters": - return true - - default: - return false - } -} - -func (cn *conn) startup(o values) { - w := cn.writeBuf(0) - w.int32(196608) - // Send the backend the name of the database we want to connect to, and the - // user we want to connect as. Additionally, we send over any run-time - // parameters potentially included in the connection string. If the server - // doesn't recognize any of them, it will reply with an error. - for k, v := range o { - if isDriverSetting(k) { - // skip options which can't be run-time parameters - continue - } - // The protocol requires us to supply the database name as "database" - // instead of "dbname". - if k == "dbname" { - k = "database" - } - w.string(k) - w.string(v) - } - w.string("") - if err := cn.sendStartupPacket(w); err != nil { - panic(err) - } - - for { - t, r := cn.recv() - switch t { - case 'K': - cn.processBackendKeyData(r) - case 'S': - cn.processParameterStatus(r) - case 'R': - cn.auth(r, o) - case 'Z': - cn.processReadyForQuery(r) - return - default: - errorf("unknown response for startup: %q", t) - } - } -} - -func (cn *conn) auth(r *readBuf, o values) { - switch code := r.int32(); code { - case 0: - // OK - case 3: - w := cn.writeBuf('p') - w.string(o["password"]) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - case 5: - s := string(r.next(4)) - w := cn.writeBuf('p') - w.string("md5" + md5s(md5s(o["password"]+o["user"])+s)) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - default: - errorf("unknown authentication response: %d", code) - } -} - -type format int - -const formatText format = 0 -const formatBinary format = 1 - -// One result-column format code with the value 1 (i.e. all binary). -var colFmtDataAllBinary = []byte{0, 1, 0, 1} - -// No result-column format codes (i.e. all text). -var colFmtDataAllText = []byte{0, 0} - -type stmt struct { - cn *conn - name string - colNames []string - colFmts []format - colFmtData []byte - colTyps []fieldDesc - paramTyps []oid.Oid - closed bool -} - -func (st *stmt) Close() (err error) { - if st.closed { - return nil - } - if st.cn.bad { - return driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - w := st.cn.writeBuf('C') - w.byte('S') - w.string(st.name) - st.cn.send(w) - - st.cn.send(st.cn.writeBuf('S')) - - t, _ := st.cn.recv1() - if t != '3' { - st.cn.bad = true - errorf("unexpected close response: %q", t) - } - st.closed = true - - t, r := st.cn.recv1() - if t != 'Z' { - st.cn.bad = true - errorf("expected ready for query, but got: %q", t) - } - st.cn.processReadyForQuery(r) - - return nil -} - -func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - return &rows{ - cn: st.cn, - colNames: st.colNames, - colTyps: st.colTyps, - colFmts: st.colFmts, - }, nil -} - -func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - res, _, err = st.cn.readExecuteResponse("simple query") - return res, err -} - -func (st *stmt) exec(v []driver.Value) { - if len(v) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) - } - if len(v) != len(st.paramTyps) { - errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) - } - - cn := st.cn - w := cn.writeBuf('B') - w.byte(0) // unnamed portal - w.string(st.name) - - if cn.binaryParameters { - cn.sendBinaryParameters(w, v) - } else { - w.int16(0) - w.int16(len(v)) - for i, x := range v { - if x == nil { - w.int32(-1) - } else { - b := encode(&cn.parameterStatus, x, st.paramTyps[i]) - w.int32(len(b)) - w.bytes(b) - } - } - } - w.bytes(st.colFmtData) - - w.next('E') - w.byte(0) - w.int32(0) - - w.next('S') - cn.send(w) - - cn.readBindResponse() - cn.postExecuteWorkaround() - -} - -func (st *stmt) NumInput() int { - return len(st.paramTyps) -} - -// parseComplete parses the "command tag" from a CommandComplete message, and -// returns the number of rows affected (if applicable) and a string -// identifying only the command that was executed, e.g. "ALTER TABLE". If the -// command tag could not be parsed, parseComplete panics. -func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { - commandsWithAffectedRows := []string{ - "SELECT ", - // INSERT is handled below - "UPDATE ", - "DELETE ", - "FETCH ", - "MOVE ", - "COPY ", - } - - var affectedRows *string - for _, tag := range commandsWithAffectedRows { - if strings.HasPrefix(commandTag, tag) { - t := commandTag[len(tag):] - affectedRows = &t - commandTag = tag[:len(tag)-1] - break - } - } - // INSERT also includes the oid of the inserted row in its command tag. - // Oids in user tables are deprecated, and the oid is only returned when - // exactly one row is inserted, so it's unlikely to be of value to any - // real-world application and we can ignore it. - if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { - parts := strings.Split(commandTag, " ") - if len(parts) != 3 { - cn.bad = true - errorf("unexpected INSERT command tag %s", commandTag) - } - affectedRows = &parts[len(parts)-1] - commandTag = "INSERT" - } - // There should be no affected rows attached to the tag, just return it - if affectedRows == nil { - return driver.RowsAffected(0), commandTag - } - n, err := strconv.ParseInt(*affectedRows, 10, 64) - if err != nil { - cn.bad = true - errorf("could not parse commandTag: %s", err) - } - return driver.RowsAffected(n), commandTag -} - -type rows struct { - cn *conn - finish func() - colNames []string - colTyps []fieldDesc - colFmts []format - done bool - rb readBuf - result driver.Result - tag string -} - -func (rs *rows) Close() error { - if finish := rs.finish; finish != nil { - defer finish() - } - // no need to look at cn.bad as Next() will - for { - err := rs.Next(nil) - switch err { - case nil: - case io.EOF: - // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row - // description, used with HasNextResultSet). We need to fetch messages until - // we hit a 'Z', which is done by waiting for done to be set. - if rs.done { - return nil - } - default: - return err - } - } -} - -func (rs *rows) Columns() []string { - return rs.colNames -} - -func (rs *rows) Result() driver.Result { - if rs.result == nil { - return emptyRows - } - return rs.result -} - -func (rs *rows) Tag() string { - return rs.tag -} - -func (rs *rows) Next(dest []driver.Value) (err error) { - if rs.done { - return io.EOF - } - - conn := rs.cn - if conn.bad { - return driver.ErrBadConn - } - defer conn.errRecover(&err) - - for { - t := conn.recv1Buf(&rs.rb) - switch t { - case 'E': - err = parseError(&rs.rb) - case 'C', 'I': - if t == 'C' { - rs.result, rs.tag = conn.parseComplete(rs.rb.string()) - } - continue - case 'Z': - conn.processReadyForQuery(&rs.rb) - rs.done = true - if err != nil { - return err - } - return io.EOF - case 'D': - n := rs.rb.int16() - if err != nil { - conn.bad = true - errorf("unexpected DataRow after error %s", err) - } - if n < len(dest) { - dest = dest[:n] - } - for i := range dest { - l := rs.rb.int32() - if l == -1 { - dest[i] = nil - continue - } - dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) - } - return - case 'T': - rs.colNames, rs.colFmts, rs.colTyps = parsePortalRowDescribe(&rs.rb) - return io.EOF - default: - errorf("unexpected message after execute: %q", t) - } - } -} - -func (rs *rows) HasNextResultSet() bool { - return !rs.done -} - -func (rs *rows) NextResultSet() error { - return nil -} - -// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be -// used as part of an SQL statement. For example: -// -// tblname := "my_table" -// data := "my_data" -// quoted := pq.QuoteIdentifier(tblname) -// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) -// -// Any double quotes in name will be escaped. The quoted identifier will be -// case sensitive when used in a query. If the input string contains a zero -// byte, the result will be truncated immediately before it. -func QuoteIdentifier(name string) string { - end := strings.IndexRune(name, 0) - if end > -1 { - name = name[:end] - } - return `"` + strings.Replace(name, `"`, `""`, -1) + `"` -} - -func md5s(s string) string { - h := md5.New() - h.Write([]byte(s)) - return fmt.Sprintf("%x", h.Sum(nil)) -} - -func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { - // Do one pass over the parameters to see if we're going to send any of - // them over in binary. If we are, create a paramFormats array at the - // same time. - var paramFormats []int - for i, x := range args { - _, ok := x.([]byte) - if ok { - if paramFormats == nil { - paramFormats = make([]int, len(args)) - } - paramFormats[i] = 1 - } - } - if paramFormats == nil { - b.int16(0) - } else { - b.int16(len(paramFormats)) - for _, x := range paramFormats { - b.int16(x) - } - } - - b.int16(len(args)) - for _, x := range args { - if x == nil { - b.int32(-1) - } else { - datum := binaryEncode(&cn.parameterStatus, x) - b.int32(len(datum)) - b.bytes(datum) - } - } -} - -func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { - if len(args) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) - } - - b := cn.writeBuf('P') - b.byte(0) // unnamed statement - b.string(query) - b.int16(0) - - b.next('B') - b.int16(0) // unnamed portal and statement - cn.sendBinaryParameters(b, args) - b.bytes(colFmtDataAllText) - - b.next('D') - b.byte('P') - b.byte(0) // unnamed portal - - b.next('E') - b.byte(0) - b.int32(0) - - b.next('S') - cn.send(b) -} - -func (cn *conn) processParameterStatus(r *readBuf) { - var err error - - param := r.string() - switch param { - case "server_version": - var major1 int - var major2 int - var minor int - _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) - if err == nil { - cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor - } - - case "TimeZone": - cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) - if err != nil { - cn.parameterStatus.currentLocation = nil - } - - default: - // ignore - } -} - -func (cn *conn) processReadyForQuery(r *readBuf) { - cn.txnStatus = transactionStatus(r.byte()) -} - -func (cn *conn) readReadyForQuery() { - t, r := cn.recv1() - switch t { - case 'Z': - cn.processReadyForQuery(r) - return - default: - cn.bad = true - errorf("unexpected message %q; expected ReadyForQuery", t) - } -} - -func (cn *conn) processBackendKeyData(r *readBuf) { - cn.processID = r.int32() - cn.secretKey = r.int32() -} - -func (cn *conn) readParseResponse() { - t, r := cn.recv1() - switch t { - case '1': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Parse response %q", t) - } -} - -func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) { - for { - t, r := cn.recv1() - switch t { - case 't': - nparams := r.int16() - paramTyps = make([]oid.Oid, nparams) - for i := range paramTyps { - paramTyps[i] = r.oid() - } - case 'n': - return paramTyps, nil, nil - case 'T': - colNames, colTyps = parseStatementRowDescribe(r) - return paramTyps, colNames, colTyps - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe statement response %q", t) - } - } -} - -func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []fieldDesc) { - t, r := cn.recv1() - switch t { - case 'T': - return parsePortalRowDescribe(r) - case 'n': - return nil, nil, nil - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe response %q", t) - } - panic("not reached") -} - -func (cn *conn) readBindResponse() { - t, r := cn.recv1() - switch t { - case '2': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Bind response %q", t) - } -} - -func (cn *conn) postExecuteWorkaround() { - // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores - // any errors from rows.Next, which masks errors that happened during the - // execution of the query. To avoid the problem in common cases, we wait - // here for one more message from the database. If it's not an error the - // query will likely succeed (or perhaps has already, if it's a - // CommandComplete), so we push the message into the conn struct; recv1 - // will return it as the next message for rows.Next or rows.Close. - // However, if it's an error, we wait until ReadyForQuery and then return - // the error to our caller. - for { - t, r := cn.recv1() - switch t { - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - case 'C', 'D', 'I': - // the query didn't fail, but we can't process this message - cn.saveMessage(t, r) - return - default: - cn.bad = true - errorf("unexpected message during extended query execution: %q", t) - } - } -} - -// Only for Exec(), since we ignore the returned data -func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { - for { - t, r := cn.recv1() - switch t { - case 'C': - if err != nil { - cn.bad = true - errorf("unexpected CommandComplete after error %s", err) - } - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - return res, commandTag, err - case 'E': - err = parseError(r) - case 'T', 'D', 'I': - if err != nil { - cn.bad = true - errorf("unexpected %q after error %s", t, err) - } - if t == 'I' { - res = emptyRows - } - // ignore any results - default: - cn.bad = true - errorf("unknown %s response: %q", protocolState, t) - } - } -} - -func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { - n := r.int16() - colNames = make([]string, n) - colTyps = make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - // format code not known when describing a statement; always 0 - r.next(2) - } - return -} - -func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []fieldDesc) { - n := r.int16() - colNames = make([]string, n) - colFmts = make([]format, n) - colTyps = make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - colFmts[i] = format(r.int16()) - } - return -} - -// parseEnviron tries to mimic some of libpq's environment handling -// -// To ease testing, it does not directly reference os.Environ, but is -// designed to accept its output. -// -// Environment-set connection information is intended to have a higher -// precedence than a library default but lower than any explicitly -// passed information (such as in the URL or connection string). -func parseEnviron(env []string) (out map[string]string) { - out = make(map[string]string) - - for _, v := range env { - parts := strings.SplitN(v, "=", 2) - - accrue := func(keyname string) { - out[keyname] = parts[1] - } - unsupported := func() { - panic(fmt.Sprintf("setting %v not supported", parts[0])) - } - - // The order of these is the same as is seen in the - // PostgreSQL 9.1 manual. Unsupported but well-defined - // keys cause a panic; these should be unset prior to - // execution. Options which pq expects to be set to a - // certain value are allowed, but must be set to that - // value if present (they can, of course, be absent). - switch parts[0] { - case "PGHOST": - accrue("host") - case "PGHOSTADDR": - unsupported() - case "PGPORT": - accrue("port") - case "PGDATABASE": - accrue("dbname") - case "PGUSER": - accrue("user") - case "PGPASSWORD": - accrue("password") - case "PGSERVICE", "PGSERVICEFILE", "PGREALM": - unsupported() - case "PGOPTIONS": - accrue("options") - case "PGAPPNAME": - accrue("application_name") - case "PGSSLMODE": - accrue("sslmode") - case "PGSSLCERT": - accrue("sslcert") - case "PGSSLKEY": - accrue("sslkey") - case "PGSSLROOTCERT": - accrue("sslrootcert") - case "PGREQUIRESSL", "PGSSLCRL": - unsupported() - case "PGREQUIREPEER": - unsupported() - case "PGKRBSRVNAME", "PGGSSLIB": - unsupported() - case "PGCONNECT_TIMEOUT": - accrue("connect_timeout") - case "PGCLIENTENCODING": - accrue("client_encoding") - case "PGDATESTYLE": - accrue("datestyle") - case "PGTZ": - accrue("timezone") - case "PGGEQO": - accrue("geqo") - case "PGSYSCONFDIR", "PGLOCALEDIR": - unsupported() - } - } - - return out -} - -// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". -func isUTF8(name string) bool { - // Recognize all sorts of silly things as "UTF-8", like Postgres does - s := strings.Map(alnumLowerASCII, name) - return s == "utf8" || s == "unicode" -} - -func alnumLowerASCII(ch rune) rune { - if 'A' <= ch && ch <= 'Z' { - return ch + ('a' - 'A') - } - if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { - return ch - } - return -1 // discard -} diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go deleted file mode 100644 index a5254f2b..00000000 --- a/vendor/github.com/lib/pq/conn_go18.go +++ /dev/null @@ -1,131 +0,0 @@ -// +build go1.8 - -package pq - -import ( - "context" - "database/sql" - "database/sql/driver" - "fmt" - "io" - "io/ioutil" -) - -// Implement the "QueryerContext" interface -func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - finish := cn.watchCancel(ctx) - r, err := cn.query(query, list) - if err != nil { - if finish != nil { - finish() - } - return nil, err - } - r.finish = finish - return r, nil -} - -// Implement the "ExecerContext" interface -func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - - if finish := cn.watchCancel(ctx); finish != nil { - defer finish() - } - - return cn.Exec(query, list) -} - -// Implement the "ConnBeginTx" interface -func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - var mode string - - switch sql.IsolationLevel(opts.Isolation) { - case sql.LevelDefault: - // Don't touch mode: use the server's default - case sql.LevelReadUncommitted: - mode = " ISOLATION LEVEL READ UNCOMMITTED" - case sql.LevelReadCommitted: - mode = " ISOLATION LEVEL READ COMMITTED" - case sql.LevelRepeatableRead: - mode = " ISOLATION LEVEL REPEATABLE READ" - case sql.LevelSerializable: - mode = " ISOLATION LEVEL SERIALIZABLE" - default: - return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation) - } - - if opts.ReadOnly { - mode += " READ ONLY" - } else { - mode += " READ WRITE" - } - - tx, err := cn.begin(mode) - if err != nil { - return nil, err - } - cn.txnFinish = cn.watchCancel(ctx) - return tx, nil -} - -func (cn *conn) watchCancel(ctx context.Context) func() { - if done := ctx.Done(); done != nil { - finished := make(chan struct{}) - go func() { - select { - case <-done: - _ = cn.cancel() - finished <- struct{}{} - case <-finished: - } - }() - return func() { - select { - case <-finished: - case finished <- struct{}{}: - } - } - } - return nil -} - -func (cn *conn) cancel() error { - c, err := dial(cn.dialer, cn.opts) - if err != nil { - return err - } - defer c.Close() - - { - can := conn{ - c: c, - } - err = can.ssl(cn.opts) - if err != nil { - return err - } - - w := can.writeBuf(0) - w.int32(80877102) // cancel request code - w.int32(cn.processID) - w.int32(cn.secretKey) - - if err := can.sendStartupPacket(w); err != nil { - return err - } - } - - // Read until EOF to ensure that the server received the cancel. - { - _, err := io.Copy(ioutil.Discard, c) - return err - } -} diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go deleted file mode 100644 index 9e66eb5d..00000000 --- a/vendor/github.com/lib/pq/connector.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build go1.10 - -package pq - -import ( - "context" - "database/sql/driver" -) - -// Connector represents a fixed configuration for the pq driver with a given -// name. Connector satisfies the database/sql/driver Connector interface and -// can be used to create any number of DB Conn's via the database/sql OpenDB -// function. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -type connector struct { - name string -} - -// Connect returns a connection to the database using the fixed configuration -// of this Connector. Context is not used. -func (c *connector) Connect(_ context.Context) (driver.Conn, error) { - return (&Driver{}).Open(c.name) -} - -// Driver returnst the underlying driver of this Connector. -func (c *connector) Driver() driver.Driver { - return &Driver{} -} - -var _ driver.Connector = &connector{} - -// NewConnector returns a connector for the pq driver in a fixed configuration -// with the given name. The returned connector can be used to create any number -// of equivalent Conn's. The returned connector is intended to be used with -// database/sql.OpenDB. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -func NewConnector(name string) (driver.Connector, error) { - return &connector{name: name}, nil -} diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go deleted file mode 100644 index 345c2398..00000000 --- a/vendor/github.com/lib/pq/copy.go +++ /dev/null @@ -1,282 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "sync" -) - -var ( - errCopyInClosed = errors.New("pq: copyin statement has already been closed") - errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") - errCopyToNotSupported = errors.New("pq: COPY TO is not supported") - errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") - errCopyInProgress = errors.New("pq: COPY in progress") -) - -// CopyIn creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). The target table should be visible in search_path. -func CopyIn(table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -// CopyInSchema creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). -func CopyInSchema(schema, table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -type copyin struct { - cn *conn - buffer []byte - rowData chan []byte - done chan bool - - closed bool - - sync.Mutex // guards err - err error -} - -const ciBufferSize = 64 * 1024 - -// flush buffer before the buffer is filled up and needs reallocation -const ciBufferFlushSize = 63 * 1024 - -func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) { - if !cn.isInTransaction() { - return nil, errCopyNotSupportedOutsideTxn - } - - ci := ©in{ - cn: cn, - buffer: make([]byte, 0, ciBufferSize), - rowData: make(chan []byte), - done: make(chan bool, 1), - } - // add CopyData identifier + 4 bytes for message length - ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - -awaitCopyInResponse: - for { - t, r := cn.recv1() - switch t { - case 'G': - if r.byte() != 0 { - err = errBinaryCopyNotSupported - break awaitCopyInResponse - } - go ci.resploop() - return ci, nil - case 'H': - err = errCopyToNotSupported - break awaitCopyInResponse - case 'E': - err = parseError(r) - case 'Z': - if err == nil { - ci.setBad() - errorf("unexpected ReadyForQuery in response to COPY") - } - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for copy query: %q", t) - } - } - - // something went wrong, abort COPY before we return - b = cn.writeBuf('f') - b.string(err.Error()) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'c', 'C', 'E': - case 'Z': - // correctly aborted, we're done - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for CopyFail: %q", t) - } - } -} - -func (ci *copyin) flush(buf []byte) { - // set message length (without message identifier) - binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) - - _, err := ci.cn.c.Write(buf) - if err != nil { - panic(err) - } -} - -func (ci *copyin) resploop() { - for { - var r readBuf - t, err := ci.cn.recvMessage(&r) - if err != nil { - ci.setBad() - ci.setError(err) - ci.done <- true - return - } - switch t { - case 'C': - // complete - case 'N': - // NoticeResponse - case 'Z': - ci.cn.processReadyForQuery(&r) - ci.done <- true - return - case 'E': - err := parseError(&r) - ci.setError(err) - default: - ci.setBad() - ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) - ci.done <- true - return - } - } -} - -func (ci *copyin) setBad() { - ci.Lock() - ci.cn.bad = true - ci.Unlock() -} - -func (ci *copyin) isBad() bool { - ci.Lock() - b := ci.cn.bad - ci.Unlock() - return b -} - -func (ci *copyin) isErrorSet() bool { - ci.Lock() - isSet := (ci.err != nil) - ci.Unlock() - return isSet -} - -// setError() sets ci.err if one has not been set already. Caller must not be -// holding ci.Mutex. -func (ci *copyin) setError(err error) { - ci.Lock() - if ci.err == nil { - ci.err = err - } - ci.Unlock() -} - -func (ci *copyin) NumInput() int { - return -1 -} - -func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { - return nil, ErrNotSupported -} - -// Exec inserts values into the COPY stream. The insert is asynchronous -// and Exec can return errors from previous Exec calls to the same -// COPY stmt. -// -// You need to call Exec(nil) to sync the COPY stream and to get any -// errors from pending data, since Stmt.Close() doesn't return errors -// to the user. -func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { - if ci.closed { - return nil, errCopyInClosed - } - - if ci.isBad() { - return nil, driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if ci.isErrorSet() { - return nil, ci.err - } - - if len(v) == 0 { - return nil, ci.Close() - } - - numValues := len(v) - for i, value := range v { - ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value) - if i < numValues-1 { - ci.buffer = append(ci.buffer, '\t') - } - } - - ci.buffer = append(ci.buffer, '\n') - - if len(ci.buffer) > ciBufferFlushSize { - ci.flush(ci.buffer) - // reset buffer, keep bytes for message identifier and length - ci.buffer = ci.buffer[:5] - } - - return driver.RowsAffected(0), nil -} - -func (ci *copyin) Close() (err error) { - if ci.closed { // Don't do anything, we're already closed - return nil - } - ci.closed = true - - if ci.isBad() { - return driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if len(ci.buffer) > 0 { - ci.flush(ci.buffer) - } - // Avoid touching the scratch buffer as resploop could be using it. - err = ci.cn.sendSimpleMessage('c') - if err != nil { - return err - } - - <-ci.done - ci.cn.inCopy = false - - if ci.isErrorSet() { - err = ci.err - return err - } - return nil -} diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go deleted file mode 100644 index a1b02971..00000000 --- a/vendor/github.com/lib/pq/doc.go +++ /dev/null @@ -1,245 +0,0 @@ -/* -Package pq is a pure Go Postgres driver for the database/sql package. - -In most cases clients will use the database/sql package instead of -using this package directly. For example: - - import ( - "database/sql" - - _ "github.com/lib/pq" - ) - - func main() { - connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - if err != nil { - log.Fatal(err) - } - - age := 21 - rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) - … - } - -You can also connect to a database using a URL. For example: - - connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - - -Connection String Parameters - - -Similarly to libpq, when establishing a connection using pq you are expected to -supply a connection string containing zero or more parameters. -A subset of the connection parameters supported by libpq are also supported by pq. -Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem) -directly in the connection string. This is different from libpq, which does not allow -run-time parameters in the connection string, instead requiring you to supply -them in the options parameter. - -For compatibility with libpq, the following special connection parameters are -supported: - - * dbname - The name of the database to connect to - * user - The user to sign in as - * password - The user's password - * host - The host to connect to. Values that start with / are for unix - domain sockets. (default is localhost) - * port - The port to bind to. (default is 5432) - * sslmode - Whether or not to use SSL (default is require, this is not - the default for libpq) - * fallback_application_name - An application_name to fall back to if one isn't provided. - * connect_timeout - Maximum wait for connection, in seconds. Zero or - not specified means wait indefinitely. - * sslcert - Cert file location. The file must contain PEM encoded data. - * sslkey - Key file location. The file must contain PEM encoded data. - * sslrootcert - The location of the root certificate file. The file - must contain PEM encoded data. - -Valid values for sslmode are: - - * disable - No SSL - * require - Always SSL (skip verification) - * verify-ca - Always SSL (verify that the certificate presented by the - server was signed by a trusted CA) - * verify-full - Always SSL (verify that the certification presented by - the server was signed by a trusted CA and the server host name - matches the one in the certificate) - -See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING -for more information about connection string parameters. - -Use single quotes for values that contain whitespace: - - "user=pqgotest password='with spaces'" - -A backslash will escape the next character in values: - - "user=space\ man password='it\'s valid'" - -Note that the connection parameter client_encoding (which sets the -text encoding for the connection) may be set but must be "UTF8", -matching with the same rules as Postgres. It is an error to provide -any other value. - -In addition to the parameters listed above, any run-time parameter that can be -set at backend start time can be set in the connection string. For more -information, see -http://www.postgresql.org/docs/current/static/runtime-config.html. - -Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html -supported by libpq are also supported by pq. If any of the environment -variables not supported by pq are set, pq will panic during connection -establishment. Environment variables have a lower precedence than explicitly -provided connection parameters. - -The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html -is supported, but on Windows PGPASSFILE must be specified explicitly. - - -Queries - - -database/sql does not dictate any specific format for parameter -markers in query strings, and pq uses the Postgres-native ordinal markers, -as shown above. The same marker can be reused for the same parameter: - - rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1 - OR age BETWEEN $2 AND $2 + 3`, "orange", 64) - -pq does not support the LastInsertId() method of the Result type in database/sql. -To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres -RETURNING clause with a standard Query or QueryRow call: - - var userid int - err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age) - VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid) - -For more details on RETURNING, see the Postgres documentation: - - http://www.postgresql.org/docs/current/static/sql-insert.html - http://www.postgresql.org/docs/current/static/sql-update.html - http://www.postgresql.org/docs/current/static/sql-delete.html - -For additional instructions on querying see the documentation for the database/sql package. - - -Data Types - - -Parameters pass through driver.DefaultParameterConverter before they are handled -by this package. When the binary_parameters connection option is enabled, -[]byte values are sent directly to the backend as data in binary format. - -This package returns the following types for values from the PostgreSQL backend: - - - integer types smallint, integer, and bigint are returned as int64 - - floating-point types real and double precision are returned as float64 - - character types char, varchar, and text are returned as string - - temporal types date, time, timetz, timestamp, and timestamptz are - returned as time.Time - - the boolean type is returned as bool - - the bytea type is returned as []byte - -All other types are returned directly from the backend as []byte values in text format. - - -Errors - - -pq may return errors of type *pq.Error which can be interrogated for error details: - - if err, ok := err.(*pq.Error); ok { - fmt.Println("pq error:", err.Code.Name()) - } - -See the pq.Error type for details. - - -Bulk imports - -You can perform bulk imports by preparing a statement returned by pq.CopyIn (or -pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement -handle can then be repeatedly "executed" to copy data into the target table. -After all data has been processed you should call Exec() once with no arguments -to flush all buffered data. Any call to Exec() might return an error which -should be handled appropriately, but because of the internal buffering an error -returned by Exec() might not be related to the data passed in the call that -failed. - -CopyIn uses COPY FROM internally. It is not possible to COPY outside of an -explicit transaction in pq. - -Usage example: - - txn, err := db.Begin() - if err != nil { - log.Fatal(err) - } - - stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age")) - if err != nil { - log.Fatal(err) - } - - for _, user := range users { - _, err = stmt.Exec(user.Name, int64(user.Age)) - if err != nil { - log.Fatal(err) - } - } - - _, err = stmt.Exec() - if err != nil { - log.Fatal(err) - } - - err = stmt.Close() - if err != nil { - log.Fatal(err) - } - - err = txn.Commit() - if err != nil { - log.Fatal(err) - } - - -Notifications - - -PostgreSQL supports a simple publish/subscribe model over database -connections. See http://www.postgresql.org/docs/current/static/sql-notify.html -for more information about the general mechanism. - -To start listening for notifications, you first have to open a new connection -to the database by calling NewListener. This connection can not be used for -anything other than LISTEN / NOTIFY. Calling Listen will open a "notification -channel"; once a notification channel is open, a notification generated on that -channel will effect a send on the Listener.Notify channel. A notification -channel will remain open until Unlisten is called, though connection loss might -result in some notifications being lost. To solve this problem, Listener sends -a nil pointer over the Notify channel any time the connection is re-established -following a connection loss. The application can get information about the -state of the underlying connection by setting an event callback in the call to -NewListener. - -A single Listener can safely be used from concurrent goroutines, which means -that there is often no need to create more than one Listener in your -application. However, a Listener is always connected to a single database, so -you will need to create a new Listener instance for every database you want to -receive notifications in. - -The channel name in both Listen and Unlisten is case sensitive, and can contain -any characters legal in an identifier (see -http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS -for more information). Note that the channel name will be truncated to 63 -bytes by the PostgreSQL server. - -You can find a complete, working example of Listener usage at -http://godoc.org/github.com/lib/pq/example/listen. - -*/ -package pq diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go deleted file mode 100644 index 3b0d365f..00000000 --- a/vendor/github.com/lib/pq/encode.go +++ /dev/null @@ -1,603 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "math" - "strconv" - "strings" - "sync" - "time" - - "github.com/lib/pq/oid" -) - -func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte { - switch v := x.(type) { - case []byte: - return v - default: - return encode(parameterStatus, x, oid.T_unknown) - } -} - -func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(nil, v, 10) - case float64: - return strconv.AppendFloat(nil, v, 'f', -1, 64) - case []byte: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, v) - } - - return v - case string: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, []byte(v)) - } - - return []byte(v) - case bool: - return strconv.AppendBool(nil, v) - case time.Time: - return formatTs(v) - - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { - switch f { - case formatBinary: - return binaryDecode(parameterStatus, s, typ) - case formatText: - return textDecode(parameterStatus, s, typ) - default: - panic("not reached") - } -} - -func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_bytea: - return s - case oid.T_int8: - return int64(binary.BigEndian.Uint64(s)) - case oid.T_int4: - return int64(int32(binary.BigEndian.Uint32(s))) - case oid.T_int2: - return int64(int16(binary.BigEndian.Uint16(s))) - case oid.T_uuid: - b, err := decodeUUIDBinary(s) - if err != nil { - panic(err) - } - return b - - default: - errorf("don't know how to decode binary parameter of type %d", uint32(typ)) - } - - panic("not reached") -} - -func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_char, oid.T_varchar, oid.T_text: - return string(s) - case oid.T_bytea: - b, err := parseBytea(s) - if err != nil { - errorf("%s", err) - } - return b - case oid.T_timestamptz: - return parseTs(parameterStatus.currentLocation, string(s)) - case oid.T_timestamp, oid.T_date: - return parseTs(nil, string(s)) - case oid.T_time: - return mustParse("15:04:05", typ, s) - case oid.T_timetz: - return mustParse("15:04:05-07", typ, s) - case oid.T_bool: - return s[0] == 't' - case oid.T_int8, oid.T_int4, oid.T_int2: - i, err := strconv.ParseInt(string(s), 10, 64) - if err != nil { - errorf("%s", err) - } - return i - case oid.T_float4, oid.T_float8: - bits := 64 - if typ == oid.T_float4 { - bits = 32 - } - f, err := strconv.ParseFloat(string(s), bits) - if err != nil { - errorf("%s", err) - } - return f - } - - return s -} - -// appendEncodedText encodes item in text format as required by COPY -// and appends to buf -func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(buf, v, 10) - case float64: - return strconv.AppendFloat(buf, v, 'f', -1, 64) - case []byte: - encodedBytea := encodeBytea(parameterStatus.serverVersion, v) - return appendEscapedText(buf, string(encodedBytea)) - case string: - return appendEscapedText(buf, v) - case bool: - return strconv.AppendBool(buf, v) - case time.Time: - return append(buf, formatTs(v)...) - case nil: - return append(buf, "\\N"...) - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func appendEscapedText(buf []byte, text string) []byte { - escapeNeeded := false - startPos := 0 - var c byte - - // check if we need to escape - for i := 0; i < len(text); i++ { - c = text[i] - if c == '\\' || c == '\n' || c == '\r' || c == '\t' { - escapeNeeded = true - startPos = i - break - } - } - if !escapeNeeded { - return append(buf, text...) - } - - // copy till first char to escape, iterate the rest - result := append(buf, text[:startPos]...) - for i := startPos; i < len(text); i++ { - c = text[i] - switch c { - case '\\': - result = append(result, '\\', '\\') - case '\n': - result = append(result, '\\', 'n') - case '\r': - result = append(result, '\\', 'r') - case '\t': - result = append(result, '\\', 't') - default: - result = append(result, c) - } - } - return result -} - -func mustParse(f string, typ oid.Oid, s []byte) time.Time { - str := string(s) - - // check for a 30-minute-offset timezone - if (typ == oid.T_timestamptz || typ == oid.T_timetz) && - str[len(str)-3] == ':' { - f += ":00" - } - t, err := time.Parse(f, str) - if err != nil { - errorf("decode: %s", err) - } - return t -} - -var errInvalidTimestamp = errors.New("invalid timestamp") - -type timestampParser struct { - err error -} - -func (p *timestampParser) expect(str string, char byte, pos int) { - if p.err != nil { - return - } - if pos+1 > len(str) { - p.err = errInvalidTimestamp - return - } - if c := str[pos]; c != char && p.err == nil { - p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c) - } -} - -func (p *timestampParser) mustAtoi(str string, begin int, end int) int { - if p.err != nil { - return 0 - } - if begin < 0 || end < 0 || begin > end || end > len(str) { - p.err = errInvalidTimestamp - return 0 - } - result, err := strconv.Atoi(str[begin:end]) - if err != nil { - if p.err == nil { - p.err = fmt.Errorf("expected number; got '%v'", str) - } - return 0 - } - return result -} - -// The location cache caches the time zones typically used by the client. -type locationCache struct { - cache map[int]*time.Location - lock sync.Mutex -} - -// All connections share the same list of timezones. Benchmarking shows that -// about 5% speed could be gained by putting the cache in the connection and -// losing the mutex, at the cost of a small amount of memory and a somewhat -// significant increase in code complexity. -var globalLocationCache = newLocationCache() - -func newLocationCache() *locationCache { - return &locationCache{cache: make(map[int]*time.Location)} -} - -// Returns the cached timezone for the specified offset, creating and caching -// it if necessary. -func (c *locationCache) getLocation(offset int) *time.Location { - c.lock.Lock() - defer c.lock.Unlock() - - location, ok := c.cache[offset] - if !ok { - location = time.FixedZone("", offset) - c.cache[offset] = location - } - - return location -} - -var infinityTsEnabled = false -var infinityTsNegative time.Time -var infinityTsPositive time.Time - -const ( - infinityTsEnabledAlready = "pq: infinity timestamp enabled already" - infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive" -) - -// EnableInfinityTs controls the handling of Postgres' "-infinity" and -// "infinity" "timestamp"s. -// -// If EnableInfinityTs is not called, "-infinity" and "infinity" will return -// []byte("-infinity") and []byte("infinity") respectively, and potentially -// cause error "sql: Scan error on column index 0: unsupported driver -> Scan -// pair: []uint8 -> *time.Time", when scanning into a time.Time value. -// -// Once EnableInfinityTs has been called, all connections created using this -// driver will decode Postgres' "-infinity" and "infinity" for "timestamp", -// "timestamp with time zone" and "date" types to the predefined minimum and -// maximum times, respectively. When encoding time.Time values, any time which -// equals or precedes the predefined minimum time will be encoded to -// "-infinity". Any values at or past the maximum time will similarly be -// encoded to "infinity". -// -// If EnableInfinityTs is called with negative >= positive, it will panic. -// Calling EnableInfinityTs after a connection has been established results in -// undefined behavior. If EnableInfinityTs is called more than once, it will -// panic. -func EnableInfinityTs(negative time.Time, positive time.Time) { - if infinityTsEnabled { - panic(infinityTsEnabledAlready) - } - if !negative.Before(positive) { - panic(infinityTsNegativeMustBeSmaller) - } - infinityTsEnabled = true - infinityTsNegative = negative - infinityTsPositive = positive -} - -/* - * Testing might want to toggle infinityTsEnabled - */ -func disableInfinityTs() { - infinityTsEnabled = false -} - -// This is a time function specific to the Postgres default DateStyle -// setting ("ISO, MDY"), the only one we currently support. This -// accounts for the discrepancies between the parsing available with -// time.Parse and the Postgres date formatting quirks. -func parseTs(currentLocation *time.Location, str string) interface{} { - switch str { - case "-infinity": - if infinityTsEnabled { - return infinityTsNegative - } - return []byte(str) - case "infinity": - if infinityTsEnabled { - return infinityTsPositive - } - return []byte(str) - } - t, err := ParseTimestamp(currentLocation, str) - if err != nil { - panic(err) - } - return t -} - -// ParseTimestamp parses Postgres' text format. It returns a time.Time in -// currentLocation iff that time's offset agrees with the offset sent from the -// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the -// fixed offset offset provided by the Postgres server. -func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) { - p := timestampParser{} - - monSep := strings.IndexRune(str, '-') - // this is Gregorian year, not ISO Year - // In Gregorian system, the year 1 BC is followed by AD 1 - year := p.mustAtoi(str, 0, monSep) - daySep := monSep + 3 - month := p.mustAtoi(str, monSep+1, daySep) - p.expect(str, '-', daySep) - timeSep := daySep + 3 - day := p.mustAtoi(str, daySep+1, timeSep) - - minLen := monSep + len("01-01") + 1 - - isBC := strings.HasSuffix(str, " BC") - if isBC { - minLen += 3 - } - - var hour, minute, second int - if len(str) > minLen { - p.expect(str, ' ', timeSep) - minSep := timeSep + 3 - p.expect(str, ':', minSep) - hour = p.mustAtoi(str, timeSep+1, minSep) - secSep := minSep + 3 - p.expect(str, ':', secSep) - minute = p.mustAtoi(str, minSep+1, secSep) - secEnd := secSep + 3 - second = p.mustAtoi(str, secSep+1, secEnd) - } - remainderIdx := monSep + len("01-01 00:00:00") + 1 - // Three optional (but ordered) sections follow: the - // fractional seconds, the time zone offset, and the BC - // designation. We set them up here and adjust the other - // offsets if the preceding sections exist. - - nanoSec := 0 - tzOff := 0 - - if remainderIdx < len(str) && str[remainderIdx] == '.' { - fracStart := remainderIdx + 1 - fracOff := strings.IndexAny(str[fracStart:], "-+ ") - if fracOff < 0 { - fracOff = len(str) - fracStart - } - fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff) - nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) - - remainderIdx += fracOff + 1 - } - if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') { - // time zone separator is always '-' or '+' (UTC is +00) - var tzSign int - switch c := str[tzStart]; c { - case '-': - tzSign = -1 - case '+': - tzSign = +1 - default: - return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c) - } - tzHours := p.mustAtoi(str, tzStart+1, tzStart+3) - remainderIdx += 3 - var tzMin, tzSec int - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) - } - var isoYear int - - if isBC { - isoYear = 1 - year - remainderIdx += 3 - } else { - isoYear = year - } - if remainderIdx < len(str) { - return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:]) - } - t := time.Date(isoYear, time.Month(month), day, - hour, minute, second, nanoSec, - globalLocationCache.getLocation(tzOff)) - - if currentLocation != nil { - // Set the location of the returned Time based on the session's - // TimeZone value, but only if the local time zone database agrees with - // the remote database on the offset. - lt := t.In(currentLocation) - _, newOff := lt.Zone() - if newOff == tzOff { - t = lt - } - } - - return t, p.err -} - -// formatTs formats t into a format postgres understands. -func formatTs(t time.Time) []byte { - if infinityTsEnabled { - // t <= -infinity : ! (t > -infinity) - if !t.After(infinityTsNegative) { - return []byte("-infinity") - } - // t >= infinity : ! (!t < infinity) - if !t.Before(infinityTsPositive) { - return []byte("infinity") - } - } - return FormatTimestamp(t) -} - -// FormatTimestamp formats t into Postgres' text format for timestamps. -func FormatTimestamp(t time.Time) []byte { - // Need to send dates before 0001 A.D. with " BC" suffix, instead of the - // minus sign preferred by Go. - // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on - bc := false - if t.Year() <= 0 { - // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" - t = t.AddDate((-t.Year())*2+1, 0, 0) - bc = true - } - b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) - - _, offset := t.Zone() - offset = offset % 60 - if offset != 0 { - // RFC3339Nano already printed the minus sign - if offset < 0 { - offset = -offset - } - - b = append(b, ':') - if offset < 10 { - b = append(b, '0') - } - b = strconv.AppendInt(b, int64(offset), 10) - } - - if bc { - b = append(b, " BC"...) - } - return b -} - -// Parse a bytea value received from the server. Both "hex" and the legacy -// "escape" format are supported. -func parseBytea(s []byte) (result []byte, err error) { - if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { - // bytea_output = hex - s = s[2:] // trim off leading "\\x" - result = make([]byte, hex.DecodedLen(len(s))) - _, err := hex.Decode(result, s) - if err != nil { - return nil, err - } - } else { - // bytea_output = escape - for len(s) > 0 { - if s[0] == '\\' { - // escaped '\\' - if len(s) >= 2 && s[1] == '\\' { - result = append(result, '\\') - s = s[2:] - continue - } - - // '\\' followed by an octal number - if len(s) < 4 { - return nil, fmt.Errorf("invalid bytea sequence %v", s) - } - r, err := strconv.ParseInt(string(s[1:4]), 8, 9) - if err != nil { - return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) - } - result = append(result, byte(r)) - s = s[4:] - } else { - // We hit an unescaped, raw byte. Try to read in as many as - // possible in one go. - i := bytes.IndexByte(s, '\\') - if i == -1 { - result = append(result, s...) - break - } - result = append(result, s[:i]...) - s = s[i:] - } - } - } - - return result, nil -} - -func encodeBytea(serverVersion int, v []byte) (result []byte) { - if serverVersion >= 90000 { - // Use the hex format if we know that the server supports it - result = make([]byte, 2+hex.EncodedLen(len(v))) - result[0] = '\\' - result[1] = 'x' - hex.Encode(result[2:], v) - } else { - // .. or resort to "escape" - for _, b := range v { - if b == '\\' { - result = append(result, '\\', '\\') - } else if b < 0x20 || b > 0x7e { - result = append(result, []byte(fmt.Sprintf("\\%03o", b))...) - } else { - result = append(result, b) - } - } - } - - return result -} - -// NullTime represents a time.Time that may be null. NullTime implements the -// sql.Scanner interface so it can be used as a scan destination, similar to -// sql.NullString. -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -// Scan implements the Scanner interface. -func (nt *NullTime) Scan(value interface{}) error { - nt.Time, nt.Valid = value.(time.Time) - return nil -} - -// Value implements the driver Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go deleted file mode 100644 index 96aae29c..00000000 --- a/vendor/github.com/lib/pq/error.go +++ /dev/null @@ -1,515 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "fmt" - "io" - "net" - "runtime" -) - -// Error severities -const ( - Efatal = "FATAL" - Epanic = "PANIC" - Ewarning = "WARNING" - Enotice = "NOTICE" - Edebug = "DEBUG" - Einfo = "INFO" - Elog = "LOG" -) - -// Error represents an error communicating with the server. -// -// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields -type Error struct { - Severity string - Code ErrorCode - Message string - Detail string - Hint string - Position string - InternalPosition string - InternalQuery string - Where string - Schema string - Table string - Column string - DataTypeName string - Constraint string - File string - Line string - Routine string -} - -// ErrorCode is a five-character error code. -type ErrorCode string - -// Name returns a more human friendly rendering of the error code, namely the -// "condition name". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Name() string { - return errorCodeNames[ec] -} - -// ErrorClass is only the class part of an error code. -type ErrorClass string - -// Name returns the condition name of an error class. It is equivalent to the -// condition name of the "standard" error code (i.e. the one having the last -// three characters "000"). -func (ec ErrorClass) Name() string { - return errorCodeNames[ErrorCode(ec+"000")] -} - -// Class returns the error class, e.g. "28". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Class() ErrorClass { - return ErrorClass(ec[0:2]) -} - -// errorCodeNames is a mapping between the five-character error codes and the -// human readable "condition names". It is derived from the list at -// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html -var errorCodeNames = map[ErrorCode]string{ - // Class 00 - Successful Completion - "00000": "successful_completion", - // Class 01 - Warning - "01000": "warning", - "0100C": "dynamic_result_sets_returned", - "01008": "implicit_zero_bit_padding", - "01003": "null_value_eliminated_in_set_function", - "01007": "privilege_not_granted", - "01006": "privilege_not_revoked", - "01004": "string_data_right_truncation", - "01P01": "deprecated_feature", - // Class 02 - No Data (this is also a warning class per the SQL standard) - "02000": "no_data", - "02001": "no_additional_dynamic_result_sets_returned", - // Class 03 - SQL Statement Not Yet Complete - "03000": "sql_statement_not_yet_complete", - // Class 08 - Connection Exception - "08000": "connection_exception", - "08003": "connection_does_not_exist", - "08006": "connection_failure", - "08001": "sqlclient_unable_to_establish_sqlconnection", - "08004": "sqlserver_rejected_establishment_of_sqlconnection", - "08007": "transaction_resolution_unknown", - "08P01": "protocol_violation", - // Class 09 - Triggered Action Exception - "09000": "triggered_action_exception", - // Class 0A - Feature Not Supported - "0A000": "feature_not_supported", - // Class 0B - Invalid Transaction Initiation - "0B000": "invalid_transaction_initiation", - // Class 0F - Locator Exception - "0F000": "locator_exception", - "0F001": "invalid_locator_specification", - // Class 0L - Invalid Grantor - "0L000": "invalid_grantor", - "0LP01": "invalid_grant_operation", - // Class 0P - Invalid Role Specification - "0P000": "invalid_role_specification", - // Class 0Z - Diagnostics Exception - "0Z000": "diagnostics_exception", - "0Z002": "stacked_diagnostics_accessed_without_active_handler", - // Class 20 - Case Not Found - "20000": "case_not_found", - // Class 21 - Cardinality Violation - "21000": "cardinality_violation", - // Class 22 - Data Exception - "22000": "data_exception", - "2202E": "array_subscript_error", - "22021": "character_not_in_repertoire", - "22008": "datetime_field_overflow", - "22012": "division_by_zero", - "22005": "error_in_assignment", - "2200B": "escape_character_conflict", - "22022": "indicator_overflow", - "22015": "interval_field_overflow", - "2201E": "invalid_argument_for_logarithm", - "22014": "invalid_argument_for_ntile_function", - "22016": "invalid_argument_for_nth_value_function", - "2201F": "invalid_argument_for_power_function", - "2201G": "invalid_argument_for_width_bucket_function", - "22018": "invalid_character_value_for_cast", - "22007": "invalid_datetime_format", - "22019": "invalid_escape_character", - "2200D": "invalid_escape_octet", - "22025": "invalid_escape_sequence", - "22P06": "nonstandard_use_of_escape_character", - "22010": "invalid_indicator_parameter_value", - "22023": "invalid_parameter_value", - "2201B": "invalid_regular_expression", - "2201W": "invalid_row_count_in_limit_clause", - "2201X": "invalid_row_count_in_result_offset_clause", - "22009": "invalid_time_zone_displacement_value", - "2200C": "invalid_use_of_escape_character", - "2200G": "most_specific_type_mismatch", - "22004": "null_value_not_allowed", - "22002": "null_value_no_indicator_parameter", - "22003": "numeric_value_out_of_range", - "2200H": "sequence_generator_limit_exceeded", - "22026": "string_data_length_mismatch", - "22001": "string_data_right_truncation", - "22011": "substring_error", - "22027": "trim_error", - "22024": "unterminated_c_string", - "2200F": "zero_length_character_string", - "22P01": "floating_point_exception", - "22P02": "invalid_text_representation", - "22P03": "invalid_binary_representation", - "22P04": "bad_copy_file_format", - "22P05": "untranslatable_character", - "2200L": "not_an_xml_document", - "2200M": "invalid_xml_document", - "2200N": "invalid_xml_content", - "2200S": "invalid_xml_comment", - "2200T": "invalid_xml_processing_instruction", - // Class 23 - Integrity Constraint Violation - "23000": "integrity_constraint_violation", - "23001": "restrict_violation", - "23502": "not_null_violation", - "23503": "foreign_key_violation", - "23505": "unique_violation", - "23514": "check_violation", - "23P01": "exclusion_violation", - // Class 24 - Invalid Cursor State - "24000": "invalid_cursor_state", - // Class 25 - Invalid Transaction State - "25000": "invalid_transaction_state", - "25001": "active_sql_transaction", - "25002": "branch_transaction_already_active", - "25008": "held_cursor_requires_same_isolation_level", - "25003": "inappropriate_access_mode_for_branch_transaction", - "25004": "inappropriate_isolation_level_for_branch_transaction", - "25005": "no_active_sql_transaction_for_branch_transaction", - "25006": "read_only_sql_transaction", - "25007": "schema_and_data_statement_mixing_not_supported", - "25P01": "no_active_sql_transaction", - "25P02": "in_failed_sql_transaction", - // Class 26 - Invalid SQL Statement Name - "26000": "invalid_sql_statement_name", - // Class 27 - Triggered Data Change Violation - "27000": "triggered_data_change_violation", - // Class 28 - Invalid Authorization Specification - "28000": "invalid_authorization_specification", - "28P01": "invalid_password", - // Class 2B - Dependent Privilege Descriptors Still Exist - "2B000": "dependent_privilege_descriptors_still_exist", - "2BP01": "dependent_objects_still_exist", - // Class 2D - Invalid Transaction Termination - "2D000": "invalid_transaction_termination", - // Class 2F - SQL Routine Exception - "2F000": "sql_routine_exception", - "2F005": "function_executed_no_return_statement", - "2F002": "modifying_sql_data_not_permitted", - "2F003": "prohibited_sql_statement_attempted", - "2F004": "reading_sql_data_not_permitted", - // Class 34 - Invalid Cursor Name - "34000": "invalid_cursor_name", - // Class 38 - External Routine Exception - "38000": "external_routine_exception", - "38001": "containing_sql_not_permitted", - "38002": "modifying_sql_data_not_permitted", - "38003": "prohibited_sql_statement_attempted", - "38004": "reading_sql_data_not_permitted", - // Class 39 - External Routine Invocation Exception - "39000": "external_routine_invocation_exception", - "39001": "invalid_sqlstate_returned", - "39004": "null_value_not_allowed", - "39P01": "trigger_protocol_violated", - "39P02": "srf_protocol_violated", - // Class 3B - Savepoint Exception - "3B000": "savepoint_exception", - "3B001": "invalid_savepoint_specification", - // Class 3D - Invalid Catalog Name - "3D000": "invalid_catalog_name", - // Class 3F - Invalid Schema Name - "3F000": "invalid_schema_name", - // Class 40 - Transaction Rollback - "40000": "transaction_rollback", - "40002": "transaction_integrity_constraint_violation", - "40001": "serialization_failure", - "40003": "statement_completion_unknown", - "40P01": "deadlock_detected", - // Class 42 - Syntax Error or Access Rule Violation - "42000": "syntax_error_or_access_rule_violation", - "42601": "syntax_error", - "42501": "insufficient_privilege", - "42846": "cannot_coerce", - "42803": "grouping_error", - "42P20": "windowing_error", - "42P19": "invalid_recursion", - "42830": "invalid_foreign_key", - "42602": "invalid_name", - "42622": "name_too_long", - "42939": "reserved_name", - "42804": "datatype_mismatch", - "42P18": "indeterminate_datatype", - "42P21": "collation_mismatch", - "42P22": "indeterminate_collation", - "42809": "wrong_object_type", - "42703": "undefined_column", - "42883": "undefined_function", - "42P01": "undefined_table", - "42P02": "undefined_parameter", - "42704": "undefined_object", - "42701": "duplicate_column", - "42P03": "duplicate_cursor", - "42P04": "duplicate_database", - "42723": "duplicate_function", - "42P05": "duplicate_prepared_statement", - "42P06": "duplicate_schema", - "42P07": "duplicate_table", - "42712": "duplicate_alias", - "42710": "duplicate_object", - "42702": "ambiguous_column", - "42725": "ambiguous_function", - "42P08": "ambiguous_parameter", - "42P09": "ambiguous_alias", - "42P10": "invalid_column_reference", - "42611": "invalid_column_definition", - "42P11": "invalid_cursor_definition", - "42P12": "invalid_database_definition", - "42P13": "invalid_function_definition", - "42P14": "invalid_prepared_statement_definition", - "42P15": "invalid_schema_definition", - "42P16": "invalid_table_definition", - "42P17": "invalid_object_definition", - // Class 44 - WITH CHECK OPTION Violation - "44000": "with_check_option_violation", - // Class 53 - Insufficient Resources - "53000": "insufficient_resources", - "53100": "disk_full", - "53200": "out_of_memory", - "53300": "too_many_connections", - "53400": "configuration_limit_exceeded", - // Class 54 - Program Limit Exceeded - "54000": "program_limit_exceeded", - "54001": "statement_too_complex", - "54011": "too_many_columns", - "54023": "too_many_arguments", - // Class 55 - Object Not In Prerequisite State - "55000": "object_not_in_prerequisite_state", - "55006": "object_in_use", - "55P02": "cant_change_runtime_param", - "55P03": "lock_not_available", - // Class 57 - Operator Intervention - "57000": "operator_intervention", - "57014": "query_canceled", - "57P01": "admin_shutdown", - "57P02": "crash_shutdown", - "57P03": "cannot_connect_now", - "57P04": "database_dropped", - // Class 58 - System Error (errors external to PostgreSQL itself) - "58000": "system_error", - "58030": "io_error", - "58P01": "undefined_file", - "58P02": "duplicate_file", - // Class F0 - Configuration File Error - "F0000": "config_file_error", - "F0001": "lock_file_exists", - // Class HV - Foreign Data Wrapper Error (SQL/MED) - "HV000": "fdw_error", - "HV005": "fdw_column_name_not_found", - "HV002": "fdw_dynamic_parameter_value_needed", - "HV010": "fdw_function_sequence_error", - "HV021": "fdw_inconsistent_descriptor_information", - "HV024": "fdw_invalid_attribute_value", - "HV007": "fdw_invalid_column_name", - "HV008": "fdw_invalid_column_number", - "HV004": "fdw_invalid_data_type", - "HV006": "fdw_invalid_data_type_descriptors", - "HV091": "fdw_invalid_descriptor_field_identifier", - "HV00B": "fdw_invalid_handle", - "HV00C": "fdw_invalid_option_index", - "HV00D": "fdw_invalid_option_name", - "HV090": "fdw_invalid_string_length_or_buffer_length", - "HV00A": "fdw_invalid_string_format", - "HV009": "fdw_invalid_use_of_null_pointer", - "HV014": "fdw_too_many_handles", - "HV001": "fdw_out_of_memory", - "HV00P": "fdw_no_schemas", - "HV00J": "fdw_option_name_not_found", - "HV00K": "fdw_reply_handle", - "HV00Q": "fdw_schema_not_found", - "HV00R": "fdw_table_not_found", - "HV00L": "fdw_unable_to_create_execution", - "HV00M": "fdw_unable_to_create_reply", - "HV00N": "fdw_unable_to_establish_connection", - // Class P0 - PL/pgSQL Error - "P0000": "plpgsql_error", - "P0001": "raise_exception", - "P0002": "no_data_found", - "P0003": "too_many_rows", - // Class XX - Internal Error - "XX000": "internal_error", - "XX001": "data_corrupted", - "XX002": "index_corrupted", -} - -func parseError(r *readBuf) *Error { - err := new(Error) - for t := r.byte(); t != 0; t = r.byte() { - msg := r.string() - switch t { - case 'S': - err.Severity = msg - case 'C': - err.Code = ErrorCode(msg) - case 'M': - err.Message = msg - case 'D': - err.Detail = msg - case 'H': - err.Hint = msg - case 'P': - err.Position = msg - case 'p': - err.InternalPosition = msg - case 'q': - err.InternalQuery = msg - case 'W': - err.Where = msg - case 's': - err.Schema = msg - case 't': - err.Table = msg - case 'c': - err.Column = msg - case 'd': - err.DataTypeName = msg - case 'n': - err.Constraint = msg - case 'F': - err.File = msg - case 'L': - err.Line = msg - case 'R': - err.Routine = msg - } - } - return err -} - -// Fatal returns true if the Error Severity is fatal. -func (err *Error) Fatal() bool { - return err.Severity == Efatal -} - -// Get implements the legacy PGError interface. New code should use the fields -// of the Error struct directly. -func (err *Error) Get(k byte) (v string) { - switch k { - case 'S': - return err.Severity - case 'C': - return string(err.Code) - case 'M': - return err.Message - case 'D': - return err.Detail - case 'H': - return err.Hint - case 'P': - return err.Position - case 'p': - return err.InternalPosition - case 'q': - return err.InternalQuery - case 'W': - return err.Where - case 's': - return err.Schema - case 't': - return err.Table - case 'c': - return err.Column - case 'd': - return err.DataTypeName - case 'n': - return err.Constraint - case 'F': - return err.File - case 'L': - return err.Line - case 'R': - return err.Routine - } - return "" -} - -func (err Error) Error() string { - return "pq: " + err.Message -} - -// PGError is an interface used by previous versions of pq. It is provided -// only to support legacy code. New code should use the Error type. -type PGError interface { - Error() string - Fatal() bool - Get(k byte) (v string) -} - -func errorf(s string, args ...interface{}) { - panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) -} - -// TODO(ainar-g) Rename to errorf after removing panics. -func fmterrorf(s string, args ...interface{}) error { - return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)) -} - -func errRecoverNoErrBadConn(err *error) { - e := recover() - if e == nil { - // Do nothing - return - } - var ok bool - *err, ok = e.(error) - if !ok { - *err = fmt.Errorf("pq: unexpected error: %#v", e) - } -} - -func (c *conn) errRecover(err *error) { - e := recover() - switch v := e.(type) { - case nil: - // Do nothing - case runtime.Error: - c.bad = true - panic(v) - case *Error: - if v.Fatal() { - *err = driver.ErrBadConn - } else { - *err = v - } - case *net.OpError: - c.bad = true - *err = v - case error: - if v == io.EOF || v.(error).Error() == "remote error: handshake failure" { - *err = driver.ErrBadConn - } else { - *err = v - } - - default: - c.bad = true - panic(fmt.Sprintf("unknown error: %#v", e)) - } - - // Any time we return ErrBadConn, we need to remember it since *Tx doesn't - // mark the connection bad in database/sql. - if *err == driver.ErrBadConn { - c.bad = true - } -} diff --git a/vendor/github.com/lib/pq/go.mod b/vendor/github.com/lib/pq/go.mod deleted file mode 100644 index edf0b343..00000000 --- a/vendor/github.com/lib/pq/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/lib/pq diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go deleted file mode 100644 index 850bb904..00000000 --- a/vendor/github.com/lib/pq/notify.go +++ /dev/null @@ -1,797 +0,0 @@ -package pq - -// Package pq is a pure Go Postgres driver for the database/sql package. -// This module contains support for Postgres LISTEN/NOTIFY. - -import ( - "errors" - "fmt" - "sync" - "sync/atomic" - "time" -) - -// Notification represents a single notification from the database. -type Notification struct { - // Process ID (PID) of the notifying postgres backend. - BePid int - // Name of the channel the notification was sent on. - Channel string - // Payload, or the empty string if unspecified. - Extra string -} - -func recvNotification(r *readBuf) *Notification { - bePid := r.int32() - channel := r.string() - extra := r.string() - - return &Notification{bePid, channel, extra} -} - -const ( - connStateIdle int32 = iota - connStateExpectResponse - connStateExpectReadyForQuery -) - -type message struct { - typ byte - err error -} - -var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") - -// ListenerConn is a low-level interface for waiting for notifications. You -// should use Listener instead. -type ListenerConn struct { - // guards cn and err - connectionLock sync.Mutex - cn *conn - err error - - connState int32 - - // the sending goroutine will be holding this lock - senderLock sync.Mutex - - notificationChan chan<- *Notification - - replyChan chan message -} - -// NewListenerConn creates a new ListenerConn. Use NewListener instead. -func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { - return newDialListenerConn(defaultDialer{}, name, notificationChan) -} - -func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) { - cn, err := DialOpen(d, name) - if err != nil { - return nil, err - } - - l := &ListenerConn{ - cn: cn.(*conn), - notificationChan: c, - connState: connStateIdle, - replyChan: make(chan message, 2), - } - - go l.listenerConnMain() - - return l, nil -} - -// We can only allow one goroutine at a time to be running a query on the -// connection for various reasons, so the goroutine sending on the connection -// must be holding senderLock. -// -// Returns an error if an unrecoverable error has occurred and the ListenerConn -// should be abandoned. -func (l *ListenerConn) acquireSenderLock() error { - // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery - l.senderLock.Lock() - - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - if err != nil { - l.senderLock.Unlock() - return err - } - return nil -} - -func (l *ListenerConn) releaseSenderLock() { - l.senderLock.Unlock() -} - -// setState advances the protocol state to newState. Returns false if moving -// to that state from the current state is not allowed. -func (l *ListenerConn) setState(newState int32) bool { - var expectedState int32 - - switch newState { - case connStateIdle: - expectedState = connStateExpectReadyForQuery - case connStateExpectResponse: - expectedState = connStateIdle - case connStateExpectReadyForQuery: - expectedState = connStateExpectResponse - default: - panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) - } - - return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) -} - -// Main logic is here: receive messages from the postgres backend, forward -// notifications and query replies and keep the internal state in sync with the -// protocol state. Returns when the connection has been lost, is about to go -// away or should be discarded because we couldn't agree on the state with the -// server backend. -func (l *ListenerConn) listenerConnLoop() (err error) { - defer errRecoverNoErrBadConn(&err) - - r := &readBuf{} - for { - t, err := l.cn.recvMessage(r) - if err != nil { - return err - } - - switch t { - case 'A': - // recvNotification copies all the data so we don't need to worry - // about the scratch buffer being overwritten. - l.notificationChan <- recvNotification(r) - - case 'T', 'D': - // only used by tests; ignore - - case 'E': - // We might receive an ErrorResponse even when not in a query; it - // is expected that the server will close the connection after - // that, but we should make sure that the error we display is the - // one from the stray ErrorResponse, not io.ErrUnexpectedEOF. - if !l.setState(connStateExpectReadyForQuery) { - return parseError(r) - } - l.replyChan <- message{t, parseError(r)} - - case 'C', 'I': - if !l.setState(connStateExpectReadyForQuery) { - // protocol out of sync - return fmt.Errorf("unexpected CommandComplete") - } - // ExecSimpleQuery doesn't need to know about this message - - case 'Z': - if !l.setState(connStateIdle) { - // protocol out of sync - return fmt.Errorf("unexpected ReadyForQuery") - } - l.replyChan <- message{t, nil} - - case 'N', 'S': - // ignore - default: - return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) - } - } -} - -// This is the main routine for the goroutine receiving on the database -// connection. Most of the main logic is in listenerConnLoop. -func (l *ListenerConn) listenerConnMain() { - err := l.listenerConnLoop() - - // listenerConnLoop terminated; we're done, but we still have to clean up. - // Make sure nobody tries to start any new queries by making sure the err - // pointer is set. It is important that we do not overwrite its value; a - // connection could be closed by either this goroutine or one sending on - // the connection -- whoever closes the connection is assumed to have the - // more meaningful error message (as the other one will probably get - // net.errClosed), so that goroutine sets the error we expose while the - // other error is discarded. If the connection is lost while two - // goroutines are operating on the socket, it probably doesn't matter which - // error we expose so we don't try to do anything more complex. - l.connectionLock.Lock() - if l.err == nil { - l.err = err - } - l.cn.Close() - l.connectionLock.Unlock() - - // There might be a query in-flight; make sure nobody's waiting for a - // response to it, since there's not going to be one. - close(l.replyChan) - - // let the listener know we're done - close(l.notificationChan) - - // this ListenerConn is done -} - -// Listen sends a LISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Listen(channel string) (bool, error) { - return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) -} - -// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Unlisten(channel string) (bool, error) { - return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) -} - -// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery. -func (l *ListenerConn) UnlistenAll() (bool, error) { - return l.ExecSimpleQuery("UNLISTEN *") -} - -// Ping the remote server to make sure it's alive. Non-nil error means the -// connection has failed and should be abandoned. -func (l *ListenerConn) Ping() error { - sent, err := l.ExecSimpleQuery("") - if !sent { - return err - } - if err != nil { - // shouldn't happen - panic(err) - } - return nil -} - -// Attempt to send a query on the connection. Returns an error if sending the -// query failed, and the caller should initiate closure of this connection. -// The caller must be holding senderLock (see acquireSenderLock and -// releaseSenderLock). -func (l *ListenerConn) sendSimpleQuery(q string) (err error) { - defer errRecoverNoErrBadConn(&err) - - // must set connection state before sending the query - if !l.setState(connStateExpectResponse) { - panic("two queries running at the same time") - } - - // Can't use l.cn.writeBuf here because it uses the scratch buffer which - // might get overwritten by listenerConnLoop. - b := &writeBuf{ - buf: []byte("Q\x00\x00\x00\x00"), - pos: 1, - } - b.string(q) - l.cn.send(b) - - return nil -} - -// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable -// parameters) on the connection. The possible return values are: -// 1) "executed" is true; the query was executed to completion on the -// database server. If the query failed, err will be set to the error -// returned by the database, otherwise err will be nil. -// 2) If "executed" is false, the query could not be executed on the remote -// server. err will be non-nil. -// -// After a call to ExecSimpleQuery has returned an executed=false value, the -// connection has either been closed or will be closed shortly thereafter, and -// all subsequently executed queries will return an error. -func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { - if err = l.acquireSenderLock(); err != nil { - return false, err - } - defer l.releaseSenderLock() - - err = l.sendSimpleQuery(q) - if err != nil { - // We can't know what state the protocol is in, so we need to abandon - // this connection. - l.connectionLock.Lock() - // Set the error pointer if it hasn't been set already; see - // listenerConnMain. - if l.err == nil { - l.err = err - } - l.connectionLock.Unlock() - l.cn.c.Close() - return false, err - } - - // now we just wait for a reply.. - for { - m, ok := <-l.replyChan - if !ok { - // We lost the connection to server, don't bother waiting for a - // a response. err should have been set already. - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - return false, err - } - switch m.typ { - case 'Z': - // sanity check - if m.err != nil { - panic("m.err != nil") - } - // done; err might or might not be set - return true, err - - case 'E': - // sanity check - if m.err == nil { - panic("m.err == nil") - } - // server responded with an error; ReadyForQuery to follow - err = m.err - - default: - return false, fmt.Errorf("unknown response for simple query: %q", m.typ) - } - } -} - -// Close closes the connection. -func (l *ListenerConn) Close() error { - l.connectionLock.Lock() - if l.err != nil { - l.connectionLock.Unlock() - return errListenerConnClosed - } - l.err = errListenerConnClosed - l.connectionLock.Unlock() - // We can't send anything on the connection without holding senderLock. - // Simply close the net.Conn to wake up everyone operating on it. - return l.cn.c.Close() -} - -// Err returns the reason the connection was closed. It is not safe to call -// this function until l.Notify has been closed. -func (l *ListenerConn) Err() error { - return l.err -} - -var errListenerClosed = errors.New("pq: Listener has been closed") - -// ErrChannelAlreadyOpen is returned from Listen when a channel is already -// open. -var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") - -// ErrChannelNotOpen is returned from Unlisten when a channel is not open. -var ErrChannelNotOpen = errors.New("pq: channel is not open") - -// ListenerEventType is an enumeration of listener event types. -type ListenerEventType int - -const ( - // ListenerEventConnected is emitted only when the database connection - // has been initially initialized. The err argument of the callback - // will always be nil. - ListenerEventConnected ListenerEventType = iota - - // ListenerEventDisconnected is emitted after a database connection has - // been lost, either because of an error or because Close has been - // called. The err argument will be set to the reason the database - // connection was lost. - ListenerEventDisconnected - - // ListenerEventReconnected is emitted after a database connection has - // been re-established after connection loss. The err argument of the - // callback will always be nil. After this event has been emitted, a - // nil pq.Notification is sent on the Listener.Notify channel. - ListenerEventReconnected - - // ListenerEventConnectionAttemptFailed is emitted after a connection - // to the database was attempted, but failed. The err argument will be - // set to an error describing why the connection attempt did not - // succeed. - ListenerEventConnectionAttemptFailed -) - -// EventCallbackType is the event callback type. See also ListenerEventType -// constants' documentation. -type EventCallbackType func(event ListenerEventType, err error) - -// Listener provides an interface for listening to notifications from a -// PostgreSQL database. For general usage information, see section -// "Notifications". -// -// Listener can safely be used from concurrently running goroutines. -type Listener struct { - // Channel for receiving notifications from the database. In some cases a - // nil value will be sent. See section "Notifications" above. - Notify chan *Notification - - name string - minReconnectInterval time.Duration - maxReconnectInterval time.Duration - dialer Dialer - eventCallback EventCallbackType - - lock sync.Mutex - isClosed bool - reconnectCond *sync.Cond - cn *ListenerConn - connNotificationChan <-chan *Notification - channels map[string]struct{} -} - -// NewListener creates a new database connection dedicated to LISTEN / NOTIFY. -// -// name should be set to a connection string to be used to establish the -// database connection (see section "Connection String Parameters" above). -// -// minReconnectInterval controls the duration to wait before trying to -// re-establish the database connection after connection loss. After each -// consecutive failure this interval is doubled, until maxReconnectInterval is -// reached. Successfully completing the connection establishment procedure -// resets the interval back to minReconnectInterval. -// -// The last parameter eventCallback can be set to a function which will be -// called by the Listener when the state of the underlying database connection -// changes. This callback will be called by the goroutine which dispatches the -// notifications over the Notify channel, so you should try to avoid doing -// potentially time-consuming operations from the callback. -func NewListener(name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback) -} - -// NewDialListener is like NewListener but it takes a Dialer. -func NewDialListener(d Dialer, - name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - - l := &Listener{ - name: name, - minReconnectInterval: minReconnectInterval, - maxReconnectInterval: maxReconnectInterval, - dialer: d, - eventCallback: eventCallback, - - channels: make(map[string]struct{}), - - Notify: make(chan *Notification, 32), - } - l.reconnectCond = sync.NewCond(&l.lock) - - go l.listenerMain() - - return l -} - -// NotificationChannel returns the notification channel for this listener. -// This is the same channel as Notify, and will not be recreated during the -// life time of the Listener. -func (l *Listener) NotificationChannel() <-chan *Notification { - return l.Notify -} - -// Listen starts listening for notifications on a channel. Calls to this -// function will block until an acknowledgement has been received from the -// server. Note that Listener automatically re-establishes the connection -// after connection loss, so this function may block indefinitely if the -// connection can not be re-established. -// -// Listen will only fail in three conditions: -// 1) The channel is already open. The returned error will be -// ErrChannelAlreadyOpen. -// 2) The query was executed on the remote server, but PostgreSQL returned an -// error message in response to the query. The returned error will be a -// pq.Error containing the information the server supplied. -// 3) Close is called on the Listener before the request could be completed. -// -// The channel name is case-sensitive. -func (l *Listener) Listen(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // The server allows you to issue a LISTEN on a channel which is already - // open, but it seems useful to be able to detect this case to spot for - // mistakes in application logic. If the application genuinely does't - // care, it can check the exported error and ignore it. - _, exists := l.channels[channel] - if exists { - return ErrChannelAlreadyOpen - } - - if l.cn != nil { - // If gotResponse is true but error is set, the query was executed on - // the remote server, but resulted in an error. This should be - // relatively rare, so it's fine if we just pass the error to our - // caller. However, if gotResponse is false, we could not complete the - // query on the remote server and our underlying connection is about - // to go away, so we only add relname to l.channels, and wait for - // resync() to take care of the rest. - gotResponse, err := l.cn.Listen(channel) - if gotResponse && err != nil { - return err - } - } - - l.channels[channel] = struct{}{} - for l.cn == nil { - l.reconnectCond.Wait() - // we let go of the mutex for a while - if l.isClosed { - return errListenerClosed - } - } - - return nil -} - -// Unlisten removes a channel from the Listener's channel list. Returns -// ErrChannelNotOpen if the Listener is not listening on the specified channel. -// Returns immediately with no error if there is no connection. Note that you -// might still get notifications for this channel even after Unlisten has -// returned. -// -// The channel name is case-sensitive. -func (l *Listener) Unlisten(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // Similarly to LISTEN, this is not an error in Postgres, but it seems - // useful to distinguish from the normal conditions. - _, exists := l.channels[channel] - if !exists { - return ErrChannelNotOpen - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.Unlisten(channel) - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - delete(l.channels, channel) - return nil -} - -// UnlistenAll removes all channels from the Listener's channel list. Returns -// immediately with no error if there is no connection. Note that you might -// still get notifications for any of the deleted channels even after -// UnlistenAll has returned. -func (l *Listener) UnlistenAll() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.UnlistenAll() - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - l.channels = make(map[string]struct{}) - return nil -} - -// Ping the remote server to make sure it's alive. Non-nil return value means -// that there is no active connection. -func (l *Listener) Ping() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - if l.cn == nil { - return errors.New("no connection") - } - - return l.cn.Ping() -} - -// Clean up after losing the server connection. Returns l.cn.Err(), which -// should have the reason the connection was lost. -func (l *Listener) disconnectCleanup() error { - l.lock.Lock() - defer l.lock.Unlock() - - // sanity check; can't look at Err() until the channel has been closed - select { - case _, ok := <-l.connNotificationChan: - if ok { - panic("connNotificationChan not closed") - } - default: - panic("connNotificationChan not closed") - } - - err := l.cn.Err() - l.cn.Close() - l.cn = nil - return err -} - -// Synchronize the list of channels we want to be listening on with the server -// after the connection has been established. -func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { - doneChan := make(chan error) - go func(notificationChan <-chan *Notification) { - for channel := range l.channels { - // If we got a response, return that error to our caller as it's - // going to be more descriptive than cn.Err(). - gotResponse, err := cn.Listen(channel) - if gotResponse && err != nil { - doneChan <- err - return - } - - // If we couldn't reach the server, wait for notificationChan to - // close and then return the error message from the connection, as - // per ListenerConn's interface. - if err != nil { - for range notificationChan { - } - doneChan <- cn.Err() - return - } - } - doneChan <- nil - }(notificationChan) - - // Ignore notifications while synchronization is going on to avoid - // deadlocks. We have to send a nil notification over Notify anyway as - // we can't possibly know which notifications (if any) were lost while - // the connection was down, so there's no reason to try and process - // these messages at all. - for { - select { - case _, ok := <-notificationChan: - if !ok { - notificationChan = nil - } - - case err := <-doneChan: - return err - } - } -} - -// caller should NOT be holding l.lock -func (l *Listener) closed() bool { - l.lock.Lock() - defer l.lock.Unlock() - - return l.isClosed -} - -func (l *Listener) connect() error { - notificationChan := make(chan *Notification, 32) - cn, err := newDialListenerConn(l.dialer, l.name, notificationChan) - if err != nil { - return err - } - - l.lock.Lock() - defer l.lock.Unlock() - - err = l.resync(cn, notificationChan) - if err != nil { - cn.Close() - return err - } - - l.cn = cn - l.connNotificationChan = notificationChan - l.reconnectCond.Broadcast() - - return nil -} - -// Close disconnects the Listener from the database and shuts it down. -// Subsequent calls to its methods will return an error. Close returns an -// error if the connection has already been closed. -func (l *Listener) Close() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - l.cn.Close() - } - l.isClosed = true - - // Unblock calls to Listen() - l.reconnectCond.Broadcast() - - return nil -} - -func (l *Listener) emitEvent(event ListenerEventType, err error) { - if l.eventCallback != nil { - l.eventCallback(event, err) - } -} - -// Main logic here: maintain a connection to the server when possible, wait -// for notifications and emit events. -func (l *Listener) listenerConnLoop() { - var nextReconnect time.Time - - reconnectInterval := l.minReconnectInterval - for { - for { - err := l.connect() - if err == nil { - break - } - - if l.closed() { - return - } - l.emitEvent(ListenerEventConnectionAttemptFailed, err) - - time.Sleep(reconnectInterval) - reconnectInterval *= 2 - if reconnectInterval > l.maxReconnectInterval { - reconnectInterval = l.maxReconnectInterval - } - } - - if nextReconnect.IsZero() { - l.emitEvent(ListenerEventConnected, nil) - } else { - l.emitEvent(ListenerEventReconnected, nil) - l.Notify <- nil - } - - reconnectInterval = l.minReconnectInterval - nextReconnect = time.Now().Add(reconnectInterval) - - for { - notification, ok := <-l.connNotificationChan - if !ok { - // lost connection, loop again - break - } - l.Notify <- notification - } - - err := l.disconnectCleanup() - if l.closed() { - return - } - l.emitEvent(ListenerEventDisconnected, err) - - time.Sleep(time.Until(nextReconnect)) - } -} - -func (l *Listener) listenerMain() { - l.listenerConnLoop() - close(l.Notify) -} diff --git a/vendor/github.com/lib/pq/oid/doc.go b/vendor/github.com/lib/pq/oid/doc.go deleted file mode 100644 index caaede24..00000000 --- a/vendor/github.com/lib/pq/oid/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Package oid contains OID constants -// as defined by the Postgres server. -package oid - -// Oid is a Postgres Object ID. -type Oid uint32 diff --git a/vendor/github.com/lib/pq/oid/gen.go b/vendor/github.com/lib/pq/oid/gen.go deleted file mode 100644 index 7c634cdc..00000000 --- a/vendor/github.com/lib/pq/oid/gen.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build ignore - -// Generate the table of OID values -// Run with 'go run gen.go'. -package main - -import ( - "database/sql" - "fmt" - "log" - "os" - "os/exec" - "strings" - - _ "github.com/lib/pq" -) - -// OID represent a postgres Object Identifier Type. -type OID struct { - ID int - Type string -} - -// Name returns an upper case version of the oid type. -func (o OID) Name() string { - return strings.ToUpper(o.Type) -} - -func main() { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - db, err := sql.Open("postgres", "") - if err != nil { - log.Fatal(err) - } - rows, err := db.Query(` - SELECT typname, oid - FROM pg_type WHERE oid < 10000 - ORDER BY oid; - `) - if err != nil { - log.Fatal(err) - } - oids := make([]*OID, 0) - for rows.Next() { - var oid OID - if err = rows.Scan(&oid.Type, &oid.ID); err != nil { - log.Fatal(err) - } - oids = append(oids, &oid) - } - if err = rows.Err(); err != nil { - log.Fatal(err) - } - cmd := exec.Command("gofmt") - cmd.Stderr = os.Stderr - w, err := cmd.StdinPipe() - if err != nil { - log.Fatal(err) - } - f, err := os.Create("types.go") - if err != nil { - log.Fatal(err) - } - cmd.Stdout = f - err = cmd.Start() - if err != nil { - log.Fatal(err) - } - fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.") - fmt.Fprintln(w, "\npackage oid") - fmt.Fprintln(w, "const (") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID) - } - fmt.Fprintln(w, ")") - fmt.Fprintln(w, "var TypeName = map[Oid]string{") - for _, oid := range oids { - fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name()) - } - fmt.Fprintln(w, "}") - w.Close() - cmd.Wait() -} diff --git a/vendor/github.com/lib/pq/oid/types.go b/vendor/github.com/lib/pq/oid/types.go deleted file mode 100644 index ecc84c2c..00000000 --- a/vendor/github.com/lib/pq/oid/types.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by gen.go. DO NOT EDIT. - -package oid - -const ( - T_bool Oid = 16 - T_bytea Oid = 17 - T_char Oid = 18 - T_name Oid = 19 - T_int8 Oid = 20 - T_int2 Oid = 21 - T_int2vector Oid = 22 - T_int4 Oid = 23 - T_regproc Oid = 24 - T_text Oid = 25 - T_oid Oid = 26 - T_tid Oid = 27 - T_xid Oid = 28 - T_cid Oid = 29 - T_oidvector Oid = 30 - T_pg_ddl_command Oid = 32 - T_pg_type Oid = 71 - T_pg_attribute Oid = 75 - T_pg_proc Oid = 81 - T_pg_class Oid = 83 - T_json Oid = 114 - T_xml Oid = 142 - T__xml Oid = 143 - T_pg_node_tree Oid = 194 - T__json Oid = 199 - T_smgr Oid = 210 - T_index_am_handler Oid = 325 - T_point Oid = 600 - T_lseg Oid = 601 - T_path Oid = 602 - T_box Oid = 603 - T_polygon Oid = 604 - T_line Oid = 628 - T__line Oid = 629 - T_cidr Oid = 650 - T__cidr Oid = 651 - T_float4 Oid = 700 - T_float8 Oid = 701 - T_abstime Oid = 702 - T_reltime Oid = 703 - T_tinterval Oid = 704 - T_unknown Oid = 705 - T_circle Oid = 718 - T__circle Oid = 719 - T_money Oid = 790 - T__money Oid = 791 - T_macaddr Oid = 829 - T_inet Oid = 869 - T__bool Oid = 1000 - T__bytea Oid = 1001 - T__char Oid = 1002 - T__name Oid = 1003 - T__int2 Oid = 1005 - T__int2vector Oid = 1006 - T__int4 Oid = 1007 - T__regproc Oid = 1008 - T__text Oid = 1009 - T__tid Oid = 1010 - T__xid Oid = 1011 - T__cid Oid = 1012 - T__oidvector Oid = 1013 - T__bpchar Oid = 1014 - T__varchar Oid = 1015 - T__int8 Oid = 1016 - T__point Oid = 1017 - T__lseg Oid = 1018 - T__path Oid = 1019 - T__box Oid = 1020 - T__float4 Oid = 1021 - T__float8 Oid = 1022 - T__abstime Oid = 1023 - T__reltime Oid = 1024 - T__tinterval Oid = 1025 - T__polygon Oid = 1027 - T__oid Oid = 1028 - T_aclitem Oid = 1033 - T__aclitem Oid = 1034 - T__macaddr Oid = 1040 - T__inet Oid = 1041 - T_bpchar Oid = 1042 - T_varchar Oid = 1043 - T_date Oid = 1082 - T_time Oid = 1083 - T_timestamp Oid = 1114 - T__timestamp Oid = 1115 - T__date Oid = 1182 - T__time Oid = 1183 - T_timestamptz Oid = 1184 - T__timestamptz Oid = 1185 - T_interval Oid = 1186 - T__interval Oid = 1187 - T__numeric Oid = 1231 - T_pg_database Oid = 1248 - T__cstring Oid = 1263 - T_timetz Oid = 1266 - T__timetz Oid = 1270 - T_bit Oid = 1560 - T__bit Oid = 1561 - T_varbit Oid = 1562 - T__varbit Oid = 1563 - T_numeric Oid = 1700 - T_refcursor Oid = 1790 - T__refcursor Oid = 2201 - T_regprocedure Oid = 2202 - T_regoper Oid = 2203 - T_regoperator Oid = 2204 - T_regclass Oid = 2205 - T_regtype Oid = 2206 - T__regprocedure Oid = 2207 - T__regoper Oid = 2208 - T__regoperator Oid = 2209 - T__regclass Oid = 2210 - T__regtype Oid = 2211 - T_record Oid = 2249 - T_cstring Oid = 2275 - T_any Oid = 2276 - T_anyarray Oid = 2277 - T_void Oid = 2278 - T_trigger Oid = 2279 - T_language_handler Oid = 2280 - T_internal Oid = 2281 - T_opaque Oid = 2282 - T_anyelement Oid = 2283 - T__record Oid = 2287 - T_anynonarray Oid = 2776 - T_pg_authid Oid = 2842 - T_pg_auth_members Oid = 2843 - T__txid_snapshot Oid = 2949 - T_uuid Oid = 2950 - T__uuid Oid = 2951 - T_txid_snapshot Oid = 2970 - T_fdw_handler Oid = 3115 - T_pg_lsn Oid = 3220 - T__pg_lsn Oid = 3221 - T_tsm_handler Oid = 3310 - T_anyenum Oid = 3500 - T_tsvector Oid = 3614 - T_tsquery Oid = 3615 - T_gtsvector Oid = 3642 - T__tsvector Oid = 3643 - T__gtsvector Oid = 3644 - T__tsquery Oid = 3645 - T_regconfig Oid = 3734 - T__regconfig Oid = 3735 - T_regdictionary Oid = 3769 - T__regdictionary Oid = 3770 - T_jsonb Oid = 3802 - T__jsonb Oid = 3807 - T_anyrange Oid = 3831 - T_event_trigger Oid = 3838 - T_int4range Oid = 3904 - T__int4range Oid = 3905 - T_numrange Oid = 3906 - T__numrange Oid = 3907 - T_tsrange Oid = 3908 - T__tsrange Oid = 3909 - T_tstzrange Oid = 3910 - T__tstzrange Oid = 3911 - T_daterange Oid = 3912 - T__daterange Oid = 3913 - T_int8range Oid = 3926 - T__int8range Oid = 3927 - T_pg_shseclabel Oid = 4066 - T_regnamespace Oid = 4089 - T__regnamespace Oid = 4090 - T_regrole Oid = 4096 - T__regrole Oid = 4097 -) - -var TypeName = map[Oid]string{ - T_bool: "BOOL", - T_bytea: "BYTEA", - T_char: "CHAR", - T_name: "NAME", - T_int8: "INT8", - T_int2: "INT2", - T_int2vector: "INT2VECTOR", - T_int4: "INT4", - T_regproc: "REGPROC", - T_text: "TEXT", - T_oid: "OID", - T_tid: "TID", - T_xid: "XID", - T_cid: "CID", - T_oidvector: "OIDVECTOR", - T_pg_ddl_command: "PG_DDL_COMMAND", - T_pg_type: "PG_TYPE", - T_pg_attribute: "PG_ATTRIBUTE", - T_pg_proc: "PG_PROC", - T_pg_class: "PG_CLASS", - T_json: "JSON", - T_xml: "XML", - T__xml: "_XML", - T_pg_node_tree: "PG_NODE_TREE", - T__json: "_JSON", - T_smgr: "SMGR", - T_index_am_handler: "INDEX_AM_HANDLER", - T_point: "POINT", - T_lseg: "LSEG", - T_path: "PATH", - T_box: "BOX", - T_polygon: "POLYGON", - T_line: "LINE", - T__line: "_LINE", - T_cidr: "CIDR", - T__cidr: "_CIDR", - T_float4: "FLOAT4", - T_float8: "FLOAT8", - T_abstime: "ABSTIME", - T_reltime: "RELTIME", - T_tinterval: "TINTERVAL", - T_unknown: "UNKNOWN", - T_circle: "CIRCLE", - T__circle: "_CIRCLE", - T_money: "MONEY", - T__money: "_MONEY", - T_macaddr: "MACADDR", - T_inet: "INET", - T__bool: "_BOOL", - T__bytea: "_BYTEA", - T__char: "_CHAR", - T__name: "_NAME", - T__int2: "_INT2", - T__int2vector: "_INT2VECTOR", - T__int4: "_INT4", - T__regproc: "_REGPROC", - T__text: "_TEXT", - T__tid: "_TID", - T__xid: "_XID", - T__cid: "_CID", - T__oidvector: "_OIDVECTOR", - T__bpchar: "_BPCHAR", - T__varchar: "_VARCHAR", - T__int8: "_INT8", - T__point: "_POINT", - T__lseg: "_LSEG", - T__path: "_PATH", - T__box: "_BOX", - T__float4: "_FLOAT4", - T__float8: "_FLOAT8", - T__abstime: "_ABSTIME", - T__reltime: "_RELTIME", - T__tinterval: "_TINTERVAL", - T__polygon: "_POLYGON", - T__oid: "_OID", - T_aclitem: "ACLITEM", - T__aclitem: "_ACLITEM", - T__macaddr: "_MACADDR", - T__inet: "_INET", - T_bpchar: "BPCHAR", - T_varchar: "VARCHAR", - T_date: "DATE", - T_time: "TIME", - T_timestamp: "TIMESTAMP", - T__timestamp: "_TIMESTAMP", - T__date: "_DATE", - T__time: "_TIME", - T_timestamptz: "TIMESTAMPTZ", - T__timestamptz: "_TIMESTAMPTZ", - T_interval: "INTERVAL", - T__interval: "_INTERVAL", - T__numeric: "_NUMERIC", - T_pg_database: "PG_DATABASE", - T__cstring: "_CSTRING", - T_timetz: "TIMETZ", - T__timetz: "_TIMETZ", - T_bit: "BIT", - T__bit: "_BIT", - T_varbit: "VARBIT", - T__varbit: "_VARBIT", - T_numeric: "NUMERIC", - T_refcursor: "REFCURSOR", - T__refcursor: "_REFCURSOR", - T_regprocedure: "REGPROCEDURE", - T_regoper: "REGOPER", - T_regoperator: "REGOPERATOR", - T_regclass: "REGCLASS", - T_regtype: "REGTYPE", - T__regprocedure: "_REGPROCEDURE", - T__regoper: "_REGOPER", - T__regoperator: "_REGOPERATOR", - T__regclass: "_REGCLASS", - T__regtype: "_REGTYPE", - T_record: "RECORD", - T_cstring: "CSTRING", - T_any: "ANY", - T_anyarray: "ANYARRAY", - T_void: "VOID", - T_trigger: "TRIGGER", - T_language_handler: "LANGUAGE_HANDLER", - T_internal: "INTERNAL", - T_opaque: "OPAQUE", - T_anyelement: "ANYELEMENT", - T__record: "_RECORD", - T_anynonarray: "ANYNONARRAY", - T_pg_authid: "PG_AUTHID", - T_pg_auth_members: "PG_AUTH_MEMBERS", - T__txid_snapshot: "_TXID_SNAPSHOT", - T_uuid: "UUID", - T__uuid: "_UUID", - T_txid_snapshot: "TXID_SNAPSHOT", - T_fdw_handler: "FDW_HANDLER", - T_pg_lsn: "PG_LSN", - T__pg_lsn: "_PG_LSN", - T_tsm_handler: "TSM_HANDLER", - T_anyenum: "ANYENUM", - T_tsvector: "TSVECTOR", - T_tsquery: "TSQUERY", - T_gtsvector: "GTSVECTOR", - T__tsvector: "_TSVECTOR", - T__gtsvector: "_GTSVECTOR", - T__tsquery: "_TSQUERY", - T_regconfig: "REGCONFIG", - T__regconfig: "_REGCONFIG", - T_regdictionary: "REGDICTIONARY", - T__regdictionary: "_REGDICTIONARY", - T_jsonb: "JSONB", - T__jsonb: "_JSONB", - T_anyrange: "ANYRANGE", - T_event_trigger: "EVENT_TRIGGER", - T_int4range: "INT4RANGE", - T__int4range: "_INT4RANGE", - T_numrange: "NUMRANGE", - T__numrange: "_NUMRANGE", - T_tsrange: "TSRANGE", - T__tsrange: "_TSRANGE", - T_tstzrange: "TSTZRANGE", - T__tstzrange: "_TSTZRANGE", - T_daterange: "DATERANGE", - T__daterange: "_DATERANGE", - T_int8range: "INT8RANGE", - T__int8range: "_INT8RANGE", - T_pg_shseclabel: "PG_SHSECLABEL", - T_regnamespace: "REGNAMESPACE", - T__regnamespace: "_REGNAMESPACE", - T_regrole: "REGROLE", - T__regrole: "_REGROLE", -} diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go deleted file mode 100644 index c6aa5b9a..00000000 --- a/vendor/github.com/lib/pq/rows.go +++ /dev/null @@ -1,93 +0,0 @@ -package pq - -import ( - "math" - "reflect" - "time" - - "github.com/lib/pq/oid" -) - -const headerSize = 4 - -type fieldDesc struct { - // The object ID of the data type. - OID oid.Oid - // The data type size (see pg_type.typlen). - // Note that negative values denote variable-width types. - Len int - // The type modifier (see pg_attribute.atttypmod). - // The meaning of the modifier is type-specific. - Mod int -} - -func (fd fieldDesc) Type() reflect.Type { - switch fd.OID { - case oid.T_int8: - return reflect.TypeOf(int64(0)) - case oid.T_int4: - return reflect.TypeOf(int32(0)) - case oid.T_int2: - return reflect.TypeOf(int16(0)) - case oid.T_varchar, oid.T_text: - return reflect.TypeOf("") - case oid.T_bool: - return reflect.TypeOf(false) - case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz: - return reflect.TypeOf(time.Time{}) - case oid.T_bytea: - return reflect.TypeOf([]byte(nil)) - default: - return reflect.TypeOf(new(interface{})).Elem() - } -} - -func (fd fieldDesc) Name() string { - return oid.TypeName[fd.OID] -} - -func (fd fieldDesc) Length() (length int64, ok bool) { - switch fd.OID { - case oid.T_text, oid.T_bytea: - return math.MaxInt64, true - case oid.T_varchar, oid.T_bpchar: - return int64(fd.Mod - headerSize), true - default: - return 0, false - } -} - -func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) { - switch fd.OID { - case oid.T_numeric, oid.T__numeric: - mod := fd.Mod - headerSize - precision = int64((mod >> 16) & 0xffff) - scale = int64(mod & 0xffff) - return precision, scale, true - default: - return 0, 0, false - } -} - -// ColumnTypeScanType returns the value type that can be used to scan types into. -func (rs *rows) ColumnTypeScanType(index int) reflect.Type { - return rs.colTyps[index].Type() -} - -// ColumnTypeDatabaseTypeName return the database system type name. -func (rs *rows) ColumnTypeDatabaseTypeName(index int) string { - return rs.colTyps[index].Name() -} - -// ColumnTypeLength returns the length of the column type if the column is a -// variable length type. If the column is not a variable length type ok -// should return false. -func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) { - return rs.colTyps[index].Length() -} - -// ColumnTypePrecisionScale should return the precision and scale for decimal -// types. If not applicable, ok should be false. -func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { - return rs.colTyps[index].PrecisionScale() -} diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go deleted file mode 100644 index e1a326a0..00000000 --- a/vendor/github.com/lib/pq/ssl.go +++ /dev/null @@ -1,169 +0,0 @@ -package pq - -import ( - "crypto/tls" - "crypto/x509" - "io/ioutil" - "net" - "os" - "os/user" - "path/filepath" -) - -// ssl generates a function to upgrade a net.Conn based on the "sslmode" and -// related settings. The function is nil when no upgrade should take place. -func ssl(o values) (func(net.Conn) (net.Conn, error), error) { - verifyCaOnly := false - tlsConf := tls.Config{} - switch mode := o["sslmode"]; mode { - // "require" is the default. - case "", "require": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - - // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: - // - // Note: For backwards compatibility with earlier versions of - // PostgreSQL, if a root CA file exists, the behavior of - // sslmode=require will be the same as that of verify-ca, meaning the - // server certificate is validated against the CA. Relying on this - // behavior is discouraged, and applications that need certificate - // validation should always use verify-ca or verify-full. - if sslrootcert, ok := o["sslrootcert"]; ok { - if _, err := os.Stat(sslrootcert); err == nil { - verifyCaOnly = true - } else { - delete(o, "sslrootcert") - } - } - case "verify-ca": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - verifyCaOnly = true - case "verify-full": - tlsConf.ServerName = o["host"] - case "disable": - return nil, nil - default: - return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) - } - - err := sslClientCertificates(&tlsConf, o) - if err != nil { - return nil, err - } - err = sslCertificateAuthority(&tlsConf, o) - if err != nil { - return nil, err - } - sslRenegotiation(&tlsConf) - - return func(conn net.Conn) (net.Conn, error) { - client := tls.Client(conn, &tlsConf) - if verifyCaOnly { - err := sslVerifyCertificateAuthority(client, &tlsConf) - if err != nil { - return nil, err - } - } - return client, nil - }, nil -} - -// sslClientCertificates adds the certificate specified in the "sslcert" and -// "sslkey" settings, or if they aren't set, from the .postgresql directory -// in the user's home directory. The configured files must exist and have -// the correct permissions. -func sslClientCertificates(tlsConf *tls.Config, o values) error { - // user.Current() might fail when cross-compiling. We have to ignore the - // error and continue without home directory defaults, since we wouldn't - // know from where to load them. - user, _ := user.Current() - - // In libpq, the client certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037 - sslcert := o["sslcert"] - if len(sslcert) == 0 && user != nil { - sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045 - if len(sslcert) == 0 { - return nil - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054 - if _, err := os.Stat(sslcert); os.IsNotExist(err) { - return nil - } else if err != nil { - return err - } - - // In libpq, the ssl key is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222 - sslkey := o["sslkey"] - if len(sslkey) == 0 && user != nil { - sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") - } - - if len(sslkey) > 0 { - if err := sslKeyPermissions(sslkey); err != nil { - return err - } - } - - cert, err := tls.LoadX509KeyPair(sslcert, sslkey) - if err != nil { - return err - } - - tlsConf.Certificates = []tls.Certificate{cert} - return nil -} - -// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting. -func sslCertificateAuthority(tlsConf *tls.Config, o values) error { - // In libpq, the root certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951 - if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 { - tlsConf.RootCAs = x509.NewCertPool() - - cert, err := ioutil.ReadFile(sslrootcert) - if err != nil { - return err - } - - if !tlsConf.RootCAs.AppendCertsFromPEM(cert) { - return fmterrorf("couldn't parse pem in sslrootcert") - } - } - - return nil -} - -// sslVerifyCertificateAuthority carries out a TLS handshake to the server and -// verifies the presented certificate against the CA, i.e. the one specified in -// sslrootcert or the system CA if sslrootcert was not specified. -func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error { - err := client.Handshake() - if err != nil { - return err - } - certs := client.ConnectionState().PeerCertificates - opts := x509.VerifyOptions{ - DNSName: client.ConnectionState().ServerName, - Intermediates: x509.NewCertPool(), - Roots: tlsConf.RootCAs, - } - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - _, err = certs[0].Verify(opts) - return err -} diff --git a/vendor/github.com/lib/pq/ssl_go1.7.go b/vendor/github.com/lib/pq/ssl_go1.7.go deleted file mode 100644 index d7ba43b3..00000000 --- a/vendor/github.com/lib/pq/ssl_go1.7.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build go1.7 - -package pq - -import "crypto/tls" - -// Accept renegotiation requests initiated by the backend. -// -// Renegotiation was deprecated then removed from PostgreSQL 9.5, but -// the default configuration of older versions has it enabled. Redshift -// also initiates renegotiations and cannot be reconfigured. -func sslRenegotiation(conf *tls.Config) { - conf.Renegotiation = tls.RenegotiateFreelyAsClient -} diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go deleted file mode 100644 index 3b7c3a2a..00000000 --- a/vendor/github.com/lib/pq/ssl_permissions.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package pq - -import "os" - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(sslkey string) error { - info, err := os.Stat(sslkey) - if err != nil { - return err - } - if info.Mode().Perm()&0077 != 0 { - return ErrSSLKeyHasWorldPermissions - } - return nil -} diff --git a/vendor/github.com/lib/pq/ssl_renegotiation.go b/vendor/github.com/lib/pq/ssl_renegotiation.go deleted file mode 100644 index 85ed5e43..00000000 --- a/vendor/github.com/lib/pq/ssl_renegotiation.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !go1.7 - -package pq - -import "crypto/tls" - -// Renegotiation is not supported by crypto/tls until Go 1.7. -func sslRenegotiation(*tls.Config) {} diff --git a/vendor/github.com/lib/pq/ssl_windows.go b/vendor/github.com/lib/pq/ssl_windows.go deleted file mode 100644 index 5d2c763c..00000000 --- a/vendor/github.com/lib/pq/ssl_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package pq - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(string) error { return nil } diff --git a/vendor/github.com/lib/pq/url.go b/vendor/github.com/lib/pq/url.go deleted file mode 100644 index f4d8a7c2..00000000 --- a/vendor/github.com/lib/pq/url.go +++ /dev/null @@ -1,76 +0,0 @@ -package pq - -import ( - "fmt" - "net" - nurl "net/url" - "sort" - "strings" -) - -// ParseURL no longer needs to be used by clients of this library since supplying a URL as a -// connection string to sql.Open() is now supported: -// -// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full") -// -// It remains exported here for backwards-compatibility. -// -// ParseURL converts a url to a connection string for driver.Open. -// Example: -// -// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full" -// -// converts to: -// -// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full" -// -// A minimal example: -// -// "postgres://" -// -// This will be blank, causing driver.Open to use all of the defaults -func ParseURL(url string) (string, error) { - u, err := nurl.Parse(url) - if err != nil { - return "", err - } - - if u.Scheme != "postgres" && u.Scheme != "postgresql" { - return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) - } - - var kvs []string - escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) - accrue := func(k, v string) { - if v != "" { - kvs = append(kvs, k+"="+escaper.Replace(v)) - } - } - - if u.User != nil { - v := u.User.Username() - accrue("user", v) - - v, _ = u.User.Password() - accrue("password", v) - } - - if host, port, err := net.SplitHostPort(u.Host); err != nil { - accrue("host", u.Host) - } else { - accrue("host", host) - accrue("port", port) - } - - if u.Path != "" { - accrue("dbname", u.Path[1:]) - } - - q := u.Query() - for k := range q { - accrue(k, q.Get(k)) - } - - sort.Strings(kvs) // Makes testing easier (not a performance concern) - return strings.Join(kvs, " "), nil -} diff --git a/vendor/github.com/lib/pq/user_posix.go b/vendor/github.com/lib/pq/user_posix.go deleted file mode 100644 index bf982524..00000000 --- a/vendor/github.com/lib/pq/user_posix.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. - -// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun - -package pq - -import ( - "os" - "os/user" -) - -func userCurrent() (string, error) { - u, err := user.Current() - if err == nil { - return u.Username, nil - } - - name := os.Getenv("USER") - if name != "" { - return name, nil - } - - return "", ErrCouldNotDetectUsername -} diff --git a/vendor/github.com/lib/pq/user_windows.go b/vendor/github.com/lib/pq/user_windows.go deleted file mode 100644 index 2b691267..00000000 --- a/vendor/github.com/lib/pq/user_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. -package pq - -import ( - "path/filepath" - "syscall" -) - -// Perform Windows user name lookup identically to libpq. -// -// The PostgreSQL code makes use of the legacy Win32 function -// GetUserName, and that function has not been imported into stock Go. -// GetUserNameEx is available though, the difference being that a -// wider range of names are available. To get the output to be the -// same as GetUserName, only the base (or last) component of the -// result is returned. -func userCurrent() (string, error) { - pw_name := make([]uint16, 128) - pwname_size := uint32(len(pw_name)) - 1 - err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size) - if err != nil { - return "", ErrCouldNotDetectUsername - } - s := syscall.UTF16ToString(pw_name) - u := filepath.Base(s) - return u, nil -} diff --git a/vendor/github.com/lib/pq/uuid.go b/vendor/github.com/lib/pq/uuid.go deleted file mode 100644 index 9a1b9e07..00000000 --- a/vendor/github.com/lib/pq/uuid.go +++ /dev/null @@ -1,23 +0,0 @@ -package pq - -import ( - "encoding/hex" - "fmt" -) - -// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format. -func decodeUUIDBinary(src []byte) ([]byte, error) { - if len(src) != 16 { - return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src)) - } - - dst := make([]byte, 36) - dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-' - hex.Encode(dst[0:], src[0:4]) - hex.Encode(dst[9:], src[4:6]) - hex.Encode(dst[14:], src[6:8]) - hex.Encode(dst[19:], src[8:10]) - hex.Encode(dst[24:], src[10:16]) - - return dst, nil -} diff --git a/vendor/github.com/mitchellh/copystructure/.travis.yml b/vendor/github.com/mitchellh/copystructure/.travis.yml deleted file mode 100644 index d7b9589a..00000000 --- a/vendor/github.com/mitchellh/copystructure/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go - -go: - - 1.7 - - tip - -script: - - go test - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/mitchellh/copystructure/LICENSE b/vendor/github.com/mitchellh/copystructure/LICENSE deleted file mode 100644 index 22985159..00000000 --- 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 f0fbd2e5..00000000 --- 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 db6a6aa1..00000000 --- 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 14043525..00000000 --- a/vendor/github.com/mitchellh/copystructure/copystructure.go +++ /dev/null @@ -1,548 +0,0 @@ -package copystructure - -import ( - "errors" - "reflect" - "sync" - - "github.com/mitchellh/reflectwalk" -) - -// Copy returns a deep copy of v. -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) - -// 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 -} - -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 - } - - 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{} - - 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) 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 := 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 - } - - // 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/copystructure/go.mod b/vendor/github.com/mitchellh/copystructure/go.mod deleted file mode 100644 index d0186430..00000000 --- a/vendor/github.com/mitchellh/copystructure/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/mitchellh/copystructure - -require github.com/mitchellh/reflectwalk v1.0.0 diff --git a/vendor/github.com/mitchellh/copystructure/go.sum b/vendor/github.com/mitchellh/copystructure/go.sum deleted file mode 100644 index be572456..00000000 --- a/vendor/github.com/mitchellh/copystructure/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a5..00000000 --- a/vendor/github.com/mitchellh/go-homedir/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/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5..00000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/go.mod b/vendor/github.com/mitchellh/go-homedir/go.mod deleted file mode 100644 index 7efa09a0..00000000 --- a/vendor/github.com/mitchellh/go-homedir/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/go-homedir diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537..00000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} 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 928d000e..00000000 --- a/vendor/github.com/mitchellh/go-testing-interface/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.8 - - 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 a3866a29..00000000 --- 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 26781bba..00000000 --- a/vendor/github.com/mitchellh/go-testing-interface/README.md +++ /dev/null @@ -1,52 +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{}) - } - -## 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/go.mod b/vendor/github.com/mitchellh/go-testing-interface/go.mod deleted file mode 100644 index 062796de..00000000 --- a/vendor/github.com/mitchellh/go-testing-interface/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/go-testing-interface 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 204afb42..00000000 --- a/vendor/github.com/mitchellh/go-testing-interface/testing.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build !go1.9 - -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 { - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - Fail() - FailNow() - Failed() bool - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Name() string - 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. Name and Skip methods are -// unimplemented noops. -type RuntimeT struct { - failed bool -} - -func (t *RuntimeT) Error(args ...interface{}) { - log.Println(fmt.Sprintln(args...)) - t.Fail() -} - -func (t *RuntimeT) Errorf(format string, args ...interface{}) { - log.Println(fmt.Sprintf(format, args...)) - t.Fail() -} - -func (t *RuntimeT) Fatal(args ...interface{}) { - log.Println(fmt.Sprintln(args...)) - t.FailNow() -} - -func (t *RuntimeT) Fatalf(format string, args ...interface{}) { - log.Println(fmt.Sprintf(format, args...)) - t.FailNow() -} - -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) 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) Skip(args ...interface{}) {} -func (t *RuntimeT) SkipNow() {} -func (t *RuntimeT) Skipf(format string, args ...interface{}) {} -func (t *RuntimeT) Skipped() bool { return false } diff --git a/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go b/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go deleted file mode 100644 index 31b42cad..00000000 --- a/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go +++ /dev/null @@ -1,108 +0,0 @@ -// +build go1.9 - -// NOTE: This is a temporary copy of testing.go for Go 1.9 with the addition -// of "Helper" to the T interface. Go 1.9 at the time of typing is in RC -// and is set for release shortly. We'll support this on master as the default -// as soon as 1.9 is released. - -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 { - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - Fail() - FailNow() - Failed() bool - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Name() string - Skip(args ...interface{}) - SkipNow() - Skipf(format string, args ...interface{}) - Skipped() bool - Helper() -} - -// 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. -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) 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() {} diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml deleted file mode 100644 index 1689c7d7..00000000 --- a/vendor/github.com/mitchellh/mapstructure/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -go: - - "1.11.x" - - tip - -script: - - go test diff --git a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md deleted file mode 100644 index 3b3cb723..00000000 --- a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md +++ /dev/null @@ -1,21 +0,0 @@ -## 1.1.2 - -* Fix error when decode hook decodes interface implementation into interface - type. [GH-140] - -## 1.1.1 - -* Fix panic that can happen in `decodePtr` - -## 1.1.0 - -* Added `StringToIPHookFunc` to convert `string` to `net.IP` and `net.IPNet` [GH-133] -* Support struct to struct decoding [GH-137] -* If source map value is nil, then destination map value is nil (instead of empty) -* If source slice value is nil, then destination slice value is nil (instead of empty) -* If source pointer is nil, then destination pointer is set to nil (instead of - allocated zero value of type) - -## 1.0.0 - -* Initial tagged stable release. diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE deleted file mode 100644 index f9c841a5..00000000 --- a/vendor/github.com/mitchellh/mapstructure/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/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md deleted file mode 100644 index 0018dc7d..00000000 --- a/vendor/github.com/mitchellh/mapstructure/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# mapstructure [![Godoc](https://godoc.org/github.com/mitchellh/mapstructure?status.svg)](https://godoc.org/github.com/mitchellh/mapstructure) - -mapstructure is a Go library for decoding generic map values to structures -and vice versa, while providing helpful error handling. - -This library is most useful when decoding values from some data stream (JSON, -Gob, etc.) where you don't _quite_ know the structure of the underlying data -until you read a part of it. You can therefore read a `map[string]interface{}` -and use this library to decode it into the proper underlying native Go -structure. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/mapstructure -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). - -The `Decode` function has examples associated with it there. - -## But Why?! - -Go offers fantastic standard libraries for decoding formats such as JSON. -The standard method is to have a struct pre-created, and populate that struct -from the bytes of the encoded format. This is great, but the problem is if -you have configuration or an encoding that changes slightly depending on -specific fields. For example, consider this JSON: - -```json -{ - "type": "person", - "name": "Mitchell" -} -``` - -Perhaps we can't populate a specific structure without first reading -the "type" field from the JSON. We could always do two passes over the -decoding of the JSON (reading the "type" first, and the rest later). -However, it is much simpler to just decode this into a `map[string]interface{}` -structure, read the "type" key, then use something like this library -to decode it into the proper structure. diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go deleted file mode 100644 index 1f0abc65..00000000 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ /dev/null @@ -1,217 +0,0 @@ -package mapstructure - -import ( - "errors" - "fmt" - "net" - "reflect" - "strconv" - "strings" - "time" -) - -// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns -// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. -func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { - // Create variables here so we can reference them with the reflect pkg - var f1 DecodeHookFuncType - var f2 DecodeHookFuncKind - - // Fill in the variables into this interface and the rest is done - // automatically using the reflect package. - potential := []interface{}{f1, f2} - - v := reflect.ValueOf(h) - vt := v.Type() - for _, raw := range potential { - pt := reflect.ValueOf(raw).Type() - if vt.ConvertibleTo(pt) { - return v.Convert(pt).Interface() - } - } - - return nil -} - -// DecodeHookExec executes the given decode hook. This should be used -// since it'll naturally degrade to the older backwards compatible DecodeHookFunc -// that took reflect.Kind instead of reflect.Type. -func DecodeHookExec( - raw DecodeHookFunc, - from reflect.Type, to reflect.Type, - data interface{}) (interface{}, error) { - switch f := typedDecodeHook(raw).(type) { - case DecodeHookFuncType: - return f(from, to, data) - case DecodeHookFuncKind: - return f(from.Kind(), to.Kind(), data) - default: - return nil, errors.New("invalid decode hook signature") - } -} - -// ComposeDecodeHookFunc creates a single DecodeHookFunc that -// automatically composes multiple DecodeHookFuncs. -// -// The composed funcs are called in order, with the result of the -// previous transformation. -func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - var err error - for _, f1 := range fs { - data, err = DecodeHookExec(f1, f, t, data) - if err != nil { - return nil, err - } - - // Modify the from kind to be correct with the new data - f = nil - if val := reflect.ValueOf(data); val.IsValid() { - f = val.Type() - } - } - - return data, nil - } -} - -// StringToSliceHookFunc returns a DecodeHookFunc that converts -// string to []string by splitting on the given sep. -func StringToSliceHookFunc(sep string) DecodeHookFunc { - return func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - if f != reflect.String || t != reflect.Slice { - return data, nil - } - - raw := data.(string) - if raw == "" { - return []string{}, nil - } - - return strings.Split(raw, sep), nil - } -} - -// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts -// strings to time.Duration. -func StringToTimeDurationHookFunc() DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(time.Duration(5)) { - return data, nil - } - - // Convert it by parsing - return time.ParseDuration(data.(string)) - } -} - -// StringToIPHookFunc returns a DecodeHookFunc that converts -// strings to net.IP -func StringToIPHookFunc() DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(net.IP{}) { - return data, nil - } - - // Convert it by parsing - ip := net.ParseIP(data.(string)) - if ip == nil { - return net.IP{}, fmt.Errorf("failed parsing ip %v", data) - } - - return ip, nil - } -} - -// StringToIPNetHookFunc returns a DecodeHookFunc that converts -// strings to net.IPNet -func StringToIPNetHookFunc() DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(net.IPNet{}) { - return data, nil - } - - // Convert it by parsing - _, net, err := net.ParseCIDR(data.(string)) - return net, err - } -} - -// StringToTimeHookFunc returns a DecodeHookFunc that converts -// strings to time.Time. -func StringToTimeHookFunc(layout string) DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(time.Time{}) { - return data, nil - } - - // Convert it by parsing - return time.Parse(layout, data.(string)) - } -} - -// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to -// the decoder. -// -// Note that this is significantly different from the WeaklyTypedInput option -// of the DecoderConfig. -func WeaklyTypedHook( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - dataVal := reflect.ValueOf(data) - switch t { - case reflect.String: - switch f { - case reflect.Bool: - if dataVal.Bool() { - return "1", nil - } - return "0", nil - case reflect.Float32: - return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil - case reflect.Int: - return strconv.FormatInt(dataVal.Int(), 10), nil - case reflect.Slice: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - if elemKind == reflect.Uint8 { - return string(dataVal.Interface().([]uint8)), nil - } - case reflect.Uint: - return strconv.FormatUint(dataVal.Uint(), 10), nil - } - } - - return data, nil -} diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go deleted file mode 100644 index 47a99e5a..00000000 --- a/vendor/github.com/mitchellh/mapstructure/error.go +++ /dev/null @@ -1,50 +0,0 @@ -package mapstructure - -import ( - "errors" - "fmt" - "sort" - "strings" -) - -// Error implements the error interface and can represents multiple -// errors that occur in the course of a single decode. -type Error struct { - Errors []string -} - -func (e *Error) Error() string { - points := make([]string, len(e.Errors)) - for i, err := range e.Errors { - points[i] = fmt.Sprintf("* %s", err) - } - - sort.Strings(points) - return fmt.Sprintf( - "%d error(s) decoding:\n\n%s", - len(e.Errors), strings.Join(points, "\n")) -} - -// WrappedErrors implements the errwrap.Wrapper interface to make this -// return value more useful with the errwrap and go-multierror libraries. -func (e *Error) WrappedErrors() []error { - if e == nil { - return nil - } - - result := make([]error, len(e.Errors)) - for i, e := range e.Errors { - result[i] = errors.New(e) - } - - return result -} - -func appendErrors(errors []string, err error) []string { - switch e := err.(type) { - case *Error: - return append(errors, e.Errors...) - default: - return append(errors, e.Error()) - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/go.mod b/vendor/github.com/mitchellh/mapstructure/go.mod deleted file mode 100644 index d2a71256..00000000 --- a/vendor/github.com/mitchellh/mapstructure/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/mapstructure diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go deleted file mode 100644 index 256ee63f..00000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ /dev/null @@ -1,1149 +0,0 @@ -// Package mapstructure exposes functionality to convert an arbitrary -// map[string]interface{} into a native Go structure. -// -// The Go structure can be arbitrarily complex, containing slices, -// other structs, etc. and the decoder will properly decode nested -// maps and so on into the proper structures in the native Go struct. -// See the examples to see what the decoder is capable of. -package mapstructure - -import ( - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "strconv" - "strings" -) - -// DecodeHookFunc is the callback function that can be used for -// data transformations. See "DecodeHook" in the DecoderConfig -// struct. -// -// The type should be DecodeHookFuncType or DecodeHookFuncKind. -// Either is accepted. Types are a superset of Kinds (Types can return -// Kinds) and are generally a richer thing to use, but Kinds are simpler -// if you only need those. -// -// The reason DecodeHookFunc is multi-typed is for backwards compatibility: -// we started with Kinds and then realized Types were the better solution, -// but have a promise to not break backwards compat so we now support -// both. -type DecodeHookFunc interface{} - -// DecodeHookFuncType is a DecodeHookFunc which has complete information about -// the source and target types. -type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) - -// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the -// source and target types. -type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) - -// DecoderConfig is the configuration that is used to create a new decoder -// and allows customization of various aspects of decoding. -type DecoderConfig struct { - // DecodeHook, if set, will be called before any decoding and any - // type conversion (if WeaklyTypedInput is on). This lets you modify - // the values before they're set down onto the resulting struct. - // - // If an error is returned, the entire decode will fail with that - // error. - DecodeHook DecodeHookFunc - - // If ErrorUnused is true, then it is an error for there to exist - // keys in the original map that were unused in the decoding process - // (extra keys). - ErrorUnused bool - - // ZeroFields, if set to true, will zero fields before writing them. - // For example, a map will be emptied before decoded values are put in - // it. If this is false, a map will be merged. - ZeroFields bool - - // If WeaklyTypedInput is true, the decoder will make the following - // "weak" conversions: - // - // - bools to string (true = "1", false = "0") - // - numbers to string (base 10) - // - bools to int/uint (true = 1, false = 0) - // - strings to int/uint (base implied by prefix) - // - int to bool (true if value != 0) - // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, - // FALSE, false, False. Anything else is an error) - // - empty array = empty map and vice versa - // - negative numbers to overflowed uint values (base 10) - // - slice of maps to a merged map - // - single values are converted to slices if required. Each - // element is weakly decoded. For example: "4" can become []int{4} - // if the target type is an int slice. - // - WeaklyTypedInput bool - - // Metadata is the struct that will contain extra metadata about - // the decoding. If this is nil, then no metadata will be tracked. - Metadata *Metadata - - // Result is a pointer to the struct that will contain the decoded - // value. - Result interface{} - - // The tag name that mapstructure reads for field names. This - // defaults to "mapstructure" - TagName string -} - -// A Decoder takes a raw interface value and turns it into structured -// data, keeping track of rich error information along the way in case -// anything goes wrong. Unlike the basic top-level Decode method, you can -// more finely control how the Decoder behaves using the DecoderConfig -// structure. The top-level Decode method is just a convenience that sets -// up the most basic Decoder. -type Decoder struct { - config *DecoderConfig -} - -// Metadata contains information about decoding a structure that -// is tedious or difficult to get otherwise. -type Metadata struct { - // Keys are the keys of the structure which were successfully decoded - Keys []string - - // Unused is a slice of keys that were found in the raw value but - // weren't decoded since there was no matching field in the result interface - Unused []string -} - -// Decode takes an input structure and uses reflection to translate it to -// the output structure. output must be a pointer to a map or struct. -func Decode(input interface{}, output interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: output, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// WeakDecode is the same as Decode but is shorthand to enable -// WeaklyTypedInput. See DecoderConfig for more info. -func WeakDecode(input, output interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: output, - WeaklyTypedInput: true, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// DecodeMetadata is the same as Decode, but is shorthand to -// enable metadata collection. See DecoderConfig for more info. -func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { - config := &DecoderConfig{ - Metadata: metadata, - Result: output, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// WeakDecodeMetadata is the same as Decode, but is shorthand to -// enable both WeaklyTypedInput and metadata collection. See -// DecoderConfig for more info. -func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { - config := &DecoderConfig{ - Metadata: metadata, - Result: output, - WeaklyTypedInput: true, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// NewDecoder returns a new decoder for the given configuration. Once -// a decoder has been returned, the same configuration must not be used -// again. -func NewDecoder(config *DecoderConfig) (*Decoder, error) { - val := reflect.ValueOf(config.Result) - if val.Kind() != reflect.Ptr { - return nil, errors.New("result must be a pointer") - } - - val = val.Elem() - if !val.CanAddr() { - return nil, errors.New("result must be addressable (a pointer)") - } - - if config.Metadata != nil { - if config.Metadata.Keys == nil { - config.Metadata.Keys = make([]string, 0) - } - - if config.Metadata.Unused == nil { - config.Metadata.Unused = make([]string, 0) - } - } - - if config.TagName == "" { - config.TagName = "mapstructure" - } - - result := &Decoder{ - config: config, - } - - return result, nil -} - -// Decode decodes the given raw interface to the target pointer specified -// by the configuration. -func (d *Decoder) Decode(input interface{}) error { - return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) -} - -// Decodes an unknown data type into a specific reflection value. -func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { - var inputVal reflect.Value - if input != nil { - inputVal = reflect.ValueOf(input) - - // We need to check here if input is a typed nil. Typed nils won't - // match the "input == nil" below so we check that here. - if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { - input = nil - } - } - - if input == nil { - // If the data is nil, then we don't set anything, unless ZeroFields is set - // to true. - if d.config.ZeroFields { - outVal.Set(reflect.Zero(outVal.Type())) - - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - } - return nil - } - - if !inputVal.IsValid() { - // If the input value is invalid, then we just set the value - // to be the zero value. - outVal.Set(reflect.Zero(outVal.Type())) - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - return nil - } - - if d.config.DecodeHook != nil { - // We have a DecodeHook, so let's pre-process the input. - var err error - input, err = DecodeHookExec( - d.config.DecodeHook, - inputVal.Type(), outVal.Type(), input) - if err != nil { - return fmt.Errorf("error decoding '%s': %s", name, err) - } - } - - var err error - outputKind := getKind(outVal) - switch outputKind { - case reflect.Bool: - err = d.decodeBool(name, input, outVal) - case reflect.Interface: - err = d.decodeBasic(name, input, outVal) - case reflect.String: - err = d.decodeString(name, input, outVal) - case reflect.Int: - err = d.decodeInt(name, input, outVal) - case reflect.Uint: - err = d.decodeUint(name, input, outVal) - case reflect.Float32: - err = d.decodeFloat(name, input, outVal) - case reflect.Struct: - err = d.decodeStruct(name, input, outVal) - case reflect.Map: - err = d.decodeMap(name, input, outVal) - case reflect.Ptr: - err = d.decodePtr(name, input, outVal) - case reflect.Slice: - err = d.decodeSlice(name, input, outVal) - case reflect.Array: - err = d.decodeArray(name, input, outVal) - case reflect.Func: - err = d.decodeFunc(name, input, outVal) - default: - // If we reached this point then we weren't able to decode it - return fmt.Errorf("%s: unsupported type: %s", name, outputKind) - } - - // If we reached here, then we successfully decoded SOMETHING, so - // mark the key as used if we're tracking metainput. - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - - return err -} - -// This decodes a basic type (bool, int, string, etc.) and sets the -// value to "data" of that type. -func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { - if val.IsValid() && val.Elem().IsValid() { - return d.decode(name, data, val.Elem()) - } - - dataVal := reflect.ValueOf(data) - - // If the input data is a pointer, and the assigned type is the dereference - // of that exact pointer, then indirect it so that we can assign it. - // Example: *string to string - if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { - dataVal = reflect.Indirect(dataVal) - } - - if !dataVal.IsValid() { - dataVal = reflect.Zero(val.Type()) - } - - dataValType := dataVal.Type() - if !dataValType.AssignableTo(val.Type()) { - return fmt.Errorf( - "'%s' expected type '%s', got '%s'", - name, val.Type(), dataValType) - } - - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataKind := getKind(dataVal) - - converted := true - switch { - case dataKind == reflect.String: - val.SetString(dataVal.String()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetString("1") - } else { - val.SetString("0") - } - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatInt(dataVal.Int(), 10)) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) - case dataKind == reflect.Slice && d.config.WeaklyTypedInput, - dataKind == reflect.Array && d.config.WeaklyTypedInput: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - switch elemKind { - case reflect.Uint8: - var uints []uint8 - if dataKind == reflect.Array { - uints = make([]uint8, dataVal.Len(), dataVal.Len()) - for i := range uints { - uints[i] = dataVal.Index(i).Interface().(uint8) - } - } else { - uints = dataVal.Interface().([]uint8) - } - val.SetString(string(uints)) - default: - converted = false - } - default: - converted = false - } - - if !converted { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetInt(dataVal.Int()) - case dataKind == reflect.Uint: - val.SetInt(int64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetInt(int64(dataVal.Float())) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetInt(1) - } else { - val.SetInt(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetInt(i) - } else { - return fmt.Errorf("cannot parse '%s' as int: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Int64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetInt(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Int: - i := dataVal.Int() - if i < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %d overflows uint", - name, i) - } - val.SetUint(uint64(i)) - case dataKind == reflect.Uint: - val.SetUint(dataVal.Uint()) - case dataKind == reflect.Float32: - f := dataVal.Float() - if f < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %f overflows uint", - name, f) - } - val.SetUint(uint64(f)) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetUint(1) - } else { - val.SetUint(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetUint(i) - } else { - return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Bool: - val.SetBool(dataVal.Bool()) - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Int() != 0) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Uint() != 0) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Float() != 0) - case dataKind == reflect.String && d.config.WeaklyTypedInput: - b, err := strconv.ParseBool(dataVal.String()) - if err == nil { - val.SetBool(b) - } else if dataVal.String() == "" { - val.SetBool(false) - } else { - return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetFloat(float64(dataVal.Int())) - case dataKind == reflect.Uint: - val.SetFloat(float64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetFloat(dataVal.Float()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetFloat(1) - } else { - val.SetFloat(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits()) - if err == nil { - val.SetFloat(f) - } else { - return fmt.Errorf("cannot parse '%s' as float: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Float64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetFloat(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { - valType := val.Type() - valKeyType := valType.Key() - valElemType := valType.Elem() - - // By default we overwrite keys in the current map - valMap := val - - // If the map is nil or we're purposely zeroing fields, make a new map - if valMap.IsNil() || d.config.ZeroFields { - // Make a new map to hold our result - mapType := reflect.MapOf(valKeyType, valElemType) - valMap = reflect.MakeMap(mapType) - } - - // Check input type and based on the input type jump to the proper func - dataVal := reflect.Indirect(reflect.ValueOf(data)) - switch dataVal.Kind() { - case reflect.Map: - return d.decodeMapFromMap(name, dataVal, val, valMap) - - case reflect.Struct: - return d.decodeMapFromStruct(name, dataVal, val, valMap) - - case reflect.Array, reflect.Slice: - if d.config.WeaklyTypedInput { - return d.decodeMapFromSlice(name, dataVal, val, valMap) - } - - fallthrough - - default: - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) - } -} - -func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - // Special case for BC reasons (covered by tests) - if dataVal.Len() == 0 { - val.Set(valMap) - return nil - } - - for i := 0; i < dataVal.Len(); i++ { - err := d.decode( - fmt.Sprintf("%s[%d]", name, i), - dataVal.Index(i).Interface(), val) - if err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - valType := val.Type() - valKeyType := valType.Key() - valElemType := valType.Elem() - - // Accumulate errors - errors := make([]string, 0) - - // If the input data is empty, then we just match what the input data is. - if dataVal.Len() == 0 { - if dataVal.IsNil() { - if !val.IsNil() { - val.Set(dataVal) - } - } else { - // Set to empty allocated value - val.Set(valMap) - } - - return nil - } - - for _, k := range dataVal.MapKeys() { - fieldName := fmt.Sprintf("%s[%s]", name, k) - - // First decode the key into the proper type - currentKey := reflect.Indirect(reflect.New(valKeyType)) - if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { - errors = appendErrors(errors, err) - continue - } - - // Next decode the data into the proper type - v := dataVal.MapIndex(k).Interface() - currentVal := reflect.Indirect(reflect.New(valElemType)) - if err := d.decode(fieldName, v, currentVal); err != nil { - errors = appendErrors(errors, err) - continue - } - - valMap.SetMapIndex(currentKey, currentVal) - } - - // Set the built up map to the value - val.Set(valMap) - - // If we had errors, return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - typ := dataVal.Type() - for i := 0; i < typ.NumField(); i++ { - // Get the StructField first since this is a cheap operation. If the - // field is unexported, then ignore it. - f := typ.Field(i) - if f.PkgPath != "" { - continue - } - - // Next get the actual value of this field and verify it is assignable - // to the map value. - v := dataVal.Field(i) - if !v.Type().AssignableTo(valMap.Type().Elem()) { - return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) - } - - tagValue := f.Tag.Get(d.config.TagName) - tagParts := strings.Split(tagValue, ",") - - // Determine the name of the key in the map - keyName := f.Name - if tagParts[0] != "" { - if tagParts[0] == "-" { - continue - } - keyName = tagParts[0] - } - - // If "squash" is specified in the tag, we squash the field down. - squash := false - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - if squash && v.Kind() != reflect.Struct { - return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) - } - - switch v.Kind() { - // this is an embedded struct, so handle it differently - case reflect.Struct: - x := reflect.New(v.Type()) - x.Elem().Set(v) - - vType := valMap.Type() - vKeyType := vType.Key() - vElemType := vType.Elem() - mType := reflect.MapOf(vKeyType, vElemType) - vMap := reflect.MakeMap(mType) - - err := d.decode(keyName, x.Interface(), vMap) - if err != nil { - return err - } - - if squash { - for _, k := range vMap.MapKeys() { - valMap.SetMapIndex(k, vMap.MapIndex(k)) - } - } else { - valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) - } - - default: - valMap.SetMapIndex(reflect.ValueOf(keyName), v) - } - } - - if val.CanAddr() { - val.Set(valMap) - } - - return nil -} - -func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error { - // If the input data is nil, then we want to just set the output - // pointer to be nil as well. - isNil := data == nil - if !isNil { - switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { - case reflect.Chan, - reflect.Func, - reflect.Interface, - reflect.Map, - reflect.Ptr, - reflect.Slice: - isNil = v.IsNil() - } - } - if isNil { - if !val.IsNil() && val.CanSet() { - nilValue := reflect.New(val.Type()).Elem() - val.Set(nilValue) - } - - return nil - } - - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - valType := val.Type() - valElemType := valType.Elem() - if val.CanSet() { - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } - - if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { - return err - } - - val.Set(realVal) - } else { - if err := d.decode(name, data, reflect.Indirect(val)); err != nil { - return err - } - } - return nil -} - -func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - dataVal := reflect.Indirect(reflect.ValueOf(data)) - if val.Type() != dataVal.Type() { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataValKind := dataVal.Kind() - valType := val.Type() - valElemType := valType.Elem() - sliceType := reflect.SliceOf(valElemType) - - valSlice := val - if valSlice.IsNil() || d.config.ZeroFields { - if d.config.WeaklyTypedInput { - switch { - // Slice and array we use the normal logic - case dataValKind == reflect.Slice, dataValKind == reflect.Array: - break - - // Empty maps turn into empty slices - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } - // Create slice of maps of other sizes - return d.decodeSlice(name, []interface{}{data}, val) - - case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: - return d.decodeSlice(name, []byte(dataVal.String()), val) - - // All other types we try to convert to the slice type - // and "lift" it into it. i.e. a string becomes a string slice. - default: - // Just re-try this function with data as a slice. - return d.decodeSlice(name, []interface{}{data}, val) - } - } - - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) - - } - - // If the input value is empty, then don't allocate since non-nil != nil - if dataVal.Len() == 0 { - return nil - } - - // Make a new slice to hold our result, same size as the original data. - valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) - } - - // Accumulate any errors - errors := make([]string, 0) - - for i := 0; i < dataVal.Len(); i++ { - currentData := dataVal.Index(i).Interface() - for valSlice.Len() <= i { - valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) - } - currentField := valSlice.Index(i) - - fieldName := fmt.Sprintf("%s[%d]", name, i) - if err := d.decode(fieldName, currentData, currentField); err != nil { - errors = appendErrors(errors, err) - } - } - - // Finally, set the value to the slice we built up - val.Set(valSlice) - - // If there were errors, we return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataValKind := dataVal.Kind() - valType := val.Type() - valElemType := valType.Elem() - arrayType := reflect.ArrayOf(valType.Len(), valElemType) - - valArray := val - - if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - if d.config.WeaklyTypedInput { - switch { - // Empty maps turn into empty arrays - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.Zero(arrayType)) - return nil - } - - // All other types we try to convert to the array type - // and "lift" it into it. i.e. a string becomes a string array. - default: - // Just re-try this function with data as a slice. - return d.decodeArray(name, []interface{}{data}, val) - } - } - - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) - - } - if dataVal.Len() > arrayType.Len() { - return fmt.Errorf( - "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) - - } - - // Make a new array to hold our result, same size as the original data. - valArray = reflect.New(arrayType).Elem() - } - - // Accumulate any errors - errors := make([]string, 0) - - for i := 0; i < dataVal.Len(); i++ { - currentData := dataVal.Index(i).Interface() - currentField := valArray.Index(i) - - fieldName := fmt.Sprintf("%s[%d]", name, i) - if err := d.decode(fieldName, currentData, currentField); err != nil { - errors = appendErrors(errors, err) - } - } - - // Finally, set the value to the array we built up - val.Set(valArray) - - // If there were errors, we return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - - // If the type of the value to write to and the data match directly, - // then we just set it directly instead of recursing into the structure. - if dataVal.Type() == val.Type() { - val.Set(dataVal) - return nil - } - - dataValKind := dataVal.Kind() - switch dataValKind { - case reflect.Map: - return d.decodeStructFromMap(name, dataVal, val) - - case reflect.Struct: - // Not the most efficient way to do this but we can optimize later if - // we want to. To convert from struct to struct we go to map first - // as an intermediary. - m := make(map[string]interface{}) - mval := reflect.Indirect(reflect.ValueOf(&m)) - if err := d.decodeMapFromStruct(name, dataVal, mval, mval); err != nil { - return err - } - - result := d.decodeStructFromMap(name, mval, val) - return result - - default: - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) - } -} - -func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error { - dataValType := dataVal.Type() - if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { - return fmt.Errorf( - "'%s' needs a map with string keys, has '%s' keys", - name, dataValType.Key().Kind()) - } - - dataValKeys := make(map[reflect.Value]struct{}) - dataValKeysUnused := make(map[interface{}]struct{}) - for _, dataValKey := range dataVal.MapKeys() { - dataValKeys[dataValKey] = struct{}{} - dataValKeysUnused[dataValKey.Interface()] = struct{}{} - } - - errors := make([]string, 0) - - // This slice will keep track of all the structs we'll be decoding. - // There can be more than one struct if there are embedded structs - // that are squashed. - structs := make([]reflect.Value, 1, 5) - structs[0] = val - - // Compile the list of all the fields that we're going to be decoding - // from all the structs. - type field struct { - field reflect.StructField - val reflect.Value - } - fields := []field{} - for len(structs) > 0 { - structVal := structs[0] - structs = structs[1:] - - structType := structVal.Type() - - for i := 0; i < structType.NumField(); i++ { - fieldType := structType.Field(i) - fieldKind := fieldType.Type.Kind() - - // If "squash" is specified in the tag, we squash the field down. - squash := false - tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - - if squash { - if fieldKind != reflect.Struct { - errors = appendErrors(errors, - fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) - } else { - structs = append(structs, structVal.FieldByName(fieldType.Name)) - } - continue - } - - // Normal struct field, store it away - fields = append(fields, field{fieldType, structVal.Field(i)}) - } - } - - // for fieldType, field := range fields { - for _, f := range fields { - field, fieldValue := f.field, f.val - fieldName := field.Name - - tagValue := field.Tag.Get(d.config.TagName) - tagValue = strings.SplitN(tagValue, ",", 2)[0] - if tagValue != "" { - fieldName = tagValue - } - - rawMapKey := reflect.ValueOf(fieldName) - rawMapVal := dataVal.MapIndex(rawMapKey) - if !rawMapVal.IsValid() { - // Do a slower search by iterating over each key and - // doing case-insensitive search. - for dataValKey := range dataValKeys { - mK, ok := dataValKey.Interface().(string) - if !ok { - // Not a string key - continue - } - - if strings.EqualFold(mK, fieldName) { - rawMapKey = dataValKey - rawMapVal = dataVal.MapIndex(dataValKey) - break - } - } - - if !rawMapVal.IsValid() { - // There was no matching key in the map for the value in - // the struct. Just ignore. - continue - } - } - - // Delete the key we're using from the unused map so we stop tracking - delete(dataValKeysUnused, rawMapKey.Interface()) - - if !fieldValue.IsValid() { - // This should never happen - panic("field is not valid") - } - - // If we can't set the field, then it is unexported or something, - // and we just continue onwards. - if !fieldValue.CanSet() { - continue - } - - // If the name is empty string, then we're at the root, and we - // don't dot-join the fields. - if name != "" { - fieldName = fmt.Sprintf("%s.%s", name, fieldName) - } - - if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { - errors = appendErrors(errors, err) - } - } - - if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { - keys := make([]string, 0, len(dataValKeysUnused)) - for rawKey := range dataValKeysUnused { - keys = append(keys, rawKey.(string)) - } - sort.Strings(keys) - - err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) - errors = appendErrors(errors, err) - } - - if len(errors) > 0 { - return &Error{errors} - } - - // Add the unused keys to the list of unused keys if we're tracking metadata - if d.config.Metadata != nil { - for rawKey := range dataValKeysUnused { - key := rawKey.(string) - if name != "" { - key = fmt.Sprintf("%s.%s", name, key) - } - - d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) - } - } - - return nil -} - -func getKind(val reflect.Value) reflect.Kind { - kind := val.Kind() - - switch { - case kind >= reflect.Int && kind <= reflect.Int64: - return reflect.Int - case kind >= reflect.Uint && kind <= reflect.Uint64: - return reflect.Uint - case kind >= reflect.Float32 && kind <= reflect.Float64: - return reflect.Float32 - default: - return kind - } -} diff --git a/vendor/github.com/mitchellh/reflectwalk/.travis.yml b/vendor/github.com/mitchellh/reflectwalk/.travis.yml deleted file mode 100644 index 4f2ee4d9..00000000 --- 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 f9c841a5..00000000 --- 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 ac82cd2e..00000000 --- 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/go.mod b/vendor/github.com/mitchellh/reflectwalk/go.mod deleted file mode 100644 index 52bb7c46..00000000 --- a/vendor/github.com/mitchellh/reflectwalk/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/reflectwalk diff --git a/vendor/github.com/mitchellh/reflectwalk/location.go b/vendor/github.com/mitchellh/reflectwalk/location.go deleted file mode 100644 index 6a7f1761..00000000 --- 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 70760cf4..00000000 --- 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 d7ab7b6d..00000000 --- a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go +++ /dev/null @@ -1,401 +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 -} - -// 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 { - 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) - } - - if err := walk(kv, 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 a1338d68..00000000 --- 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/.travis.yml b/vendor/github.com/oklog/run/.travis.yml deleted file mode 100644 index 362bdd41..00000000 --- a/vendor/github.com/oklog/run/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -sudo: false -go: - - 1.x - - tip -install: - - go get -v github.com/golang/lint/golint - - go build ./... -script: - - go vet ./... - - $HOME/gopath/bin/golint . - - go test -v -race ./... diff --git a/vendor/github.com/oklog/run/LICENSE b/vendor/github.com/oklog/run/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- 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 a7228cd9..00000000 --- a/vendor/github.com/oklog/run/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# run - -[![GoDoc](https://godoc.org/github.com/oklog/run?status.svg)](https://godoc.org/github.com/oklog/run) -[![Build Status](https://travis-ci.org/oklog/run.svg?branch=master)](https://travis-ci.org/oklog/run) -[![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 blocks until the first actor -returns. 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/group.go b/vendor/github.com/oklog/run/group.go deleted file mode 100644 index 832d47dd..00000000 --- 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/onsi/ginkgo/.gitignore b/vendor/github.com/onsi/ginkgo/.gitignore deleted file mode 100644 index b9f9659d..00000000 --- a/vendor/github.com/onsi/ginkgo/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -.DS_Store -TODO -tmp/**/* -*.coverprofile -.vscode -.idea/ -*.log diff --git a/vendor/github.com/onsi/ginkgo/.travis.yml b/vendor/github.com/onsi/ginkgo/.travis.yml deleted file mode 100644 index 3900878b..00000000 --- a/vendor/github.com/onsi/ginkgo/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: go -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - -install: - - go get -v -t ./... - - go get golang.org/x/tools/cmd/cover - - go get github.com/onsi/gomega - - go install github.com/onsi/ginkgo/ginkgo - - export PATH=$PATH:$HOME/gopath/bin - -script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --randomizeSuites --race --trace && go vet diff --git a/vendor/github.com/onsi/ginkgo/CHANGELOG.md b/vendor/github.com/onsi/ginkgo/CHANGELOG.md deleted file mode 100644 index d7d79701..00000000 --- a/vendor/github.com/onsi/ginkgo/CHANGELOG.md +++ /dev/null @@ -1,207 +0,0 @@ -## 1.7.0 - -### New Features -- Add JustAfterEach (#484) [0d4f080] - -### Fixes -- Correctly round suite time in junit reporter [2445fc1] -- Avoid using -i argument to go test for Golang 1.10+ [46bbc26] - -## 1.6.0 - -### New Features -- add --debug flag to emit node output to files (#499) [39febac] - -### Fixes -- fix: for `go vet` to pass [69338ec] -- docs: fix for contributing instructions [7004cb1] -- consolidate and streamline contribution docs (#494) [d848015] -- Make generated Junit file compatable with "Maven Surefire" (#488) [e51bee6] -- all: gofmt [000d317] -- Increase eventually timeout to 30s [c73579c] -- Clarify asynchronous test behaviour [294d8f4] -- Travis badge should only show master [26d2143] - -## 1.5.0 5/10/2018 - -### New Features -- Supports go v1.10 (#443, #446, #451) [e873237, 468e89e, e37dbfe, a37f4c0, c0b857d, bca5260, 4177ca8] -- Add a When() synonym for Context() (#386) [747514b, 7484dad, 7354a07, dd826c8] -- Re-add noisySkippings flag [652e15c] -- Allow coverage to be displayed for focused specs (#367) [11459a8] -- Handle -outputdir flag (#364) [228e3a8] -- Handle -coverprofile flag (#355) [43392d5] - -### Fixes -- When using custom reporters register the custom reporters *before* the default reporter. This allows users to see the output of any print statements in their customer reporters. (#365) [8382b23] -- When running a test and calculating the coverage using the `-coverprofile` and `-outputdir` flags, Ginkgo fails with an error if the directory does not exist. This is due to an [issue in go 1.10](https://github.com/golang/go/issues/24588) (#446) [b36a6e0] -- `unfocus` command ignores vendor folder (#459) [e5e551c, c556e43, a3b6351, 9a820dd] -- Ignore packages whose tests are all ignored by go (#456) [7430ca7, 6d8be98] -- Increase the threshold when checking time measuments (#455) [2f714bf, 68f622c] -- Fix race condition in coverage tests (#423) [a5a8ff7, ab9c08b] -- Add an extra new line after reporting spec run completion for test2json [874520d] -- added name name field to junit reported testsuite [ae61c63] -- Do not set the run time of a spec when the dryRun flag is used (#438) [457e2d9, ba8e856] -- Process FWhen and FSpecify when unfocusing (#434) [9008c7b, ee65bd, df87dfe] -- Synchronise the access to the state of specs to avoid race conditions (#430) [7d481bc, ae6829d] -- Added Duration on GinkgoTestDescription (#383) [5f49dad, 528417e, 0747408, 329d7ed] -- Fix Ginkgo stack trace on failure for Specify (#415) [b977ede, 65ca40e, 6c46eb8] -- Update README with Go 1.6+, Golang -> Go (#409) [17f6b97, bc14b66, 20d1598] -- Use fmt.Errorf instead of errors.New(fmt.Sprintf (#401) [a299f56, 44e2eaa] -- Imports in generated code should follow conventions (#398) [0bec0b0, e8536d8] -- Prevent data race error when Recording a benchmark value from multiple go routines (#390) [c0c4881, 7a241e9] -- Replace GOPATH in Environment [4b883f0] - - -## 1.4.0 7/16/2017 - -- `ginkgo` now provides a hint if you accidentally forget to run `ginkgo bootstrap` to generate a `*_suite_test.go` file that actually invokes the Ginkgo test runner. [#345](https://github.com/onsi/ginkgo/pull/345) -- thanks to improvements in `go test -c` `ginkgo` no longer needs to fix Go's compilation output to ensure compilation errors are expressed relative to the CWD. [#357] -- `ginkgo watch -watchRegExp=...` allows you to specify a custom regular expression to watch. Only files matching the regular expression are watched for changes (the default is `\.go$`) [#356] -- `ginkgo` now always emits compilation output. Previously, only failed compilation output was printed out. [#277] -- `ginkgo -requireSuite` now fails the test run if there are `*_test.go` files but `go test` fails to detect any tests. Typically this means you forgot to run `ginkgo bootstrap` to generate a suite file. [#344] -- `ginkgo -timeout=DURATION` allows you to adjust the timeout for the entire test suite (default is 24 hours) [#248] - -## 1.3.0 3/28/2017 - -Improvements: - -- Significantly improved parallel test distribution. Now instead of pre-sharding test cases across workers (which can result in idle workers and poor test performance) Ginkgo uses a shared queue to keep all workers busy until all tests are complete. This improves test-time performance and consistency. -- `Skip(message)` can be used to skip the current test. -- Added `extensions/table` - a Ginkgo DSL for [Table Driven Tests](http://onsi.github.io/ginkgo/#table-driven-tests) -- Add `GinkgoRandomSeed()` - shorthand for `config.GinkgoConfig.RandomSeed` -- Support for retrying flaky tests with `--flakeAttempts` -- `ginkgo ./...` now recurses as you'd expect -- Added `Specify` a synonym for `It` -- Support colorise on Windows -- Broader support for various go compilation flags in the `ginkgo` CLI - -Bug Fixes: - -- Ginkgo tests now fail when you `panic(nil)` (#167) - -## 1.2.0 5/31/2015 - -Improvements - -- `ginkgo -coverpkg` calls down to `go test -coverpkg` (#160) -- `ginkgo -afterSuiteHook COMMAND` invokes the passed-in `COMMAND` after a test suite completes (#152) -- Relaxed requirement for Go 1.4+. `ginkgo` now works with Go v1.3+ (#166) - -## 1.2.0-beta - -Ginkgo now requires Go 1.4+ - -Improvements: - -- Call reporters in reverse order when announcing spec completion -- allows custom reporters to emit output before the default reporter does. -- Improved focus behavior. Now, this: - - ```golang - FDescribe("Some describe", func() { - It("A", func() {}) - - FIt("B", func() {}) - }) - ``` - - will run `B` but *not* `A`. This tends to be a common usage pattern when in the thick of writing and debugging tests. -- When `SIGINT` is received, Ginkgo will emit the contents of the `GinkgoWriter` before running the `AfterSuite`. Useful for debugging stuck tests. -- When `--progress` is set, Ginkgo will write test progress (in particular, Ginkgo will say when it is about to run a BeforeEach, AfterEach, It, etc...) to the `GinkgoWriter`. This is useful for debugging stuck tests and tests that generate many logs. -- Improved output when an error occurs in a setup or teardown block. -- When `--dryRun` is set, Ginkgo will walk the spec tree and emit to its reporter *without* actually running anything. Best paired with `-v` to understand which specs will run in which order. -- Add `By` to help document long `It`s. `By` simply writes to the `GinkgoWriter`. -- Add support for precompiled tests: - - `ginkgo build ` will now compile the package, producing a file named `package.test` - - The compiled `package.test` file can be run directly. This runs the tests in series. - - To run precompiled tests in parallel, you can run: `ginkgo -p package.test` -- Support `bootstrap`ping and `generate`ing [Agouti](http://agouti.org) specs. -- `ginkgo generate` and `ginkgo bootstrap` now honor the package name already defined in a given directory -- The `ginkgo` CLI ignores `SIGQUIT`. Prevents its stack dump from interlacing with the underlying test suite's stack dump. -- The `ginkgo` CLI now compiles tests into a temporary directory instead of the package directory. This necessitates upgrading to Go v1.4+. -- `ginkgo -notify` now works on Linux - -Bug Fixes: - -- If --skipPackages is used and all packages are skipped, Ginkgo should exit 0. -- Fix tempfile leak when running in parallel -- Fix incorrect failure message when a panic occurs during a parallel test run -- Fixed an issue where a pending test within a focused context (or a focused test within a pending context) would skip all other tests. -- Be more consistent about handling SIGTERM as well as SIGINT -- When interupted while concurrently compiling test suites in the background, Ginkgo now cleans up the compiled artifacts. -- Fixed a long standing bug where `ginkgo -p` would hang if a process spawned by one of the Ginkgo parallel nodes does not exit. (Hooray!) - -## 1.1.0 (8/2/2014) - -No changes, just dropping the beta. - -## 1.1.0-beta (7/22/2014) -New Features: - -- `ginkgo watch` now monitors packages *and their dependencies* for changes. The depth of the dependency tree can be modified with the `-depth` flag. -- Test suites with a programmatic focus (`FIt`, `FDescribe`, etc...) exit with non-zero status code, even when they pass. This allows CI systems to detect accidental commits of focused test suites. -- `ginkgo -p` runs the testsuite in parallel with an auto-detected number of nodes. -- `ginkgo -tags=TAG_LIST` passes a list of tags down to the `go build` command. -- `ginkgo --failFast` aborts the test suite after the first failure. -- `ginkgo generate file_1 file_2` can take multiple file arguments. -- Ginkgo now summarizes any spec failures that occured at the end of the test run. -- `ginkgo --randomizeSuites` will run tests *suites* in random order using the generated/passed-in seed. - -Improvements: - -- `ginkgo -skipPackage` now takes a comma-separated list of strings. If the *relative path* to a package matches one of the entries in the comma-separated list, that package is skipped. -- `ginkgo --untilItFails` no longer recompiles between attempts. -- Ginkgo now panics when a runnable node (`It`, `BeforeEach`, `JustBeforeEach`, `AfterEach`, `Measure`) is nested within another runnable node. This is always a mistake. Any test suites that panic because of this change should be fixed. - -Bug Fixes: - -- `ginkgo boostrap` and `ginkgo generate` no longer fail when dealing with `hyphen-separated-packages`. -- parallel specs are now better distributed across nodes - fixed a crashing bug where (for example) distributing 11 tests across 7 nodes would panic - -## 1.0.0 (5/24/2014) -New Features: - -- Add `GinkgoParallelNode()` - shorthand for `config.GinkgoConfig.ParallelNode` - -Improvements: - -- When compilation fails, the compilation output is rewritten to present a correct *relative* path. Allows ⌘-clicking in iTerm open the file in your text editor. -- `--untilItFails` and `ginkgo watch` now generate new random seeds between test runs, unless a particular random seed is specified. - -Bug Fixes: - -- `-cover` now generates a correctly combined coverprofile when running with in parallel with multiple `-node`s. -- Print out the contents of the `GinkgoWriter` when `BeforeSuite` or `AfterSuite` fail. -- Fix all remaining race conditions in Ginkgo's test suite. - -## 1.0.0-beta (4/14/2014) -Breaking changes: - -- `thirdparty/gomocktestreporter` is gone. Use `GinkgoT()` instead -- Modified the Reporter interface -- `watch` is now a subcommand, not a flag. - -DSL changes: - -- `BeforeSuite` and `AfterSuite` for setting up and tearing down test suites. -- `AfterSuite` is triggered on interrupt (`^C`) as well as exit. -- `SynchronizedBeforeSuite` and `SynchronizedAfterSuite` for setting up and tearing down singleton resources across parallel nodes. - -CLI changes: - -- `watch` is now a subcommand, not a flag -- `--nodot` flag can be passed to `ginkgo generate` and `ginkgo bootstrap` to avoid dot imports. This explicitly imports all exported identifiers in Ginkgo and Gomega. Refreshing this list can be done by running `ginkgo nodot` -- Additional arguments can be passed to specs. Pass them after the `--` separator -- `--skipPackage` flag takes a regexp and ignores any packages with package names passing said regexp. -- `--trace` flag prints out full stack traces when errors occur, not just the line at which the error occurs. - -Misc: - -- Start using semantic versioning -- Start maintaining changelog - -Major refactor: - -- Pull out Ginkgo's internal to `internal` -- Rename `example` everywhere to `spec` -- Much more! diff --git a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md b/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md deleted file mode 100644 index 908b95c2..00000000 --- a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md +++ /dev/null @@ -1,33 +0,0 @@ -# Contributing to Ginkgo - -Your contributions to Ginkgo are essential for its long-term maintenance and improvement. - -- Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code! -- Ensure adequate test coverage: - - When adding to the Ginkgo library, add unit and/or integration tests (under the `integration` folder). - - When adding to the Ginkgo CLI, note that there are very few unit tests. Please add an integration test. -- Update the documentation. Ginko uses `godoc` comments and documentation on the `gh-pages` branch. - If relevant, please submit a docs PR to that branch alongside your code PR. - -Thanks for supporting Ginkgo! - -## Setup - -Fork the repo, then: - -``` -go get github.com/onsi/ginkgo -go get github.com/onsi/gomega/... -cd $GOPATH/src/github.com/onsi/ginkgo -git remote add fork git@github.com:/ginkgo.git - -ginkgo -r -p # ensure tests are green -go vet ./... # ensure linter is happy -``` - -## Making the PR - - go to a new branch `git checkout -b my-feature` - - make your changes - - run tests and linter again (see above) - - `git push fork` - - open PR 🎉 diff --git a/vendor/github.com/onsi/ginkgo/LICENSE b/vendor/github.com/onsi/ginkgo/LICENSE deleted file mode 100644 index 9415ee72..00000000 --- a/vendor/github.com/onsi/ginkgo/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013-2014 Onsi Fakhouri - -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/onsi/ginkgo/README.md b/vendor/github.com/onsi/ginkgo/README.md deleted file mode 100644 index cdf8d054..00000000 --- a/vendor/github.com/onsi/ginkgo/README.md +++ /dev/null @@ -1,121 +0,0 @@ -![Ginkgo: A Go BDD Testing Framework](http://onsi.github.io/ginkgo/images/ginkgo.png) - -[![Build Status](https://travis-ci.org/onsi/ginkgo.svg?branch=master)](https://travis-ci.org/onsi/ginkgo) - -Jump to the [docs](http://onsi.github.io/ginkgo/) to learn more. To start rolling your Ginkgo tests *now* [keep reading](#set-me-up)! - -If you have a question, comment, bug report, feature request, etc. please open a GitHub issue. - -## Feature List - -- Ginkgo uses Go's `testing` package and can live alongside your existing `testing` tests. It's easy to [bootstrap](http://onsi.github.io/ginkgo/#bootstrapping-a-suite) and start writing your [first tests](http://onsi.github.io/ginkgo/#adding-specs-to-a-suite) - -- Structure your BDD-style tests expressively: - - Nestable [`Describe`, `Context` and `When` container blocks](http://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context) - - [`BeforeEach` and `AfterEach` blocks](http://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach) for setup and teardown - - [`It` and `Specify` blocks](http://onsi.github.io/ginkgo/#individual-specs-) that hold your assertions - - [`JustBeforeEach` blocks](http://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach) that separate creation from configuration (also known as the subject action pattern). - - [`BeforeSuite` and `AfterSuite` blocks](http://onsi.github.io/ginkgo/#global-setup-and-teardown-beforesuite-and-aftersuite) to prep for and cleanup after a suite. - -- A comprehensive test runner that lets you: - - Mark specs as [pending](http://onsi.github.io/ginkgo/#pending-specs) - - [Focus](http://onsi.github.io/ginkgo/#focused-specs) individual specs, and groups of specs, either programmatically or on the command line - - Run your tests in [random order](http://onsi.github.io/ginkgo/#spec-permutation), and then reuse random seeds to replicate the same order. - - Break up your test suite into parallel processes for straightforward [test parallelization](http://onsi.github.io/ginkgo/#parallel-specs) - -- `ginkgo`: a command line interface with plenty of handy command line arguments for [running your tests](http://onsi.github.io/ginkgo/#running-tests) and [generating](http://onsi.github.io/ginkgo/#generators) test files. Here are a few choice examples: - - `ginkgo -nodes=N` runs your tests in `N` parallel processes and print out coherent output in realtime - - `ginkgo -cover` runs your tests using Go's code coverage tool - - `ginkgo convert` converts an XUnit-style `testing` package to a Ginkgo-style package - - `ginkgo -focus="REGEXP"` and `ginkgo -skip="REGEXP"` allow you to specify a subset of tests to run via regular expression - - `ginkgo -r` runs all tests suites under the current directory - - `ginkgo -v` prints out identifying information for each tests just before it runs - - And much more: run `ginkgo help` for details! - - The `ginkgo` CLI is convenient, but purely optional -- Ginkgo works just fine with `go test` - -- `ginkgo watch` [watches](https://onsi.github.io/ginkgo/#watching-for-changes) packages *and their dependencies* for changes, then reruns tests. Run tests immediately as you develop! - -- Built-in support for testing [asynchronicity](http://onsi.github.io/ginkgo/#asynchronous-tests) - -- Built-in support for [benchmarking](http://onsi.github.io/ginkgo/#benchmark-tests) your code. Control the number of benchmark samples as you gather runtimes and other, arbitrary, bits of numerical information about your code. - -- [Completions for Sublime Text](https://github.com/onsi/ginkgo-sublime-completions): just use [Package Control](https://sublime.wbond.net/) to install `Ginkgo Completions`. - -- [Completions for VSCode](https://github.com/onsi/vscode-ginkgo): just use VSCode's extension installer to install `vscode-ginkgo`. - -- Straightforward support for third-party testing libraries such as [Gomock](https://code.google.com/p/gomock/) and [Testify](https://github.com/stretchr/testify). Check out the [docs](http://onsi.github.io/ginkgo/#third-party-integrations) for details. - -- A modular architecture that lets you easily: - - Write [custom reporters](http://onsi.github.io/ginkgo/#writing-custom-reporters) (for example, Ginkgo comes with a [JUnit XML reporter](http://onsi.github.io/ginkgo/#generating-junit-xml-output) and a TeamCity reporter). - - [Adapt an existing matcher library (or write your own!)](http://onsi.github.io/ginkgo/#using-other-matcher-libraries) to work with Ginkgo - -## [Gomega](http://github.com/onsi/gomega): Ginkgo's Preferred Matcher Library - -Ginkgo is best paired with Gomega. Learn more about Gomega [here](http://onsi.github.io/gomega/) - -## [Agouti](http://github.com/sclevine/agouti): A Go Acceptance Testing Framework - -Agouti allows you run WebDriver integration tests. Learn more about Agouti [here](http://agouti.org) - -## Set Me Up! - -You'll need the Go command-line tools. Ginkgo is tested with Go 1.6+, but preferably you should get the latest. Follow the [installation instructions](https://golang.org/doc/install) if you don't have it installed. - -```bash - -go get -u github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI -go get -u github.com/onsi/gomega/... # fetches the matcher library - -cd path/to/package/you/want/to/test - -ginkgo bootstrap # set up a new ginkgo suite -ginkgo generate # will create a sample test file. edit this file and add your tests then... - -go test # to run your tests - -ginkgo # also runs your tests - -``` - -## I'm new to Go: What are my testing options? - -Of course, I heartily recommend [Ginkgo](https://github.com/onsi/ginkgo) and [Gomega](https://github.com/onsi/gomega). Both packages are seeing heavy, daily, production use on a number of projects and boast a mature and comprehensive feature-set. - -With that said, it's great to know what your options are :) - -### What Go gives you out of the box - -Testing is a first class citizen in Go, however Go's built-in testing primitives are somewhat limited: The [testing](http://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library. - -### Matcher libraries for Go's XUnit style tests - -A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction: - -- [testify](https://github.com/stretchr/testify) -- [gocheck](http://labix.org/gocheck) - -You can also use Ginkgo's matcher library [Gomega](https://github.com/onsi/gomega) in [XUnit style tests](http://onsi.github.io/gomega/#using-gomega-with-golangs-xunitstyle-tests) - -### BDD style testing frameworks - -There are a handful of BDD-style testing frameworks written for Go. Here are a few: - -- [Ginkgo](https://github.com/onsi/ginkgo) ;) -- [GoConvey](https://github.com/smartystreets/goconvey) -- [Goblin](https://github.com/franela/goblin) -- [Mao](https://github.com/azer/mao) -- [Zen](https://github.com/pranavraja/zen) - -Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of Go testing libraries. - -Go explore! - -## License - -Ginkgo is MIT-Licensed - -## Contributing - -See [CONTRIBUTING.md](CONTRIBUTING.md) diff --git a/vendor/github.com/onsi/ginkgo/RELEASING.md b/vendor/github.com/onsi/ginkgo/RELEASING.md deleted file mode 100644 index 1e298c2d..00000000 --- a/vendor/github.com/onsi/ginkgo/RELEASING.md +++ /dev/null @@ -1,14 +0,0 @@ -A Ginkgo release is a tagged git sha and a GitHub release. To cut a release: - -1. Ensure CHANGELOG.md is up to date. - - Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release - - Categorize the changes into - - Breaking Changes (requires a major version) - - New Features (minor version) - - Fixes (fix version) - - Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact) -1. Update `VERSION` in `config/config.go` -1. Create a commit with the version number as the commit message (e.g. `v1.3.0`) -1. Tag the commit with the version number as the tag name (e.g. `v1.3.0`) -1. Push the commit and tag to GitHub -1. Create a new [GitHub release](https://help.github.com/articles/creating-releases/) with the version number as the tag (e.g. `v1.3.0`). List the key changes in the release notes. diff --git a/vendor/github.com/onsi/ginkgo/config/config.go b/vendor/github.com/onsi/ginkgo/config/config.go deleted file mode 100644 index 5e509313..00000000 --- a/vendor/github.com/onsi/ginkgo/config/config.go +++ /dev/null @@ -1,200 +0,0 @@ -/* -Ginkgo accepts a number of configuration options. - -These are documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli) - -You can also learn more via - - ginkgo help - -or (I kid you not): - - go test -asdf -*/ -package config - -import ( - "flag" - "time" - - "fmt" -) - -const VERSION = "1.7.0" - -type GinkgoConfigType struct { - RandomSeed int64 - RandomizeAllSpecs bool - RegexScansFilePath bool - FocusString string - SkipString string - SkipMeasurements bool - FailOnPending bool - FailFast bool - FlakeAttempts int - EmitSpecProgress bool - DryRun bool - DebugParallel bool - - ParallelNode int - ParallelTotal int - SyncHost string - StreamHost string -} - -var GinkgoConfig = GinkgoConfigType{} - -type DefaultReporterConfigType struct { - NoColor bool - SlowSpecThreshold float64 - NoisyPendings bool - NoisySkippings bool - Succinct bool - Verbose bool - FullTrace bool -} - -var DefaultReporterConfig = DefaultReporterConfigType{} - -func processPrefix(prefix string) string { - if prefix != "" { - prefix = prefix + "." - } - return prefix -} - -func Flags(flagSet *flag.FlagSet, prefix string, includeParallelFlags bool) { - prefix = processPrefix(prefix) - flagSet.Int64Var(&(GinkgoConfig.RandomSeed), prefix+"seed", time.Now().Unix(), "The seed used to randomize the spec suite.") - flagSet.BoolVar(&(GinkgoConfig.RandomizeAllSpecs), prefix+"randomizeAllSpecs", false, "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe, Context and When groups.") - flagSet.BoolVar(&(GinkgoConfig.SkipMeasurements), prefix+"skipMeasurements", false, "If set, ginkgo will skip any measurement specs.") - flagSet.BoolVar(&(GinkgoConfig.FailOnPending), prefix+"failOnPending", false, "If set, ginkgo will mark the test suite as failed if any specs are pending.") - flagSet.BoolVar(&(GinkgoConfig.FailFast), prefix+"failFast", false, "If set, ginkgo will stop running a test suite after a failure occurs.") - - flagSet.BoolVar(&(GinkgoConfig.DryRun), prefix+"dryRun", false, "If set, ginkgo will walk the test hierarchy without actually running anything. Best paired with -v.") - - flagSet.StringVar(&(GinkgoConfig.FocusString), prefix+"focus", "", "If set, ginkgo will only run specs that match this regular expression.") - flagSet.StringVar(&(GinkgoConfig.SkipString), prefix+"skip", "", "If set, ginkgo will only run specs that do not match this regular expression.") - - flagSet.BoolVar(&(GinkgoConfig.RegexScansFilePath), prefix+"regexScansFilePath", false, "If set, ginkgo regex matching also will look at the file path (code location).") - - flagSet.IntVar(&(GinkgoConfig.FlakeAttempts), prefix+"flakeAttempts", 1, "Make up to this many attempts to run each spec. Please note that if any of the attempts succeed, the suite will not be failed. But any failures will still be recorded.") - - flagSet.BoolVar(&(GinkgoConfig.EmitSpecProgress), prefix+"progress", false, "If set, ginkgo will emit progress information as each spec runs to the GinkgoWriter.") - - flagSet.BoolVar(&(GinkgoConfig.DebugParallel), prefix+"debug", false, "If set, ginkgo will emit node output to files when running in parallel.") - - if includeParallelFlags { - flagSet.IntVar(&(GinkgoConfig.ParallelNode), prefix+"parallel.node", 1, "This worker node's (one-indexed) node number. For running specs in parallel.") - flagSet.IntVar(&(GinkgoConfig.ParallelTotal), prefix+"parallel.total", 1, "The total number of worker nodes. For running specs in parallel.") - flagSet.StringVar(&(GinkgoConfig.SyncHost), prefix+"parallel.synchost", "", "The address for the server that will synchronize the running nodes.") - flagSet.StringVar(&(GinkgoConfig.StreamHost), prefix+"parallel.streamhost", "", "The address for the server that the running nodes should stream data to.") - } - - flagSet.BoolVar(&(DefaultReporterConfig.NoColor), prefix+"noColor", false, "If set, suppress color output in default reporter.") - flagSet.Float64Var(&(DefaultReporterConfig.SlowSpecThreshold), prefix+"slowSpecThreshold", 5.0, "(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter.") - flagSet.BoolVar(&(DefaultReporterConfig.NoisyPendings), prefix+"noisyPendings", true, "If set, default reporter will shout about pending tests.") - flagSet.BoolVar(&(DefaultReporterConfig.NoisySkippings), prefix+"noisySkippings", true, "If set, default reporter will shout about skipping tests.") - flagSet.BoolVar(&(DefaultReporterConfig.Verbose), prefix+"v", false, "If set, default reporter print out all specs as they begin.") - flagSet.BoolVar(&(DefaultReporterConfig.Succinct), prefix+"succinct", false, "If set, default reporter prints out a very succinct report") - flagSet.BoolVar(&(DefaultReporterConfig.FullTrace), prefix+"trace", false, "If set, default reporter prints out the full stack trace when a failure occurs") -} - -func BuildFlagArgs(prefix string, ginkgo GinkgoConfigType, reporter DefaultReporterConfigType) []string { - prefix = processPrefix(prefix) - result := make([]string, 0) - - if ginkgo.RandomSeed > 0 { - result = append(result, fmt.Sprintf("--%sseed=%d", prefix, ginkgo.RandomSeed)) - } - - if ginkgo.RandomizeAllSpecs { - result = append(result, fmt.Sprintf("--%srandomizeAllSpecs", prefix)) - } - - if ginkgo.SkipMeasurements { - result = append(result, fmt.Sprintf("--%sskipMeasurements", prefix)) - } - - if ginkgo.FailOnPending { - result = append(result, fmt.Sprintf("--%sfailOnPending", prefix)) - } - - if ginkgo.FailFast { - result = append(result, fmt.Sprintf("--%sfailFast", prefix)) - } - - if ginkgo.DryRun { - result = append(result, fmt.Sprintf("--%sdryRun", prefix)) - } - - if ginkgo.FocusString != "" { - result = append(result, fmt.Sprintf("--%sfocus=%s", prefix, ginkgo.FocusString)) - } - - if ginkgo.SkipString != "" { - result = append(result, fmt.Sprintf("--%sskip=%s", prefix, ginkgo.SkipString)) - } - - if ginkgo.FlakeAttempts > 1 { - result = append(result, fmt.Sprintf("--%sflakeAttempts=%d", prefix, ginkgo.FlakeAttempts)) - } - - if ginkgo.EmitSpecProgress { - result = append(result, fmt.Sprintf("--%sprogress", prefix)) - } - - if ginkgo.DebugParallel { - result = append(result, fmt.Sprintf("--%sdebug", prefix)) - } - - if ginkgo.ParallelNode != 0 { - result = append(result, fmt.Sprintf("--%sparallel.node=%d", prefix, ginkgo.ParallelNode)) - } - - if ginkgo.ParallelTotal != 0 { - result = append(result, fmt.Sprintf("--%sparallel.total=%d", prefix, ginkgo.ParallelTotal)) - } - - if ginkgo.StreamHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.streamhost=%s", prefix, ginkgo.StreamHost)) - } - - if ginkgo.SyncHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.synchost=%s", prefix, ginkgo.SyncHost)) - } - - if ginkgo.RegexScansFilePath { - result = append(result, fmt.Sprintf("--%sregexScansFilePath", prefix)) - } - - if reporter.NoColor { - result = append(result, fmt.Sprintf("--%snoColor", prefix)) - } - - if reporter.SlowSpecThreshold > 0 { - result = append(result, fmt.Sprintf("--%sslowSpecThreshold=%.5f", prefix, reporter.SlowSpecThreshold)) - } - - if !reporter.NoisyPendings { - result = append(result, fmt.Sprintf("--%snoisyPendings=false", prefix)) - } - - if !reporter.NoisySkippings { - result = append(result, fmt.Sprintf("--%snoisySkippings=false", prefix)) - } - - if reporter.Verbose { - result = append(result, fmt.Sprintf("--%sv", prefix)) - } - - if reporter.Succinct { - result = append(result, fmt.Sprintf("--%ssuccinct", prefix)) - } - - if reporter.FullTrace { - result = append(result, fmt.Sprintf("--%strace", prefix)) - } - - return result -} diff --git a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go b/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go deleted file mode 100644 index 5aa96b4d..00000000 --- a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go +++ /dev/null @@ -1,619 +0,0 @@ -/* -Ginkgo is a BDD-style testing framework for Golang - -The godoc documentation describes Ginkgo's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/ginkgo/ - -Ginkgo's preferred matcher library is [Gomega](http://github.com/onsi/gomega) - -Ginkgo on Github: http://github.com/onsi/ginkgo - -Ginkgo is MIT-Licensed -*/ -package ginkgo - -import ( - "flag" - "fmt" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/internal/suite" - "github.com/onsi/ginkgo/internal/testingtproxy" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/reporters/stenographer" - colorable "github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable" - "github.com/onsi/ginkgo/types" -) - -const GINKGO_VERSION = config.VERSION -const GINKGO_PANIC = ` -Your test failed. -Ginkgo panics to prevent subsequent assertions from running. -Normally Ginkgo rescues this panic so you shouldn't see it. - -But, if you make an assertion in a goroutine, Ginkgo can't capture the panic. -To circumvent this, you should call - - defer GinkgoRecover() - -at the top of the goroutine that caused this panic. -` -const defaultTimeout = 1 - -var globalSuite *suite.Suite -var globalFailer *failer.Failer - -func init() { - config.Flags(flag.CommandLine, "ginkgo", true) - GinkgoWriter = writer.New(os.Stdout) - globalFailer = failer.New() - globalSuite = suite.New(globalFailer) -} - -//GinkgoWriter implements an io.Writer -//When running in verbose mode any writes to GinkgoWriter will be immediately printed -//to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen -//only if the current test fails. -var GinkgoWriter io.Writer - -//The interface by which Ginkgo receives *testing.T -type GinkgoTestingT interface { - Fail() -} - -//GinkgoRandomSeed returns the seed used to randomize spec execution order. It is -//useful for seeding your own pseudorandom number generators (PRNGs) to ensure -//consistent executions from run to run, where your tests contain variability (for -//example, when selecting random test data). -func GinkgoRandomSeed() int64 { - return config.GinkgoConfig.RandomSeed -} - -//GinkgoParallelNode returns the parallel node number for the current ginkgo process -//The node number is 1-indexed -func GinkgoParallelNode() int { - return config.GinkgoConfig.ParallelNode -} - -//Some matcher libraries or legacy codebases require a *testing.T -//GinkgoT implements an interface analogous to *testing.T and can be used if -//the library in question accepts *testing.T through an interface -// -// For example, with testify: -// assert.Equal(GinkgoT(), 123, 123, "they should be equal") -// -// Or with gomock: -// gomock.NewController(GinkgoT()) -// -// GinkgoT() takes an optional offset argument that can be used to get the -// correct line number associated with the failure. -func GinkgoT(optionalOffset ...int) GinkgoTInterface { - offset := 3 - if len(optionalOffset) > 0 { - offset = optionalOffset[0] - } - return testingtproxy.New(GinkgoWriter, Fail, offset) -} - -//The interface returned by GinkgoT(). This covers most of the methods -//in the testing package's T. -type GinkgoTInterface interface { - Fail() - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - FailNow() - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Failed() bool - Parallel() - Skip(args ...interface{}) - Skipf(format string, args ...interface{}) - SkipNow() - Skipped() bool -} - -//Custom Ginkgo test reporters must implement the Reporter interface. -// -//The custom reporter is passed in a SuiteSummary when the suite begins and ends, -//and a SpecSummary just before a spec begins and just after a spec ends -type Reporter reporters.Reporter - -//Asynchronous specs are given a channel of the Done type. You must close or write to the channel -//to tell Ginkgo that your async test is done. -type Done chan<- interface{} - -//GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription -// FullTestText: a concatenation of ComponentTexts and the TestText -// ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test -// TestText: the text in the actual It or Measure node -// IsMeasurement: true if the current test is a measurement -// FileName: the name of the file containing the current test -// LineNumber: the line number for the current test -// Failed: if the current test has failed, this will be true (useful in an AfterEach) -type GinkgoTestDescription struct { - FullTestText string - ComponentTexts []string - TestText string - - IsMeasurement bool - - FileName string - LineNumber int - - Failed bool - Duration time.Duration -} - -//CurrentGinkgoTestDescripton returns information about the current running test. -func CurrentGinkgoTestDescription() GinkgoTestDescription { - summary, ok := globalSuite.CurrentRunningSpecSummary() - if !ok { - return GinkgoTestDescription{} - } - - subjectCodeLocation := summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1] - - return GinkgoTestDescription{ - ComponentTexts: summary.ComponentTexts[1:], - FullTestText: strings.Join(summary.ComponentTexts[1:], " "), - TestText: summary.ComponentTexts[len(summary.ComponentTexts)-1], - IsMeasurement: summary.IsMeasurement, - FileName: subjectCodeLocation.FileName, - LineNumber: subjectCodeLocation.LineNumber, - Failed: summary.HasFailureState(), - Duration: summary.RunTime, - } -} - -//Measurement tests receive a Benchmarker. -// -//You use the Time() function to time how long the passed in body function takes to run -//You use the RecordValue() function to track arbitrary numerical measurements. -//The RecordValueWithPrecision() function can be used alternatively to provide the unit -//and resolution of the numeric measurement. -//The optional info argument is passed to the test reporter and can be used to -// provide the measurement data to a custom reporter with context. -// -//See http://onsi.github.io/ginkgo/#benchmark_tests for more details -type Benchmarker interface { - Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) - RecordValue(name string, value float64, info ...interface{}) - RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) -} - -//RunSpecs is the entry point for the Ginkgo test runner. -//You must call this within a Golang testing TestX(t *testing.T) function. -// -//To bootstrap a test suite you can use the Ginkgo CLI: -// -// ginkgo bootstrap -func RunSpecs(t GinkgoTestingT, description string) bool { - specReporters := []Reporter{buildDefaultReporter()} - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with Ginkgo's default reporter and your custom reporter(s), replace -//RunSpecs() with this method. -func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - specReporters = append(specReporters, buildDefaultReporter()) - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace -//RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter -func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - writer := GinkgoWriter.(*writer.Writer) - writer.SetStream(config.DefaultReporterConfig.Verbose) - reporters := make([]reporters.Reporter, len(specReporters)) - for i, reporter := range specReporters { - reporters[i] = reporter - } - passed, hasFocusedTests := globalSuite.Run(t, description, reporters, writer, config.GinkgoConfig) - if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" { - fmt.Println("PASS | FOCUSED") - os.Exit(types.GINKGO_FOCUS_EXIT_CODE) - } - return passed -} - -func buildDefaultReporter() Reporter { - remoteReportingServer := config.GinkgoConfig.StreamHost - if remoteReportingServer == "" { - stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor, config.GinkgoConfig.FlakeAttempts > 1, colorable.NewColorableStdout()) - return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer) - } else { - debugFile := "" - if config.GinkgoConfig.DebugParallel { - debugFile = fmt.Sprintf("ginkgo-node-%d.log", config.GinkgoConfig.ParallelNode) - } - return remote.NewForwardingReporter(config.DefaultReporterConfig, remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor(), GinkgoWriter.(*writer.Writer), debugFile) - } -} - -//Skip notifies Ginkgo that the current spec was skipped. -func Skip(message string, callerSkip ...int) { - skip := 0 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - - globalFailer.Skip(message, codelocation.New(skip+1)) - panic(GINKGO_PANIC) -} - -//Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.) -func Fail(message string, callerSkip ...int) { - skip := 0 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - - globalFailer.Fail(message, codelocation.New(skip+1)) - panic(GINKGO_PANIC) -} - -//GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail` -//Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that -//calls out to Gomega -// -//Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent -//further assertions from running. This panic must be recovered. Ginkgo does this for you -//if the panic originates in a Ginkgo node (an It, BeforeEach, etc...) -// -//Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no -//way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine. -func GinkgoRecover() { - e := recover() - if e != nil { - globalFailer.Panic(codelocation.New(1), e) - } -} - -//Describe blocks allow you to organize your specs. A Describe block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts and Whens. -func Describe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FDescribe -func FDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PDescribe -func PDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XDescribe -func XDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//Context blocks allow you to organize your specs. A Context block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts and Whens. -func Context(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FContext -func FContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PContext -func PContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XContext -func XContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//When blocks allow you to organize your specs. A When block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts and Whens. -func When(text string, body func()) bool { - globalSuite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FWhen -func FWhen(text string, body func()) bool { - globalSuite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PWhen -func PWhen(text string, body func()) bool { - globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XWhen -func XWhen(text string, body func()) bool { - globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks -//within an It block. -// -//Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a -//function that accepts a Done channel. When you do this, you can also provide an optional timeout. -func It(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can focus individual Its using FIt -func FIt(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can mark Its as pending using PIt -func PIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Its as pending using XIt -func XIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//Specify blocks are aliases for It blocks and allow for more natural wording in situations -//which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks -//which apply to It blocks. -func Specify(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can focus individual Specifys using FSpecify -func FSpecify(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can mark Specifys as pending using PSpecify -func PSpecify(text string, is ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Specifys as pending using XSpecify -func XSpecify(text string, is ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//By allows you to better document large Its. -// -//Generally you should try to keep your Its short and to the point. This is not always possible, however, -//especially in the context of integration tests that capture a particular workflow. -// -//By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...) -//By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function. -func By(text string, callbacks ...func()) { - preamble := "\x1b[1mSTEP\x1b[0m" - if config.DefaultReporterConfig.NoColor { - preamble = "STEP" - } - fmt.Fprintln(GinkgoWriter, preamble+": "+text) - if len(callbacks) == 1 { - callbacks[0]() - } - if len(callbacks) > 1 { - panic("just one callback per By, please") - } -} - -//Measure blocks run the passed in body function repeatedly (determined by the samples argument) -//and accumulate metrics provided to the Benchmarker by the body function. -// -//The body function must have the signature: -// func(b Benchmarker) -func Measure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples) - return true -} - -//You can focus individual Measures using FMeasure -func FMeasure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples) - return true -} - -//You can mark Maeasurements as pending using PMeasure -func PMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Maeasurements as pending using XMeasure -func XMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//BeforeSuite blocks are run just once before any specs are run. When running in parallel, each -//parallel node process will call BeforeSuite. -// -//BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func BeforeSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed. -//Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting. -// -//When running in parallel, each parallel node process will call AfterSuite. -// -//AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func AfterSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across -//nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that -//must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait -//until that node is done before running. -// -//SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is -//run on all nodes, but *only* after the first function completes succesfully. Ginkgo also makes it possible to send data from the first function (on Node 1) -//to the second function (on all the other nodes). -// -//The functions have the following signatures. The first function (which only runs on node 1) has the signature: -// -// func() []byte -// -//or, to run asynchronously: -// -// func(done Done) []byte -// -//The byte array returned by the first function is then passed to the second function, which has the signature: -// -// func(data []byte) -// -//or, to run asynchronously: -// -// func(data []byte, done Done) -// -//Here's a simple pseudo-code example that starts a shared database on Node 1 and shares the database's address with the other nodes: -// -// var dbClient db.Client -// var dbRunner db.Runner -// -// var _ = SynchronizedBeforeSuite(func() []byte { -// dbRunner = db.NewRunner() -// err := dbRunner.Start() -// Ω(err).ShouldNot(HaveOccurred()) -// return []byte(dbRunner.URL) -// }, func(data []byte) { -// dbClient = db.NewClient() -// err := dbClient.Connect(string(data)) -// Ω(err).ShouldNot(HaveOccurred()) -// }) -func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedBeforeSuiteNode( - node1Body, - allNodesBody, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up -//external singleton resources shared across nodes when running tests in parallel. -// -//SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1 -//and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until -//all other nodes are finished. -// -//Both functions have the same signature: either func() or func(done Done) to run asynchronously. -// -//Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database -//only after all nodes have finished: -// -// var _ = SynchronizedAfterSuite(func() { -// dbClient.Cleanup() -// }, func() { -// dbRunner.Stop() -// }) -func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedAfterSuiteNode( - allNodesBody, - node1Body, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested -//Describe and Context blocks the outermost BeforeEach blocks are run first. -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func BeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details, -//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_) -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func JustBeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//JustAfterEach blocks are run after It blocks but *before* all AfterEach blocks. For more details, -//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_) -// -//Like It blocks, JustAfterEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func JustAfterEach(body interface{}, timeout ...float64) bool { - globalSuite.PushJustAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested -//Describe and Context blocks the innermost AfterEach blocks are run first. -// -//Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func AfterEach(body interface{}, timeout ...float64) bool { - globalSuite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -func parseTimeout(timeout ...float64) time.Duration { - if len(timeout) == 0 { - return time.Duration(defaultTimeout * int64(time.Second)) - } else { - return time.Duration(timeout[0] * float64(time.Second)) - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go deleted file mode 100644 index fa2f0bf7..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go +++ /dev/null @@ -1,32 +0,0 @@ -package codelocation - -import ( - "regexp" - "runtime" - "runtime/debug" - "strings" - - "github.com/onsi/ginkgo/types" -) - -func New(skip int) types.CodeLocation { - _, file, line, _ := runtime.Caller(skip + 1) - stackTrace := PruneStack(string(debug.Stack()), skip) - return types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace} -} - -func PruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n") - if len(stack) > 2*(skip+1) { - stack = stack[2*(skip+1):] - } - prunedStack := []string{} - re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) - for i := 0; i < len(stack)/2; i++ { - if !re.Match([]byte(stack[i*2])) { - prunedStack = append(prunedStack, stack[i*2]) - prunedStack = append(prunedStack, stack[i*2+1]) - } - } - return strings.Join(prunedStack, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go deleted file mode 100644 index 0737746d..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go +++ /dev/null @@ -1,151 +0,0 @@ -package containernode - -import ( - "math/rand" - "sort" - - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type subjectOrContainerNode struct { - containerNode *ContainerNode - subjectNode leafnodes.SubjectNode -} - -func (n subjectOrContainerNode) text() string { - if n.containerNode != nil { - return n.containerNode.Text() - } else { - return n.subjectNode.Text() - } -} - -type CollatedNodes struct { - Containers []*ContainerNode - Subject leafnodes.SubjectNode -} - -type ContainerNode struct { - text string - flag types.FlagType - codeLocation types.CodeLocation - - setupNodes []leafnodes.BasicNode - subjectAndContainerNodes []subjectOrContainerNode -} - -func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { - return &ContainerNode{ - text: text, - flag: flag, - codeLocation: codeLocation, - } -} - -func (container *ContainerNode) Shuffle(r *rand.Rand) { - sort.Sort(container) - permutation := r.Perm(len(container.subjectAndContainerNodes)) - shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) - for i, j := range permutation { - shuffledNodes[i] = container.subjectAndContainerNodes[j] - } - container.subjectAndContainerNodes = shuffledNodes -} - -func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { - if node.flag == types.FlagTypePending { - return false - } - - shouldUnfocus := false - for _, subjectOrContainerNode := range node.subjectAndContainerNodes { - if subjectOrContainerNode.containerNode != nil { - shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus - } else { - shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus - } - } - - if shouldUnfocus { - if node.flag == types.FlagTypeFocused { - node.flag = types.FlagTypeNone - } - return true - } - - return node.flag == types.FlagTypeFocused -} - -func (node *ContainerNode) Collate() []CollatedNodes { - return node.collate([]*ContainerNode{}) -} - -func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { - collated := make([]CollatedNodes, 0) - - containers := make([]*ContainerNode, len(enclosingContainers)) - copy(containers, enclosingContainers) - containers = append(containers, node) - - for _, subjectOrContainer := range node.subjectAndContainerNodes { - if subjectOrContainer.containerNode != nil { - collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) - } else { - collated = append(collated, CollatedNodes{ - Containers: containers, - Subject: subjectOrContainer.subjectNode, - }) - } - } - - return collated -} - -func (node *ContainerNode) PushContainerNode(container *ContainerNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) -} - -func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) -} - -func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { - node.setupNodes = append(node.setupNodes, setupNode) -} - -func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { - nodes := []leafnodes.BasicNode{} - for _, setupNode := range node.setupNodes { - if setupNode.Type() == nodeType { - nodes = append(nodes, setupNode) - } - } - return nodes -} - -func (node *ContainerNode) Text() string { - return node.text -} - -func (node *ContainerNode) CodeLocation() types.CodeLocation { - return node.codeLocation -} - -func (node *ContainerNode) Flag() types.FlagType { - return node.flag -} - -//sort.Interface - -func (node *ContainerNode) Len() int { - return len(node.subjectAndContainerNodes) -} - -func (node *ContainerNode) Less(i, j int) bool { - return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() -} - -func (node *ContainerNode) Swap(i, j int) { - node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] -} diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer.go deleted file mode 100644 index 678ea251..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer.go +++ /dev/null @@ -1,92 +0,0 @@ -package failer - -import ( - "fmt" - "sync" - - "github.com/onsi/ginkgo/types" -) - -type Failer struct { - lock *sync.Mutex - failure types.SpecFailure - state types.SpecState -} - -func New() *Failer { - return &Failer{ - lock: &sync.Mutex{}, - state: types.SpecStatePassed, - } -} - -func (f *Failer) Panic(location types.CodeLocation, forwardedPanic interface{}) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStatePanicked - f.failure = types.SpecFailure{ - Message: "Test Panicked", - Location: location, - ForwardedPanic: fmt.Sprintf("%v", forwardedPanic), - } - } -} - -func (f *Failer) Timeout(location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateTimedOut - f.failure = types.SpecFailure{ - Message: "Timed out", - Location: location, - } - } -} - -func (f *Failer) Fail(message string, location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateFailed - f.failure = types.SpecFailure{ - Message: message, - Location: location, - } - } -} - -func (f *Failer) Drain(componentType types.SpecComponentType, componentIndex int, componentCodeLocation types.CodeLocation) (types.SpecFailure, types.SpecState) { - f.lock.Lock() - defer f.lock.Unlock() - - failure := f.failure - outcome := f.state - if outcome != types.SpecStatePassed { - failure.ComponentType = componentType - failure.ComponentIndex = componentIndex - failure.ComponentCodeLocation = componentCodeLocation - } - - f.state = types.SpecStatePassed - f.failure = types.SpecFailure{} - - return failure, outcome -} - -func (f *Failer) Skip(message string, location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateSkipped - f.failure = types.SpecFailure{ - Message: message, - Location: location, - } - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go deleted file mode 100644 index d6d54234..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go +++ /dev/null @@ -1,103 +0,0 @@ -package leafnodes - -import ( - "math" - "time" - - "sync" - - "github.com/onsi/ginkgo/types" -) - -type benchmarker struct { - mu sync.Mutex - measurements map[string]*types.SpecMeasurement - orderCounter int -} - -func newBenchmarker() *benchmarker { - return &benchmarker{ - measurements: make(map[string]*types.SpecMeasurement, 0), - } -} - -func (b *benchmarker) Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) { - t := time.Now() - body() - elapsedTime = time.Since(t) - - b.mu.Lock() - defer b.mu.Unlock() - measurement := b.getMeasurement(name, "Fastest Time", "Slowest Time", "Average Time", "s", 3, info...) - measurement.Results = append(measurement.Results, elapsedTime.Seconds()) - - return -} - -func (b *benchmarker) RecordValue(name string, value float64, info ...interface{}) { - b.mu.Lock() - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", "", 3, info...) - defer b.mu.Unlock() - measurement.Results = append(measurement.Results, value) -} - -func (b *benchmarker) RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) { - b.mu.Lock() - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", units, precision, info...) - defer b.mu.Unlock() - measurement.Results = append(measurement.Results, value) -} - -func (b *benchmarker) getMeasurement(name string, smallestLabel string, largestLabel string, averageLabel string, units string, precision int, info ...interface{}) *types.SpecMeasurement { - measurement, ok := b.measurements[name] - if !ok { - var computedInfo interface{} - computedInfo = nil - if len(info) > 0 { - computedInfo = info[0] - } - measurement = &types.SpecMeasurement{ - Name: name, - Info: computedInfo, - Order: b.orderCounter, - SmallestLabel: smallestLabel, - LargestLabel: largestLabel, - AverageLabel: averageLabel, - Units: units, - Precision: precision, - Results: make([]float64, 0), - } - b.measurements[name] = measurement - b.orderCounter++ - } - - return measurement -} - -func (b *benchmarker) measurementsReport() map[string]*types.SpecMeasurement { - b.mu.Lock() - defer b.mu.Unlock() - for _, measurement := range b.measurements { - measurement.Smallest = math.MaxFloat64 - measurement.Largest = -math.MaxFloat64 - sum := float64(0) - sumOfSquares := float64(0) - - for _, result := range measurement.Results { - if result > measurement.Largest { - measurement.Largest = result - } - if result < measurement.Smallest { - measurement.Smallest = result - } - sum += result - sumOfSquares += result * result - } - - n := float64(len(measurement.Results)) - measurement.Average = sum / n - measurement.StdDeviation = math.Sqrt(sumOfSquares/n - (sum/n)*(sum/n)) - } - - return b.measurements -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go deleted file mode 100644 index 8c3902d6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go +++ /dev/null @@ -1,19 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/types" -) - -type BasicNode interface { - Type() types.SpecComponentType - Run() (types.SpecState, types.SpecFailure) - CodeLocation() types.CodeLocation -} - -type SubjectNode interface { - BasicNode - - Text() string - Flag() types.FlagType - Samples() int -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go deleted file mode 100644 index 6eded7b7..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go +++ /dev/null @@ -1,47 +0,0 @@ -package leafnodes - -import ( - "time" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type ItNode struct { - runner *runner - - flag types.FlagType - text string -} - -func NewItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *ItNode { - return &ItNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeIt, componentIndex), - flag: flag, - text: text, - } -} - -func (node *ItNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *ItNode) Type() types.SpecComponentType { - return types.SpecComponentTypeIt -} - -func (node *ItNode) Text() string { - return node.text -} - -func (node *ItNode) Flag() types.FlagType { - return node.flag -} - -func (node *ItNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *ItNode) Samples() int { - return 1 -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go deleted file mode 100644 index 3ab9a6d5..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go +++ /dev/null @@ -1,62 +0,0 @@ -package leafnodes - -import ( - "reflect" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type MeasureNode struct { - runner *runner - - text string - flag types.FlagType - samples int - benchmarker *benchmarker -} - -func NewMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int, failer *failer.Failer, componentIndex int) *MeasureNode { - benchmarker := newBenchmarker() - - wrappedBody := func() { - reflect.ValueOf(body).Call([]reflect.Value{reflect.ValueOf(benchmarker)}) - } - - return &MeasureNode{ - runner: newRunner(wrappedBody, codeLocation, 0, failer, types.SpecComponentTypeMeasure, componentIndex), - - text: text, - flag: flag, - samples: samples, - benchmarker: benchmarker, - } -} - -func (node *MeasureNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *MeasureNode) MeasurementsReport() map[string]*types.SpecMeasurement { - return node.benchmarker.measurementsReport() -} - -func (node *MeasureNode) Type() types.SpecComponentType { - return types.SpecComponentTypeMeasure -} - -func (node *MeasureNode) Text() string { - return node.text -} - -func (node *MeasureNode) Flag() types.FlagType { - return node.flag -} - -func (node *MeasureNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *MeasureNode) Samples() int { - return node.samples -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go deleted file mode 100644 index 16cb66c3..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go +++ /dev/null @@ -1,117 +0,0 @@ -package leafnodes - -import ( - "fmt" - "reflect" - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type runner struct { - isAsync bool - asyncFunc func(chan<- interface{}) - syncFunc func() - codeLocation types.CodeLocation - timeoutThreshold time.Duration - nodeType types.SpecComponentType - componentIndex int - failer *failer.Failer -} - -func newRunner(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, nodeType types.SpecComponentType, componentIndex int) *runner { - bodyType := reflect.TypeOf(body) - if bodyType.Kind() != reflect.Func { - panic(fmt.Sprintf("Expected a function but got something else at %v", codeLocation)) - } - - runner := &runner{ - codeLocation: codeLocation, - timeoutThreshold: timeout, - failer: failer, - nodeType: nodeType, - componentIndex: componentIndex, - } - - switch bodyType.NumIn() { - case 0: - runner.syncFunc = body.(func()) - return runner - case 1: - if !(bodyType.In(0).Kind() == reflect.Chan && bodyType.In(0).Elem().Kind() == reflect.Interface) { - panic(fmt.Sprintf("Must pass a Done channel to function at %v", codeLocation)) - } - - wrappedBody := func(done chan<- interface{}) { - bodyValue := reflect.ValueOf(body) - bodyValue.Call([]reflect.Value{reflect.ValueOf(done)}) - } - - runner.isAsync = true - runner.asyncFunc = wrappedBody - return runner - } - - panic(fmt.Sprintf("Too many arguments to function at %v", codeLocation)) -} - -func (r *runner) run() (outcome types.SpecState, failure types.SpecFailure) { - if r.isAsync { - return r.runAsync() - } else { - return r.runSync() - } -} - -func (r *runner) runAsync() (outcome types.SpecState, failure types.SpecFailure) { - done := make(chan interface{}, 1) - - go func() { - finished := false - - defer func() { - if e := recover(); e != nil || !finished { - r.failer.Panic(codelocation.New(2), e) - select { - case <-done: - break - default: - close(done) - } - } - }() - - r.asyncFunc(done) - finished = true - }() - - // If this goroutine gets no CPU time before the select block, - // the <-done case may complete even if the test took longer than the timeoutThreshold. - // This can cause flaky behaviour, but we haven't seen it in the wild. - select { - case <-done: - case <-time.After(r.timeoutThreshold): - r.failer.Timeout(r.codeLocation) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - return -} -func (r *runner) runSync() (outcome types.SpecState, failure types.SpecFailure) { - finished := false - - defer func() { - if e := recover(); e != nil || !finished { - r.failer.Panic(codelocation.New(2), e) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - }() - - r.syncFunc() - finished = true - - return -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go deleted file mode 100644 index e3e9cb7c..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go +++ /dev/null @@ -1,48 +0,0 @@ -package leafnodes - -import ( - "time" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type SetupNode struct { - runner *runner -} - -func (node *SetupNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *SetupNode) Type() types.SpecComponentType { - return node.runner.nodeType -} - -func (node *SetupNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func NewBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeEach, componentIndex), - } -} - -func NewAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterEach, componentIndex), - } -} - -func NewJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeJustBeforeEach, componentIndex), - } -} - -func NewJustAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeJustAfterEach, componentIndex), - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go deleted file mode 100644 index 80f16ed7..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go +++ /dev/null @@ -1,55 +0,0 @@ -package leafnodes - -import ( - "time" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type SuiteNode interface { - Run(parallelNode int, parallelTotal int, syncHost string) bool - Passed() bool - Summary() *types.SetupSummary -} - -type simpleSuiteNode struct { - runner *runner - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func (node *simpleSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - node.outcome, node.failure = node.runner.run() - node.runTime = time.Since(t) - - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runner.nodeType, - CodeLocation: node.runner.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func NewBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0), - } -} - -func NewAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go deleted file mode 100644 index a721d0cf..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go +++ /dev/null @@ -1,90 +0,0 @@ -package leafnodes - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "time" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type synchronizedAfterSuiteNode struct { - runnerA *runner - runnerB *runner - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &synchronizedAfterSuiteNode{ - runnerA: newRunner(bodyA, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - runnerB: newRunner(bodyB, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} - -func (node *synchronizedAfterSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - node.outcome, node.failure = node.runnerA.run() - - if parallelNode == 1 { - if parallelTotal > 1 { - node.waitUntilOtherNodesAreDone(syncHost) - } - - outcome, failure := node.runnerB.run() - - if node.outcome == types.SpecStatePassed { - node.outcome, node.failure = outcome, failure - } - } - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedAfterSuiteNode) waitUntilOtherNodesAreDone(syncHost string) { - for { - if node.canRun(syncHost) { - return - } - - time.Sleep(50 * time.Millisecond) - } -} - -func (node *synchronizedAfterSuiteNode) canRun(syncHost string) bool { - resp, err := http.Get(syncHost + "/RemoteAfterSuiteData") - if err != nil || resp.StatusCode != http.StatusOK { - return false - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return false - } - resp.Body.Close() - - afterSuiteData := types.RemoteAfterSuiteData{} - err = json.Unmarshal(body, &afterSuiteData) - if err != nil { - return false - } - - return afterSuiteData.CanRun -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go deleted file mode 100644 index d5c88931..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go +++ /dev/null @@ -1,181 +0,0 @@ -package leafnodes - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "reflect" - "time" - - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type synchronizedBeforeSuiteNode struct { - runnerA *runner - runnerB *runner - - data []byte - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - node := &synchronizedBeforeSuiteNode{} - - node.runnerA = newRunner(node.wrapA(bodyA), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - node.runnerB = newRunner(node.wrapB(bodyB), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - - return node -} - -func (node *synchronizedBeforeSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - defer func() { - node.runTime = time.Since(t) - }() - - if parallelNode == 1 { - node.outcome, node.failure = node.runA(parallelTotal, syncHost) - } else { - node.outcome, node.failure = node.waitForA(syncHost) - } - - if node.outcome != types.SpecStatePassed { - return false - } - node.outcome, node.failure = node.runnerB.run() - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) runA(parallelTotal int, syncHost string) (types.SpecState, types.SpecFailure) { - outcome, failure := node.runnerA.run() - - if parallelTotal > 1 { - state := types.RemoteBeforeSuiteStatePassed - if outcome != types.SpecStatePassed { - state = types.RemoteBeforeSuiteStateFailed - } - json := (types.RemoteBeforeSuiteData{ - Data: node.data, - State: state, - }).ToJSON() - http.Post(syncHost+"/BeforeSuiteState", "application/json", bytes.NewBuffer(json)) - } - - return outcome, failure -} - -func (node *synchronizedBeforeSuiteNode) waitForA(syncHost string) (types.SpecState, types.SpecFailure) { - failure := func(message string) types.SpecFailure { - return types.SpecFailure{ - Message: message, - Location: node.runnerA.codeLocation, - ComponentType: node.runnerA.nodeType, - ComponentIndex: node.runnerA.componentIndex, - ComponentCodeLocation: node.runnerA.codeLocation, - } - } - for { - resp, err := http.Get(syncHost + "/BeforeSuiteState") - if err != nil || resp.StatusCode != http.StatusOK { - return types.SpecStateFailed, failure("Failed to fetch BeforeSuite state") - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return types.SpecStateFailed, failure("Failed to read BeforeSuite state") - } - resp.Body.Close() - - beforeSuiteData := types.RemoteBeforeSuiteData{} - err = json.Unmarshal(body, &beforeSuiteData) - if err != nil { - return types.SpecStateFailed, failure("Failed to decode BeforeSuite state") - } - - switch beforeSuiteData.State { - case types.RemoteBeforeSuiteStatePassed: - node.data = beforeSuiteData.Data - return types.SpecStatePassed, types.SpecFailure{} - case types.RemoteBeforeSuiteStateFailed: - return types.SpecStateFailed, failure("BeforeSuite on Node 1 failed") - case types.RemoteBeforeSuiteStateDisappeared: - return types.SpecStateFailed, failure("Node 1 disappeared before completing BeforeSuite") - } - - time.Sleep(50 * time.Millisecond) - } -} - -func (node *synchronizedBeforeSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedBeforeSuiteNode) wrapA(bodyA interface{}) interface{} { - typeA := reflect.TypeOf(bodyA) - if typeA.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its first argument") - } - - takesNothing := typeA.NumIn() == 0 - takesADoneChannel := typeA.NumIn() == 1 && typeA.In(0).Kind() == reflect.Chan && typeA.In(0).Elem().Kind() == reflect.Interface - returnsBytes := typeA.NumOut() == 1 && typeA.Out(0).Kind() == reflect.Slice && typeA.Out(0).Elem().Kind() == reflect.Uint8 - - if !((takesNothing || takesADoneChannel) && returnsBytes) { - panic("SynchronizedBeforeSuite's first argument should be a function that returns []byte and either takes no arguments or takes a Done channel.") - } - - if takesADoneChannel { - return func(done chan<- interface{}) { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{reflect.ValueOf(done)}) - node.data = out[0].Interface().([]byte) - } - } - - return func() { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{}) - node.data = out[0].Interface().([]byte) - } -} - -func (node *synchronizedBeforeSuiteNode) wrapB(bodyB interface{}) interface{} { - typeB := reflect.TypeOf(bodyB) - if typeB.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its second argument") - } - - returnsNothing := typeB.NumOut() == 0 - takesBytesOnly := typeB.NumIn() == 1 && typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 - takesBytesAndDone := typeB.NumIn() == 2 && - typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 && - typeB.In(1).Kind() == reflect.Chan && typeB.In(1).Elem().Kind() == reflect.Interface - - if !((takesBytesOnly || takesBytesAndDone) && returnsNothing) { - panic("SynchronizedBeforeSuite's second argument should be a function that returns nothing and either takes []byte or ([]byte, Done)") - } - - if takesBytesAndDone { - return func(done chan<- interface{}) { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data), reflect.ValueOf(done)}) - } - } - - return func() { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data)}) - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go deleted file mode 100644 index 6b54afe0..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go +++ /dev/null @@ -1,249 +0,0 @@ -/* - -Aggregator is a reporter used by the Ginkgo CLI to aggregate and present parallel test output -coherently as tests complete. You shouldn't need to use this in your code. To run tests in parallel: - - ginkgo -nodes=N - -where N is the number of nodes you desire. -*/ -package remote - -import ( - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type configAndSuite struct { - config config.GinkgoConfigType - summary *types.SuiteSummary -} - -type Aggregator struct { - nodeCount int - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - result chan bool - - suiteBeginnings chan configAndSuite - aggregatedSuiteBeginnings []configAndSuite - - beforeSuites chan *types.SetupSummary - aggregatedBeforeSuites []*types.SetupSummary - - afterSuites chan *types.SetupSummary - aggregatedAfterSuites []*types.SetupSummary - - specCompletions chan *types.SpecSummary - completedSpecs []*types.SpecSummary - - suiteEndings chan *types.SuiteSummary - aggregatedSuiteEndings []*types.SuiteSummary - specs []*types.SpecSummary - - startTime time.Time -} - -func NewAggregator(nodeCount int, result chan bool, config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *Aggregator { - aggregator := &Aggregator{ - nodeCount: nodeCount, - result: result, - config: config, - stenographer: stenographer, - - suiteBeginnings: make(chan configAndSuite, 0), - beforeSuites: make(chan *types.SetupSummary, 0), - afterSuites: make(chan *types.SetupSummary, 0), - specCompletions: make(chan *types.SpecSummary, 0), - suiteEndings: make(chan *types.SuiteSummary, 0), - } - - go aggregator.mux() - - return aggregator -} - -func (aggregator *Aggregator) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - aggregator.suiteBeginnings <- configAndSuite{config, summary} -} - -func (aggregator *Aggregator) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.beforeSuites <- setupSummary -} - -func (aggregator *Aggregator) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.afterSuites <- setupSummary -} - -func (aggregator *Aggregator) SpecWillRun(specSummary *types.SpecSummary) { - //noop -} - -func (aggregator *Aggregator) SpecDidComplete(specSummary *types.SpecSummary) { - aggregator.specCompletions <- specSummary -} - -func (aggregator *Aggregator) SpecSuiteDidEnd(summary *types.SuiteSummary) { - aggregator.suiteEndings <- summary -} - -func (aggregator *Aggregator) mux() { -loop: - for { - select { - case configAndSuite := <-aggregator.suiteBeginnings: - aggregator.registerSuiteBeginning(configAndSuite) - case setupSummary := <-aggregator.beforeSuites: - aggregator.registerBeforeSuite(setupSummary) - case setupSummary := <-aggregator.afterSuites: - aggregator.registerAfterSuite(setupSummary) - case specSummary := <-aggregator.specCompletions: - aggregator.registerSpecCompletion(specSummary) - case suite := <-aggregator.suiteEndings: - finished, passed := aggregator.registerSuiteEnding(suite) - if finished { - aggregator.result <- passed - break loop - } - } - } -} - -func (aggregator *Aggregator) registerSuiteBeginning(configAndSuite configAndSuite) { - aggregator.aggregatedSuiteBeginnings = append(aggregator.aggregatedSuiteBeginnings, configAndSuite) - - if len(aggregator.aggregatedSuiteBeginnings) == 1 { - aggregator.startTime = time.Now() - } - - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - aggregator.stenographer.AnnounceSuite(configAndSuite.summary.SuiteDescription, configAndSuite.config.RandomSeed, configAndSuite.config.RandomizeAllSpecs, aggregator.config.Succinct) - - totalNumberOfSpecs := 0 - if len(aggregator.aggregatedSuiteBeginnings) > 0 { - totalNumberOfSpecs = configAndSuite.summary.NumberOfSpecsBeforeParallelization - } - - aggregator.stenographer.AnnounceTotalNumberOfSpecs(totalNumberOfSpecs, aggregator.config.Succinct) - aggregator.stenographer.AnnounceAggregatedParallelRun(aggregator.nodeCount, aggregator.config.Succinct) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedBeforeSuites = append(aggregator.aggregatedBeforeSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerAfterSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedAfterSuites = append(aggregator.aggregatedAfterSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerSpecCompletion(specSummary *types.SpecSummary) { - aggregator.completedSpecs = append(aggregator.completedSpecs, specSummary) - aggregator.specs = append(aggregator.specs, specSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) flushCompletedSpecs() { - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - for _, setupSummary := range aggregator.aggregatedBeforeSuites { - aggregator.announceBeforeSuite(setupSummary) - } - - for _, specSummary := range aggregator.completedSpecs { - aggregator.announceSpec(specSummary) - } - - for _, setupSummary := range aggregator.aggregatedAfterSuites { - aggregator.announceAfterSuite(setupSummary) - } - - aggregator.aggregatedBeforeSuites = []*types.SetupSummary{} - aggregator.completedSpecs = []*types.SpecSummary{} - aggregator.aggregatedAfterSuites = []*types.SetupSummary{} -} - -func (aggregator *Aggregator) announceBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceBeforeSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceAfterSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceAfterSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceSpec(specSummary *types.SpecSummary) { - if aggregator.config.Verbose && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - aggregator.stenographer.AnnounceSpecWillRun(specSummary) - } - - aggregator.stenographer.AnnounceCapturedOutput(specSummary.CapturedOutput) - - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - aggregator.stenographer.AnnounceSuccesfulMeasurement(specSummary, aggregator.config.Succinct) - } else if specSummary.RunTime.Seconds() >= aggregator.config.SlowSpecThreshold { - aggregator.stenographer.AnnounceSuccesfulSlowSpec(specSummary, aggregator.config.Succinct) - } else { - aggregator.stenographer.AnnounceSuccesfulSpec(specSummary) - } - - case types.SpecStatePending: - aggregator.stenographer.AnnouncePendingSpec(specSummary, aggregator.config.NoisyPendings && !aggregator.config.Succinct) - case types.SpecStateSkipped: - aggregator.stenographer.AnnounceSkippedSpec(specSummary, aggregator.config.Succinct || !aggregator.config.NoisySkippings, aggregator.config.FullTrace) - case types.SpecStateTimedOut: - aggregator.stenographer.AnnounceSpecTimedOut(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStatePanicked: - aggregator.stenographer.AnnounceSpecPanicked(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStateFailed: - aggregator.stenographer.AnnounceSpecFailed(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) registerSuiteEnding(suite *types.SuiteSummary) (finished bool, passed bool) { - aggregator.aggregatedSuiteEndings = append(aggregator.aggregatedSuiteEndings, suite) - if len(aggregator.aggregatedSuiteEndings) < aggregator.nodeCount { - return false, false - } - - aggregatedSuiteSummary := &types.SuiteSummary{} - aggregatedSuiteSummary.SuiteSucceeded = true - - for _, suiteSummary := range aggregator.aggregatedSuiteEndings { - if suiteSummary.SuiteSucceeded == false { - aggregatedSuiteSummary.SuiteSucceeded = false - } - - aggregatedSuiteSummary.NumberOfSpecsThatWillBeRun += suiteSummary.NumberOfSpecsThatWillBeRun - aggregatedSuiteSummary.NumberOfTotalSpecs += suiteSummary.NumberOfTotalSpecs - aggregatedSuiteSummary.NumberOfPassedSpecs += suiteSummary.NumberOfPassedSpecs - aggregatedSuiteSummary.NumberOfFailedSpecs += suiteSummary.NumberOfFailedSpecs - aggregatedSuiteSummary.NumberOfPendingSpecs += suiteSummary.NumberOfPendingSpecs - aggregatedSuiteSummary.NumberOfSkippedSpecs += suiteSummary.NumberOfSkippedSpecs - aggregatedSuiteSummary.NumberOfFlakedSpecs += suiteSummary.NumberOfFlakedSpecs - } - - aggregatedSuiteSummary.RunTime = time.Since(aggregator.startTime) - - aggregator.stenographer.SummarizeFailures(aggregator.specs) - aggregator.stenographer.AnnounceSpecRunCompletion(aggregatedSuiteSummary, aggregator.config.Succinct) - - return true, aggregatedSuiteSummary.SuiteSucceeded -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go b/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go deleted file mode 100644 index 284bc62e..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go +++ /dev/null @@ -1,147 +0,0 @@ -package remote - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/reporters/stenographer" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//An interface to net/http's client to allow the injection of fakes under test -type Poster interface { - Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) -} - -/* -The ForwardingReporter is a Ginkgo reporter that forwards information to -a Ginkgo remote server. - -When streaming parallel test output, this repoter is automatically installed by Ginkgo. - -This is accomplished by passing in the GINKGO_REMOTE_REPORTING_SERVER environment variable to `go test`, the Ginkgo test runner -detects this environment variable (which should contain the host of the server) and automatically installs a ForwardingReporter -in place of Ginkgo's DefaultReporter. -*/ - -type ForwardingReporter struct { - serverHost string - poster Poster - outputInterceptor OutputInterceptor - debugMode bool - debugFile *os.File - nestedReporter *reporters.DefaultReporter -} - -func NewForwardingReporter(config config.DefaultReporterConfigType, serverHost string, poster Poster, outputInterceptor OutputInterceptor, ginkgoWriter *writer.Writer, debugFile string) *ForwardingReporter { - reporter := &ForwardingReporter{ - serverHost: serverHost, - poster: poster, - outputInterceptor: outputInterceptor, - } - - if debugFile != "" { - var err error - reporter.debugMode = true - reporter.debugFile, err = os.Create(debugFile) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - if !config.Verbose { - //if verbose is true then the GinkgoWriter emits to stdout. Don't _also_ redirect GinkgoWriter output as that will result in duplication. - ginkgoWriter.AndRedirectTo(reporter.debugFile) - } - outputInterceptor.StreamTo(reporter.debugFile) //This is not working - - stenographer := stenographer.New(false, true, reporter.debugFile) - config.Succinct = false - config.Verbose = true - config.FullTrace = true - reporter.nestedReporter = reporters.NewDefaultReporter(config, stenographer) - } - - return reporter -} - -func (reporter *ForwardingReporter) post(path string, data interface{}) { - encoded, _ := json.Marshal(data) - buffer := bytes.NewBuffer(encoded) - reporter.poster.Post(reporter.serverHost+path, "application/json", buffer) -} - -func (reporter *ForwardingReporter) SpecSuiteWillBegin(conf config.GinkgoConfigType, summary *types.SuiteSummary) { - data := struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - }{ - conf, - summary, - } - - reporter.outputInterceptor.StartInterceptingOutput() - if reporter.debugMode { - reporter.nestedReporter.SpecSuiteWillBegin(conf, summary) - reporter.debugFile.Sync() - } - reporter.post("/SpecSuiteWillBegin", data) -} - -func (reporter *ForwardingReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - if reporter.debugMode { - reporter.nestedReporter.BeforeSuiteDidRun(setupSummary) - reporter.debugFile.Sync() - } - reporter.post("/BeforeSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecWillRun(specSummary *types.SpecSummary) { - if reporter.debugMode { - reporter.nestedReporter.SpecWillRun(specSummary) - reporter.debugFile.Sync() - } - reporter.post("/SpecWillRun", specSummary) -} - -func (reporter *ForwardingReporter) SpecDidComplete(specSummary *types.SpecSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - specSummary.CapturedOutput = output - if reporter.debugMode { - reporter.nestedReporter.SpecDidComplete(specSummary) - reporter.debugFile.Sync() - } - reporter.post("/SpecDidComplete", specSummary) -} - -func (reporter *ForwardingReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - if reporter.debugMode { - reporter.nestedReporter.AfterSuiteDidRun(setupSummary) - reporter.debugFile.Sync() - } - reporter.post("/AfterSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.outputInterceptor.StopInterceptingAndReturnOutput() - if reporter.debugMode { - reporter.nestedReporter.SpecSuiteDidEnd(summary) - reporter.debugFile.Sync() - } - reporter.post("/SpecSuiteDidEnd", summary) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go deleted file mode 100644 index 5154abe8..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go +++ /dev/null @@ -1,13 +0,0 @@ -package remote - -import "os" - -/* -The OutputInterceptor is used by the ForwardingReporter to -intercept and capture all stdin and stderr output during a test run. -*/ -type OutputInterceptor interface { - StartInterceptingOutput() error - StopInterceptingAndReturnOutput() (string, error) - StreamTo(*os.File) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go deleted file mode 100644 index ab6622a2..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go +++ /dev/null @@ -1,83 +0,0 @@ -// +build freebsd openbsd netbsd dragonfly darwin linux solaris - -package remote - -import ( - "errors" - "io/ioutil" - "os" - - "github.com/hpcloud/tail" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - redirectFile *os.File - streamTarget *os.File - intercepting bool - tailer *tail.Tail - doneTailing chan bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - var err error - - interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo-output") - if err != nil { - return err - } - - // Call a function in ./syscall_dup_*.go - // If building for everything other than linux_arm64, - // use a "normal" syscall.Dup2(oldfd, newfd) call. If building for linux_arm64 (which doesn't have syscall.Dup2) - // call syscall.Dup3(oldfd, newfd, 0). They are nearly identical, see: http://linux.die.net/man/2/dup3 - syscallDup(int(interceptor.redirectFile.Fd()), 1) - syscallDup(int(interceptor.redirectFile.Fd()), 2) - - if interceptor.streamTarget != nil { - interceptor.tailer, _ = tail.TailFile(interceptor.redirectFile.Name(), tail.Config{Follow: true}) - interceptor.doneTailing = make(chan bool) - - go func() { - for line := range interceptor.tailer.Lines { - interceptor.streamTarget.Write([]byte(line.Text + "\n")) - } - close(interceptor.doneTailing) - }() - } - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - if !interceptor.intercepting { - return "", errors.New("Not intercepting output!") - } - - interceptor.redirectFile.Close() - output, err := ioutil.ReadFile(interceptor.redirectFile.Name()) - os.Remove(interceptor.redirectFile.Name()) - - interceptor.intercepting = false - - if interceptor.streamTarget != nil { - interceptor.tailer.Stop() - interceptor.tailer.Cleanup() - <-interceptor.doneTailing - interceptor.streamTarget.Sync() - } - - return string(output), err -} - -func (interceptor *outputInterceptor) StreamTo(out *os.File) { - interceptor.streamTarget = out -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go deleted file mode 100644 index 40c79033..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build windows - -package remote - -import ( - "errors" - "os" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - intercepting bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - // not working on windows... - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - // not working on windows... - interceptor.intercepting = false - - return "", nil -} - -func (interceptor *outputInterceptor) StreamTo(*os.File) {} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/server.go b/vendor/github.com/onsi/ginkgo/internal/remote/server.go deleted file mode 100644 index 367c54da..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/server.go +++ /dev/null @@ -1,224 +0,0 @@ -/* - -The remote package provides the pieces to allow Ginkgo test suites to report to remote listeners. -This is used, primarily, to enable streaming parallel test output but has, in principal, broader applications (e.g. streaming test output to a browser). - -*/ - -package remote - -import ( - "encoding/json" - "io/ioutil" - "net" - "net/http" - "sync" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -/* -Server spins up on an automatically selected port and listens for communication from the forwarding reporter. -It then forwards that communication to attached reporters. -*/ -type Server struct { - listener net.Listener - reporters []reporters.Reporter - alives []func() bool - lock *sync.Mutex - beforeSuiteData types.RemoteBeforeSuiteData - parallelTotal int - counter int -} - -//Create a new server, automatically selecting a port -func NewServer(parallelTotal int) (*Server, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return nil, err - } - return &Server{ - listener: listener, - lock: &sync.Mutex{}, - alives: make([]func() bool, parallelTotal), - beforeSuiteData: types.RemoteBeforeSuiteData{Data: nil, State: types.RemoteBeforeSuiteStatePending}, - parallelTotal: parallelTotal, - }, nil -} - -//Start the server. You don't need to `go s.Start()`, just `s.Start()` -func (server *Server) Start() { - httpServer := &http.Server{} - mux := http.NewServeMux() - httpServer.Handler = mux - - //streaming endpoints - mux.HandleFunc("/SpecSuiteWillBegin", server.specSuiteWillBegin) - mux.HandleFunc("/BeforeSuiteDidRun", server.beforeSuiteDidRun) - mux.HandleFunc("/AfterSuiteDidRun", server.afterSuiteDidRun) - mux.HandleFunc("/SpecWillRun", server.specWillRun) - mux.HandleFunc("/SpecDidComplete", server.specDidComplete) - mux.HandleFunc("/SpecSuiteDidEnd", server.specSuiteDidEnd) - - //synchronization endpoints - mux.HandleFunc("/BeforeSuiteState", server.handleBeforeSuiteState) - mux.HandleFunc("/RemoteAfterSuiteData", server.handleRemoteAfterSuiteData) - mux.HandleFunc("/counter", server.handleCounter) - mux.HandleFunc("/has-counter", server.handleHasCounter) //for backward compatibility - - go httpServer.Serve(server.listener) -} - -//Stop the server -func (server *Server) Close() { - server.listener.Close() -} - -//The address the server can be reached it. Pass this into the `ForwardingReporter`. -func (server *Server) Address() string { - return "http://" + server.listener.Addr().String() -} - -// -// Streaming Endpoints -// - -//The server will forward all received messages to Ginkgo reporters registered with `RegisterReporters` -func (server *Server) readAll(request *http.Request) []byte { - defer request.Body.Close() - body, _ := ioutil.ReadAll(request.Body) - return body -} - -func (server *Server) RegisterReporters(reporters ...reporters.Reporter) { - server.reporters = reporters -} - -func (server *Server) specSuiteWillBegin(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - - var data struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - } - - json.Unmarshal(body, &data) - - for _, reporter := range server.reporters { - reporter.SpecSuiteWillBegin(data.Config, data.Summary) - } -} - -func (server *Server) beforeSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.BeforeSuiteDidRun(setupSummary) - } -} - -func (server *Server) afterSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.AfterSuiteDidRun(setupSummary) - } -} - -func (server *Server) specWillRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecWillRun(specSummary) - } -} - -func (server *Server) specDidComplete(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecDidComplete(specSummary) - } -} - -func (server *Server) specSuiteDidEnd(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var suiteSummary *types.SuiteSummary - json.Unmarshal(body, &suiteSummary) - - for _, reporter := range server.reporters { - reporter.SpecSuiteDidEnd(suiteSummary) - } -} - -// -// Synchronization Endpoints -// - -func (server *Server) RegisterAlive(node int, alive func() bool) { - server.lock.Lock() - defer server.lock.Unlock() - server.alives[node-1] = alive -} - -func (server *Server) nodeIsAlive(node int) bool { - server.lock.Lock() - defer server.lock.Unlock() - alive := server.alives[node-1] - if alive == nil { - return true - } - return alive() -} - -func (server *Server) handleBeforeSuiteState(writer http.ResponseWriter, request *http.Request) { - if request.Method == "POST" { - dec := json.NewDecoder(request.Body) - dec.Decode(&(server.beforeSuiteData)) - } else { - beforeSuiteData := server.beforeSuiteData - if beforeSuiteData.State == types.RemoteBeforeSuiteStatePending && !server.nodeIsAlive(1) { - beforeSuiteData.State = types.RemoteBeforeSuiteStateDisappeared - } - enc := json.NewEncoder(writer) - enc.Encode(beforeSuiteData) - } -} - -func (server *Server) handleRemoteAfterSuiteData(writer http.ResponseWriter, request *http.Request) { - afterSuiteData := types.RemoteAfterSuiteData{ - CanRun: true, - } - for i := 2; i <= server.parallelTotal; i++ { - afterSuiteData.CanRun = afterSuiteData.CanRun && !server.nodeIsAlive(i) - } - - enc := json.NewEncoder(writer) - enc.Encode(afterSuiteData) -} - -func (server *Server) handleCounter(writer http.ResponseWriter, request *http.Request) { - c := spec_iterator.Counter{} - server.lock.Lock() - c.Index = server.counter - server.counter = server.counter + 1 - server.lock.Unlock() - - json.NewEncoder(writer).Encode(c) -} - -func (server *Server) handleHasCounter(writer http.ResponseWriter, request *http.Request) { - writer.Write([]byte("")) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go deleted file mode 100644 index 9550d37b..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux,arm64 - -package remote - -import "syscall" - -// linux_arm64 doesn't have syscall.Dup2 which ginkgo uses, so -// use the nearly identical syscall.Dup3 instead -func syscallDup(oldfd int, newfd int) (err error) { - return syscall.Dup3(oldfd, newfd, 0) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go deleted file mode 100644 index 75ef7fb7..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build solaris - -package remote - -import "golang.org/x/sys/unix" - -func syscallDup(oldfd int, newfd int) (err error) { - return unix.Dup2(oldfd, newfd) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go deleted file mode 100644 index ef625596..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !linux !arm64 -// +build !windows -// +build !solaris - -package remote - -import "syscall" - -func syscallDup(oldfd int, newfd int) (err error) { - return syscall.Dup2(oldfd, newfd) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec.go deleted file mode 100644 index 7fd68ee8..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go +++ /dev/null @@ -1,247 +0,0 @@ -package spec - -import ( - "fmt" - "io" - "time" - - "sync" - - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type Spec struct { - subject leafnodes.SubjectNode - focused bool - announceProgress bool - - containers []*containernode.ContainerNode - - state types.SpecState - runTime time.Duration - startTime time.Time - failure types.SpecFailure - previousFailures bool - - stateMutex *sync.Mutex -} - -func New(subject leafnodes.SubjectNode, containers []*containernode.ContainerNode, announceProgress bool) *Spec { - spec := &Spec{ - subject: subject, - containers: containers, - focused: subject.Flag() == types.FlagTypeFocused, - announceProgress: announceProgress, - stateMutex: &sync.Mutex{}, - } - - spec.processFlag(subject.Flag()) - for i := len(containers) - 1; i >= 0; i-- { - spec.processFlag(containers[i].Flag()) - } - - return spec -} - -func (spec *Spec) processFlag(flag types.FlagType) { - if flag == types.FlagTypeFocused { - spec.focused = true - } else if flag == types.FlagTypePending { - spec.setState(types.SpecStatePending) - } -} - -func (spec *Spec) Skip() { - spec.setState(types.SpecStateSkipped) -} - -func (spec *Spec) Failed() bool { - return spec.getState() == types.SpecStateFailed || spec.getState() == types.SpecStatePanicked || spec.getState() == types.SpecStateTimedOut -} - -func (spec *Spec) Passed() bool { - return spec.getState() == types.SpecStatePassed -} - -func (spec *Spec) Flaked() bool { - return spec.getState() == types.SpecStatePassed && spec.previousFailures -} - -func (spec *Spec) Pending() bool { - return spec.getState() == types.SpecStatePending -} - -func (spec *Spec) Skipped() bool { - return spec.getState() == types.SpecStateSkipped -} - -func (spec *Spec) Focused() bool { - return spec.focused -} - -func (spec *Spec) IsMeasurement() bool { - return spec.subject.Type() == types.SpecComponentTypeMeasure -} - -func (spec *Spec) Summary(suiteID string) *types.SpecSummary { - componentTexts := make([]string, len(spec.containers)+1) - componentCodeLocations := make([]types.CodeLocation, len(spec.containers)+1) - - for i, container := range spec.containers { - componentTexts[i] = container.Text() - componentCodeLocations[i] = container.CodeLocation() - } - - componentTexts[len(spec.containers)] = spec.subject.Text() - componentCodeLocations[len(spec.containers)] = spec.subject.CodeLocation() - - runTime := spec.runTime - if runTime == 0 && !spec.startTime.IsZero() { - runTime = time.Since(spec.startTime) - } - - return &types.SpecSummary{ - IsMeasurement: spec.IsMeasurement(), - NumberOfSamples: spec.subject.Samples(), - ComponentTexts: componentTexts, - ComponentCodeLocations: componentCodeLocations, - State: spec.getState(), - RunTime: runTime, - Failure: spec.failure, - Measurements: spec.measurementsReport(), - SuiteID: suiteID, - } -} - -func (spec *Spec) ConcatenatedString() string { - s := "" - for _, container := range spec.containers { - s += container.Text() + " " - } - - return s + spec.subject.Text() -} - -func (spec *Spec) Run(writer io.Writer) { - if spec.getState() == types.SpecStateFailed { - spec.previousFailures = true - } - - spec.startTime = time.Now() - defer func() { - spec.runTime = time.Since(spec.startTime) - }() - - for sample := 0; sample < spec.subject.Samples(); sample++ { - spec.runSample(sample, writer) - - if spec.getState() != types.SpecStatePassed { - return - } - } -} - -func (spec *Spec) getState() types.SpecState { - spec.stateMutex.Lock() - defer spec.stateMutex.Unlock() - return spec.state -} - -func (spec *Spec) setState(state types.SpecState) { - spec.stateMutex.Lock() - defer spec.stateMutex.Unlock() - spec.state = state -} - -func (spec *Spec) runSample(sample int, writer io.Writer) { - spec.setState(types.SpecStatePassed) - spec.failure = types.SpecFailure{} - innerMostContainerIndexToUnwind := -1 - - defer func() { - for i := innerMostContainerIndexToUnwind; i >= 0; i-- { - container := spec.containers[i] - for _, justAfterEach := range container.SetupNodesOfType(types.SpecComponentTypeJustAfterEach) { - spec.announceSetupNode(writer, "JustAfterEach", container, justAfterEach) - justAfterEachState, justAfterEachFailure := justAfterEach.Run() - if justAfterEachState != types.SpecStatePassed && spec.state == types.SpecStatePassed { - spec.state = justAfterEachState - spec.failure = justAfterEachFailure - } - } - } - - for i := innerMostContainerIndexToUnwind; i >= 0; i-- { - container := spec.containers[i] - for _, afterEach := range container.SetupNodesOfType(types.SpecComponentTypeAfterEach) { - spec.announceSetupNode(writer, "AfterEach", container, afterEach) - afterEachState, afterEachFailure := afterEach.Run() - if afterEachState != types.SpecStatePassed && spec.getState() == types.SpecStatePassed { - spec.setState(afterEachState) - spec.failure = afterEachFailure - } - } - } - }() - - for i, container := range spec.containers { - innerMostContainerIndexToUnwind = i - for _, beforeEach := range container.SetupNodesOfType(types.SpecComponentTypeBeforeEach) { - spec.announceSetupNode(writer, "BeforeEach", container, beforeEach) - s, f := beforeEach.Run() - spec.failure = f - spec.setState(s) - if spec.getState() != types.SpecStatePassed { - return - } - } - } - - for _, container := range spec.containers { - for _, justBeforeEach := range container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach) { - spec.announceSetupNode(writer, "JustBeforeEach", container, justBeforeEach) - s, f := justBeforeEach.Run() - spec.failure = f - spec.setState(s) - if spec.getState() != types.SpecStatePassed { - return - } - } - } - - spec.announceSubject(writer, spec.subject) - s, f := spec.subject.Run() - spec.failure = f - spec.setState(s) -} - -func (spec *Spec) announceSetupNode(writer io.Writer, nodeType string, container *containernode.ContainerNode, setupNode leafnodes.BasicNode) { - if spec.announceProgress { - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, container.Text(), setupNode.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) announceSubject(writer io.Writer, subject leafnodes.SubjectNode) { - if spec.announceProgress { - nodeType := "" - switch subject.Type() { - case types.SpecComponentTypeIt: - nodeType = "It" - case types.SpecComponentTypeMeasure: - nodeType = "Measure" - } - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, subject.Text(), subject.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) measurementsReport() map[string]*types.SpecMeasurement { - if !spec.IsMeasurement() || spec.Failed() { - return map[string]*types.SpecMeasurement{} - } - - return spec.subject.(*leafnodes.MeasureNode).MeasurementsReport() -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/specs.go b/vendor/github.com/onsi/ginkgo/internal/spec/specs.go deleted file mode 100644 index 006185ab..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/specs.go +++ /dev/null @@ -1,123 +0,0 @@ -package spec - -import ( - "math/rand" - "regexp" - "sort" -) - -type Specs struct { - specs []*Spec - hasProgrammaticFocus bool - RegexScansFilePath bool -} - -func NewSpecs(specs []*Spec) *Specs { - return &Specs{ - specs: specs, - } -} - -func (e *Specs) Specs() []*Spec { - return e.specs -} - -func (e *Specs) HasProgrammaticFocus() bool { - return e.hasProgrammaticFocus -} - -func (e *Specs) Shuffle(r *rand.Rand) { - sort.Sort(e) - permutation := r.Perm(len(e.specs)) - shuffledSpecs := make([]*Spec, len(e.specs)) - for i, j := range permutation { - shuffledSpecs[i] = e.specs[j] - } - e.specs = shuffledSpecs -} - -func (e *Specs) ApplyFocus(description string, focusString string, skipString string) { - if focusString == "" && skipString == "" { - e.applyProgrammaticFocus() - } else { - e.applyRegExpFocusAndSkip(description, focusString, skipString) - } -} - -func (e *Specs) applyProgrammaticFocus() { - e.hasProgrammaticFocus = false - for _, spec := range e.specs { - if spec.Focused() && !spec.Pending() { - e.hasProgrammaticFocus = true - break - } - } - - if e.hasProgrammaticFocus { - for _, spec := range e.specs { - if !spec.Focused() { - spec.Skip() - } - } - } -} - -// toMatch returns a byte[] to be used by regex matchers. When adding new behaviours to the matching function, -// this is the place which we append to. -func (e *Specs) toMatch(description string, spec *Spec) []byte { - if e.RegexScansFilePath { - return []byte( - description + " " + - spec.ConcatenatedString() + " " + - spec.subject.CodeLocation().FileName) - } else { - return []byte( - description + " " + - spec.ConcatenatedString()) - } -} - -func (e *Specs) applyRegExpFocusAndSkip(description string, focusString string, skipString string) { - for _, spec := range e.specs { - matchesFocus := true - matchesSkip := false - - toMatch := e.toMatch(description, spec) - - if focusString != "" { - focusFilter := regexp.MustCompile(focusString) - matchesFocus = focusFilter.Match([]byte(toMatch)) - } - - if skipString != "" { - skipFilter := regexp.MustCompile(skipString) - matchesSkip = skipFilter.Match([]byte(toMatch)) - } - - if !matchesFocus || matchesSkip { - spec.Skip() - } - } -} - -func (e *Specs) SkipMeasurements() { - for _, spec := range e.specs { - if spec.IsMeasurement() { - spec.Skip() - } - } -} - -//sort.Interface - -func (e *Specs) Len() int { - return len(e.specs) -} - -func (e *Specs) Less(i, j int) bool { - return e.specs[i].ConcatenatedString() < e.specs[j].ConcatenatedString() -} - -func (e *Specs) Swap(i, j int) { - e.specs[i], e.specs[j] = e.specs[j], e.specs[i] -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go deleted file mode 100644 index 82272554..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go +++ /dev/null @@ -1,55 +0,0 @@ -package spec_iterator - -func ParallelizedIndexRange(length int, parallelTotal int, parallelNode int) (startIndex int, count int) { - if length == 0 { - return 0, 0 - } - - // We have more nodes than tests. Trivial case. - if parallelTotal >= length { - if parallelNode > length { - return 0, 0 - } else { - return parallelNode - 1, 1 - } - } - - // This is the minimum amount of tests that a node will be required to run - minTestsPerNode := length / parallelTotal - - // This is the maximum amount of tests that a node will be required to run - // The algorithm guarantees that this would be equal to at least the minimum amount - // and at most one more - maxTestsPerNode := minTestsPerNode - if length%parallelTotal != 0 { - maxTestsPerNode++ - } - - // Number of nodes that will have to run the maximum amount of tests per node - numMaxLoadNodes := length % parallelTotal - - // Number of nodes that precede the current node and will have to run the maximum amount of tests per node - var numPrecedingMaxLoadNodes int - if parallelNode > numMaxLoadNodes { - numPrecedingMaxLoadNodes = numMaxLoadNodes - } else { - numPrecedingMaxLoadNodes = parallelNode - 1 - } - - // Number of nodes that precede the current node and will have to run the minimum amount of tests per node - var numPrecedingMinLoadNodes int - if parallelNode <= numMaxLoadNodes { - numPrecedingMinLoadNodes = 0 - } else { - numPrecedingMinLoadNodes = parallelNode - numMaxLoadNodes - 1 - } - - // Evaluate the test start index and number of tests to run - startIndex = numPrecedingMaxLoadNodes*maxTestsPerNode + numPrecedingMinLoadNodes*minTestsPerNode - if parallelNode > numMaxLoadNodes { - count = minTestsPerNode - } else { - count = maxTestsPerNode - } - return -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go deleted file mode 100644 index 99f548bc..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go +++ /dev/null @@ -1,59 +0,0 @@ -package spec_iterator - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/onsi/ginkgo/internal/spec" -) - -type ParallelIterator struct { - specs []*spec.Spec - host string - client *http.Client -} - -func NewParallelIterator(specs []*spec.Spec, host string) *ParallelIterator { - return &ParallelIterator{ - specs: specs, - host: host, - client: &http.Client{}, - } -} - -func (s *ParallelIterator) Next() (*spec.Spec, error) { - resp, err := s.client.Get(s.host + "/counter") - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode) - } - - var counter Counter - err = json.NewDecoder(resp.Body).Decode(&counter) - if err != nil { - return nil, err - } - - if counter.Index >= len(s.specs) { - return nil, ErrClosed - } - - return s.specs[counter.Index], nil -} - -func (s *ParallelIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *ParallelIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return -1, false -} - -func (s *ParallelIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - return -1, false -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go deleted file mode 100644 index a51c93b8..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go +++ /dev/null @@ -1,45 +0,0 @@ -package spec_iterator - -import ( - "github.com/onsi/ginkgo/internal/spec" -) - -type SerialIterator struct { - specs []*spec.Spec - index int -} - -func NewSerialIterator(specs []*spec.Spec) *SerialIterator { - return &SerialIterator{ - specs: specs, - index: 0, - } -} - -func (s *SerialIterator) Next() (*spec.Spec, error) { - if s.index >= len(s.specs) { - return nil, ErrClosed - } - - spec := s.specs[s.index] - s.index += 1 - return spec, nil -} - -func (s *SerialIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *SerialIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return len(s.specs), true -} - -func (s *SerialIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - count := 0 - for _, s := range s.specs { - if !s.Skipped() && !s.Pending() { - count += 1 - } - } - return count, true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go deleted file mode 100644 index ad4a3ea3..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go +++ /dev/null @@ -1,47 +0,0 @@ -package spec_iterator - -import "github.com/onsi/ginkgo/internal/spec" - -type ShardedParallelIterator struct { - specs []*spec.Spec - index int - maxIndex int -} - -func NewShardedParallelIterator(specs []*spec.Spec, total int, node int) *ShardedParallelIterator { - startIndex, count := ParallelizedIndexRange(len(specs), total, node) - - return &ShardedParallelIterator{ - specs: specs, - index: startIndex, - maxIndex: startIndex + count, - } -} - -func (s *ShardedParallelIterator) Next() (*spec.Spec, error) { - if s.index >= s.maxIndex { - return nil, ErrClosed - } - - spec := s.specs[s.index] - s.index += 1 - return spec, nil -} - -func (s *ShardedParallelIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *ShardedParallelIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return s.maxIndex - s.index, true -} - -func (s *ShardedParallelIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - count := 0 - for i := s.index; i < s.maxIndex; i += 1 { - if !s.specs[i].Skipped() && !s.specs[i].Pending() { - count += 1 - } - } - return count, true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go deleted file mode 100644 index 74bffad6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go +++ /dev/null @@ -1,20 +0,0 @@ -package spec_iterator - -import ( - "errors" - - "github.com/onsi/ginkgo/internal/spec" -) - -var ErrClosed = errors.New("no more specs to run") - -type SpecIterator interface { - Next() (*spec.Spec, error) - NumberOfSpecsPriorToIteration() int - NumberOfSpecsToProcessIfKnown() (int, bool) - NumberOfSpecsThatWillBeRunIfKnown() (int, bool) -} - -type Counter struct { - Index int `json:"index"` -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go deleted file mode 100644 index a0b8b62d..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go +++ /dev/null @@ -1,15 +0,0 @@ -package specrunner - -import ( - "crypto/rand" - "fmt" -) - -func randomID() string { - b := make([]byte, 8) - _, err := rand.Read(b) - if err != nil { - return "" - } - return fmt.Sprintf("%x-%x-%x-%x", b[0:2], b[2:4], b[4:6], b[6:8]) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go deleted file mode 100644 index 2c683cb8..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go +++ /dev/null @@ -1,411 +0,0 @@ -package specrunner - -import ( - "fmt" - "os" - "os/signal" - "sync" - "syscall" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "time" -) - -type SpecRunner struct { - description string - beforeSuiteNode leafnodes.SuiteNode - iterator spec_iterator.SpecIterator - afterSuiteNode leafnodes.SuiteNode - reporters []reporters.Reporter - startTime time.Time - suiteID string - runningSpec *spec.Spec - writer Writer.WriterInterface - config config.GinkgoConfigType - interrupted bool - processedSpecs []*spec.Spec - lock *sync.Mutex -} - -func New(description string, beforeSuiteNode leafnodes.SuiteNode, iterator spec_iterator.SpecIterator, afterSuiteNode leafnodes.SuiteNode, reporters []reporters.Reporter, writer Writer.WriterInterface, config config.GinkgoConfigType) *SpecRunner { - return &SpecRunner{ - description: description, - beforeSuiteNode: beforeSuiteNode, - iterator: iterator, - afterSuiteNode: afterSuiteNode, - reporters: reporters, - writer: writer, - config: config, - suiteID: randomID(), - lock: &sync.Mutex{}, - } -} - -func (runner *SpecRunner) Run() bool { - if runner.config.DryRun { - runner.performDryRun() - return true - } - - runner.reportSuiteWillBegin() - signalRegistered := make(chan struct{}) - go runner.registerForInterrupts(signalRegistered) - <-signalRegistered - - suitePassed := runner.runBeforeSuite() - - if suitePassed { - suitePassed = runner.runSpecs() - } - - runner.blockForeverIfInterrupted() - - suitePassed = runner.runAfterSuite() && suitePassed - - runner.reportSuiteDidEnd(suitePassed) - - return suitePassed -} - -func (runner *SpecRunner) performDryRun() { - runner.reportSuiteWillBegin() - - if runner.beforeSuiteNode != nil { - summary := runner.beforeSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportBeforeSuite(summary) - } - - for { - spec, err := runner.iterator.Next() - if err == spec_iterator.ErrClosed { - break - } - if err != nil { - fmt.Println("failed to iterate over tests:\n" + err.Error()) - break - } - - runner.processedSpecs = append(runner.processedSpecs, spec) - - summary := spec.Summary(runner.suiteID) - runner.reportSpecWillRun(summary) - if summary.State == types.SpecStateInvalid { - summary.State = types.SpecStatePassed - } - runner.reportSpecDidComplete(summary, false) - } - - if runner.afterSuiteNode != nil { - summary := runner.afterSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportAfterSuite(summary) - } - - runner.reportSuiteDidEnd(true) -} - -func (runner *SpecRunner) runBeforeSuite() bool { - if runner.beforeSuiteNode == nil || runner.wasInterrupted() { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.beforeSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportBeforeSuite(runner.beforeSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runAfterSuite() bool { - if runner.afterSuiteNode == nil { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.afterSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportAfterSuite(runner.afterSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runSpecs() bool { - suiteFailed := false - skipRemainingSpecs := false - for { - spec, err := runner.iterator.Next() - if err == spec_iterator.ErrClosed { - break - } - if err != nil { - fmt.Println("failed to iterate over tests:\n" + err.Error()) - suiteFailed = true - break - } - - runner.processedSpecs = append(runner.processedSpecs, spec) - - if runner.wasInterrupted() { - break - } - if skipRemainingSpecs { - spec.Skip() - } - - if !spec.Skipped() && !spec.Pending() { - if passed := runner.runSpec(spec); !passed { - suiteFailed = true - } - } else if spec.Pending() && runner.config.FailOnPending { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - suiteFailed = true - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - } else { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - } - - if spec.Failed() && runner.config.FailFast { - skipRemainingSpecs = true - } - } - - return !suiteFailed -} - -func (runner *SpecRunner) runSpec(spec *spec.Spec) (passed bool) { - maxAttempts := 1 - if runner.config.FlakeAttempts > 0 { - // uninitialized configs count as 1 - maxAttempts = runner.config.FlakeAttempts - } - - for i := 0; i < maxAttempts; i++ { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - runner.runningSpec = spec - spec.Run(runner.writer) - runner.runningSpec = nil - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - if !spec.Failed() { - return true - } - } - return false -} - -func (runner *SpecRunner) CurrentSpecSummary() (*types.SpecSummary, bool) { - if runner.runningSpec == nil { - return nil, false - } - - return runner.runningSpec.Summary(runner.suiteID), true -} - -func (runner *SpecRunner) registerForInterrupts(signalRegistered chan struct{}) { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - close(signalRegistered) - - <-c - signal.Stop(c) - runner.markInterrupted() - go runner.registerForHardInterrupts() - runner.writer.DumpOutWithHeader(` -Received interrupt. Emitting contents of GinkgoWriter... ---------------------------------------------------------- -`) - if runner.afterSuiteNode != nil { - fmt.Fprint(os.Stderr, ` ---------------------------------------------------------- -Received interrupt. Running AfterSuite... -^C again to terminate immediately -`) - runner.runAfterSuite() - } - runner.reportSuiteDidEnd(false) - os.Exit(1) -} - -func (runner *SpecRunner) registerForHardInterrupts() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - fmt.Fprintln(os.Stderr, "\nReceived second interrupt. Shutting down.") - os.Exit(1) -} - -func (runner *SpecRunner) blockForeverIfInterrupted() { - runner.lock.Lock() - interrupted := runner.interrupted - runner.lock.Unlock() - - if interrupted { - select {} - } -} - -func (runner *SpecRunner) markInterrupted() { - runner.lock.Lock() - defer runner.lock.Unlock() - runner.interrupted = true -} - -func (runner *SpecRunner) wasInterrupted() bool { - runner.lock.Lock() - defer runner.lock.Unlock() - return runner.interrupted -} - -func (runner *SpecRunner) reportSuiteWillBegin() { - runner.startTime = time.Now() - summary := runner.suiteWillBeginSummary() - for _, reporter := range runner.reporters { - reporter.SpecSuiteWillBegin(runner.config, summary) - } -} - -func (runner *SpecRunner) reportBeforeSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.BeforeSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportAfterSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.AfterSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportSpecWillRun(summary *types.SpecSummary) { - runner.writer.Truncate() - - for _, reporter := range runner.reporters { - reporter.SpecWillRun(summary) - } -} - -func (runner *SpecRunner) reportSpecDidComplete(summary *types.SpecSummary, failed bool) { - if failed && len(summary.CapturedOutput) == 0 { - summary.CapturedOutput = string(runner.writer.Bytes()) - } - for i := len(runner.reporters) - 1; i >= 1; i-- { - runner.reporters[i].SpecDidComplete(summary) - } - - if failed { - runner.writer.DumpOut() - } - - runner.reporters[0].SpecDidComplete(summary) -} - -func (runner *SpecRunner) reportSuiteDidEnd(success bool) { - summary := runner.suiteDidEndSummary(success) - summary.RunTime = time.Since(runner.startTime) - for _, reporter := range runner.reporters { - reporter.SpecSuiteDidEnd(summary) - } -} - -func (runner *SpecRunner) countSpecsThatRanSatisfying(filter func(ex *spec.Spec) bool) (count int) { - count = 0 - - for _, spec := range runner.processedSpecs { - if filter(spec) { - count++ - } - } - - return count -} - -func (runner *SpecRunner) suiteDidEndSummary(success bool) *types.SuiteSummary { - numberOfSpecsThatWillBeRun := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return !ex.Skipped() && !ex.Pending() - }) - - numberOfPendingSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Pending() - }) - - numberOfSkippedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Skipped() - }) - - numberOfPassedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Passed() - }) - - numberOfFlakedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Flaked() - }) - - numberOfFailedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Failed() - }) - - if runner.beforeSuiteNode != nil && !runner.beforeSuiteNode.Passed() && !runner.config.DryRun { - var known bool - numberOfSpecsThatWillBeRun, known = runner.iterator.NumberOfSpecsThatWillBeRunIfKnown() - if !known { - numberOfSpecsThatWillBeRun = runner.iterator.NumberOfSpecsPriorToIteration() - } - numberOfFailedSpecs = numberOfSpecsThatWillBeRun - } - - return &types.SuiteSummary{ - SuiteDescription: runner.description, - SuiteSucceeded: success, - SuiteID: runner.suiteID, - - NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(), - NumberOfTotalSpecs: len(runner.processedSpecs), - NumberOfSpecsThatWillBeRun: numberOfSpecsThatWillBeRun, - NumberOfPendingSpecs: numberOfPendingSpecs, - NumberOfSkippedSpecs: numberOfSkippedSpecs, - NumberOfPassedSpecs: numberOfPassedSpecs, - NumberOfFailedSpecs: numberOfFailedSpecs, - NumberOfFlakedSpecs: numberOfFlakedSpecs, - } -} - -func (runner *SpecRunner) suiteWillBeginSummary() *types.SuiteSummary { - numTotal, known := runner.iterator.NumberOfSpecsToProcessIfKnown() - if !known { - numTotal = -1 - } - - numToRun, known := runner.iterator.NumberOfSpecsThatWillBeRunIfKnown() - if !known { - numToRun = -1 - } - - return &types.SuiteSummary{ - SuiteDescription: runner.description, - SuiteID: runner.suiteID, - - NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(), - NumberOfTotalSpecs: numTotal, - NumberOfSpecsThatWillBeRun: numToRun, - NumberOfPendingSpecs: -1, - NumberOfSkippedSpecs: -1, - NumberOfPassedSpecs: -1, - NumberOfFailedSpecs: -1, - NumberOfFlakedSpecs: -1, - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite.go deleted file mode 100644 index 3104bbc8..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go +++ /dev/null @@ -1,190 +0,0 @@ -package suite - -import ( - "math/rand" - "net/http" - "time" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -type ginkgoTestingT interface { - Fail() -} - -type Suite struct { - topLevelContainer *containernode.ContainerNode - currentContainer *containernode.ContainerNode - containerIndex int - beforeSuiteNode leafnodes.SuiteNode - afterSuiteNode leafnodes.SuiteNode - runner *specrunner.SpecRunner - failer *failer.Failer - running bool -} - -func New(failer *failer.Failer) *Suite { - topLevelContainer := containernode.New("[Top Level]", types.FlagTypeNone, types.CodeLocation{}) - - return &Suite{ - topLevelContainer: topLevelContainer, - currentContainer: topLevelContainer, - failer: failer, - containerIndex: 1, - } -} - -func (suite *Suite) Run(t ginkgoTestingT, description string, reporters []reporters.Reporter, writer writer.WriterInterface, config config.GinkgoConfigType) (bool, bool) { - if config.ParallelTotal < 1 { - panic("ginkgo.parallel.total must be >= 1") - } - - if config.ParallelNode > config.ParallelTotal || config.ParallelNode < 1 { - panic("ginkgo.parallel.node is one-indexed and must be <= ginkgo.parallel.total") - } - - r := rand.New(rand.NewSource(config.RandomSeed)) - suite.topLevelContainer.Shuffle(r) - iterator, hasProgrammaticFocus := suite.generateSpecsIterator(description, config) - suite.runner = specrunner.New(description, suite.beforeSuiteNode, iterator, suite.afterSuiteNode, reporters, writer, config) - - suite.running = true - success := suite.runner.Run() - if !success { - t.Fail() - } - return success, hasProgrammaticFocus -} - -func (suite *Suite) generateSpecsIterator(description string, config config.GinkgoConfigType) (spec_iterator.SpecIterator, bool) { - specsSlice := []*spec.Spec{} - suite.topLevelContainer.BackPropagateProgrammaticFocus() - for _, collatedNodes := range suite.topLevelContainer.Collate() { - specsSlice = append(specsSlice, spec.New(collatedNodes.Subject, collatedNodes.Containers, config.EmitSpecProgress)) - } - - specs := spec.NewSpecs(specsSlice) - specs.RegexScansFilePath = config.RegexScansFilePath - - if config.RandomizeAllSpecs { - specs.Shuffle(rand.New(rand.NewSource(config.RandomSeed))) - } - - specs.ApplyFocus(description, config.FocusString, config.SkipString) - - if config.SkipMeasurements { - specs.SkipMeasurements() - } - - var iterator spec_iterator.SpecIterator - - if config.ParallelTotal > 1 { - iterator = spec_iterator.NewParallelIterator(specs.Specs(), config.SyncHost) - resp, err := http.Get(config.SyncHost + "/has-counter") - if err != nil || resp.StatusCode != http.StatusOK { - iterator = spec_iterator.NewShardedParallelIterator(specs.Specs(), config.ParallelTotal, config.ParallelNode) - } - } else { - iterator = spec_iterator.NewSerialIterator(specs.Specs()) - } - - return iterator, specs.HasProgrammaticFocus() -} - -func (suite *Suite) CurrentRunningSpecSummary() (*types.SpecSummary, bool) { - return suite.runner.CurrentSpecSummary() -} - -func (suite *Suite) SetBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewBeforeSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewAfterSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) PushContainerNode(text string, body func(), flag types.FlagType, codeLocation types.CodeLocation) { - container := containernode.New(text, flag, codeLocation) - suite.currentContainer.PushContainerNode(container) - - previousContainer := suite.currentContainer - suite.currentContainer = container - suite.containerIndex++ - - body() - - suite.containerIndex-- - suite.currentContainer = previousContainer -} - -func (suite *Suite) PushItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call It from within a Describe, Context or When", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewItNode(text, body, flag, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int) { - if suite.running { - suite.failer.Fail("You may only call Measure from within a Describe, Context or When", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewMeasureNode(text, body, flag, codeLocation, samples, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call BeforeEach from within a Describe, Context or When", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call JustBeforeEach from within a Describe, Context or When", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewJustBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushJustAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call JustAfterEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewJustAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call AfterEach from within a Describe, Context or When", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go b/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go deleted file mode 100644 index 090445d0..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go +++ /dev/null @@ -1,76 +0,0 @@ -package testingtproxy - -import ( - "fmt" - "io" -) - -type failFunc func(message string, callerSkip ...int) - -func New(writer io.Writer, fail failFunc, offset int) *ginkgoTestingTProxy { - return &ginkgoTestingTProxy{ - fail: fail, - offset: offset, - writer: writer, - } -} - -type ginkgoTestingTProxy struct { - fail failFunc - offset int - writer io.Writer -} - -func (t *ginkgoTestingTProxy) Error(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Errorf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fail() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) FailNow() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) Fatal(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fatalf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Log(args ...interface{}) { - fmt.Fprintln(t.writer, args...) -} - -func (t *ginkgoTestingTProxy) Logf(format string, args ...interface{}) { - t.Log(fmt.Sprintf(format, args...)) -} - -func (t *ginkgoTestingTProxy) Failed() bool { - return false -} - -func (t *ginkgoTestingTProxy) Parallel() { -} - -func (t *ginkgoTestingTProxy) Skip(args ...interface{}) { - fmt.Println(args...) -} - -func (t *ginkgoTestingTProxy) Skipf(format string, args ...interface{}) { - t.Skip(fmt.Sprintf(format, args...)) -} - -func (t *ginkgoTestingTProxy) SkipNow() { -} - -func (t *ginkgoTestingTProxy) Skipped() bool { - return false -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go b/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go deleted file mode 100644 index 6739c3f6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go +++ /dev/null @@ -1,36 +0,0 @@ -package writer - -type FakeGinkgoWriter struct { - EventStream []string -} - -func NewFake() *FakeGinkgoWriter { - return &FakeGinkgoWriter{ - EventStream: []string{}, - } -} - -func (writer *FakeGinkgoWriter) AddEvent(event string) { - writer.EventStream = append(writer.EventStream, event) -} - -func (writer *FakeGinkgoWriter) Truncate() { - writer.EventStream = append(writer.EventStream, "TRUNCATE") -} - -func (writer *FakeGinkgoWriter) DumpOut() { - writer.EventStream = append(writer.EventStream, "DUMP") -} - -func (writer *FakeGinkgoWriter) DumpOutWithHeader(header string) { - writer.EventStream = append(writer.EventStream, "DUMP_WITH_HEADER: "+header) -} - -func (writer *FakeGinkgoWriter) Bytes() []byte { - writer.EventStream = append(writer.EventStream, "BYTES") - return nil -} - -func (writer *FakeGinkgoWriter) Write(data []byte) (n int, err error) { - return 0, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer.go deleted file mode 100644 index 98eca3bd..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer.go +++ /dev/null @@ -1,89 +0,0 @@ -package writer - -import ( - "bytes" - "io" - "sync" -) - -type WriterInterface interface { - io.Writer - - Truncate() - DumpOut() - DumpOutWithHeader(header string) - Bytes() []byte -} - -type Writer struct { - buffer *bytes.Buffer - outWriter io.Writer - lock *sync.Mutex - stream bool - redirector io.Writer -} - -func New(outWriter io.Writer) *Writer { - return &Writer{ - buffer: &bytes.Buffer{}, - lock: &sync.Mutex{}, - outWriter: outWriter, - stream: true, - } -} - -func (w *Writer) AndRedirectTo(writer io.Writer) { - w.redirector = writer -} - -func (w *Writer) SetStream(stream bool) { - w.lock.Lock() - defer w.lock.Unlock() - w.stream = stream -} - -func (w *Writer) Write(b []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - n, err = w.buffer.Write(b) - if w.redirector != nil { - w.redirector.Write(b) - } - if w.stream { - return w.outWriter.Write(b) - } - return n, err -} - -func (w *Writer) Truncate() { - w.lock.Lock() - defer w.lock.Unlock() - w.buffer.Reset() -} - -func (w *Writer) DumpOut() { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream { - w.buffer.WriteTo(w.outWriter) - } -} - -func (w *Writer) Bytes() []byte { - w.lock.Lock() - defer w.lock.Unlock() - b := w.buffer.Bytes() - copied := make([]byte, len(b)) - copy(copied, b) - return copied -} - -func (w *Writer) DumpOutWithHeader(header string) { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream && w.buffer.Len() > 0 { - w.outWriter.Write([]byte(header)) - w.buffer.WriteTo(w.outWriter) - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go deleted file mode 100644 index ac58dd5f..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Ginkgo's Default Reporter - -A number of command line flags are available to tweak Ginkgo's default output. - -These are documented [here](http://onsi.github.io/ginkgo/#running_tests) -*/ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type DefaultReporter struct { - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - specSummaries []*types.SpecSummary -} - -func NewDefaultReporter(config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *DefaultReporter { - return &DefaultReporter{ - config: config, - stenographer: stenographer, - } -} - -func (reporter *DefaultReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.stenographer.AnnounceSuite(summary.SuiteDescription, config.RandomSeed, config.RandomizeAllSpecs, reporter.config.Succinct) - if config.ParallelTotal > 1 { - reporter.stenographer.AnnounceParallelRun(config.ParallelNode, config.ParallelTotal, reporter.config.Succinct) - } else { - reporter.stenographer.AnnounceNumberOfSpecs(summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, reporter.config.Succinct) - } -} - -func (reporter *DefaultReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceBeforeSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceAfterSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) SpecWillRun(specSummary *types.SpecSummary) { - if reporter.config.Verbose && !reporter.config.Succinct && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - reporter.stenographer.AnnounceSpecWillRun(specSummary) - } -} - -func (reporter *DefaultReporter) SpecDidComplete(specSummary *types.SpecSummary) { - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - reporter.stenographer.AnnounceSuccesfulMeasurement(specSummary, reporter.config.Succinct) - } else if specSummary.RunTime.Seconds() >= reporter.config.SlowSpecThreshold { - reporter.stenographer.AnnounceSuccesfulSlowSpec(specSummary, reporter.config.Succinct) - } else { - reporter.stenographer.AnnounceSuccesfulSpec(specSummary) - } - case types.SpecStatePending: - reporter.stenographer.AnnouncePendingSpec(specSummary, reporter.config.NoisyPendings && !reporter.config.Succinct) - case types.SpecStateSkipped: - reporter.stenographer.AnnounceSkippedSpec(specSummary, reporter.config.Succinct || !reporter.config.NoisySkippings, reporter.config.FullTrace) - case types.SpecStateTimedOut: - reporter.stenographer.AnnounceSpecTimedOut(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStatePanicked: - reporter.stenographer.AnnounceSpecPanicked(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStateFailed: - reporter.stenographer.AnnounceSpecFailed(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - } - - reporter.specSummaries = append(reporter.specSummaries, specSummary) -} - -func (reporter *DefaultReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.stenographer.SummarizeFailures(reporter.specSummaries) - reporter.stenographer.AnnounceSpecRunCompletion(summary, reporter.config.Succinct) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go deleted file mode 100644 index 27db4794..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go +++ /dev/null @@ -1,59 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//FakeReporter is useful for testing purposes -type FakeReporter struct { - Config config.GinkgoConfigType - - BeginSummary *types.SuiteSummary - BeforeSuiteSummary *types.SetupSummary - SpecWillRunSummaries []*types.SpecSummary - SpecSummaries []*types.SpecSummary - AfterSuiteSummary *types.SetupSummary - EndSummary *types.SuiteSummary - - SpecWillRunStub func(specSummary *types.SpecSummary) - SpecDidCompleteStub func(specSummary *types.SpecSummary) -} - -func NewFakeReporter() *FakeReporter { - return &FakeReporter{ - SpecWillRunSummaries: make([]*types.SpecSummary, 0), - SpecSummaries: make([]*types.SpecSummary, 0), - } -} - -func (fakeR *FakeReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - fakeR.Config = config - fakeR.BeginSummary = summary -} - -func (fakeR *FakeReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.BeforeSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecWillRun(specSummary *types.SpecSummary) { - if fakeR.SpecWillRunStub != nil { - fakeR.SpecWillRunStub(specSummary) - } - fakeR.SpecWillRunSummaries = append(fakeR.SpecWillRunSummaries, specSummary) -} - -func (fakeR *FakeReporter) SpecDidComplete(specSummary *types.SpecSummary) { - if fakeR.SpecDidCompleteStub != nil { - fakeR.SpecDidCompleteStub(specSummary) - } - fakeR.SpecSummaries = append(fakeR.SpecSummaries, specSummary) -} - -func (fakeR *FakeReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.AfterSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fakeR.EndSummary = summary -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go deleted file mode 100644 index 2c9f3c79..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go +++ /dev/null @@ -1,152 +0,0 @@ -/* - -JUnit XML Reporter for Ginkgo - -For usage instructions: http://onsi.github.io/ginkgo/#generating_junit_xml_output - -*/ - -package reporters - -import ( - "encoding/xml" - "fmt" - "math" - "os" - "strings" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -type JUnitTestSuite struct { - XMLName xml.Name `xml:"testsuite"` - TestCases []JUnitTestCase `xml:"testcase"` - Name string `xml:"name,attr"` - Tests int `xml:"tests,attr"` - Failures int `xml:"failures,attr"` - Errors int `xml:"errors,attr"` - Time float64 `xml:"time,attr"` -} - -type JUnitTestCase struct { - Name string `xml:"name,attr"` - ClassName string `xml:"classname,attr"` - FailureMessage *JUnitFailureMessage `xml:"failure,omitempty"` - Skipped *JUnitSkipped `xml:"skipped,omitempty"` - Time float64 `xml:"time,attr"` - SystemOut string `xml:"system-out,omitempty"` -} - -type JUnitFailureMessage struct { - Type string `xml:"type,attr"` - Message string `xml:",chardata"` -} - -type JUnitSkipped struct { - XMLName xml.Name `xml:"skipped"` -} - -type JUnitReporter struct { - suite JUnitTestSuite - filename string - testSuiteName string -} - -//NewJUnitReporter creates a new JUnit XML reporter. The XML will be stored in the passed in filename. -func NewJUnitReporter(filename string) *JUnitReporter { - return &JUnitReporter{ - filename: filename, - } -} - -func (reporter *JUnitReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.suite = JUnitTestSuite{ - Name: summary.SuiteDescription, - TestCases: []JUnitTestCase{}, - } - reporter.testSuiteName = summary.SuiteDescription -} - -func (reporter *JUnitReporter) SpecWillRun(specSummary *types.SpecSummary) { -} - -func (reporter *JUnitReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *JUnitReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func failureMessage(failure types.SpecFailure) string { - return fmt.Sprintf("%s\n%s\n%s", failure.ComponentCodeLocation.String(), failure.Message, failure.Location.String()) -} - -func (reporter *JUnitReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testCase := JUnitTestCase{ - Name: name, - ClassName: reporter.testSuiteName, - } - - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(setupSummary.State), - Message: failureMessage(setupSummary.Failure), - } - testCase.SystemOut = setupSummary.CapturedOutput - testCase.Time = setupSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) - } -} - -func (reporter *JUnitReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testCase := JUnitTestCase{ - Name: strings.Join(specSummary.ComponentTexts[1:], " "), - ClassName: reporter.testSuiteName, - } - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(specSummary.State), - Message: failureMessage(specSummary.Failure), - } - testCase.SystemOut = specSummary.CapturedOutput - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - testCase.Skipped = &JUnitSkipped{} - } - testCase.Time = specSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) -} - -func (reporter *JUnitReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.suite.Tests = summary.NumberOfSpecsThatWillBeRun - reporter.suite.Time = math.Trunc(summary.RunTime.Seconds()*1000) / 1000 - reporter.suite.Failures = summary.NumberOfFailedSpecs - reporter.suite.Errors = 0 - file, err := os.Create(reporter.filename) - if err != nil { - fmt.Printf("Failed to create JUnit report file: %s\n\t%s", reporter.filename, err.Error()) - } - defer file.Close() - file.WriteString(xml.Header) - encoder := xml.NewEncoder(file) - encoder.Indent(" ", " ") - err = encoder.Encode(reporter.suite) - if err != nil { - fmt.Printf("Failed to generate JUnit report\n\t%s", err.Error()) - } -} - -func (reporter *JUnitReporter) failureTypeForState(state types.SpecState) string { - switch state { - case types.SpecStateFailed: - return "Failure" - case types.SpecStateTimedOut: - return "Timeout" - case types.SpecStatePanicked: - return "Panic" - default: - return "" - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/reporter.go b/vendor/github.com/onsi/ginkgo/reporters/reporter.go deleted file mode 100644 index 348b9dfc..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/reporter.go +++ /dev/null @@ -1,15 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -type Reporter interface { - SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) - BeforeSuiteDidRun(setupSummary *types.SetupSummary) - SpecWillRun(specSummary *types.SpecSummary) - SpecDidComplete(specSummary *types.SpecSummary) - AfterSuiteDidRun(setupSummary *types.SetupSummary) - SpecSuiteDidEnd(summary *types.SuiteSummary) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go deleted file mode 100644 index 45b8f886..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go +++ /dev/null @@ -1,64 +0,0 @@ -package stenographer - -import ( - "fmt" - "strings" -) - -func (s *consoleStenographer) colorize(colorCode string, format string, args ...interface{}) string { - var out string - - if len(args) > 0 { - out = fmt.Sprintf(format, args...) - } else { - out = format - } - - if s.color { - return fmt.Sprintf("%s%s%s", colorCode, out, defaultStyle) - } else { - return out - } -} - -func (s *consoleStenographer) printBanner(text string, bannerCharacter string) { - fmt.Fprintln(s.w, text) - fmt.Fprintln(s.w, strings.Repeat(bannerCharacter, len(text))) -} - -func (s *consoleStenographer) printNewLine() { - fmt.Fprintln(s.w, "") -} - -func (s *consoleStenographer) printDelimiter() { - fmt.Fprintln(s.w, s.colorize(grayColor, "%s", strings.Repeat("-", 30))) -} - -func (s *consoleStenographer) print(indentation int, format string, args ...interface{}) { - fmt.Fprint(s.w, s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) println(indentation int, format string, args ...interface{}) { - fmt.Fprintln(s.w, s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) indent(indentation int, format string, args ...interface{}) string { - var text string - - if len(args) > 0 { - text = fmt.Sprintf(format, args...) - } else { - text = format - } - - stringArray := strings.Split(text, "\n") - padding := "" - if indentation >= 0 { - padding = strings.Repeat(" ", indentation) - } - for i, s := range stringArray { - stringArray[i] = fmt.Sprintf("%s%s", padding, s) - } - - return strings.Join(stringArray, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go deleted file mode 100644 index 98854e7d..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go +++ /dev/null @@ -1,142 +0,0 @@ -package stenographer - -import ( - "sync" - - "github.com/onsi/ginkgo/types" -) - -func NewFakeStenographerCall(method string, args ...interface{}) FakeStenographerCall { - return FakeStenographerCall{ - Method: method, - Args: args, - } -} - -type FakeStenographer struct { - calls []FakeStenographerCall - lock *sync.Mutex -} - -type FakeStenographerCall struct { - Method string - Args []interface{} -} - -func NewFakeStenographer() *FakeStenographer { - stenographer := &FakeStenographer{ - lock: &sync.Mutex{}, - } - stenographer.Reset() - return stenographer -} - -func (stenographer *FakeStenographer) Calls() []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - return stenographer.calls -} - -func (stenographer *FakeStenographer) Reset() { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = make([]FakeStenographerCall, 0) -} - -func (stenographer *FakeStenographer) CallsTo(method string) []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - results := make([]FakeStenographerCall, 0) - for _, call := range stenographer.calls { - if call.Method == method { - results = append(results, call) - } - } - - return results -} - -func (stenographer *FakeStenographer) registerCall(method string, args ...interface{}) { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = append(stenographer.calls, NewFakeStenographerCall(method, args...)) -} - -func (stenographer *FakeStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - stenographer.registerCall("AnnounceSuite", description, randomSeed, randomizingAll, succinct) -} - -func (stenographer *FakeStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - stenographer.registerCall("AnnounceAggregatedParallelRun", nodes, succinct) -} - -func (stenographer *FakeStenographer) AnnounceParallelRun(node int, nodes int, succinct bool) { - stenographer.registerCall("AnnounceParallelRun", node, nodes, succinct) -} - -func (stenographer *FakeStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - stenographer.registerCall("AnnounceNumberOfSpecs", specsToRun, total, succinct) -} - -func (stenographer *FakeStenographer) AnnounceTotalNumberOfSpecs(total int, succinct bool) { - stenographer.registerCall("AnnounceTotalNumberOfSpecs", total, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - stenographer.registerCall("AnnounceSpecRunCompletion", summary, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSpecWillRun", spec) -} - -func (stenographer *FakeStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceBeforeSuiteFailure", summary, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceAfterSuiteFailure", summary, succinct, fullTrace) -} -func (stenographer *FakeStenographer) AnnounceCapturedOutput(output string) { - stenographer.registerCall("AnnounceCapturedOutput", output) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSuccesfulSpec", spec) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulSlowSpec", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulMeasurement", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - stenographer.registerCall("AnnouncePendingSpec", spec, noisy) -} - -func (stenographer *FakeStenographer) AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSkippedSpec", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecTimedOut", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecPanicked", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecFailed", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - stenographer.registerCall("SummarizeFailures", summaries) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go deleted file mode 100644 index 601c74d6..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go +++ /dev/null @@ -1,572 +0,0 @@ -/* -The stenographer is used by Ginkgo's reporters to generate output. - -Move along, nothing to see here. -*/ - -package stenographer - -import ( - "fmt" - "io" - "runtime" - "strings" - - "github.com/onsi/ginkgo/types" -) - -const defaultStyle = "\x1b[0m" -const boldStyle = "\x1b[1m" -const redColor = "\x1b[91m" -const greenColor = "\x1b[32m" -const yellowColor = "\x1b[33m" -const cyanColor = "\x1b[36m" -const grayColor = "\x1b[90m" -const lightGrayColor = "\x1b[37m" - -type cursorStateType int - -const ( - cursorStateTop cursorStateType = iota - cursorStateStreaming - cursorStateMidBlock - cursorStateEndBlock -) - -type Stenographer interface { - AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) - AnnounceAggregatedParallelRun(nodes int, succinct bool) - AnnounceParallelRun(node int, nodes int, succinct bool) - AnnounceTotalNumberOfSpecs(total int, succinct bool) - AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) - AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) - - AnnounceSpecWillRun(spec *types.SpecSummary) - AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - - AnnounceCapturedOutput(output string) - - AnnounceSuccesfulSpec(spec *types.SpecSummary) - AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) - AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) - - AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) - AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) - - AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) - - SummarizeFailures(summaries []*types.SpecSummary) -} - -func New(color bool, enableFlakes bool, writer io.Writer) Stenographer { - denoter := "•" - if runtime.GOOS == "windows" { - denoter = "+" - } - return &consoleStenographer{ - color: color, - denoter: denoter, - cursorState: cursorStateTop, - enableFlakes: enableFlakes, - w: writer, - } -} - -type consoleStenographer struct { - color bool - denoter string - cursorState cursorStateType - enableFlakes bool - w io.Writer -} - -var alternatingColors = []string{defaultStyle, grayColor} - -func (s *consoleStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - if succinct { - s.print(0, "[%d] %s ", randomSeed, s.colorize(boldStyle, description)) - return - } - s.printBanner(fmt.Sprintf("Running Suite: %s", description), "=") - s.print(0, "Random Seed: %s", s.colorize(boldStyle, "%d", randomSeed)) - if randomizingAll { - s.print(0, " - Will randomize all specs") - } - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceParallelRun(node int, nodes int, succinct bool) { - if succinct { - s.print(0, "- node #%d ", node) - return - } - s.println(0, - "Parallel test node %s/%s.", - s.colorize(boldStyle, "%d", node), - s.colorize(boldStyle, "%d", nodes), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - if succinct { - s.print(0, "- %d nodes ", nodes) - return - } - s.println(0, - "Running in parallel across %s nodes", - s.colorize(boldStyle, "%d", nodes), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - if succinct { - s.print(0, "- %d/%d specs ", specsToRun, total) - s.stream() - return - } - s.println(0, - "Will run %s of %s specs", - s.colorize(boldStyle, "%d", specsToRun), - s.colorize(boldStyle, "%d", total), - ) - - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceTotalNumberOfSpecs(total int, succinct bool) { - if succinct { - s.print(0, "- %d specs ", total) - s.stream() - return - } - s.println(0, - "Will run %s specs", - s.colorize(boldStyle, "%d", total), - ) - - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - if succinct && summary.SuiteSucceeded { - s.print(0, " %s %s ", s.colorize(greenColor, "SUCCESS!"), summary.RunTime) - return - } - s.printNewLine() - color := greenColor - if !summary.SuiteSucceeded { - color = redColor - } - s.println(0, s.colorize(boldStyle+color, "Ran %d of %d Specs in %.3f seconds", summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, summary.RunTime.Seconds())) - - status := "" - if summary.SuiteSucceeded { - status = s.colorize(boldStyle+greenColor, "SUCCESS!") - } else { - status = s.colorize(boldStyle+redColor, "FAIL!") - } - - flakes := "" - if s.enableFlakes { - flakes = " | " + s.colorize(yellowColor+boldStyle, "%d Flaked", summary.NumberOfFlakedSpecs) - } - - s.print(0, - "%s -- %s | %s | %s | %s\n", - status, - s.colorize(greenColor+boldStyle, "%d Passed", summary.NumberOfPassedSpecs), - s.colorize(redColor+boldStyle, "%d Failed", summary.NumberOfFailedSpecs)+flakes, - s.colorize(yellowColor+boldStyle, "%d Pending", summary.NumberOfPendingSpecs), - s.colorize(cyanColor+boldStyle, "%d Skipped", summary.NumberOfSkippedSpecs), - ) -} - -func (s *consoleStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - s.startBlock() - for i, text := range spec.ComponentTexts[1 : len(spec.ComponentTexts)-1] { - s.print(0, s.colorize(alternatingColors[i%2], text)+" ") - } - - indentation := 0 - if len(spec.ComponentTexts) > 2 { - indentation = 1 - s.printNewLine() - } - index := len(spec.ComponentTexts) - 1 - s.print(indentation, s.colorize(boldStyle, spec.ComponentTexts[index])) - s.printNewLine() - s.print(indentation, s.colorize(lightGrayColor, spec.ComponentCodeLocations[index].String())) - s.printNewLine() - s.midBlock() -} - -func (s *consoleStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("BeforeSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("AfterSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) announceSetupFailure(name string, summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.startBlock() - var message string - switch summary.State { - case types.SpecStateFailed: - message = "Failure" - case types.SpecStatePanicked: - message = "Panic" - case types.SpecStateTimedOut: - message = "Timeout" - } - - s.println(0, s.colorize(redColor+boldStyle, "%s [%.3f seconds]", message, summary.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock([]string{name}, []types.CodeLocation{summary.CodeLocation}, summary.ComponentType, 0, summary.State, true) - - s.printNewLine() - s.printFailure(indentation, summary.State, summary.Failure, fullTrace) - - s.endBlock() -} - -func (s *consoleStenographer) AnnounceCapturedOutput(output string) { - if output == "" { - return - } - - s.startBlock() - s.println(0, output) - s.midBlock() -} - -func (s *consoleStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - s.print(0, s.colorize(greenColor, s.denoter)) - s.stream() -} - -func (s *consoleStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "%s [SLOW TEST:%.3f seconds]", s.denoter, spec.RunTime.Seconds()), - "", - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "%s [MEASUREMENT]", s.denoter), - s.measurementReport(spec, succinct), - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - if noisy { - s.printBlockWithMessage( - s.colorize(yellowColor, "P [PENDING]"), - "", - spec, - false, - ) - } else { - s.print(0, s.colorize(yellowColor, "P")) - s.stream() - } -} - -func (s *consoleStenographer) AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) { - // Skips at runtime will have a non-empty spec.Failure. All others should be succinct. - if succinct || spec.Failure == (types.SpecFailure{}) { - s.print(0, s.colorize(cyanColor, "S")) - s.stream() - } else { - s.startBlock() - s.println(0, s.colorize(cyanColor+boldStyle, "S [SKIPPING]%s [%.3f seconds]", s.failureContext(spec.Failure.ComponentType), spec.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, spec.Failure.ComponentType, spec.Failure.ComponentIndex, spec.State, succinct) - - s.printNewLine() - s.printSkip(indentation, spec.Failure) - s.endBlock() - } -} - -func (s *consoleStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s... Timeout", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s! Panic", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s Failure", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - failingSpecs := []*types.SpecSummary{} - - for _, summary := range summaries { - if summary.HasFailureState() { - failingSpecs = append(failingSpecs, summary) - } - } - - if len(failingSpecs) == 0 { - return - } - - s.printNewLine() - s.printNewLine() - plural := "s" - if len(failingSpecs) == 1 { - plural = "" - } - s.println(0, s.colorize(redColor+boldStyle, "Summarizing %d Failure%s:", len(failingSpecs), plural)) - for _, summary := range failingSpecs { - s.printNewLine() - if summary.HasFailureState() { - if summary.TimedOut() { - s.print(0, s.colorize(redColor+boldStyle, "[Timeout...] ")) - } else if summary.Panicked() { - s.print(0, s.colorize(redColor+boldStyle, "[Panic!] ")) - } else if summary.Failed() { - s.print(0, s.colorize(redColor+boldStyle, "[Fail] ")) - } - s.printSpecContext(summary.ComponentTexts, summary.ComponentCodeLocations, summary.Failure.ComponentType, summary.Failure.ComponentIndex, summary.State, true) - s.printNewLine() - s.println(0, s.colorize(lightGrayColor, summary.Failure.Location.String())) - } - } -} - -func (s *consoleStenographer) startBlock() { - if s.cursorState == cursorStateStreaming { - s.printNewLine() - s.printDelimiter() - } else if s.cursorState == cursorStateMidBlock { - s.printNewLine() - } -} - -func (s *consoleStenographer) midBlock() { - s.cursorState = cursorStateMidBlock -} - -func (s *consoleStenographer) endBlock() { - s.printDelimiter() - s.cursorState = cursorStateEndBlock -} - -func (s *consoleStenographer) stream() { - s.cursorState = cursorStateStreaming -} - -func (s *consoleStenographer) printBlockWithMessage(header string, message string, spec *types.SpecSummary, succinct bool) { - s.startBlock() - s.println(0, header) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, types.SpecComponentTypeInvalid, 0, spec.State, succinct) - - if message != "" { - s.printNewLine() - s.println(indentation, message) - } - - s.endBlock() -} - -func (s *consoleStenographer) printSpecFailure(message string, spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.startBlock() - s.println(0, s.colorize(redColor+boldStyle, "%s%s [%.3f seconds]", message, s.failureContext(spec.Failure.ComponentType), spec.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, spec.Failure.ComponentType, spec.Failure.ComponentIndex, spec.State, succinct) - - s.printNewLine() - s.printFailure(indentation, spec.State, spec.Failure, fullTrace) - s.endBlock() -} - -func (s *consoleStenographer) failureContext(failedComponentType types.SpecComponentType) string { - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - return " in Suite Setup (BeforeSuite)" - case types.SpecComponentTypeAfterSuite: - return " in Suite Teardown (AfterSuite)" - case types.SpecComponentTypeBeforeEach: - return " in Spec Setup (BeforeEach)" - case types.SpecComponentTypeJustBeforeEach: - return " in Spec Setup (JustBeforeEach)" - case types.SpecComponentTypeAfterEach: - return " in Spec Teardown (AfterEach)" - } - - return "" -} - -func (s *consoleStenographer) printSkip(indentation int, spec types.SpecFailure) { - s.println(indentation, s.colorize(cyanColor, spec.Message)) - s.printNewLine() - s.println(indentation, spec.Location.String()) -} - -func (s *consoleStenographer) printFailure(indentation int, state types.SpecState, failure types.SpecFailure, fullTrace bool) { - if state == types.SpecStatePanicked { - s.println(indentation, s.colorize(redColor+boldStyle, failure.Message)) - s.println(indentation, s.colorize(redColor, failure.ForwardedPanic)) - s.println(indentation, failure.Location.String()) - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } else { - s.println(indentation, s.colorize(redColor, failure.Message)) - s.printNewLine() - s.println(indentation, failure.Location.String()) - if fullTrace { - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } - } -} - -func (s *consoleStenographer) printSpecContext(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, state types.SpecState, succinct bool) int { - startIndex := 1 - indentation := 0 - - if len(componentTexts) == 1 { - startIndex = 0 - } - - for i := startIndex; i < len(componentTexts); i++ { - if (state.IsFailure() || state == types.SpecStateSkipped) && i == failedComponentIndex { - color := redColor - if state == types.SpecStateSkipped { - color = cyanColor - } - blockType := "" - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - blockType = "BeforeSuite" - case types.SpecComponentTypeAfterSuite: - blockType = "AfterSuite" - case types.SpecComponentTypeBeforeEach: - blockType = "BeforeEach" - case types.SpecComponentTypeJustBeforeEach: - blockType = "JustBeforeEach" - case types.SpecComponentTypeAfterEach: - blockType = "AfterEach" - case types.SpecComponentTypeIt: - blockType = "It" - case types.SpecComponentTypeMeasure: - blockType = "Measurement" - } - if succinct { - s.print(0, s.colorize(color+boldStyle, "[%s] %s ", blockType, componentTexts[i])) - } else { - s.println(indentation, s.colorize(color+boldStyle, "%s [%s]", componentTexts[i], blockType)) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } else { - if succinct { - s.print(0, s.colorize(alternatingColors[i%2], "%s ", componentTexts[i])) - } else { - s.println(indentation, componentTexts[i]) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } - indentation++ - } - - return indentation -} - -func (s *consoleStenographer) printCodeLocationBlock(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, state types.SpecState, succinct bool) int { - indentation := s.printSpecContext(componentTexts, componentCodeLocations, failedComponentType, failedComponentIndex, state, succinct) - - if succinct { - if len(componentTexts) > 0 { - s.printNewLine() - s.print(0, s.colorize(lightGrayColor, "%s", componentCodeLocations[len(componentCodeLocations)-1])) - } - s.printNewLine() - indentation = 1 - } else { - indentation-- - } - - return indentation -} - -func (s *consoleStenographer) orderedMeasurementKeys(measurements map[string]*types.SpecMeasurement) []string { - orderedKeys := make([]string, len(measurements)) - for key, measurement := range measurements { - orderedKeys[measurement.Order] = key - } - return orderedKeys -} - -func (s *consoleStenographer) measurementReport(spec *types.SpecSummary, succinct bool) string { - if len(spec.Measurements) == 0 { - return "Found no measurements" - } - - message := []string{} - orderedKeys := s.orderedMeasurementKeys(spec.Measurements) - - if succinct { - message = append(message, fmt.Sprintf("%s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - message = append(message, fmt.Sprintf(" %s - %s: %s%s, %s: %s%s ± %s%s, %s: %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - measurement.SmallestLabel, - s.colorize(greenColor, measurement.PrecisionFmt(), measurement.Smallest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.Average), - measurement.Units, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.StdDeviation), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, measurement.PrecisionFmt(), measurement.Largest), - measurement.Units, - )) - } - } else { - message = append(message, fmt.Sprintf("Ran %s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - info := "" - if measurement.Info != nil { - message = append(message, fmt.Sprintf("%v", measurement.Info)) - } - - message = append(message, fmt.Sprintf("%s:\n%s %s: %s%s\n %s: %s%s\n %s: %s%s ± %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - info, - measurement.SmallestLabel, - s.colorize(greenColor, measurement.PrecisionFmt(), measurement.Smallest), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, measurement.PrecisionFmt(), measurement.Largest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.Average), - measurement.Units, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.StdDeviation), - measurement.Units, - )) - } - } - - return strings.Join(message, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE deleted file mode 100644 index 91b5cef3..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Yasuhiro Matsumoto - -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/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md deleted file mode 100644 index e84226a7..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# go-colorable - -Colorable writer for windows. - -For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) -This package is possible to handle escape sequence for ansi color on windows. - -## Too Bad! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) - - -## So Good! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) - -## Usage - -```go -logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) -logrus.SetOutput(colorable.NewColorableStdout()) - -logrus.Info("succeeded") -logrus.Warn("not correct") -logrus.Error("something error") -logrus.Fatal("panic") -``` - -You can compile above code on non-windows OSs. - -## Installation - -``` -$ go get github.com/mattn/go-colorable -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go deleted file mode 100644 index 52d6653b..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build !windows - -package colorable - -import ( - "io" - "os" -) - -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -func NewColorableStdout() io.Writer { - return os.Stdout -} - -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go deleted file mode 100644 index 10880092..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go +++ /dev/null @@ -1,783 +0,0 @@ -package colorable - -import ( - "bytes" - "fmt" - "io" - "math" - "os" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 - -type coord struct { - x short - y short -} - -type smallRect struct { - left short - top short - right short - bottom short -} - -type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect - maximumWindowSize coord -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") -) - -type Writer struct { - out io.Writer - handle syscall.Handle - lastbuf bytes.Buffer - oldattr word -} - -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - if isatty.IsTerminal(file.Fd()) { - var csbi consoleScreenBufferInfo - handle := syscall.Handle(file.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: file, handle: handle, oldattr: csbi.attributes} - } else { - return file - } -} - -func NewColorableStdout() io.Writer { - return NewColorable(os.Stdout) -} - -func NewColorableStderr() io.Writer { - return NewColorable(os.Stderr) -} - -var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, - 100: 0x878700, - 101: 0x87875f, - 102: 0x878787, - 103: 0x8787af, - 104: 0x8787d7, - 105: 0x8787ff, - 106: 0x87af00, - 107: 0x87af5f, - 108: 0x87af87, - 109: 0x87afaf, - 110: 0x87afd7, - 111: 0x87afff, - 112: 0x87d700, - 113: 0x87d75f, - 114: 0x87d787, - 115: 0x87d7af, - 116: 0x87d7d7, - 117: 0x87d7ff, - 118: 0x87ff00, - 119: 0x87ff5f, - 120: 0x87ff87, - 121: 0x87ffaf, - 122: 0x87ffd7, - 123: 0x87ffff, - 124: 0xaf0000, - 125: 0xaf005f, - 126: 0xaf0087, - 127: 0xaf00af, - 128: 0xaf00d7, - 129: 0xaf00ff, - 130: 0xaf5f00, - 131: 0xaf5f5f, - 132: 0xaf5f87, - 133: 0xaf5faf, - 134: 0xaf5fd7, - 135: 0xaf5fff, - 136: 0xaf8700, - 137: 0xaf875f, - 138: 0xaf8787, - 139: 0xaf87af, - 140: 0xaf87d7, - 141: 0xaf87ff, - 142: 0xafaf00, - 143: 0xafaf5f, - 144: 0xafaf87, - 145: 0xafafaf, - 146: 0xafafd7, - 147: 0xafafff, - 148: 0xafd700, - 149: 0xafd75f, - 150: 0xafd787, - 151: 0xafd7af, - 152: 0xafd7d7, - 153: 0xafd7ff, - 154: 0xafff00, - 155: 0xafff5f, - 156: 0xafff87, - 157: 0xafffaf, - 158: 0xafffd7, - 159: 0xafffff, - 160: 0xd70000, - 161: 0xd7005f, - 162: 0xd70087, - 163: 0xd700af, - 164: 0xd700d7, - 165: 0xd700ff, - 166: 0xd75f00, - 167: 0xd75f5f, - 168: 0xd75f87, - 169: 0xd75faf, - 170: 0xd75fd7, - 171: 0xd75fff, - 172: 0xd78700, - 173: 0xd7875f, - 174: 0xd78787, - 175: 0xd787af, - 176: 0xd787d7, - 177: 0xd787ff, - 178: 0xd7af00, - 179: 0xd7af5f, - 180: 0xd7af87, - 181: 0xd7afaf, - 182: 0xd7afd7, - 183: 0xd7afff, - 184: 0xd7d700, - 185: 0xd7d75f, - 186: 0xd7d787, - 187: 0xd7d7af, - 188: 0xd7d7d7, - 189: 0xd7d7ff, - 190: 0xd7ff00, - 191: 0xd7ff5f, - 192: 0xd7ff87, - 193: 0xd7ffaf, - 194: 0xd7ffd7, - 195: 0xd7ffff, - 196: 0xff0000, - 197: 0xff005f, - 198: 0xff0087, - 199: 0xff00af, - 200: 0xff00d7, - 201: 0xff00ff, - 202: 0xff5f00, - 203: 0xff5f5f, - 204: 0xff5f87, - 205: 0xff5faf, - 206: 0xff5fd7, - 207: 0xff5fff, - 208: 0xff8700, - 209: 0xff875f, - 210: 0xff8787, - 211: 0xff87af, - 212: 0xff87d7, - 213: 0xff87ff, - 214: 0xffaf00, - 215: 0xffaf5f, - 216: 0xffaf87, - 217: 0xffafaf, - 218: 0xffafd7, - 219: 0xffafff, - 220: 0xffd700, - 221: 0xffd75f, - 222: 0xffd787, - 223: 0xffd7af, - 224: 0xffd7d7, - 225: 0xffd7ff, - 226: 0xffff00, - 227: 0xffff5f, - 228: 0xffff87, - 229: 0xffffaf, - 230: 0xffffd7, - 231: 0xffffff, - 232: 0x080808, - 233: 0x121212, - 234: 0x1c1c1c, - 235: 0x262626, - 236: 0x303030, - 237: 0x3a3a3a, - 238: 0x444444, - 239: 0x4e4e4e, - 240: 0x585858, - 241: 0x626262, - 242: 0x6c6c6c, - 243: 0x767676, - 244: 0x808080, - 245: 0x8a8a8a, - 246: 0x949494, - 247: 0x9e9e9e, - 248: 0xa8a8a8, - 249: 0xb2b2b2, - 250: 0xbcbcbc, - 251: 0xc6c6c6, - 252: 0xd0d0d0, - 253: 0xdadada, - 254: 0xe4e4e4, - 255: 0xeeeeee, -} - -func (w *Writer) Write(data []byte) (n int, err error) { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - - er := bytes.NewBuffer(data) -loop: - for { - r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - if r1 == 0 { - break loop - } - - c1, _, err := er.ReadRune() - if err != nil { - break loop - } - if c1 != 0x1b { - fmt.Fprint(w.out, string(c1)) - continue - } - c2, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - break loop - } - if c2 != 0x5b { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - continue - } - - var buf bytes.Buffer - var m rune - for { - c, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - w.lastbuf.Write(buf.Bytes()) - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - m = c - break - } - buf.Write([]byte(string(c))) - } - - var csbi consoleScreenBufferInfo - switch m { - case 'A': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'B': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'C': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'D': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - if n, err = strconv.Atoi(buf.String()); err == nil { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - } - case 'E': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'F': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'G': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'H': - token := strings.Split(buf.String(), ";") - if len(token) != 2 { - continue - } - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - n2, err := strconv.Atoi(token[1]) - if err != nil { - continue - } - csbi.cursorPosition.x = short(n2) - csbi.cursorPosition.x = short(n1) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'J': - n, err := strconv.Atoi(buf.String()) - if err != nil { - continue - } - var cursor coord - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - } - var count, written dword - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'K': - n, err := strconv.Atoi(buf.String()) - if err != nil { - continue - } - var cursor coord - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - } - var count, written dword - count = dword(csbi.size.x - csbi.cursorPosition.x) - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'm': - attr := csbi.attributes - cs := buf.String() - if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) - continue - } - token := strings.Split(cs, ";") - for i := 0; i < len(token); i += 1 { - ns := token[i] - if n, err = strconv.Atoi(ns); err == nil { - switch { - case n == 0 || n == 100: - attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 22 == n || n == 25 || n == 25: - attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 30 <= n && n <= 37: - attr = (attr & backgroundMask) - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case n == 38: // set foreground color. - if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256foreAttr == nil { - n256setup() - } - attr &= backgroundMask - attr |= n256foreAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & backgroundMask) - } - case n == 39: // reset foreground color. - attr &= backgroundMask - attr |= w.oldattr & foregroundMask - case 40 <= n && n <= 47: - attr = (attr & foregroundMask) - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case n == 48: // set background color. - if i < len(token)-2 && token[i+1] == "5" { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256backAttr == nil { - n256setup() - } - attr &= foregroundMask - attr |= n256backAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & foregroundMask) - } - case n == 49: // reset foreground color. - attr &= foregroundMask - attr |= w.oldattr & backgroundMask - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) - } - } - } - } - return len(data) - w.lastbuf.Len(), nil -} - -type consoleColor struct { - rgb int - red bool - green bool - blue bool - intensity bool -} - -func (c consoleColor) foregroundAttr() (attr word) { - if c.red { - attr |= foregroundRed - } - if c.green { - attr |= foregroundGreen - } - if c.blue { - attr |= foregroundBlue - } - if c.intensity { - attr |= foregroundIntensity - } - return -} - -func (c consoleColor) backgroundAttr() (attr word) { - if c.red { - attr |= backgroundRed - } - if c.green { - attr |= backgroundGreen - } - if c.blue { - attr |= backgroundBlue - } - if c.intensity { - attr |= backgroundIntensity - } - return -} - -var color16 = []consoleColor{ - consoleColor{0x000000, false, false, false, false}, - consoleColor{0x000080, false, false, true, false}, - consoleColor{0x008000, false, true, false, false}, - consoleColor{0x008080, false, true, true, false}, - consoleColor{0x800000, true, false, false, false}, - consoleColor{0x800080, true, false, true, false}, - consoleColor{0x808000, true, true, false, false}, - consoleColor{0xc0c0c0, true, true, true, false}, - consoleColor{0x808080, false, false, false, true}, - consoleColor{0x0000ff, false, false, true, true}, - consoleColor{0x00ff00, false, true, false, true}, - consoleColor{0x00ffff, false, true, true, true}, - consoleColor{0xff0000, true, false, false, true}, - consoleColor{0xff00ff, true, false, true, true}, - consoleColor{0xffff00, true, true, false, true}, - consoleColor{0xffffff, true, true, true, true}, -} - -type hsv struct { - h, s, v float32 -} - -func (a hsv) dist(b hsv) float32 { - dh := a.h - b.h - switch { - case dh > 0.5: - dh = 1 - dh - case dh < -0.5: - dh = -1 - dh - } - ds := a.s - b.s - dv := a.v - b.v - return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) -} - -func toHSV(rgb int) hsv { - r, g, b := float32((rgb&0xFF0000)>>16)/256.0, - float32((rgb&0x00FF00)>>8)/256.0, - float32(rgb&0x0000FF)/256.0 - min, max := minmax3f(r, g, b) - h := max - min - if h > 0 { - if max == r { - h = (g - b) / h - if h < 0 { - h += 6 - } - } else if max == g { - h = 2 + (b-r)/h - } else { - h = 4 + (r-g)/h - } - } - h /= 6.0 - s := max - min - if max != 0 { - s /= max - } - v := max - return hsv{h: h, s: s, v: v} -} - -type hsvTable []hsv - -func toHSVTable(rgbTable []consoleColor) hsvTable { - t := make(hsvTable, len(rgbTable)) - for i, c := range rgbTable { - t[i] = toHSV(c.rgb) - } - return t -} - -func (t hsvTable) find(rgb int) consoleColor { - hsv := toHSV(rgb) - n := 7 - l := float32(5.0) - for i, p := range t { - d := hsv.dist(p) - if d < l { - l, n = d, i - } - } - return color16[n] -} - -func minmax3f(a, b, c float32) (min, max float32) { - if a < b { - if b < c { - return a, c - } else if a < c { - return a, b - } else { - return c, b - } - } else { - if a < c { - return b, c - } else if b < c { - return b, a - } else { - return c, a - } - } -} - -var n256foreAttr []word -var n256backAttr []word - -func n256setup() { - n256foreAttr = make([]word, 256) - n256backAttr = make([]word, 256) - t := toHSVTable(color16) - for i, rgb := range color256 { - c := t.find(rgb) - n256foreAttr[i] = c.foregroundAttr() - n256backAttr[i] = c.backgroundAttr() - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go deleted file mode 100644 index fb976dbd..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go +++ /dev/null @@ -1,57 +0,0 @@ -package colorable - -import ( - "bytes" - "fmt" - "io" -) - -type NonColorable struct { - out io.Writer - lastbuf bytes.Buffer -} - -func NewNonColorable(w io.Writer) io.Writer { - return &NonColorable{out: w} -} - -func (w *NonColorable) Write(data []byte) (n int, err error) { - er := bytes.NewBuffer(data) -loop: - for { - c1, _, err := er.ReadRune() - if err != nil { - break loop - } - if c1 != 0x1b { - fmt.Fprint(w.out, string(c1)) - continue - } - c2, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - break loop - } - if c2 != 0x5b { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - continue - } - - var buf bytes.Buffer - for { - c, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - w.lastbuf.Write(buf.Bytes()) - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - buf.Write([]byte(string(c))) - } - } - return len(data) - w.lastbuf.Len(), nil -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE deleted file mode 100644 index 65dc692b..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -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/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md deleted file mode 100644 index 74845de4..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# go-isatty - -isatty for golang - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/mattn/go-isatty" - "os" -) - -func main() { - if isatty.IsTerminal(os.Stdout.Fd()) { - fmt.Println("Is Terminal") - } else { - fmt.Println("Is Not Terminal") - } -} -``` - -## Installation - -``` -$ go get github.com/mattn/go-isatty -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go deleted file mode 100644 index 17d4f90e..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go deleted file mode 100644 index 83c58877..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build appengine - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on on appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go deleted file mode 100644 index 98ffe86a..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build darwin freebsd openbsd netbsd -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go deleted file mode 100644 index 9d24bac1..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go deleted file mode 100644 index 1f0c6bf5..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build solaris -// +build !appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func IsTerminal(fd uintptr) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) - return err == nil -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go deleted file mode 100644 index 83c398b1..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build windows -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -var kernel32 = syscall.NewLazyDLL("kernel32.dll") -var procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go deleted file mode 100644 index 36ee2a60..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - -TeamCity Reporter for Ginkgo - -Makes use of TeamCity's support for Service Messages -http://confluence.jetbrains.com/display/TCD7/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ReportingTests -*/ - -package reporters - -import ( - "fmt" - "io" - "strings" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -const ( - messageId = "##teamcity" -) - -type TeamCityReporter struct { - writer io.Writer - testSuiteName string -} - -func NewTeamCityReporter(writer io.Writer) *TeamCityReporter { - return &TeamCityReporter{ - writer: writer, - } -} - -func (reporter *TeamCityReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.testSuiteName = escape(summary.SuiteDescription) - fmt.Fprintf(reporter.writer, "%s[testSuiteStarted name='%s']", messageId, reporter.testSuiteName) -} - -func (reporter *TeamCityReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *TeamCityReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func (reporter *TeamCityReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testName := escape(name) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) - message := escape(setupSummary.Failure.ComponentCodeLocation.String()) - details := escape(setupSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - durationInMilliseconds := setupSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) - } -} - -func (reporter *TeamCityReporter) SpecWillRun(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) -} - -func (reporter *TeamCityReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - message := escape(specSummary.Failure.ComponentCodeLocation.String()) - details := escape(specSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - fmt.Fprintf(reporter.writer, "%s[testIgnored name='%s']", messageId, testName) - } - - durationInMilliseconds := specSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) -} - -func (reporter *TeamCityReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fmt.Fprintf(reporter.writer, "%s[testSuiteFinished name='%s']", messageId, reporter.testSuiteName) -} - -func escape(output string) string { - output = strings.Replace(output, "|", "||", -1) - output = strings.Replace(output, "'", "|'", -1) - output = strings.Replace(output, "\n", "|n", -1) - output = strings.Replace(output, "\r", "|r", -1) - output = strings.Replace(output, "[", "|[", -1) - output = strings.Replace(output, "]", "|]", -1) - return output -} diff --git a/vendor/github.com/onsi/ginkgo/types/code_location.go b/vendor/github.com/onsi/ginkgo/types/code_location.go deleted file mode 100644 index 935a89e1..00000000 --- a/vendor/github.com/onsi/ginkgo/types/code_location.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -import ( - "fmt" -) - -type CodeLocation struct { - FileName string - LineNumber int - FullStackTrace string -} - -func (codeLocation CodeLocation) String() string { - return fmt.Sprintf("%s:%d", codeLocation.FileName, codeLocation.LineNumber) -} diff --git a/vendor/github.com/onsi/ginkgo/types/synchronization.go b/vendor/github.com/onsi/ginkgo/types/synchronization.go deleted file mode 100644 index fdd6ed5b..00000000 --- a/vendor/github.com/onsi/ginkgo/types/synchronization.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import ( - "encoding/json" -) - -type RemoteBeforeSuiteState int - -const ( - RemoteBeforeSuiteStateInvalid RemoteBeforeSuiteState = iota - - RemoteBeforeSuiteStatePending - RemoteBeforeSuiteStatePassed - RemoteBeforeSuiteStateFailed - RemoteBeforeSuiteStateDisappeared -) - -type RemoteBeforeSuiteData struct { - Data []byte - State RemoteBeforeSuiteState -} - -func (r RemoteBeforeSuiteData) ToJSON() []byte { - data, _ := json.Marshal(r) - return data -} - -type RemoteAfterSuiteData struct { - CanRun bool -} diff --git a/vendor/github.com/onsi/ginkgo/types/types.go b/vendor/github.com/onsi/ginkgo/types/types.go deleted file mode 100644 index 0e89521b..00000000 --- a/vendor/github.com/onsi/ginkgo/types/types.go +++ /dev/null @@ -1,174 +0,0 @@ -package types - -import ( - "strconv" - "time" -) - -const GINKGO_FOCUS_EXIT_CODE = 197 - -/* -SuiteSummary represents the a summary of the test suite and is passed to both -Reporter.SpecSuiteWillBegin -Reporter.SpecSuiteDidEnd - -this is unfortunate as these two methods should receive different objects. When running in parallel -each node does not deterministically know how many specs it will end up running. - -Unfortunately making such a change would break backward compatibility. - -Until Ginkgo 2.0 comes out we will continue to reuse this struct but populate unkown fields -with -1. -*/ -type SuiteSummary struct { - SuiteDescription string - SuiteSucceeded bool - SuiteID string - - NumberOfSpecsBeforeParallelization int - NumberOfTotalSpecs int - NumberOfSpecsThatWillBeRun int - NumberOfPendingSpecs int - NumberOfSkippedSpecs int - NumberOfPassedSpecs int - NumberOfFailedSpecs int - // Flaked specs are those that failed initially, but then passed on a - // subsequent try. - NumberOfFlakedSpecs int - RunTime time.Duration -} - -type SpecSummary struct { - ComponentTexts []string - ComponentCodeLocations []CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - IsMeasurement bool - NumberOfSamples int - Measurements map[string]*SpecMeasurement - - CapturedOutput string - SuiteID string -} - -func (s SpecSummary) HasFailureState() bool { - return s.State.IsFailure() -} - -func (s SpecSummary) TimedOut() bool { - return s.State == SpecStateTimedOut -} - -func (s SpecSummary) Panicked() bool { - return s.State == SpecStatePanicked -} - -func (s SpecSummary) Failed() bool { - return s.State == SpecStateFailed -} - -func (s SpecSummary) Passed() bool { - return s.State == SpecStatePassed -} - -func (s SpecSummary) Skipped() bool { - return s.State == SpecStateSkipped -} - -func (s SpecSummary) Pending() bool { - return s.State == SpecStatePending -} - -type SetupSummary struct { - ComponentType SpecComponentType - CodeLocation CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - - CapturedOutput string - SuiteID string -} - -type SpecFailure struct { - Message string - Location CodeLocation - ForwardedPanic string - - ComponentIndex int - ComponentType SpecComponentType - ComponentCodeLocation CodeLocation -} - -type SpecMeasurement struct { - Name string - Info interface{} - Order int - - Results []float64 - - Smallest float64 - Largest float64 - Average float64 - StdDeviation float64 - - SmallestLabel string - LargestLabel string - AverageLabel string - Units string - Precision int -} - -func (s SpecMeasurement) PrecisionFmt() string { - if s.Precision == 0 { - return "%f" - } - - str := strconv.Itoa(s.Precision) - - return "%." + str + "f" -} - -type SpecState uint - -const ( - SpecStateInvalid SpecState = iota - - SpecStatePending - SpecStateSkipped - SpecStatePassed - SpecStateFailed - SpecStatePanicked - SpecStateTimedOut -) - -func (state SpecState) IsFailure() bool { - return state == SpecStateTimedOut || state == SpecStatePanicked || state == SpecStateFailed -} - -type SpecComponentType uint - -const ( - SpecComponentTypeInvalid SpecComponentType = iota - - SpecComponentTypeContainer - SpecComponentTypeBeforeSuite - SpecComponentTypeAfterSuite - SpecComponentTypeBeforeEach - SpecComponentTypeJustBeforeEach - SpecComponentTypeJustAfterEach - SpecComponentTypeAfterEach - SpecComponentTypeIt - SpecComponentTypeMeasure -) - -type FlagType uint - -const ( - FlagTypeNone FlagType = iota - FlagTypeFocused - FlagTypePending -) diff --git a/vendor/github.com/onsi/gomega/.gitignore b/vendor/github.com/onsi/gomega/.gitignore deleted file mode 100644 index 720c13cb..00000000 --- a/vendor/github.com/onsi/gomega/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.DS_Store -*.test -. -.idea -gomega.iml diff --git a/vendor/github.com/onsi/gomega/.travis.yml b/vendor/github.com/onsi/gomega/.travis.yml deleted file mode 100644 index 4d71367f..00000000 --- a/vendor/github.com/onsi/gomega/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go - -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - -env: - - GO111MODULE=on - -install: - - go get -v ./... - - go build ./... - - go get github.com/onsi/ginkgo - - go install github.com/onsi/ginkgo/ginkgo - -script: | - $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && - go vet && - [ -z "`gofmt -l -e -s -w .`" ] diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md deleted file mode 100644 index 9153294f..00000000 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ /dev/null @@ -1,125 +0,0 @@ -## 1.4.3 - -### Fixes: - -- ensure file name and line numbers are correctly reported for XUnit [6fff58f] -- Fixed matcher for content-type (#305) [69d9b43] - -## 1.4.2 - -### Fixes: - -- Add go.mod and go.sum files to define the gomega go module [f3de367, a085d30] -- Work around go vet issue with Go v1.11 (#300) [40dd6ad] -- Better output when using with go XUnit-style tests, fixes #255 (#297) [29a4b97] -- Fix MatchJSON fail to parse json.RawMessage (#298) [ae19f1b] -- show threshold in failure message of BeNumericallyMatcher (#293) [4bbecc8] - -## 1.4.1 - -### Fixes: - -- Update documentation formatting and examples (#289) [9be8410] -- allow 'Receive' matcher to be used with concrete types (#286) [41673fd] -- Fix data race in ghttp server (#283) [7ac6b01] -- Travis badge should only show master [cc102ab] - -## 1.4.0 - -### Features -- Make string pretty diff user configurable (#273) [eb112ce, 649b44d] - -### Fixes -- Use httputil.DumpRequest to pretty-print unhandled requests (#278) [a4ff0fc, b7d1a52] -- fix typo floa32 > float32 (#272) [041ae3b, 6e33911] -- Fix link to documentation on adding your own matchers (#270) [bb2c830, fcebc62] -- Use setters and getters to avoid race condition (#262) [13057c3, a9c79f1] -- Avoid sending a signal if the process is not alive (#259) [b8043e5, 4fc1762] -- Improve message from AssignableToTypeOf when expected value is nil (#281) [9c1fb20] - -## 1.3.0 - -Improvements: - -- The `Equal` matcher matches byte slices more performantly. -- Improved how `MatchError` matches error strings. -- `MatchXML` ignores the order of xml node attributes. -- Improve support for XUnit style golang tests. ([#254](https://github.com/onsi/gomega/issues/254)) - -Bug Fixes: - -- Diff generation now handles multi-byte sequences correctly. -- Multiple goroutines can now call `gexec.Build` concurrently. - -## 1.2.0 - -Improvements: - -- Added `BeSent` which attempts to send a value down a channel and fails if the attempt blocks. Can be paired with `Eventually` to safely send a value down a channel with a timeout. -- `Ω`, `Expect`, `Eventually`, and `Consistently` now immediately `panic` if there is no registered fail handler. This is always a mistake that can hide failing tests. -- `Receive()` no longer errors when passed a closed channel, it's perfectly fine to attempt to read from a closed channel so Ω(c).Should(Receive()) always fails and Ω(c).ShoudlNot(Receive()) always passes with a closed channel. -- Added `HavePrefix` and `HaveSuffix` matchers. -- `ghttp` can now handle concurrent requests. -- Added `Succeed` which allows one to write `Ω(MyFunction()).Should(Succeed())`. -- Improved `ghttp`'s behavior around failing assertions and panics: - - If a registered handler makes a failing assertion `ghttp` will return `500`. - - If a registered handler panics, `ghttp` will return `500` *and* fail the test. This is new behavior that may cause existing code to break. This code is almost certainly incorrect and creating a false positive. -- `ghttp` servers can take an `io.Writer`. `ghttp` will write a line to the writer when each request arrives. -- Added `WithTransform` matcher to allow munging input data before feeding into the relevant matcher -- Added boolean `And`, `Or`, and `Not` matchers to allow creating composite matchers -- Added `gbytes.TimeoutCloser`, `gbytes.TimeoutReader`, and `gbytes.TimeoutWriter` - these are convenience wrappers that timeout if the underlying Closer/Reader/Writer does not return within the alloted time. -- Added `gbytes.BufferReader` - this constructs a `gbytes.Buffer` that asynchronously reads the passed-in `io.Reader` into its buffer. - -Bug Fixes: -- gexec: `session.Wait` now uses `EventuallyWithOffset` to get the right line number in the failure. -- `ContainElement` no longer bails if a passed-in matcher errors. - -## 1.0 (8/2/2014) - -No changes. Dropping "beta" from the version number. - -## 1.0.0-beta (7/8/2014) -Breaking Changes: - -- Changed OmegaMatcher interface. Instead of having `Match` return failure messages, two new methods `FailureMessage` and `NegatedFailureMessage` are called instead. -- Moved and renamed OmegaFailHandler to types.GomegaFailHandler and OmegaMatcher to types.GomegaMatcher. Any references to OmegaMatcher in any custom matchers will need to be changed to point to types.GomegaMatcher - -New Test-Support Features: - -- `ghttp`: supports testing http clients - - Provides a flexible fake http server - - Provides a collection of chainable http handlers that perform assertions. -- `gbytes`: supports making ordered assertions against streams of data - - Provides a `gbytes.Buffer` - - Provides a `Say` matcher to perform ordered assertions against output data -- `gexec`: supports testing external processes - - Provides support for building Go binaries - - Wraps and starts `exec.Cmd` commands - - Makes it easy to assert against stdout and stderr - - Makes it easy to send signals and wait for processes to exit - - Provides an `Exit` matcher to assert against exit code. - -DSL Changes: - -- `Eventually` and `Consistently` can accept `time.Duration` interval and polling inputs. -- The default timeouts for `Eventually` and `Consistently` are now configurable. - -New Matchers: - -- `ConsistOf`: order-independent assertion against the elements of an array/slice or keys of a map. -- `BeTemporally`: like `BeNumerically` but for `time.Time` -- `HaveKeyWithValue`: asserts a map has a given key with the given value. - -Updated Matchers: - -- `Receive` matcher can take a matcher as an argument and passes only if the channel under test receives an objet that satisfies the passed-in matcher. -- Matchers that implement `MatchMayChangeInTheFuture(actual interface{}) bool` can inform `Eventually` and/or `Consistently` when a match has no chance of changing status in the future. For example, `Receive` returns `false` when a channel is closed. - -Misc: - -- Start using semantic versioning -- Start maintaining changelog - -Major refactor: - -- Pull out Gomega's internal to `internal` diff --git a/vendor/github.com/onsi/gomega/CONTRIBUTING.md b/vendor/github.com/onsi/gomega/CONTRIBUTING.md deleted file mode 100644 index 0d7a0992..00000000 --- a/vendor/github.com/onsi/gomega/CONTRIBUTING.md +++ /dev/null @@ -1,14 +0,0 @@ -# Contributing to Gomega - -Your contributions to Gomega are essential for its long-term maintenance and improvement. To make a contribution: - -- Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code! -- Ensure adequate test coverage: - - Make sure to add appropriate unit tests - - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR - - Please run following linter locally `go vet ./...` and make sure output does not contain any warnings -- Update the documentation. In addition to standard `godoc` comments Gomega has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. - -If you're a committer, check out RELEASING.md to learn how to cut a release. - -Thanks for supporting Gomega! diff --git a/vendor/github.com/onsi/gomega/LICENSE b/vendor/github.com/onsi/gomega/LICENSE deleted file mode 100644 index 9415ee72..00000000 --- a/vendor/github.com/onsi/gomega/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013-2014 Onsi Fakhouri - -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/onsi/gomega/README.md b/vendor/github.com/onsi/gomega/README.md deleted file mode 100644 index 76aa6b55..00000000 --- a/vendor/github.com/onsi/gomega/README.md +++ /dev/null @@ -1,21 +0,0 @@ -![Gomega: Ginkgo's Preferred Matcher Library](http://onsi.github.io/gomega/images/gomega.png) - -[![Build Status](https://travis-ci.org/onsi/gomega.svg?branch=master)](https://travis-ci.org/onsi/gomega) - -Jump straight to the [docs](http://onsi.github.io/gomega/) to learn about Gomega, including a list of [all available matchers](http://onsi.github.io/gomega/#provided-matchers). - -If you have a question, comment, bug report, feature request, etc. please open a GitHub issue. - -## [Ginkgo](http://github.com/onsi/ginkgo): a BDD Testing Framework for Golang - -Learn more about Ginkgo [here](http://onsi.github.io/ginkgo/) - -## Community Matchers - -A collection of community matchers is available on the [wiki](https://github.com/onsi/gomega/wiki). - -## License - -Gomega is MIT-Licensed - -The `ConsistOf` matcher uses [goraph](https://github.com/amitkgupta/goraph) which is embedded in the source to simplify distribution. goraph has an MIT license. diff --git a/vendor/github.com/onsi/gomega/RELEASING.md b/vendor/github.com/onsi/gomega/RELEASING.md deleted file mode 100644 index 998d64ee..00000000 --- a/vendor/github.com/onsi/gomega/RELEASING.md +++ /dev/null @@ -1,12 +0,0 @@ -A Gomega release is a tagged sha and a GitHub release. To cut a release: - -1. Ensure CHANGELOG.md is up to date. - - Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release - - Categorize the changes into - - Breaking Changes (requires a major version) - - New Features (minor version) - - Fixes (fix version) - - Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact) -2. Update GOMEGA_VERSION in `gomega_dsl.go` -3. Push a commit with the version number as the commit message (e.g. `v1.3.0`) -4. Create a new [GitHub release](https://help.github.com/articles/creating-releases/) with the version number as the tag (e.g. `v1.3.0`). List the key changes in the release notes. diff --git a/vendor/github.com/onsi/gomega/format/format.go b/vendor/github.com/onsi/gomega/format/format.go deleted file mode 100644 index 6559525f..00000000 --- a/vendor/github.com/onsi/gomega/format/format.go +++ /dev/null @@ -1,382 +0,0 @@ -/* -Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information. -*/ -package format - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "time" -) - -// Use MaxDepth to set the maximum recursion depth when printing deeply nested objects -var MaxDepth = uint(10) - -/* -By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output. - -Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead. - -Note that GoString and String don't always have all the information you need to understand why a test failed! -*/ -var UseStringerRepresentation = false - -/* -Print the content of context objects. By default it will be suppressed. - -Set PrintContextObjects = true to enable printing of the context internals. -*/ -var PrintContextObjects = false - -// TruncatedDiff choose if we should display a truncated pretty diff or not -var TruncatedDiff = true - -// Ctx interface defined here to keep backwards compatability with go < 1.7 -// It matches the context.Context interface -type Ctx interface { - Deadline() (deadline time.Time, ok bool) - Done() <-chan struct{} - Err() error - Value(key interface{}) interface{} -} - -var contextType = reflect.TypeOf((*Ctx)(nil)).Elem() -var timeType = reflect.TypeOf(time.Time{}) - -//The default indentation string emitted by the format package -var Indent = " " - -var longFormThreshold = 20 - -/* -Generates a formatted matcher success/failure message of the form: - - Expected - - - - -If expected is omited, then the message looks like: - - Expected - - -*/ -func Message(actual interface{}, message string, expected ...interface{}) string { - if len(expected) == 0 { - return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) - } - return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) -} - -/* - -Generates a nicely formatted matcher success / failure message - -Much like Message(...), but it attempts to pretty print diffs in strings - -Expected - : "...aaaaabaaaaa..." -to equal | - : "...aaaaazaaaaa..." - -*/ - -func MessageWithDiff(actual, message, expected string) string { - if TruncatedDiff && len(actual) >= truncateThreshold && len(expected) >= truncateThreshold { - diffPoint := findFirstMismatch(actual, expected) - formattedActual := truncateAndFormat(actual, diffPoint) - formattedExpected := truncateAndFormat(expected, diffPoint) - - spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected) - - tabLength := 4 - spaceFromMessageToActual := tabLength + len(": ") - len(message) - padding := strings.Repeat(" ", spaceFromMessageToActual+spacesBeforeFormattedMismatch) + "|" - return Message(formattedActual, message+padding, formattedExpected) - } - return Message(actual, message, expected) -} - -func truncateAndFormat(str string, index int) string { - leftPadding := `...` - rightPadding := `...` - - start := index - charactersAroundMismatchToInclude - if start < 0 { - start = 0 - leftPadding = "" - } - - // slice index must include the mis-matched character - lengthOfMismatchedCharacter := 1 - end := index + charactersAroundMismatchToInclude + lengthOfMismatchedCharacter - if end > len(str) { - end = len(str) - rightPadding = "" - - } - return fmt.Sprintf("\"%s\"", leftPadding+str[start:end]+rightPadding) -} - -func findFirstMismatch(a, b string) int { - aSlice := strings.Split(a, "") - bSlice := strings.Split(b, "") - - for index, str := range aSlice { - if index > len(bSlice)-1 { - return index - } - if str != bSlice[index] { - return index - } - } - - if len(b) > len(a) { - return len(a) + 1 - } - - return 0 -} - -const ( - truncateThreshold = 50 - charactersAroundMismatchToInclude = 5 -) - -/* -Pretty prints the passed in object at the passed in indentation level. - -Object recurses into deeply nested objects emitting pretty-printed representations of their components. - -Modify format.MaxDepth to control how deep the recursion is allowed to go -Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of -recursing into the object. - -Set PrintContextObjects to true to print the content of objects implementing context.Context -*/ -func Object(object interface{}, indentation uint) string { - indent := strings.Repeat(Indent, int(indentation)) - value := reflect.ValueOf(object) - return fmt.Sprintf("%s<%s>: %s", indent, formatType(object), formatValue(value, indentation)) -} - -/* -IndentString takes a string and indents each line by the specified amount. -*/ -func IndentString(s string, indentation uint) string { - components := strings.Split(s, "\n") - result := "" - indent := strings.Repeat(Indent, int(indentation)) - for i, component := range components { - result += indent + component - if i < len(components)-1 { - result += "\n" - } - } - - return result -} - -func formatType(object interface{}) string { - t := reflect.TypeOf(object) - if t == nil { - return "nil" - } - switch t.Kind() { - case reflect.Chan: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Ptr: - return fmt.Sprintf("%T | %p", object, object) - case reflect.Slice: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Map: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d", object, v.Len()) - default: - return fmt.Sprintf("%T", object) - } -} - -func formatValue(value reflect.Value, indentation uint) string { - if indentation > MaxDepth { - return "..." - } - - if isNilValue(value) { - return "nil" - } - - if UseStringerRepresentation { - if value.CanInterface() { - obj := value.Interface() - switch x := obj.(type) { - case fmt.GoStringer: - return x.GoString() - case fmt.Stringer: - return x.String() - } - } - } - - if !PrintContextObjects { - if value.Type().Implements(contextType) && indentation > 1 { - return "" - } - } - - switch value.Kind() { - case reflect.Bool: - return fmt.Sprintf("%v", value.Bool()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return fmt.Sprintf("%v", value.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return fmt.Sprintf("%v", value.Uint()) - case reflect.Uintptr: - return fmt.Sprintf("0x%x", value.Uint()) - case reflect.Float32, reflect.Float64: - return fmt.Sprintf("%v", value.Float()) - case reflect.Complex64, reflect.Complex128: - return fmt.Sprintf("%v", value.Complex()) - case reflect.Chan: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Func: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Ptr: - return formatValue(value.Elem(), indentation) - case reflect.Slice: - return formatSlice(value, indentation) - case reflect.String: - return formatString(value.String(), indentation) - case reflect.Array: - return formatSlice(value, indentation) - case reflect.Map: - return formatMap(value, indentation) - case reflect.Struct: - if value.Type() == timeType && value.CanInterface() { - t, _ := value.Interface().(time.Time) - return t.Format(time.RFC3339Nano) - } - return formatStruct(value, indentation) - case reflect.Interface: - return formatValue(value.Elem(), indentation) - default: - if value.CanInterface() { - return fmt.Sprintf("%#v", value.Interface()) - } - return fmt.Sprintf("%#v", value) - } -} - -func formatString(object interface{}, indentation uint) string { - if indentation == 1 { - s := fmt.Sprintf("%s", object) - components := strings.Split(s, "\n") - result := "" - for i, component := range components { - if i == 0 { - result += component - } else { - result += Indent + component - } - if i < len(components)-1 { - result += "\n" - } - } - - return fmt.Sprintf("%s", result) - } else { - return fmt.Sprintf("%q", object) - } -} - -func formatSlice(v reflect.Value, indentation uint) string { - if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && isPrintableString(string(v.Bytes())) { - return formatString(v.Bytes(), indentation) - } - - l := v.Len() - result := make([]string, l) - longest := 0 - for i := 0; i < l; i++ { - result[i] = formatValue(v.Index(i), indentation+1) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("[%s]", strings.Join(result, ", ")) -} - -func formatMap(v reflect.Value, indentation uint) string { - l := v.Len() - result := make([]string, l) - - longest := 0 - for i, key := range v.MapKeys() { - value := v.MapIndex(key) - result[i] = fmt.Sprintf("%s: %s", formatValue(key, indentation+1), formatValue(value, indentation+1)) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) -} - -func formatStruct(v reflect.Value, indentation uint) string { - t := v.Type() - - l := v.NumField() - result := []string{} - longest := 0 - for i := 0; i < l; i++ { - structField := t.Field(i) - fieldEntry := v.Field(i) - representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1)) - result = append(result, representation) - if len(representation) > longest { - longest = len(representation) - } - } - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) -} - -func isNilValue(a reflect.Value) bool { - switch a.Kind() { - case reflect.Invalid: - return true - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return a.IsNil() - } - - return false -} - -/* -Returns true when the string is entirely made of printable runes, false otherwise. -*/ -func isPrintableString(str string) bool { - for _, runeValue := range str { - if !strconv.IsPrint(runeValue) { - return false - } - } - return true -} diff --git a/vendor/github.com/onsi/gomega/go.mod b/vendor/github.com/onsi/gomega/go.mod deleted file mode 100644 index 65eedf69..00000000 --- a/vendor/github.com/onsi/gomega/go.mod +++ /dev/null @@ -1,15 +0,0 @@ -module github.com/onsi/gomega - -require ( - github.com/fsnotify/fsnotify v1.4.7 // indirect - github.com/golang/protobuf v1.2.0 - github.com/hpcloud/tail v1.0.0 // indirect - github.com/onsi/ginkgo v1.6.0 - golang.org/x/net v0.0.0-20180906233101-161cd47e91fd - golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f // indirect - golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e // indirect - golang.org/x/text v0.3.0 // indirect - gopkg.in/fsnotify.v1 v1.4.7 // indirect - gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect - gopkg.in/yaml.v2 v2.2.1 -) diff --git a/vendor/github.com/onsi/gomega/go.sum b/vendor/github.com/onsi/gomega/go.sum deleted file mode 100644 index b23f6ef0..00000000 --- a/vendor/github.com/onsi/gomega/go.sum +++ /dev/null @@ -1,24 +0,0 @@ -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go deleted file mode 100644 index 471f691a..00000000 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ /dev/null @@ -1,421 +0,0 @@ -/* -Gomega is the Ginkgo BDD-style testing framework's preferred matcher library. - -The godoc documentation describes Gomega's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/gomega/ - -Gomega on Github: http://github.com/onsi/gomega - -Learn more about Ginkgo online: http://onsi.github.io/ginkgo - -Ginkgo on Github: http://github.com/onsi/ginkgo - -Gomega is MIT-Licensed -*/ -package gomega - -import ( - "fmt" - "reflect" - "time" - - "github.com/onsi/gomega/internal/assertion" - "github.com/onsi/gomega/internal/asyncassertion" - "github.com/onsi/gomega/internal/testingtsupport" - "github.com/onsi/gomega/types" -) - -const GOMEGA_VERSION = "1.4.3" - -const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil. -If you're using Ginkgo then you probably forgot to put your assertion in an It(). -Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT(). -Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations. -` - -var globalFailWrapper *types.GomegaFailWrapper - -var defaultEventuallyTimeout = time.Second -var defaultEventuallyPollingInterval = 10 * time.Millisecond -var defaultConsistentlyDuration = 100 * time.Millisecond -var defaultConsistentlyPollingInterval = 10 * time.Millisecond - -//RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails -//the fail handler passed into RegisterFailHandler is called. -func RegisterFailHandler(handler types.GomegaFailHandler) { - if handler == nil { - globalFailWrapper = nil - return - } - - globalFailWrapper = &types.GomegaFailWrapper{ - Fail: handler, - TWithHelper: testingtsupport.EmptyTWithHelper{}, - } -} - -func RegisterFailHandlerWithT(t types.TWithHelper, handler types.GomegaFailHandler) { - if handler == nil { - globalFailWrapper = nil - return - } - - globalFailWrapper = &types.GomegaFailWrapper{ - Fail: handler, - TWithHelper: t, - } -} - -//RegisterTestingT connects Gomega to Golang's XUnit style -//Testing.T tests. It is now deprecated and you should use NewGomegaWithT() instead. -// -//Legacy Documentation: -// -//You'll need to call this at the top of each XUnit style test: -// -// func TestFarmHasCow(t *testing.T) { -// RegisterTestingT(t) -// -// f := farm.New([]string{"Cow", "Horse"}) -// Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") -// } -// -// Note that this *testing.T is registered *globally* by Gomega (this is why you don't have to -// pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests -// in parallel as the global fail handler cannot point to more than one testing.T at a time. -// -// NewGomegaWithT() does not have this limitation -// -// (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*). -func RegisterTestingT(t types.GomegaTestingT) { - tWithHelper, hasHelper := t.(types.TWithHelper) - if !hasHelper { - RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail) - return - } - RegisterFailHandlerWithT(tWithHelper, testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail) -} - -//InterceptGomegaHandlers runs a given callback and returns an array of -//failure messages generated by any Gomega assertions within the callback. -// -//This is accomplished by temporarily replacing the *global* fail handler -//with a fail handler that simply annotates failures. The original fail handler -//is reset when InterceptGomegaFailures returns. -// -//This is most useful when testing custom matchers, but can also be used to check -//on a value using a Gomega assertion without causing a test failure. -func InterceptGomegaFailures(f func()) []string { - originalHandler := globalFailWrapper.Fail - failures := []string{} - RegisterFailHandler(func(message string, callerSkip ...int) { - failures = append(failures, message) - }) - f() - RegisterFailHandler(originalHandler) - return failures -} - -//Ω wraps an actual value allowing assertions to be made on it: -// Ω("foo").Should(Equal("foo")) -// -//If Ω is passed more than one argument it will pass the *first* argument to the matcher. -//All subsequent arguments will be required to be nil/zero. -// -//This is convenient if you want to make an assertion on a method/function that returns -//a value and an error - a common patter in Go. -// -//For example, given a function with signature: -// func MyAmazingThing() (int, error) -// -//Then: -// Ω(MyAmazingThing()).Should(Equal(3)) -//Will succeed only if `MyAmazingThing()` returns `(3, nil)` -// -//Ω and Expect are identical -func Ω(actual interface{}, extra ...interface{}) GomegaAssertion { - return ExpectWithOffset(0, actual, extra...) -} - -//Expect wraps an actual value allowing assertions to be made on it: -// Expect("foo").To(Equal("foo")) -// -//If Expect is passed more than one argument it will pass the *first* argument to the matcher. -//All subsequent arguments will be required to be nil/zero. -// -//This is convenient if you want to make an assertion on a method/function that returns -//a value and an error - a common patter in Go. -// -//For example, given a function with signature: -// func MyAmazingThing() (int, error) -// -//Then: -// Expect(MyAmazingThing()).Should(Equal(3)) -//Will succeed only if `MyAmazingThing()` returns `(3, nil)` -// -//Expect and Ω are identical -func Expect(actual interface{}, extra ...interface{}) GomegaAssertion { - return ExpectWithOffset(0, actual, extra...) -} - -//ExpectWithOffset wraps an actual value allowing assertions to be made on it: -// ExpectWithOffset(1, "foo").To(Equal("foo")) -// -//Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument -//this is used to modify the call-stack offset when computing line numbers. -// -//This is most useful in helper functions that make assertions. If you want Gomega's -//error message to refer to the calling line in the test (as opposed to the line in the helper function) -//set the first argument of `ExpectWithOffset` appropriately. -func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) GomegaAssertion { - if globalFailWrapper == nil { - panic(nilFailHandlerPanic) - } - return assertion.New(actual, globalFailWrapper, offset, extra...) -} - -//Eventually wraps an actual value allowing assertions to be made on it. -//The assertion is tried periodically until it passes or a timeout occurs. -// -//Both the timeout and polling interval are configurable as optional arguments: -//The first optional argument is the timeout -//The second optional argument is the polling interval -// -//Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the -//last case they are interpreted as seconds. -// -//If Eventually is passed an actual that is a function taking no arguments and returning at least one value, -//then Eventually will call the function periodically and try the matcher against the function's first return value. -// -//Example: -// -// Eventually(func() int { -// return thingImPolling.Count() -// }).Should(BeNumerically(">=", 17)) -// -//Note that this example could be rewritten: -// -// Eventually(thingImPolling.Count).Should(BeNumerically(">=", 17)) -// -//If the function returns more than one value, then Eventually will pass the first value to the matcher and -//assert that all other values are nil/zero. -//This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go. -// -//For example, consider a method that returns a value and an error: -// func FetchFromDB() (string, error) -// -//Then -// Eventually(FetchFromDB).Should(Equal("hasselhoff")) -// -//Will pass only if the the returned error is nil and the returned string passes the matcher. -// -//Eventually's default timeout is 1 second, and its default polling interval is 10ms -func Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - return EventuallyWithOffset(0, actual, intervals...) -} - -//EventuallyWithOffset operates like Eventually but takes an additional -//initial argument to indicate an offset in the call stack. This is useful when building helper -//functions that contain matchers. To learn more, read about `ExpectWithOffset`. -func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailWrapper == nil { - panic(nilFailHandlerPanic) - } - timeoutInterval := defaultEventuallyTimeout - pollingInterval := defaultEventuallyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset) -} - -//Consistently wraps an actual value allowing assertions to be made on it. -//The assertion is tried periodically and is required to pass for a period of time. -// -//Both the total time and polling interval are configurable as optional arguments: -//The first optional argument is the duration that Consistently will run for -//The second optional argument is the polling interval -// -//Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the -//last case they are interpreted as seconds. -// -//If Consistently is passed an actual that is a function taking no arguments and returning at least one value, -//then Consistently will call the function periodically and try the matcher against the function's first return value. -// -//If the function returns more than one value, then Consistently will pass the first value to the matcher and -//assert that all other values are nil/zero. -//This allows you to pass Consistently a function that returns a value and an error - a common pattern in Go. -// -//Consistently is useful in cases where you want to assert that something *does not happen* over a period of tiem. -//For example, you want to assert that a goroutine does *not* send data down a channel. In this case, you could: -// -// Consistently(channel).ShouldNot(Receive()) -// -//Consistently's default duration is 100ms, and its default polling interval is 10ms -func Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - return ConsistentlyWithOffset(0, actual, intervals...) -} - -//ConsistentlyWithOffset operates like Consistnetly but takes an additional -//initial argument to indicate an offset in the call stack. This is useful when building helper -//functions that contain matchers. To learn more, read about `ExpectWithOffset`. -func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailWrapper == nil { - panic(nilFailHandlerPanic) - } - timeoutInterval := defaultConsistentlyDuration - pollingInterval := defaultConsistentlyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset) -} - -//Set the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses. -func SetDefaultEventuallyTimeout(t time.Duration) { - defaultEventuallyTimeout = t -} - -//Set the default polling interval for Eventually. -func SetDefaultEventuallyPollingInterval(t time.Duration) { - defaultEventuallyPollingInterval = t -} - -//Set the default duration for Consistently. Consistently will verify that your condition is satsified for this long. -func SetDefaultConsistentlyDuration(t time.Duration) { - defaultConsistentlyDuration = t -} - -//Set the default polling interval for Consistently. -func SetDefaultConsistentlyPollingInterval(t time.Duration) { - defaultConsistentlyPollingInterval = t -} - -//GomegaAsyncAssertion is returned by Eventually and Consistently and polls the actual value passed into Eventually against -//the matcher passed to the Should and ShouldNot methods. -// -//Both Should and ShouldNot take a variadic optionalDescription argument. This is passed on to -//fmt.Sprintf() and is used to annotate failure messages. This allows you to make your failure messages more -//descriptive -// -//Both Should and ShouldNot return a boolean that is true if the assertion passed and false if it failed. -// -//Example: -// -// Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.") -// Consistently(myChannel).ShouldNot(Receive(), "Nothing should have come down the pipe.") -type GomegaAsyncAssertion interface { - Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool -} - -//GomegaAssertion is returned by Ω and Expect and compares the actual value to the matcher -//passed to the Should/ShouldNot and To/ToNot/NotTo methods. -// -//Typically Should/ShouldNot are used with Ω and To/ToNot/NotTo are used with Expect -//though this is not enforced. -// -//All methods take a variadic optionalDescription argument. This is passed on to fmt.Sprintf() -//and is used to annotate failure messages. -// -//All methods return a bool that is true if hte assertion passed and false if it failed. -// -//Example: -// -// Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm) -type GomegaAssertion interface { - Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - - To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool -} - -//OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it -type OmegaMatcher types.GomegaMatcher - -//GomegaWithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage -//Gomega's rich ecosystem of matchers in standard `testing` test suites. -// -//Use `NewGomegaWithT` to instantiate a `GomegaWithT` -type GomegaWithT struct { - t types.GomegaTestingT -} - -//NewGomegaWithT takes a *testing.T and returngs a `GomegaWithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with -//Gomega's rich ecosystem of matchers in standard `testing` test suits. -// -// func TestFarmHasCow(t *testing.T) { -// g := GomegaWithT(t) -// -// f := farm.New([]string{"Cow", "Horse"}) -// g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") -// } -func NewGomegaWithT(t types.GomegaTestingT) *GomegaWithT { - return &GomegaWithT{ - t: t, - } -} - -//See documentation for Expect -func (g *GomegaWithT) Expect(actual interface{}, extra ...interface{}) GomegaAssertion { - return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), 0, extra...) -} - -//See documentation for Eventually -func (g *GomegaWithT) Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - timeoutInterval := defaultEventuallyTimeout - pollingInterval := defaultEventuallyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0) -} - -//See documentation for Consistently -func (g *GomegaWithT) Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - timeoutInterval := defaultConsistentlyDuration - pollingInterval := defaultConsistentlyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0) -} - -func toDuration(input interface{}) time.Duration { - duration, ok := input.(time.Duration) - if ok { - return duration - } - - value := reflect.ValueOf(input) - kind := reflect.TypeOf(input).Kind() - - if reflect.Int <= kind && kind <= reflect.Int64 { - return time.Duration(value.Int()) * time.Second - } else if reflect.Uint <= kind && kind <= reflect.Uint64 { - return time.Duration(value.Uint()) * time.Second - } else if reflect.Float32 <= kind && kind <= reflect.Float64 { - return time.Duration(value.Float() * float64(time.Second)) - } else if reflect.String == kind { - duration, err := time.ParseDuration(value.String()) - if err != nil { - panic(fmt.Sprintf("%#v is not a valid parsable duration string.", input)) - } - return duration - } - - panic(fmt.Sprintf("%v is not a valid interval. Must be time.Duration, parsable duration string or a number.", input)) -} diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion.go deleted file mode 100644 index 00197b67..00000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go +++ /dev/null @@ -1,105 +0,0 @@ -package assertion - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/types" -) - -type Assertion struct { - actualInput interface{} - failWrapper *types.GomegaFailWrapper - offset int - extra []interface{} -} - -func New(actualInput interface{}, failWrapper *types.GomegaFailWrapper, offset int, extra ...interface{}) *Assertion { - return &Assertion{ - actualInput: actualInput, - failWrapper: failWrapper, - offset: offset, - extra: extra, - } -} - -func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) string { - switch len(optionalDescription) { - case 0: - return "" - default: - return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" - } -} - -func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { - matches, err := matcher.Match(assertion.actualInput) - description := assertion.buildDescription(optionalDescription...) - assertion.failWrapper.TWithHelper.Helper() - if err != nil { - assertion.failWrapper.Fail(description+err.Error(), 2+assertion.offset) - return false - } - if matches != desiredMatch { - var message string - if desiredMatch { - message = matcher.FailureMessage(assertion.actualInput) - } else { - message = matcher.NegatedFailureMessage(assertion.actualInput) - } - assertion.failWrapper.Fail(description+message, 2+assertion.offset) - return false - } - - return true -} - -func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool { - success, message := vetExtras(assertion.extra) - if success { - return true - } - - description := assertion.buildDescription(optionalDescription...) - assertion.failWrapper.TWithHelper.Helper() - assertion.failWrapper.Fail(description+message, 2+assertion.offset) - return false -} - -func vetExtras(extras []interface{}) (bool, string) { - for i, extra := range extras { - if extra != nil { - zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface() - if !reflect.DeepEqual(zeroValue, extra) { - message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra) - return false, message - } - } - } - return true, "" -} diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go deleted file mode 100644 index cdab233e..00000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go +++ /dev/null @@ -1,194 +0,0 @@ -package asyncassertion - -import ( - "errors" - "fmt" - "reflect" - "time" - - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type AsyncAssertionType uint - -const ( - AsyncAssertionTypeEventually AsyncAssertionType = iota - AsyncAssertionTypeConsistently -) - -type AsyncAssertion struct { - asyncType AsyncAssertionType - actualInput interface{} - timeoutInterval time.Duration - pollingInterval time.Duration - failWrapper *types.GomegaFailWrapper - offset int -} - -func New(asyncType AsyncAssertionType, actualInput interface{}, failWrapper *types.GomegaFailWrapper, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion { - actualType := reflect.TypeOf(actualInput) - if actualType.Kind() == reflect.Func { - if actualType.NumIn() != 0 || actualType.NumOut() == 0 { - panic("Expected a function with no arguments and one or more return values.") - } - } - - return &AsyncAssertion{ - asyncType: asyncType, - actualInput: actualInput, - failWrapper: failWrapper, - timeoutInterval: timeoutInterval, - pollingInterval: pollingInterval, - offset: offset, - } -} - -func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - assertion.failWrapper.TWithHelper.Helper() - return assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interface{}) string { - switch len(optionalDescription) { - case 0: - return "" - default: - return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" - } -} - -func (assertion *AsyncAssertion) actualInputIsAFunction() bool { - actualType := reflect.TypeOf(assertion.actualInput) - return actualType.Kind() == reflect.Func && actualType.NumIn() == 0 && actualType.NumOut() > 0 -} - -func (assertion *AsyncAssertion) pollActual() (interface{}, error) { - if assertion.actualInputIsAFunction() { - values := reflect.ValueOf(assertion.actualInput).Call([]reflect.Value{}) - - extras := []interface{}{} - for _, value := range values[1:] { - extras = append(extras, value.Interface()) - } - - success, message := vetExtras(extras) - - if !success { - return nil, errors.New(message) - } - - return values[0].Interface(), nil - } - - return assertion.actualInput, nil -} - -func (assertion *AsyncAssertion) matcherMayChange(matcher types.GomegaMatcher, value interface{}) bool { - if assertion.actualInputIsAFunction() { - return true - } - - return oraclematcher.MatchMayChangeInTheFuture(matcher, value) -} - -func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { - timer := time.Now() - timeout := time.After(assertion.timeoutInterval) - - description := assertion.buildDescription(optionalDescription...) - - var matches bool - var err error - mayChange := true - value, err := assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - - assertion.failWrapper.TWithHelper.Helper() - - fail := func(preamble string) { - errMsg := "" - message := "" - if err != nil { - errMsg = "Error: " + err.Error() - } else { - if desiredMatch { - message = matcher.FailureMessage(value) - } else { - message = matcher.NegatedFailureMessage(value) - } - } - assertion.failWrapper.TWithHelper.Helper() - assertion.failWrapper.Fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset) - } - - if assertion.asyncType == AsyncAssertionTypeEventually { - for { - if err == nil && matches == desiredMatch { - return true - } - - if !mayChange { - fail("No future change is possible. Bailing out early") - return false - } - - select { - case <-time.After(assertion.pollingInterval): - value, err = assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - case <-timeout: - fail("Timed out") - return false - } - } - } else if assertion.asyncType == AsyncAssertionTypeConsistently { - for { - if !(err == nil && matches == desiredMatch) { - fail("Failed") - return false - } - - if !mayChange { - return true - } - - select { - case <-time.After(assertion.pollingInterval): - value, err = assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - case <-timeout: - return true - } - } - } - - return false -} - -func vetExtras(extras []interface{}) (bool, string) { - for i, extra := range extras { - if extra != nil { - zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface() - if !reflect.DeepEqual(zeroValue, extra) { - message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra) - return false, message - } - } - } - return true, "" -} diff --git a/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go b/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go deleted file mode 100644 index 66cad88a..00000000 --- a/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go +++ /dev/null @@ -1,25 +0,0 @@ -package oraclematcher - -import "github.com/onsi/gomega/types" - -/* -GomegaMatchers that also match the OracleMatcher interface can convey information about -whether or not their result will change upon future attempts. - -This allows `Eventually` and `Consistently` to short circuit if success becomes impossible. - -For example, a process' exit code can never change. So, gexec's Exit matcher returns `true` -for `MatchMayChangeInTheFuture` until the process exits, at which point it returns `false` forevermore. -*/ -type OracleMatcher interface { - MatchMayChangeInTheFuture(actual interface{}) bool -} - -func MatchMayChangeInTheFuture(matcher types.GomegaMatcher, value interface{}) bool { - oracleMatcher, ok := matcher.(OracleMatcher) - if !ok { - return true - } - - return oracleMatcher.MatchMayChangeInTheFuture(value) -} diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go deleted file mode 100644 index bb27032f..00000000 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go +++ /dev/null @@ -1,60 +0,0 @@ -package testingtsupport - -import ( - "regexp" - "runtime/debug" - "strings" - - "github.com/onsi/gomega/types" -) - -var StackTracePruneRE = regexp.MustCompile(`\/gomega\/|\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) - -type EmptyTWithHelper struct{} - -func (e EmptyTWithHelper) Helper() {} - -type gomegaTestingT interface { - Fatalf(format string, args ...interface{}) -} - -func BuildTestingTGomegaFailWrapper(t gomegaTestingT) *types.GomegaFailWrapper { - tWithHelper, hasHelper := t.(types.TWithHelper) - if !hasHelper { - tWithHelper = EmptyTWithHelper{} - } - - fail := func(message string, callerSkip ...int) { - if hasHelper { - tWithHelper.Helper() - t.Fatalf("\n%s", message) - } else { - skip := 2 - if len(callerSkip) > 0 { - skip += callerSkip[0] - } - stackTrace := pruneStack(string(debug.Stack()), skip) - t.Fatalf("\n%s\n%s\n", stackTrace, message) - } - } - - return &types.GomegaFailWrapper{ - Fail: fail, - TWithHelper: tWithHelper, - } -} - -func pruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n")[1:] - if len(stack) > 2*skip { - stack = stack[2*skip:] - } - prunedStack := []string{} - for i := 0; i < len(stack)/2; i++ { - if !StackTracePruneRE.Match([]byte(stack[i*2])) { - prunedStack = append(prunedStack, stack[i*2]) - prunedStack = append(prunedStack, stack[i*2+1]) - } - } - return strings.Join(prunedStack, "\n") -} diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go deleted file mode 100644 index c3a326dd..00000000 --- a/vendor/github.com/onsi/gomega/matchers.go +++ /dev/null @@ -1,427 +0,0 @@ -package gomega - -import ( - "time" - - "github.com/onsi/gomega/matchers" - "github.com/onsi/gomega/types" -) - -//Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about -//types when performing comparisons. -//It is an error for both actual and expected to be nil. Use BeNil() instead. -func Equal(expected interface{}) types.GomegaMatcher { - return &matchers.EqualMatcher{ - Expected: expected, - } -} - -//BeEquivalentTo is more lax than Equal, allowing equality between different types. -//This is done by converting actual to have the type of expected before -//attempting equality with reflect.DeepEqual. -//It is an error for actual and expected to be nil. Use BeNil() instead. -func BeEquivalentTo(expected interface{}) types.GomegaMatcher { - return &matchers.BeEquivalentToMatcher{ - Expected: expected, - } -} - -//BeIdenticalTo uses the == operator to compare actual with expected. -//BeIdenticalTo is strict about types when performing comparisons. -//It is an error for both actual and expected to be nil. Use BeNil() instead. -func BeIdenticalTo(expected interface{}) types.GomegaMatcher { - return &matchers.BeIdenticalToMatcher{ - Expected: expected, - } -} - -//BeNil succeeds if actual is nil -func BeNil() types.GomegaMatcher { - return &matchers.BeNilMatcher{} -} - -//BeTrue succeeds if actual is true -func BeTrue() types.GomegaMatcher { - return &matchers.BeTrueMatcher{} -} - -//BeFalse succeeds if actual is false -func BeFalse() types.GomegaMatcher { - return &matchers.BeFalseMatcher{} -} - -//HaveOccurred succeeds if actual is a non-nil error -//The typical Go error checking pattern looks like: -// err := SomethingThatMightFail() -// Expect(err).ShouldNot(HaveOccurred()) -func HaveOccurred() types.GomegaMatcher { - return &matchers.HaveOccurredMatcher{} -} - -//Succeed passes if actual is a nil error -//Succeed is intended to be used with functions that return a single error value. Instead of -// err := SomethingThatMightFail() -// Expect(err).ShouldNot(HaveOccurred()) -// -//You can write: -// Expect(SomethingThatMightFail()).Should(Succeed()) -// -//It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect -//functions automatically trigger failure if any return values after the first return value are non-zero/non-nil. -//This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass. -func Succeed() types.GomegaMatcher { - return &matchers.SucceedMatcher{} -} - -//MatchError succeeds if actual is a non-nil error that matches the passed in string/error. -// -//These are valid use-cases: -// Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error" -// Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual) -// -//It is an error for err to be nil or an object that does not implement the Error interface -func MatchError(expected interface{}) types.GomegaMatcher { - return &matchers.MatchErrorMatcher{ - Expected: expected, - } -} - -//BeClosed succeeds if actual is a closed channel. -//It is an error to pass a non-channel to BeClosed, it is also an error to pass nil -// -//In order to check whether or not the channel is closed, Gomega must try to read from the channel -//(even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about -//values coming down the channel. -// -//Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before -//asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read). -// -//Finally, as a corollary: it is an error to check whether or not a send-only channel is closed. -func BeClosed() types.GomegaMatcher { - return &matchers.BeClosedMatcher{} -} - -//Receive succeeds if there is a value to be received on actual. -//Actual must be a channel (and cannot be a send-only channel) -- anything else is an error. -// -//Receive returns immediately and never blocks: -// -//- If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. -// -//- If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. -// -//- If there is something on the channel `c` ready to be read, then Expect(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail. -// -//If you have a go-routine running in the background that will write to channel `c` you can: -// Eventually(c).Should(Receive()) -// -//This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`) -// -//A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`: -// Consistently(c).ShouldNot(Receive()) -// -//You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example: -// Expect(c).Should(Receive(Equal("foo"))) -// -//When given a matcher, `Receive` will always fail if there is nothing to be received on the channel. -// -//Passing Receive a matcher is especially useful when paired with Eventually: -// -// Eventually(c).Should(Receive(ContainSubstring("bar"))) -// -//will repeatedly attempt to pull values out of `c` until a value matching "bar" is received. -// -//Finally, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type: -// var myThing thing -// Eventually(thingChan).Should(Receive(&myThing)) -// Expect(myThing.Sprocket).Should(Equal("foo")) -// Expect(myThing.IsValid()).Should(BeTrue()) -func Receive(args ...interface{}) types.GomegaMatcher { - var arg interface{} - if len(args) > 0 { - arg = args[0] - } - - return &matchers.ReceiveMatcher{ - Arg: arg, - } -} - -//BeSent succeeds if a value can be sent to actual. -//Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error. -//In addition, actual must not be closed. -// -//BeSent never blocks: -// -//- If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately -//- If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout -//- If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately -// -//Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). -//Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. -func BeSent(arg interface{}) types.GomegaMatcher { - return &matchers.BeSentMatcher{ - Arg: arg, - } -} - -//MatchRegexp succeeds if actual is a string or stringer that matches the -//passed-in regexp. Optional arguments can be provided to construct a regexp -//via fmt.Sprintf(). -func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { - return &matchers.MatchRegexpMatcher{ - Regexp: regexp, - Args: args, - } -} - -//ContainSubstring succeeds if actual is a string or stringer that contains the -//passed-in substring. Optional arguments can be provided to construct the substring -//via fmt.Sprintf(). -func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { - return &matchers.ContainSubstringMatcher{ - Substr: substr, - Args: args, - } -} - -//HavePrefix succeeds if actual is a string or stringer that contains the -//passed-in string as a prefix. Optional arguments can be provided to construct -//via fmt.Sprintf(). -func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { - return &matchers.HavePrefixMatcher{ - Prefix: prefix, - Args: args, - } -} - -//HaveSuffix succeeds if actual is a string or stringer that contains the -//passed-in string as a suffix. Optional arguments can be provided to construct -//via fmt.Sprintf(). -func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { - return &matchers.HaveSuffixMatcher{ - Suffix: suffix, - Args: args, - } -} - -//MatchJSON succeeds if actual is a string or stringer of JSON that matches -//the expected JSON. The JSONs are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchJSON(json interface{}) types.GomegaMatcher { - return &matchers.MatchJSONMatcher{ - JSONToMatch: json, - } -} - -//MatchXML succeeds if actual is a string or stringer of XML that matches -//the expected XML. The XMLs are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like whitespaces shouldn't matter. -func MatchXML(xml interface{}) types.GomegaMatcher { - return &matchers.MatchXMLMatcher{ - XMLToMatch: xml, - } -} - -//MatchYAML succeeds if actual is a string or stringer of YAML that matches -//the expected YAML. The YAML's are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchYAML(yaml interface{}) types.GomegaMatcher { - return &matchers.MatchYAMLMatcher{ - YAMLToMatch: yaml, - } -} - -//BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice. -func BeEmpty() types.GomegaMatcher { - return &matchers.BeEmptyMatcher{} -} - -//HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice. -func HaveLen(count int) types.GomegaMatcher { - return &matchers.HaveLenMatcher{ - Count: count, - } -} - -//HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice. -func HaveCap(count int) types.GomegaMatcher { - return &matchers.HaveCapMatcher{ - Count: count, - } -} - -//BeZero succeeds if actual is the zero value for its type or if actual is nil. -func BeZero() types.GomegaMatcher { - return &matchers.BeZeroMatcher{} -} - -//ContainElement succeeds if actual contains the passed in element. -//By default ContainElement() uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) -// -//Actual must be an array, slice or map. -//For maps, ContainElement searches through the map's values. -func ContainElement(element interface{}) types.GomegaMatcher { - return &matchers.ContainElementMatcher{ - Element: element, - } -} - -//ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter. -//By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: -// -// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) -// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) -// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) -// -//Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values. -// -//You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it -//is the only element passed in to ConsistOf: -// -// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) -// -//Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule. -func ConsistOf(elements ...interface{}) types.GomegaMatcher { - return &matchers.ConsistOfMatcher{ - Elements: elements, - } -} - -//HaveKey succeeds if actual is a map with the passed in key. -//By default HaveKey uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) -func HaveKey(key interface{}) types.GomegaMatcher { - return &matchers.HaveKeyMatcher{ - Key: key, - } -} - -//HaveKeyWithValue succeeds if actual is a map with the passed in key and value. -//By default HaveKeyWithValue uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) -// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) -func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { - return &matchers.HaveKeyWithValueMatcher{ - Key: key, - Value: value, - } -} - -//BeNumerically performs numerical assertions in a type-agnostic way. -//Actual and expected should be numbers, though the specific type of -//number is irrelevant (float32, float64, uint8, etc...). -// -//There are six, self-explanatory, supported comparators: -// Expect(1.0).Should(BeNumerically("==", 1)) -// Expect(1.0).Should(BeNumerically("~", 0.999, 0.01)) -// Expect(1.0).Should(BeNumerically(">", 0.9)) -// Expect(1.0).Should(BeNumerically(">=", 1.0)) -// Expect(1.0).Should(BeNumerically("<", 3)) -// Expect(1.0).Should(BeNumerically("<=", 1.0)) -func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher { - return &matchers.BeNumericallyMatcher{ - Comparator: comparator, - CompareTo: compareTo, - } -} - -//BeTemporally compares time.Time's like BeNumerically -//Actual and expected must be time.Time. The comparators are the same as for BeNumerically -// Expect(time.Now()).Should(BeTemporally(">", time.Time{})) -// Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second)) -func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { - return &matchers.BeTemporallyMatcher{ - Comparator: comparator, - CompareTo: compareTo, - Threshold: threshold, - } -} - -//BeAssignableToTypeOf succeeds if actual is assignable to the type of expected. -//It will return an error when one of the values is nil. -// Expect(0).Should(BeAssignableToTypeOf(0)) // Same values -// Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type -// Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type -// Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) -func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher { - return &matchers.AssignableToTypeOfMatcher{ - Expected: expected, - } -} - -//Panic succeeds if actual is a function that, when invoked, panics. -//Actual must be a function that takes no arguments and returns no results. -func Panic() types.GomegaMatcher { - return &matchers.PanicMatcher{} -} - -//BeAnExistingFile succeeds if a file exists. -//Actual must be a string representing the abs path to the file being checked. -func BeAnExistingFile() types.GomegaMatcher { - return &matchers.BeAnExistingFileMatcher{} -} - -//BeARegularFile succeeds if a file exists and is a regular file. -//Actual must be a string representing the abs path to the file being checked. -func BeARegularFile() types.GomegaMatcher { - return &matchers.BeARegularFileMatcher{} -} - -//BeADirectory succeeds if a file exists and is a directory. -//Actual must be a string representing the abs path to the file being checked. -func BeADirectory() types.GomegaMatcher { - return &matchers.BeADirectoryMatcher{} -} - -//And succeeds only if all of the given matchers succeed. -//The matchers are tried in order, and will fail-fast if one doesn't succeed. -// Expect("hi").To(And(HaveLen(2), Equal("hi")) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func And(ms ...types.GomegaMatcher) types.GomegaMatcher { - return &matchers.AndMatcher{Matchers: ms} -} - -//SatisfyAll is an alias for And(). -// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi"))) -func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { - return And(matchers...) -} - -//Or succeeds if any of the given matchers succeed. -//The matchers are tried in order and will return immediately upon the first successful match. -// Expect("hi").To(Or(HaveLen(3), HaveLen(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { - return &matchers.OrMatcher{Matchers: ms} -} - -//SatisfyAny is an alias for Or(). -// Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2)) -func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { - return Or(matchers...) -} - -//Not negates the given matcher; it succeeds if the given matcher fails. -// Expect(1).To(Not(Equal(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func Not(matcher types.GomegaMatcher) types.GomegaMatcher { - return &matchers.NotMatcher{Matcher: matcher} -} - -//WithTransform applies the `transform` to the actual value and matches it against `matcher`. -//The given transform must be a function of one parameter that returns one value. -// var plus1 = func(i int) int { return i + 1 } -// Expect(1).To(WithTransform(plus1, Equal(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher { - return matchers.NewWithTransformMatcher(transform, matcher) -} diff --git a/vendor/github.com/onsi/gomega/matchers/and.go b/vendor/github.com/onsi/gomega/matchers/and.go deleted file mode 100644 index d83a2916..00000000 --- a/vendor/github.com/onsi/gomega/matchers/and.go +++ /dev/null @@ -1,63 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type AndMatcher struct { - Matchers []types.GomegaMatcher - - // state - firstFailedMatcher types.GomegaMatcher -} - -func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { - m.firstFailedMatcher = nil - for _, matcher := range m.Matchers { - success, err := matcher.Match(actual) - if !success || err != nil { - m.firstFailedMatcher = matcher - return false, err - } - } - return true, nil -} - -func (m *AndMatcher) FailureMessage(actual interface{}) (message string) { - return m.firstFailedMatcher.FailureMessage(actual) -} - -func (m *AndMatcher) NegatedFailureMessage(actual interface{}) (message string) { - // not the most beautiful list of matchers, but not bad either... - return format.Message(actual, fmt.Sprintf("To not satisfy all of these matchers: %s", m.Matchers)) -} - -func (m *AndMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - /* - Example with 3 matchers: A, B, C - - Match evaluates them: T, F, => F - So match is currently F, what should MatchMayChangeInTheFuture() return? - Seems like it only depends on B, since currently B MUST change to allow the result to become T - - Match eval: T, T, T => T - So match is currently T, what should MatchMayChangeInTheFuture() return? - Seems to depend on ANY of them being able to change to F. - */ - - if m.firstFailedMatcher == nil { - // so all matchers succeeded.. Any one of them changing would change the result. - for _, matcher := range m.Matchers { - if oraclematcher.MatchMayChangeInTheFuture(matcher, actual) { - return true - } - } - return false // none of were going to change - } - // one of the matchers failed.. it must be able to change in order to affect the result - return oraclematcher.MatchMayChangeInTheFuture(m.firstFailedMatcher, actual) -} diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go deleted file mode 100644 index 51f8be6a..00000000 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go +++ /dev/null @@ -1,35 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type AssignableToTypeOfMatcher struct { - Expected interface{} -} - -func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } else if matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare type to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } else if actual == nil { - return false, nil - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(matcher.Expected) - - return actualType.AssignableTo(expectedType), nil -} - -func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual interface{}) string { - return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) -} - -func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual interface{}) string { - return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) -} diff --git a/vendor/github.com/onsi/gomega/matchers/attributes_slice.go b/vendor/github.com/onsi/gomega/matchers/attributes_slice.go deleted file mode 100644 index 355b362f..00000000 --- a/vendor/github.com/onsi/gomega/matchers/attributes_slice.go +++ /dev/null @@ -1,14 +0,0 @@ -package matchers - -import ( - "encoding/xml" - "strings" -) - -type attributesSlice []xml.Attr - -func (attrs attributesSlice) Len() int { return len(attrs) } -func (attrs attributesSlice) Less(i, j int) bool { - return strings.Compare(attrs[i].Name.Local, attrs[j].Name.Local) == -1 -} -func (attrs attributesSlice) Swap(i, j int) { attrs[i], attrs[j] = attrs[j], attrs[i] } diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go b/vendor/github.com/onsi/gomega/matchers/be_a_directory.go deleted file mode 100644 index 7b6975e4..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go +++ /dev/null @@ -1,54 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type notADirectoryError struct { - os.FileInfo -} - -func (t notADirectoryError) Error() string { - fileInfo := os.FileInfo(t) - switch { - case fileInfo.Mode().IsRegular(): - return "file is a regular file" - default: - return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) - } -} - -type BeADirectoryMatcher struct { - expected interface{} - err error -} - -func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeADirectoryMatcher matcher expects a file path") - } - - fileInfo, err := os.Stat(actualFilename) - if err != nil { - matcher.err = err - return false, nil - } - - if !fileInfo.Mode().IsDir() { - matcher.err = notADirectoryError{fileInfo} - return false, nil - } - return true, nil -} - -func (matcher *BeADirectoryMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be a directory: %s", matcher.err)) -} - -func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not be a directory")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go deleted file mode 100644 index e239131f..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go +++ /dev/null @@ -1,54 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type notARegularFileError struct { - os.FileInfo -} - -func (t notARegularFileError) Error() string { - fileInfo := os.FileInfo(t) - switch { - case fileInfo.IsDir(): - return "file is a directory" - default: - return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) - } -} - -type BeARegularFileMatcher struct { - expected interface{} - err error -} - -func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeARegularFileMatcher matcher expects a file path") - } - - fileInfo, err := os.Stat(actualFilename) - if err != nil { - matcher.err = err - return false, nil - } - - if !fileInfo.Mode().IsRegular() { - matcher.err = notARegularFileError{fileInfo} - return false, nil - } - return true, nil -} - -func (matcher *BeARegularFileMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be a regular file: %s", matcher.err)) -} - -func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not be a regular file")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go deleted file mode 100644 index d42eba22..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go +++ /dev/null @@ -1,38 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type BeAnExistingFileMatcher struct { - expected interface{} -} - -func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeAnExistingFileMatcher matcher expects a file path") - } - - if _, err = os.Stat(actualFilename); err != nil { - switch { - case os.IsNotExist(err): - return false, nil - default: - return false, err - } - } - - return true, nil -} - -func (matcher *BeAnExistingFileMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to exist")) -} - -func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to exist")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go deleted file mode 100644 index 80c9c8bb..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go +++ /dev/null @@ -1,46 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type BeClosedMatcher struct { -} - -func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("BeClosed matcher expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.SendDir { - return false, fmt.Errorf("BeClosed matcher cannot determine if a send-only channel is closed or open. Got:\n%s", format.Object(actual, 1)) - } - - winnerIndex, _, open := reflect.Select([]reflect.SelectCase{ - {Dir: reflect.SelectRecv, Chan: channelValue}, - {Dir: reflect.SelectDefault}, - }) - - var closed bool - if winnerIndex == 0 { - closed = !open - } else if winnerIndex == 1 { - closed = false - } - - return closed, nil -} - -func (matcher *BeClosedMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be closed") -} - -func (matcher *BeClosedMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be open") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go deleted file mode 100644 index 8b00311b..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go +++ /dev/null @@ -1,27 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type BeEmptyMatcher struct { -} - -func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := lengthOf(actual) - if !ok { - return false, fmt.Errorf("BeEmpty matcher expects a string/array/map/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == 0, nil -} - -func (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be empty") -} - -func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be empty") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go deleted file mode 100644 index 97ab20a4..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go +++ /dev/null @@ -1,34 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type BeEquivalentToMatcher struct { - Expected interface{} -} - -func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Both actual and expected must not be nil.") - } - - convertedActual := actual - - if actual != nil && matcher.Expected != nil && reflect.TypeOf(actual).ConvertibleTo(reflect.TypeOf(matcher.Expected)) { - convertedActual = reflect.ValueOf(actual).Convert(reflect.TypeOf(matcher.Expected)).Interface() - } - - return reflect.DeepEqual(convertedActual, matcher.Expected), nil -} - -func (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be equivalent to", matcher.Expected) -} - -func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be equivalent to", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go deleted file mode 100644 index 91d3b779..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go +++ /dev/null @@ -1,26 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type BeFalseMatcher struct { -} - -func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { - if !isBool(actual) { - return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) - } - - return actual == false, nil -} - -func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be false") -} - -func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be false") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go b/vendor/github.com/onsi/gomega/matchers/be_identical_to.go deleted file mode 100644 index fdcda4d1..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go +++ /dev/null @@ -1,37 +0,0 @@ -package matchers - -import ( - "fmt" - "runtime" - - "github.com/onsi/gomega/format" -) - -type BeIdenticalToMatcher struct { - Expected interface{} -} - -func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, matchErr error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } - - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - success = false - matchErr = nil - } - } - }() - - return actual == matcher.Expected, nil -} - -func (matcher *BeIdenticalToMatcher) FailureMessage(actual interface{}) string { - return format.Message(actual, "to be identical to", matcher.Expected) -} - -func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual interface{}) string { - return format.Message(actual, "not to be identical to", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go deleted file mode 100644 index 7ee84fe1..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go +++ /dev/null @@ -1,18 +0,0 @@ -package matchers - -import "github.com/onsi/gomega/format" - -type BeNilMatcher struct { -} - -func (matcher *BeNilMatcher) Match(actual interface{}) (success bool, err error) { - return isNil(actual), nil -} - -func (matcher *BeNilMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be nil") -} - -func (matcher *BeNilMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be nil") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go deleted file mode 100644 index 9f4f77ee..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go +++ /dev/null @@ -1,132 +0,0 @@ -package matchers - -import ( - "fmt" - "math" - - "github.com/onsi/gomega/format" -) - -type BeNumericallyMatcher struct { - Comparator string - CompareTo []interface{} -} - -func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) { - return matcher.FormatFailureMessage(actual, false) -} - -func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return matcher.FormatFailureMessage(actual, true) -} - -func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, negated bool) (message string) { - if len(matcher.CompareTo) == 1 { - message = fmt.Sprintf("to be %s", matcher.Comparator) - } else { - message = fmt.Sprintf("to be within %v of %s", matcher.CompareTo[1], matcher.Comparator) - } - if negated { - message = "not " + message - } - return format.Message(actual, message, matcher.CompareTo[0]) -} - -func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) { - if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { - return false, fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) - } - if !isNumber(actual) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(actual, 1)) - } - if !isNumber(matcher.CompareTo[0]) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) - } - if len(matcher.CompareTo) == 2 && !isNumber(matcher.CompareTo[1]) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) - } - - switch matcher.Comparator { - case "==", "~", ">", ">=", "<", "<=": - default: - return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) - } - - if isFloat(actual) || isFloat(matcher.CompareTo[0]) { - var secondOperand float64 = 1e-8 - if len(matcher.CompareTo) == 2 { - secondOperand = toFloat(matcher.CompareTo[1]) - } - success = matcher.matchFloats(toFloat(actual), toFloat(matcher.CompareTo[0]), secondOperand) - } else if isInteger(actual) { - var secondOperand int64 = 0 - if len(matcher.CompareTo) == 2 { - secondOperand = toInteger(matcher.CompareTo[1]) - } - success = matcher.matchIntegers(toInteger(actual), toInteger(matcher.CompareTo[0]), secondOperand) - } else if isUnsignedInteger(actual) { - var secondOperand uint64 = 0 - if len(matcher.CompareTo) == 2 { - secondOperand = toUnsignedInteger(matcher.CompareTo[1]) - } - success = matcher.matchUnsignedIntegers(toUnsignedInteger(actual), toUnsignedInteger(matcher.CompareTo[0]), secondOperand) - } else { - return false, fmt.Errorf("Failed to compare:\n%s\n%s:\n%s", format.Object(actual, 1), matcher.Comparator, format.Object(matcher.CompareTo[0], 1)) - } - - return success, nil -} - -func (matcher *BeNumericallyMatcher) matchIntegers(actual, compareTo, threshold int64) (success bool) { - switch matcher.Comparator { - case "==", "~": - diff := actual - compareTo - return -threshold <= diff && diff <= threshold - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} - -func (matcher *BeNumericallyMatcher) matchUnsignedIntegers(actual, compareTo, threshold uint64) (success bool) { - switch matcher.Comparator { - case "==", "~": - if actual < compareTo { - actual, compareTo = compareTo, actual - } - return actual-compareTo <= threshold - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} - -func (matcher *BeNumericallyMatcher) matchFloats(actual, compareTo, threshold float64) (success bool) { - switch matcher.Comparator { - case "~": - return math.Abs(actual-compareTo) <= threshold - case "==": - return (actual == compareTo) - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go deleted file mode 100644 index 302dd1a0..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go +++ /dev/null @@ -1,71 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type BeSentMatcher struct { - Arg interface{} - channelClosed bool -} - -func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("BeSent expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.RecvDir { - return false, fmt.Errorf("BeSent matcher cannot be passed a receive-only channel. Got:\n%s", format.Object(actual, 1)) - } - - argType := reflect.TypeOf(matcher.Arg) - assignable := argType.AssignableTo(channelType.Elem()) - - if !assignable { - return false, fmt.Errorf("Cannot pass:\n%s to the channel:\n%s\nThe types don't match.", format.Object(matcher.Arg, 1), format.Object(actual, 1)) - } - - argValue := reflect.ValueOf(matcher.Arg) - - defer func() { - if e := recover(); e != nil { - success = false - err = fmt.Errorf("Cannot send to a closed channel") - matcher.channelClosed = true - } - }() - - winnerIndex, _, _ := reflect.Select([]reflect.SelectCase{ - {Dir: reflect.SelectSend, Chan: channelValue, Send: argValue}, - {Dir: reflect.SelectDefault}, - }) - - var didSend bool - if winnerIndex == 0 { - didSend = true - } - - return didSend, nil -} - -func (matcher *BeSentMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to send:", matcher.Arg) -} - -func (matcher *BeSentMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to send:", matcher.Arg) -} - -func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - if !isChan(actual) { - return false - } - - return !matcher.channelClosed -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go deleted file mode 100644 index cb7c038e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go +++ /dev/null @@ -1,66 +0,0 @@ -package matchers - -import ( - "fmt" - "time" - - "github.com/onsi/gomega/format" -) - -type BeTemporallyMatcher struct { - Comparator string - CompareTo time.Time - Threshold []time.Duration -} - -func (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo) -} - -func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo) -} - -func (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) { - // predicate to test for time.Time type - isTime := func(t interface{}) bool { - _, ok := t.(time.Time) - return ok - } - - if !isTime(actual) { - return false, fmt.Errorf("Expected a time.Time. Got:\n%s", format.Object(actual, 1)) - } - - switch matcher.Comparator { - case "==", "~", ">", ">=", "<", "<=": - default: - return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) - } - - var threshold = time.Millisecond - if len(matcher.Threshold) == 1 { - threshold = matcher.Threshold[0] - } - - return matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil -} - -func (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) { - switch matcher.Comparator { - case "==": - return actual.Equal(compareTo) - case "~": - diff := actual.Sub(compareTo) - return -threshold <= diff && diff <= threshold - case ">": - return actual.After(compareTo) - case ">=": - return !actual.Before(compareTo) - case "<": - return actual.Before(compareTo) - case "<=": - return !actual.After(compareTo) - } - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go deleted file mode 100644 index ec57c5db..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go +++ /dev/null @@ -1,26 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type BeTrueMatcher struct { -} - -func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error) { - if !isBool(actual) { - return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) - } - - return actual.(bool), nil -} - -func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be true") -} - -func (matcher *BeTrueMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be true") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go deleted file mode 100644 index 26196f16..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers - -import ( - "reflect" - - "github.com/onsi/gomega/format" -) - -type BeZeroMatcher struct { -} - -func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil { - return true, nil - } - zeroValue := reflect.Zero(reflect.TypeOf(actual)).Interface() - - return reflect.DeepEqual(zeroValue, actual), nil - -} - -func (matcher *BeZeroMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be zero-valued") -} - -func (matcher *BeZeroMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be zero-valued") -} diff --git a/vendor/github.com/onsi/gomega/matchers/consist_of.go b/vendor/github.com/onsi/gomega/matchers/consist_of.go deleted file mode 100644 index 7b0e0886..00000000 --- a/vendor/github.com/onsi/gomega/matchers/consist_of.go +++ /dev/null @@ -1,80 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph" -) - -type ConsistOfMatcher struct { - Elements []interface{} -} - -func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err error) { - if !isArrayOrSlice(actual) && !isMap(actual) { - return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1)) - } - - elements := matcher.Elements - if len(matcher.Elements) == 1 && isArrayOrSlice(matcher.Elements[0]) { - elements = []interface{}{} - value := reflect.ValueOf(matcher.Elements[0]) - for i := 0; i < value.Len(); i++ { - elements = append(elements, value.Index(i).Interface()) - } - } - - matchers := []interface{}{} - for _, element := range elements { - matcher, isMatcher := element.(omegaMatcher) - if !isMatcher { - matcher = &EqualMatcher{Expected: element} - } - matchers = append(matchers, matcher) - } - - values := matcher.valuesOf(actual) - - if len(values) != len(matchers) { - return false, nil - } - - neighbours := func(v, m interface{}) (bool, error) { - match, err := m.(omegaMatcher).Match(v) - return match && err == nil, nil - } - - bipartiteGraph, err := bipartitegraph.NewBipartiteGraph(values, matchers, neighbours) - if err != nil { - return false, err - } - - return len(bipartiteGraph.LargestMatching()) == len(values), nil -} - -func (matcher *ConsistOfMatcher) valuesOf(actual interface{}) []interface{} { - value := reflect.ValueOf(actual) - values := []interface{}{} - if isMap(actual) { - keys := value.MapKeys() - for i := 0; i < value.Len(); i++ { - values = append(values, value.MapIndex(keys[i]).Interface()) - } - } else { - for i := 0; i < value.Len(); i++ { - values = append(values, value.Index(i).Interface()) - } - } - - return values -} - -func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to consist of", matcher.Elements) -} - -func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to consist of", matcher.Elements) -} diff --git a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go deleted file mode 100644 index 4159335d..00000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go +++ /dev/null @@ -1,56 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type ContainElementMatcher struct { - Element interface{} -} - -func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) { - if !isArrayOrSlice(actual) && !isMap(actual) { - return false, fmt.Errorf("ContainElement matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1)) - } - - elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher) - if !elementIsMatcher { - elemMatcher = &EqualMatcher{Expected: matcher.Element} - } - - value := reflect.ValueOf(actual) - var keys []reflect.Value - if isMap(actual) { - keys = value.MapKeys() - } - var lastError error - for i := 0; i < value.Len(); i++ { - var success bool - var err error - if isMap(actual) { - success, err = elemMatcher.Match(value.MapIndex(keys[i]).Interface()) - } else { - success, err = elemMatcher.Match(value.Index(i).Interface()) - } - if err != nil { - lastError = err - continue - } - if success { - return true, nil - } - } - - return false, lastError -} - -func (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to contain element matching", matcher.Element) -} - -func (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to contain element matching", matcher.Element) -} diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go deleted file mode 100644 index f8dc41e7..00000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go +++ /dev/null @@ -1,38 +0,0 @@ -package matchers - -import ( - "fmt" - "strings" - - "github.com/onsi/gomega/format" -) - -type ContainSubstringMatcher struct { - Substr string - Args []interface{} -} - -func (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("ContainSubstring matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - - return strings.Contains(actualString, matcher.stringToMatch()), nil -} - -func (matcher *ContainSubstringMatcher) stringToMatch() string { - stringToMatch := matcher.Substr - if len(matcher.Args) > 0 { - stringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...) - } - return stringToMatch -} - -func (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to contain substring", matcher.stringToMatch()) -} - -func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to contain substring", matcher.stringToMatch()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go deleted file mode 100644 index befb7bdf..00000000 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go +++ /dev/null @@ -1,42 +0,0 @@ -package matchers - -import ( - "bytes" - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type EqualMatcher struct { - Expected interface{} -} - -func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } - // Shortcut for byte slices. - // Comparing long byte slices with reflect.DeepEqual is very slow, - // so use bytes.Equal if actual and expected are both byte slices. - if actualByteSlice, ok := actual.([]byte); ok { - if expectedByteSlice, ok := matcher.Expected.([]byte); ok { - return bytes.Equal(actualByteSlice, expectedByteSlice), nil - } - } - return reflect.DeepEqual(actual, matcher.Expected), nil -} - -func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) { - actualString, actualOK := actual.(string) - expectedString, expectedOK := matcher.Expected.(string) - if actualOK && expectedOK { - return format.MessageWithDiff(actualString, "to equal", expectedString) - } - - return format.Message(actual, "to equal", matcher.Expected) -} - -func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to equal", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go deleted file mode 100644 index 7ace93dc..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveCapMatcher struct { - Count int -} - -func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := capOf(actual) - if !ok { - return false, fmt.Errorf("HaveCap matcher expects a array/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == matcher.Count, nil -} - -func (matcher *HaveCapMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nto have capacity %d", format.Object(actual, 1), matcher.Count) -} - -func (matcher *HaveCapMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nnot to have capacity %d", format.Object(actual, 1), matcher.Count) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go deleted file mode 100644 index ea5b9233..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go +++ /dev/null @@ -1,54 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type HaveKeyMatcher struct { - Key interface{} -} - -func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) { - if !isMap(actual) { - return false, fmt.Errorf("HaveKey matcher expects a map. Got:%s", format.Object(actual, 1)) - } - - keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) - if !keyIsMatcher { - keyMatcher = &EqualMatcher{Expected: matcher.Key} - } - - keys := reflect.ValueOf(actual).MapKeys() - for i := 0; i < len(keys); i++ { - success, err := keyMatcher.Match(keys[i].Interface()) - if err != nil { - return false, fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error()) - } - if success { - return true, nil - } - } - - return false, nil -} - -func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) { - switch matcher.Key.(type) { - case omegaMatcher: - return format.Message(actual, "to have key matching", matcher.Key) - default: - return format.Message(actual, "to have key", matcher.Key) - } -} - -func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - switch matcher.Key.(type) { - case omegaMatcher: - return format.Message(actual, "not to have key matching", matcher.Key) - default: - return format.Message(actual, "not to have key", matcher.Key) - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go deleted file mode 100644 index 06355b1e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go +++ /dev/null @@ -1,74 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type HaveKeyWithValueMatcher struct { - Key interface{} - Value interface{} -} - -func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, err error) { - if !isMap(actual) { - return false, fmt.Errorf("HaveKeyWithValue matcher expects a map. Got:%s", format.Object(actual, 1)) - } - - keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) - if !keyIsMatcher { - keyMatcher = &EqualMatcher{Expected: matcher.Key} - } - - valueMatcher, valueIsMatcher := matcher.Value.(omegaMatcher) - if !valueIsMatcher { - valueMatcher = &EqualMatcher{Expected: matcher.Value} - } - - keys := reflect.ValueOf(actual).MapKeys() - for i := 0; i < len(keys); i++ { - success, err := keyMatcher.Match(keys[i].Interface()) - if err != nil { - return false, fmt.Errorf("HaveKeyWithValue's key matcher failed with:\n%s%s", format.Indent, err.Error()) - } - if success { - actualValue := reflect.ValueOf(actual).MapIndex(keys[i]) - success, err := valueMatcher.Match(actualValue.Interface()) - if err != nil { - return false, fmt.Errorf("HaveKeyWithValue's value matcher failed with:\n%s%s", format.Indent, err.Error()) - } - return success, nil - } - } - - return false, nil -} - -func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (message string) { - str := "to have {key: value}" - if _, ok := matcher.Key.(omegaMatcher); ok { - str += " matching" - } else if _, ok := matcher.Value.(omegaMatcher); ok { - str += " matching" - } - - expect := make(map[interface{}]interface{}, 1) - expect[matcher.Key] = matcher.Value - return format.Message(actual, str, expect) -} - -func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { - kStr := "not to have key" - if _, ok := matcher.Key.(omegaMatcher); ok { - kStr = "not to have key matching" - } - - vStr := "or that key's value not be" - if _, ok := matcher.Value.(omegaMatcher); ok { - vStr = "or to have that key's value not matching" - } - - return format.Message(actual, kStr, matcher.Key, vStr, matcher.Value) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go deleted file mode 100644 index ee427618..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveLenMatcher struct { - Count int -} - -func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := lengthOf(actual) - if !ok { - return false, fmt.Errorf("HaveLen matcher expects a string/array/map/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == matcher.Count, nil -} - -func (matcher *HaveLenMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nto have length %d", format.Object(actual, 1), matcher.Count) -} - -func (matcher *HaveLenMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nnot to have length %d", format.Object(actual, 1), matcher.Count) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go deleted file mode 100644 index ebdd7178..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveOccurredMatcher struct { -} - -func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) { - // is purely nil? - if actual == nil { - return false, nil - } - - // must be an 'error' type - if !isError(actual) { - return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) - } - - // must be non-nil (or a pointer to a non-nil) - return !isNil(actual), nil -} - -func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1)) -} - -func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "not to have occurred") -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go deleted file mode 100644 index 1d8e8027..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HavePrefixMatcher struct { - Prefix string - Args []interface{} -} - -func (matcher *HavePrefixMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("HavePrefix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - prefix := matcher.prefix() - return len(actualString) >= len(prefix) && actualString[0:len(prefix)] == prefix, nil -} - -func (matcher *HavePrefixMatcher) prefix() string { - if len(matcher.Args) > 0 { - return fmt.Sprintf(matcher.Prefix, matcher.Args...) - } - return matcher.Prefix -} - -func (matcher *HavePrefixMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to have prefix", matcher.prefix()) -} - -func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to have prefix", matcher.prefix()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go deleted file mode 100644 index 40a3526e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveSuffixMatcher struct { - Suffix string - Args []interface{} -} - -func (matcher *HaveSuffixMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("HaveSuffix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - suffix := matcher.suffix() - return len(actualString) >= len(suffix) && actualString[len(actualString)-len(suffix):] == suffix, nil -} - -func (matcher *HaveSuffixMatcher) suffix() string { - if len(matcher.Args) > 0 { - return fmt.Sprintf(matcher.Suffix, matcher.Args...) - } - return matcher.Suffix -} - -func (matcher *HaveSuffixMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to have suffix", matcher.suffix()) -} - -func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to have suffix", matcher.suffix()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go deleted file mode 100644 index 07499ac9..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go +++ /dev/null @@ -1,51 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type MatchErrorMatcher struct { - Expected interface{} -} - -func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err error) { - if isNil(actual) { - return false, fmt.Errorf("Expected an error, got nil") - } - - if !isError(actual) { - return false, fmt.Errorf("Expected an error. Got:\n%s", format.Object(actual, 1)) - } - - actualErr := actual.(error) - - if isError(matcher.Expected) { - return reflect.DeepEqual(actualErr, matcher.Expected), nil - } - - if isString(matcher.Expected) { - return actualErr.Error() == matcher.Expected, nil - } - - var subMatcher omegaMatcher - var hasSubMatcher bool - if matcher.Expected != nil { - subMatcher, hasSubMatcher = (matcher.Expected).(omegaMatcher) - if hasSubMatcher { - return subMatcher.Match(actualErr.Error()) - } - } - - return false, fmt.Errorf("MatchError must be passed an error, string, or Matcher that can match on strings. Got:\n%s", format.Object(matcher.Expected, 1)) -} - -func (matcher *MatchErrorMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to match error", matcher.Expected) -} - -func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match error", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go deleted file mode 100644 index f962f139..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go +++ /dev/null @@ -1,65 +0,0 @@ -package matchers - -import ( - "bytes" - "encoding/json" - "fmt" - - "github.com/onsi/gomega/format" -) - -type MatchJSONMatcher struct { - JSONToMatch interface{} - firstFailurePath []interface{} -} - -func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.prettyPrint(actual) - if err != nil { - return false, err - } - - var aval interface{} - var eval interface{} - - // this is guarded by prettyPrint - json.Unmarshal([]byte(actualString), &aval) - json.Unmarshal([]byte(expectedString), &eval) - var equal bool - equal, matcher.firstFailurePath = deepEqual(aval, eval) - return equal, nil -} - -func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.prettyPrint(actual) - return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath) -} - -func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.prettyPrint(actual) - return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) -} - -func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, ok := toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok := toString(matcher.JSONToMatch) - if !ok { - return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1)) - } - - abuf := new(bytes.Buffer) - ebuf := new(bytes.Buffer) - - if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil { - return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err) - } - - if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil { - return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err) - } - - return abuf.String(), ebuf.String(), nil -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go deleted file mode 100644 index adac5db6..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go +++ /dev/null @@ -1,43 +0,0 @@ -package matchers - -import ( - "fmt" - "regexp" - - "github.com/onsi/gomega/format" -) - -type MatchRegexpMatcher struct { - Regexp string - Args []interface{} -} - -func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) - } - - match, err := regexp.Match(matcher.regexp(), []byte(actualString)) - if err != nil { - return false, fmt.Errorf("RegExp match failed to compile with error:\n\t%s", err.Error()) - } - - return match, nil -} - -func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to match regular expression", matcher.regexp()) -} - -func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match regular expression", matcher.regexp()) -} - -func (matcher *MatchRegexpMatcher) regexp() string { - re := matcher.Regexp - if len(matcher.Args) > 0 { - re = fmt.Sprintf(matcher.Regexp, matcher.Args...) - } - return re -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go deleted file mode 100644 index 3b412ce8..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go +++ /dev/null @@ -1,134 +0,0 @@ -package matchers - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "reflect" - "sort" - "strings" - - "github.com/onsi/gomega/format" - "golang.org/x/net/html/charset" -) - -type MatchXMLMatcher struct { - XMLToMatch interface{} -} - -func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.formattedPrint(actual) - if err != nil { - return false, err - } - - aval, err := parseXmlContent(actualString) - if err != nil { - return false, fmt.Errorf("Actual '%s' should be valid XML, but it is not.\nUnderlying error:%s", actualString, err) - } - - eval, err := parseXmlContent(expectedString) - if err != nil { - return false, fmt.Errorf("Expected '%s' should be valid XML, but it is not.\nUnderlying error:%s", expectedString, err) - } - - return reflect.DeepEqual(aval, eval), nil -} - -func (matcher *MatchXMLMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.formattedPrint(actual) - return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString) -} - -func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.formattedPrint(actual) - return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString) -} - -func (matcher *MatchXMLMatcher) formattedPrint(actual interface{}) (actualString, expectedString string, err error) { - var ok bool - actualString, ok = toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok = toString(matcher.XMLToMatch) - if !ok { - return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.XMLToMatch, 1)) - } - return actualString, expectedString, nil -} - -func parseXmlContent(content string) (*xmlNode, error) { - allNodes := []*xmlNode{} - - dec := newXmlDecoder(strings.NewReader(content)) - for { - tok, err := dec.Token() - if err != nil { - if err == io.EOF { - break - } - return nil, fmt.Errorf("failed to decode next token: %v", err) - } - - lastNodeIndex := len(allNodes) - 1 - var lastNode *xmlNode - if len(allNodes) > 0 { - lastNode = allNodes[lastNodeIndex] - } else { - lastNode = &xmlNode{} - } - - switch tok := tok.(type) { - case xml.StartElement: - attrs := attributesSlice(tok.Attr) - sort.Sort(attrs) - allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr}) - case xml.EndElement: - if len(allNodes) > 1 { - allNodes[lastNodeIndex-1].Nodes = append(allNodes[lastNodeIndex-1].Nodes, lastNode) - allNodes = allNodes[:lastNodeIndex] - } - case xml.CharData: - lastNode.Content = append(lastNode.Content, tok.Copy()...) - case xml.Comment: - lastNode.Comments = append(lastNode.Comments, tok.Copy()) - case xml.ProcInst: - lastNode.ProcInsts = append(lastNode.ProcInsts, tok.Copy()) - } - } - - if len(allNodes) == 0 { - return nil, errors.New("found no nodes") - } - firstNode := allNodes[0] - trimParentNodesContentSpaces(firstNode) - - return firstNode, nil -} - -func newXmlDecoder(reader io.Reader) *xml.Decoder { - dec := xml.NewDecoder(reader) - dec.CharsetReader = charset.NewReaderLabel - return dec -} - -func trimParentNodesContentSpaces(node *xmlNode) { - if len(node.Nodes) > 0 { - node.Content = bytes.TrimSpace(node.Content) - for _, childNode := range node.Nodes { - trimParentNodesContentSpaces(childNode) - } - } -} - -type xmlNode struct { - XMLName xml.Name - Comments []xml.Comment - ProcInsts []xml.ProcInst - XMLAttr []xml.Attr - Content []byte - Nodes []*xmlNode -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go deleted file mode 100644 index 0c83c2b6..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go +++ /dev/null @@ -1,76 +0,0 @@ -package matchers - -import ( - "fmt" - "strings" - - "github.com/onsi/gomega/format" - "gopkg.in/yaml.v2" -) - -type MatchYAMLMatcher struct { - YAMLToMatch interface{} - firstFailurePath []interface{} -} - -func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.toStrings(actual) - if err != nil { - return false, err - } - - var aval interface{} - var eval interface{} - - if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { - return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) - } - if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil { - return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err) - } - - var equal bool - equal, matcher.firstFailurePath = deepEqual(aval, eval) - return equal, nil -} - -func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath) -} - -func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath) -} - -func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, expectedString, err := matcher.toStrings(actual) - return normalise(actualString), normalise(expectedString), err -} - -func normalise(input string) string { - var val interface{} - err := yaml.Unmarshal([]byte(input), &val) - if err != nil { - panic(err) // unreachable since Match already calls Unmarshal - } - output, err := yaml.Marshal(val) - if err != nil { - panic(err) // untested section, unreachable since we Unmarshal above - } - return strings.TrimSpace(string(output)) -} - -func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, ok := toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok := toString(matcher.YAMLToMatch) - if !ok { - return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1)) - } - - return actualString, expectedString, nil -} diff --git a/vendor/github.com/onsi/gomega/matchers/not.go b/vendor/github.com/onsi/gomega/matchers/not.go deleted file mode 100644 index 2c91670b..00000000 --- a/vendor/github.com/onsi/gomega/matchers/not.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers - -import ( - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type NotMatcher struct { - Matcher types.GomegaMatcher -} - -func (m *NotMatcher) Match(actual interface{}) (bool, error) { - success, err := m.Matcher.Match(actual) - if err != nil { - return false, err - } - return !success, nil -} - -func (m *NotMatcher) FailureMessage(actual interface{}) (message string) { - return m.Matcher.NegatedFailureMessage(actual) // works beautifully -} - -func (m *NotMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return m.Matcher.FailureMessage(actual) // works beautifully -} - -func (m *NotMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - return oraclematcher.MatchMayChangeInTheFuture(m.Matcher, actual) // just return m.Matcher's value -} diff --git a/vendor/github.com/onsi/gomega/matchers/or.go b/vendor/github.com/onsi/gomega/matchers/or.go deleted file mode 100644 index 3bf79980..00000000 --- a/vendor/github.com/onsi/gomega/matchers/or.go +++ /dev/null @@ -1,67 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type OrMatcher struct { - Matchers []types.GomegaMatcher - - // state - firstSuccessfulMatcher types.GomegaMatcher -} - -func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { - m.firstSuccessfulMatcher = nil - for _, matcher := range m.Matchers { - success, err := matcher.Match(actual) - if err != nil { - return false, err - } - if success { - m.firstSuccessfulMatcher = matcher - return true, nil - } - } - return false, nil -} - -func (m *OrMatcher) FailureMessage(actual interface{}) (message string) { - // not the most beautiful list of matchers, but not bad either... - return format.Message(actual, fmt.Sprintf("To satisfy at least one of these matchers: %s", m.Matchers)) -} - -func (m *OrMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return m.firstSuccessfulMatcher.NegatedFailureMessage(actual) -} - -func (m *OrMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - /* - Example with 3 matchers: A, B, C - - Match evaluates them: F, T, => T - So match is currently T, what should MatchMayChangeInTheFuture() return? - Seems like it only depends on B, since currently B MUST change to allow the result to become F - - Match eval: F, F, F => F - So match is currently F, what should MatchMayChangeInTheFuture() return? - Seems to depend on ANY of them being able to change to T. - */ - - if m.firstSuccessfulMatcher != nil { - // one of the matchers succeeded.. it must be able to change in order to affect the result - return oraclematcher.MatchMayChangeInTheFuture(m.firstSuccessfulMatcher, actual) - } else { - // so all matchers failed.. Any one of them changing would change the result. - for _, matcher := range m.Matchers { - if oraclematcher.MatchMayChangeInTheFuture(matcher, actual) { - return true - } - } - return false // none of were going to change - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go b/vendor/github.com/onsi/gomega/matchers/panic_matcher.go deleted file mode 100644 index 640f4db1..00000000 --- a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go +++ /dev/null @@ -1,46 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type PanicMatcher struct { - object interface{} -} - -func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil { - return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") - } - - actualType := reflect.TypeOf(actual) - if actualType.Kind() != reflect.Func { - return false, fmt.Errorf("PanicMatcher expects a function. Got:\n%s", format.Object(actual, 1)) - } - if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) { - return false, fmt.Errorf("PanicMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1)) - } - - success = false - defer func() { - if e := recover(); e != nil { - matcher.object = e - success = true - } - }() - - reflect.ValueOf(actual).Call([]reflect.Value{}) - - return -} - -func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to panic") -} - -func (matcher *PanicMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1))) -} diff --git a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go b/vendor/github.com/onsi/gomega/matchers/receive_matcher.go deleted file mode 100644 index 2018a612..00000000 --- a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go +++ /dev/null @@ -1,128 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type ReceiveMatcher struct { - Arg interface{} - receivedValue reflect.Value - channelClosed bool -} - -func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("ReceiveMatcher expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.SendDir { - return false, fmt.Errorf("ReceiveMatcher matcher cannot be passed a send-only channel. Got:\n%s", format.Object(actual, 1)) - } - - var subMatcher omegaMatcher - var hasSubMatcher bool - - if matcher.Arg != nil { - subMatcher, hasSubMatcher = (matcher.Arg).(omegaMatcher) - if !hasSubMatcher { - argType := reflect.TypeOf(matcher.Arg) - if argType.Kind() != reflect.Ptr { - return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s\nYou need to pass a pointer!", format.Object(actual, 1), format.Object(matcher.Arg, 1)) - } - } - } - - winnerIndex, value, open := reflect.Select([]reflect.SelectCase{ - {Dir: reflect.SelectRecv, Chan: channelValue}, - {Dir: reflect.SelectDefault}, - }) - - var closed bool - var didReceive bool - if winnerIndex == 0 { - closed = !open - didReceive = open - } - matcher.channelClosed = closed - - if closed { - return false, nil - } - - if hasSubMatcher { - if didReceive { - matcher.receivedValue = value - return subMatcher.Match(matcher.receivedValue.Interface()) - } - return false, nil - } - - if didReceive { - if matcher.Arg != nil { - outValue := reflect.ValueOf(matcher.Arg) - - if value.Type().AssignableTo(outValue.Elem().Type()) { - outValue.Elem().Set(value) - return true, nil - } - if value.Type().Kind() == reflect.Interface && value.Elem().Type().AssignableTo(outValue.Elem().Type()) { - outValue.Elem().Set(value.Elem()) - return true, nil - } else { - return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nType:\n%s\nTo:\n%s", format.Object(actual, 1), format.Object(value.Interface(), 1), format.Object(matcher.Arg, 1)) - } - - } - - return true, nil - } - return false, nil -} - -func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message string) { - subMatcher, hasSubMatcher := (matcher.Arg).(omegaMatcher) - - closedAddendum := "" - if matcher.channelClosed { - closedAddendum = " The channel is closed." - } - - if hasSubMatcher { - if matcher.receivedValue.IsValid() { - return subMatcher.FailureMessage(matcher.receivedValue.Interface()) - } - return "When passed a matcher, ReceiveMatcher's channel *must* receive something." - } - return format.Message(actual, "to receive something."+closedAddendum) -} - -func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (message string) { - subMatcher, hasSubMatcher := (matcher.Arg).(omegaMatcher) - - closedAddendum := "" - if matcher.channelClosed { - closedAddendum = " The channel is closed." - } - - if hasSubMatcher { - if matcher.receivedValue.IsValid() { - return subMatcher.NegatedFailureMessage(matcher.receivedValue.Interface()) - } - return "When passed a matcher, ReceiveMatcher's channel *must* receive something." - } - return format.Message(actual, "not to receive anything."+closedAddendum) -} - -func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - if !isChan(actual) { - return false - } - - return !matcher.channelClosed -} diff --git a/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go b/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go deleted file mode 100644 index 63929568..00000000 --- a/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go +++ /dev/null @@ -1,92 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - "strings" -) - -func formattedMessage(comparisonMessage string, failurePath []interface{}) string { - var diffMessage string - if len(failurePath) == 0 { - diffMessage = "" - } else { - diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath)) - } - return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) -} - -func formattedFailurePath(failurePath []interface{}) string { - formattedPaths := []string{} - for i := len(failurePath) - 1; i >= 0; i-- { - switch p := failurePath[i].(type) { - case int: - formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p)) - default: - if i != len(failurePath)-1 { - formattedPaths = append(formattedPaths, ".") - } - formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p)) - } - } - return strings.Join(formattedPaths, "") -} - -func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { - var errorPath []interface{} - if reflect.TypeOf(a) != reflect.TypeOf(b) { - return false, errorPath - } - - switch a.(type) { - case []interface{}: - if len(a.([]interface{})) != len(b.([]interface{})) { - return false, errorPath - } - - for i, v := range a.([]interface{}) { - elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) - if !elementEqual { - return false, append(keyPath, i) - } - } - return true, errorPath - - case map[interface{}]interface{}: - if len(a.(map[interface{}]interface{})) != len(b.(map[interface{}]interface{})) { - return false, errorPath - } - - for k, v1 := range a.(map[interface{}]interface{}) { - v2, ok := b.(map[interface{}]interface{})[k] - if !ok { - return false, errorPath - } - elementEqual, keyPath := deepEqual(v1, v2) - if !elementEqual { - return false, append(keyPath, k) - } - } - return true, errorPath - - case map[string]interface{}: - if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { - return false, errorPath - } - - for k, v1 := range a.(map[string]interface{}) { - v2, ok := b.(map[string]interface{})[k] - if !ok { - return false, errorPath - } - elementEqual, keyPath := deepEqual(v1, v2) - if !elementEqual { - return false, append(keyPath, k) - } - } - return true, errorPath - - default: - return a == b, errorPath - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go b/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go deleted file mode 100644 index 721ed552..00000000 --- a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type SucceedMatcher struct { -} - -func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) { - // is purely nil? - if actual == nil { - return true, nil - } - - // must be an 'error' type - if !isError(actual) { - return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) - } - - // must be nil (or a pointer to a nil) - return isNil(actual), nil -} - -func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected success, but got an error:\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1)) -} - -func (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return "Expected failure, but got no error." -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go deleted file mode 100644 index 8aaf8759..00000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go +++ /dev/null @@ -1,41 +0,0 @@ -package bipartitegraph - -import "errors" -import "fmt" - -import . "github.com/onsi/gomega/matchers/support/goraph/node" -import . "github.com/onsi/gomega/matchers/support/goraph/edge" - -type BipartiteGraph struct { - Left NodeOrderedSet - Right NodeOrderedSet - Edges EdgeSet -} - -func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) { - left := NodeOrderedSet{} - for i := range leftValues { - left = append(left, Node{Id: i}) - } - - right := NodeOrderedSet{} - for j := range rightValues { - right = append(right, Node{Id: j + len(left)}) - } - - edges := EdgeSet{} - for i, leftValue := range leftValues { - for j, rightValue := range rightValues { - neighbours, err := neighbours(leftValue, rightValue) - if err != nil { - return nil, errors.New(fmt.Sprintf("error determining adjacency for %v and %v: %s", leftValue, rightValue, err.Error())) - } - - if neighbours { - edges = append(edges, Edge{Node1: left[i], Node2: right[j]}) - } - } - } - - return &BipartiteGraph{left, right, edges}, nil -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go deleted file mode 100644 index 8181f43a..00000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go +++ /dev/null @@ -1,159 +0,0 @@ -package bipartitegraph - -import . "github.com/onsi/gomega/matchers/support/goraph/node" -import . "github.com/onsi/gomega/matchers/support/goraph/edge" -import "github.com/onsi/gomega/matchers/support/goraph/util" - -func (bg *BipartiteGraph) LargestMatching() (matching EdgeSet) { - paths := bg.maximalDisjointSLAPCollection(matching) - - for len(paths) > 0 { - for _, path := range paths { - matching = matching.SymmetricDifference(path) - } - paths = bg.maximalDisjointSLAPCollection(matching) - } - - return -} - -func (bg *BipartiteGraph) maximalDisjointSLAPCollection(matching EdgeSet) (result []EdgeSet) { - guideLayers := bg.createSLAPGuideLayers(matching) - if len(guideLayers) == 0 { - return - } - - used := make(map[Node]bool) - - for _, u := range guideLayers[len(guideLayers)-1] { - slap, found := bg.findDisjointSLAP(u, matching, guideLayers, used) - if found { - for _, edge := range slap { - used[edge.Node1] = true - used[edge.Node2] = true - } - result = append(result, slap) - } - } - - return -} - -func (bg *BipartiteGraph) findDisjointSLAP( - start Node, - matching EdgeSet, - guideLayers []NodeOrderedSet, - used map[Node]bool, -) ([]Edge, bool) { - return bg.findDisjointSLAPHelper(start, EdgeSet{}, len(guideLayers)-1, matching, guideLayers, used) -} - -func (bg *BipartiteGraph) findDisjointSLAPHelper( - currentNode Node, - currentSLAP EdgeSet, - currentLevel int, - matching EdgeSet, - guideLayers []NodeOrderedSet, - used map[Node]bool, -) (EdgeSet, bool) { - used[currentNode] = true - - if currentLevel == 0 { - return currentSLAP, true - } - - for _, nextNode := range guideLayers[currentLevel-1] { - if used[nextNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(currentNode, nextNode) - if !found { - continue - } - - if matching.Contains(edge) == util.Odd(currentLevel) { - continue - } - - currentSLAP = append(currentSLAP, edge) - slap, found := bg.findDisjointSLAPHelper(nextNode, currentSLAP, currentLevel-1, matching, guideLayers, used) - if found { - return slap, true - } - currentSLAP = currentSLAP[:len(currentSLAP)-1] - } - - used[currentNode] = false - return nil, false -} - -func (bg *BipartiteGraph) createSLAPGuideLayers(matching EdgeSet) (guideLayers []NodeOrderedSet) { - used := make(map[Node]bool) - currentLayer := NodeOrderedSet{} - - for _, node := range bg.Left { - if matching.Free(node) { - used[node] = true - currentLayer = append(currentLayer, node) - } - } - - if len(currentLayer) == 0 { - return []NodeOrderedSet{} - } - guideLayers = append(guideLayers, currentLayer) - - done := false - - for !done { - lastLayer := currentLayer - currentLayer = NodeOrderedSet{} - - if util.Odd(len(guideLayers)) { - for _, leftNode := range lastLayer { - for _, rightNode := range bg.Right { - if used[rightNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(leftNode, rightNode) - if !found || matching.Contains(edge) { - continue - } - - currentLayer = append(currentLayer, rightNode) - used[rightNode] = true - - if matching.Free(rightNode) { - done = true - } - } - } - } else { - for _, rightNode := range lastLayer { - for _, leftNode := range bg.Left { - if used[leftNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(leftNode, rightNode) - if !found || !matching.Contains(edge) { - continue - } - - currentLayer = append(currentLayer, leftNode) - used[leftNode] = true - } - } - - } - - if len(currentLayer) == 0 { - return []NodeOrderedSet{} - } - guideLayers = append(guideLayers, currentLayer) - } - - return -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go deleted file mode 100644 index 4fd15cc0..00000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go +++ /dev/null @@ -1,61 +0,0 @@ -package edge - -import . "github.com/onsi/gomega/matchers/support/goraph/node" - -type Edge struct { - Node1 Node - Node2 Node -} - -type EdgeSet []Edge - -func (ec EdgeSet) Free(node Node) bool { - for _, e := range ec { - if e.Node1 == node || e.Node2 == node { - return false - } - } - - return true -} - -func (ec EdgeSet) Contains(edge Edge) bool { - for _, e := range ec { - if e == edge { - return true - } - } - - return false -} - -func (ec EdgeSet) FindByNodes(node1, node2 Node) (Edge, bool) { - for _, e := range ec { - if (e.Node1 == node1 && e.Node2 == node2) || (e.Node1 == node2 && e.Node2 == node1) { - return e, true - } - } - - return Edge{}, false -} - -func (ec EdgeSet) SymmetricDifference(ec2 EdgeSet) EdgeSet { - edgesToInclude := make(map[Edge]bool) - - for _, e := range ec { - edgesToInclude[e] = true - } - - for _, e := range ec2 { - edgesToInclude[e] = !edgesToInclude[e] - } - - result := EdgeSet{} - for e, include := range edgesToInclude { - if include { - result = append(result, e) - } - } - - return result -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go deleted file mode 100644 index 800c2ea8..00000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go +++ /dev/null @@ -1,7 +0,0 @@ -package node - -type Node struct { - Id int -} - -type NodeOrderedSet []Node diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go deleted file mode 100644 index d76a1ee0..00000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go +++ /dev/null @@ -1,7 +0,0 @@ -package util - -import "math" - -func Odd(n int) bool { - return math.Mod(float64(n), 2.0) == 1.0 -} diff --git a/vendor/github.com/onsi/gomega/matchers/type_support.go b/vendor/github.com/onsi/gomega/matchers/type_support.go deleted file mode 100644 index 75afcd84..00000000 --- a/vendor/github.com/onsi/gomega/matchers/type_support.go +++ /dev/null @@ -1,179 +0,0 @@ -/* -Gomega matchers - -This package implements the Gomega matchers and does not typically need to be imported. -See the docs for Gomega for documentation on the matchers - -http://onsi.github.io/gomega/ -*/ -package matchers - -import ( - "encoding/json" - "fmt" - "reflect" -) - -type omegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) -} - -func isBool(a interface{}) bool { - return reflect.TypeOf(a).Kind() == reflect.Bool -} - -func isNumber(a interface{}) bool { - if a == nil { - return false - } - kind := reflect.TypeOf(a).Kind() - return reflect.Int <= kind && kind <= reflect.Float64 -} - -func isInteger(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Int <= kind && kind <= reflect.Int64 -} - -func isUnsignedInteger(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Uint <= kind && kind <= reflect.Uint64 -} - -func isFloat(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Float32 <= kind && kind <= reflect.Float64 -} - -func toInteger(a interface{}) int64 { - if isInteger(a) { - return reflect.ValueOf(a).Int() - } else if isUnsignedInteger(a) { - return int64(reflect.ValueOf(a).Uint()) - } else if isFloat(a) { - return int64(reflect.ValueOf(a).Float()) - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func toUnsignedInteger(a interface{}) uint64 { - if isInteger(a) { - return uint64(reflect.ValueOf(a).Int()) - } else if isUnsignedInteger(a) { - return reflect.ValueOf(a).Uint() - } else if isFloat(a) { - return uint64(reflect.ValueOf(a).Float()) - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func toFloat(a interface{}) float64 { - if isInteger(a) { - return float64(reflect.ValueOf(a).Int()) - } else if isUnsignedInteger(a) { - return float64(reflect.ValueOf(a).Uint()) - } else if isFloat(a) { - return reflect.ValueOf(a).Float() - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func isError(a interface{}) bool { - _, ok := a.(error) - return ok -} - -func isChan(a interface{}) bool { - if isNil(a) { - return false - } - return reflect.TypeOf(a).Kind() == reflect.Chan -} - -func isMap(a interface{}) bool { - if a == nil { - return false - } - return reflect.TypeOf(a).Kind() == reflect.Map -} - -func isArrayOrSlice(a interface{}) bool { - if a == nil { - return false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Array, reflect.Slice: - return true - default: - return false - } -} - -func isString(a interface{}) bool { - if a == nil { - return false - } - return reflect.TypeOf(a).Kind() == reflect.String -} - -func toString(a interface{}) (string, bool) { - aString, isString := a.(string) - if isString { - return aString, true - } - - aBytes, isBytes := a.([]byte) - if isBytes { - return string(aBytes), true - } - - aStringer, isStringer := a.(fmt.Stringer) - if isStringer { - return aStringer.String(), true - } - - aJSONRawMessage, isJSONRawMessage := a.(json.RawMessage) - if isJSONRawMessage { - return string(aJSONRawMessage), true - } - - return "", false -} - -func lengthOf(a interface{}) (int, bool) { - if a == nil { - return 0, false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Map, reflect.Array, reflect.String, reflect.Chan, reflect.Slice: - return reflect.ValueOf(a).Len(), true - default: - return 0, false - } -} -func capOf(a interface{}) (int, bool) { - if a == nil { - return 0, false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Array, reflect.Chan, reflect.Slice: - return reflect.ValueOf(a).Cap(), true - default: - return 0, false - } -} - -func isNil(a interface{}) bool { - if a == nil { - return true - } - - switch reflect.TypeOf(a).Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return reflect.ValueOf(a).IsNil() - } - - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/with_transform.go b/vendor/github.com/onsi/gomega/matchers/with_transform.go deleted file mode 100644 index 8e58d8a0..00000000 --- a/vendor/github.com/onsi/gomega/matchers/with_transform.go +++ /dev/null @@ -1,72 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type WithTransformMatcher struct { - // input - Transform interface{} // must be a function of one parameter that returns one value - Matcher types.GomegaMatcher - - // cached value - transformArgType reflect.Type - - // state - transformedValue interface{} -} - -func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher { - if transform == nil { - panic("transform function cannot be nil") - } - txType := reflect.TypeOf(transform) - if txType.NumIn() != 1 { - panic("transform function must have 1 argument") - } - if txType.NumOut() != 1 { - panic("transform function must have 1 return value") - } - - return &WithTransformMatcher{ - Transform: transform, - Matcher: matcher, - transformArgType: reflect.TypeOf(transform).In(0), - } -} - -func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { - // return error if actual's type is incompatible with Transform function's argument type - actualType := reflect.TypeOf(actual) - if !actualType.AssignableTo(m.transformArgType) { - return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType) - } - - // call the Transform function with `actual` - fn := reflect.ValueOf(m.Transform) - result := fn.Call([]reflect.Value{reflect.ValueOf(actual)}) - m.transformedValue = result[0].Interface() // expect exactly one value - - return m.Matcher.Match(m.transformedValue) -} - -func (m *WithTransformMatcher) FailureMessage(_ interface{}) (message string) { - return m.Matcher.FailureMessage(m.transformedValue) -} - -func (m *WithTransformMatcher) NegatedFailureMessage(_ interface{}) (message string) { - return m.Matcher.NegatedFailureMessage(m.transformedValue) -} - -func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ interface{}) bool { - // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.) - // - // Querying the next matcher is fine if the transformer always will return the same value. - // But if the transformer is non-deterministic and returns a different value each time, then there - // is no point in querying the next matcher, since it can only comment on the last transformed value. - return oraclematcher.MatchMayChangeInTheFuture(m.Matcher, m.transformedValue) -} diff --git a/vendor/github.com/onsi/gomega/types/types.go b/vendor/github.com/onsi/gomega/types/types.go deleted file mode 100644 index ac59a3a5..00000000 --- a/vendor/github.com/onsi/gomega/types/types.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -type TWithHelper interface { - Helper() -} - -type GomegaFailHandler func(message string, callerSkip ...int) - -type GomegaFailWrapper struct { - Fail GomegaFailHandler - TWithHelper TWithHelper -} - -//A simple *testing.T interface wrapper -type GomegaTestingT interface { - Fatalf(format string, args ...interface{}) -} - -//All Gomega matchers must implement the GomegaMatcher interface -// -//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers -type GomegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) -} diff --git a/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS b/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS deleted file mode 100644 index 2b16e997..00000000 --- a/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -This is a list of people who have contributed code to go-cache. They, or their -employers, are the copyright holders of the contributed code. Contributed code -is subject to the license restrictions listed in LICENSE (as they were when the -code was contributed.) - -Dustin Sallings -Jason Mooberry -Sergey Shepelev -Alex Edwards diff --git a/vendor/github.com/patrickmn/go-cache/LICENSE b/vendor/github.com/patrickmn/go-cache/LICENSE deleted file mode 100644 index db9903c7..00000000 --- a/vendor/github.com/patrickmn/go-cache/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012-2017 Patrick Mylund Nielsen and the go-cache contributors - -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/patrickmn/go-cache/README.md b/vendor/github.com/patrickmn/go-cache/README.md deleted file mode 100644 index c5789cc6..00000000 --- a/vendor/github.com/patrickmn/go-cache/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# go-cache - -go-cache is an in-memory key:value store/cache similar to memcached that is -suitable for applications running on a single machine. Its major advantage is -that, being essentially a thread-safe `map[string]interface{}` with expiration -times, it doesn't need to serialize or transmit its contents over the network. - -Any object can be stored, for a given duration or forever, and the cache can be -safely used by multiple goroutines. - -Although go-cache isn't meant to be used as a persistent datastore, the entire -cache can be saved to and loaded from a file (using `c.Items()` to retrieve the -items map to serialize, and `NewFrom()` to create a cache from a deserialized -one) to recover from downtime quickly. (See the docs for `NewFrom()` for caveats.) - -### Installation - -`go get github.com/patrickmn/go-cache` - -### Usage - -```go -import ( - "fmt" - "github.com/patrickmn/go-cache" - "time" -) - -func main() { - // Create a cache with a default expiration time of 5 minutes, and which - // purges expired items every 10 minutes - c := cache.New(5*time.Minute, 10*time.Minute) - - // Set the value of the key "foo" to "bar", with the default expiration time - c.Set("foo", "bar", cache.DefaultExpiration) - - // Set the value of the key "baz" to 42, with no expiration time - // (the item won't be removed until it is re-set, or removed using - // c.Delete("baz") - c.Set("baz", 42, cache.NoExpiration) - - // Get the string associated with the key "foo" from the cache - foo, found := c.Get("foo") - if found { - fmt.Println(foo) - } - - // Since Go is statically typed, and cache values can be anything, type - // assertion is needed when values are being passed to functions that don't - // take arbitrary types, (i.e. interface{}). The simplest way to do this for - // values which will only be used once--e.g. for passing to another - // function--is: - foo, found := c.Get("foo") - if found { - MyFunction(foo.(string)) - } - - // This gets tedious if the value is used several times in the same function. - // You might do either of the following instead: - if x, found := c.Get("foo"); found { - foo := x.(string) - // ... - } - // or - var foo string - if x, found := c.Get("foo"); found { - foo = x.(string) - } - // ... - // foo can then be passed around freely as a string - - // Want performance? Store pointers! - c.Set("foo", &MyStruct, cache.DefaultExpiration) - if x, found := c.Get("foo"); found { - foo := x.(*MyStruct) - // ... - } -} -``` - -### Reference - -`godoc` or [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache) diff --git a/vendor/github.com/patrickmn/go-cache/cache.go b/vendor/github.com/patrickmn/go-cache/cache.go deleted file mode 100644 index db88d2f2..00000000 --- a/vendor/github.com/patrickmn/go-cache/cache.go +++ /dev/null @@ -1,1161 +0,0 @@ -package cache - -import ( - "encoding/gob" - "fmt" - "io" - "os" - "runtime" - "sync" - "time" -) - -type Item struct { - Object interface{} - Expiration int64 -} - -// Returns true if the item has expired. -func (item Item) Expired() bool { - if item.Expiration == 0 { - return false - } - return time.Now().UnixNano() > item.Expiration -} - -const ( - // For use with functions that take an expiration time. - NoExpiration time.Duration = -1 - // For use with functions that take an expiration time. Equivalent to - // passing in the same expiration duration as was given to New() or - // NewFrom() when the cache was created (e.g. 5 minutes.) - DefaultExpiration time.Duration = 0 -) - -type Cache struct { - *cache - // If this is confusing, see the comment at the bottom of New() -} - -type cache struct { - defaultExpiration time.Duration - items map[string]Item - mu sync.RWMutex - onEvicted func(string, interface{}) - janitor *janitor -} - -// Add an item to the cache, replacing any existing item. If the duration is 0 -// (DefaultExpiration), the cache's default expiration time is used. If it is -1 -// (NoExpiration), the item never expires. -func (c *cache) Set(k string, x interface{}, d time.Duration) { - // "Inlining" of set - var e int64 - if d == DefaultExpiration { - d = c.defaultExpiration - } - if d > 0 { - e = time.Now().Add(d).UnixNano() - } - c.mu.Lock() - c.items[k] = Item{ - Object: x, - Expiration: e, - } - // TODO: Calls to mu.Unlock are currently not deferred because defer - // adds ~200 ns (as of go1.) - c.mu.Unlock() -} - -func (c *cache) set(k string, x interface{}, d time.Duration) { - var e int64 - if d == DefaultExpiration { - d = c.defaultExpiration - } - if d > 0 { - e = time.Now().Add(d).UnixNano() - } - c.items[k] = Item{ - Object: x, - Expiration: e, - } -} - -// Add an item to the cache, replacing any existing item, using the default -// expiration. -func (c *cache) SetDefault(k string, x interface{}) { - c.Set(k, x, DefaultExpiration) -} - -// Add an item to the cache only if an item doesn't already exist for the given -// key, or if the existing item has expired. Returns an error otherwise. -func (c *cache) Add(k string, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if found { - c.mu.Unlock() - return fmt.Errorf("Item %s already exists", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - -// Set a new value for the cache key only if it already exists, and the existing -// item hasn't expired. Returns an error otherwise. -func (c *cache) Replace(k string, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if !found { - c.mu.Unlock() - return fmt.Errorf("Item %s doesn't exist", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - -// Get an item from the cache. Returns the item or nil, and a bool indicating -// whether the key was found. -func (c *cache) Get(k string) (interface{}, bool) { - c.mu.RLock() - // "Inlining" of get and Expired - item, found := c.items[k] - if !found { - c.mu.RUnlock() - return nil, false - } - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - c.mu.RUnlock() - return nil, false - } - } - c.mu.RUnlock() - return item.Object, true -} - -// GetWithExpiration returns an item and its expiration time from the cache. -// It returns the item or nil, the expiration time if one is set (if the item -// never expires a zero value for time.Time is returned), and a bool indicating -// whether the key was found. -func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) { - c.mu.RLock() - // "Inlining" of get and Expired - item, found := c.items[k] - if !found { - c.mu.RUnlock() - return nil, time.Time{}, false - } - - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - c.mu.RUnlock() - return nil, time.Time{}, false - } - - // Return the item and the expiration time - c.mu.RUnlock() - return item.Object, time.Unix(0, item.Expiration), true - } - - // If expiration <= 0 (i.e. no expiration time set) then return the item - // and a zeroed time.Time - c.mu.RUnlock() - return item.Object, time.Time{}, true -} - -func (c *cache) get(k string) (interface{}, bool) { - item, found := c.items[k] - if !found { - return nil, false - } - // "Inlining" of Expired - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - return nil, false - } - } - return item.Object, true -} - -// Increment an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to increment it by n. To retrieve the incremented value, use one -// of the specialized methods, e.g. IncrementInt64. -func (c *cache) Increment(k string, n int64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) + int(n) - case int8: - v.Object = v.Object.(int8) + int8(n) - case int16: - v.Object = v.Object.(int16) + int16(n) - case int32: - v.Object = v.Object.(int32) + int32(n) - case int64: - v.Object = v.Object.(int64) + n - case uint: - v.Object = v.Object.(uint) + uint(n) - case uintptr: - v.Object = v.Object.(uintptr) + uintptr(n) - case uint8: - v.Object = v.Object.(uint8) + uint8(n) - case uint16: - v.Object = v.Object.(uint16) + uint16(n) - case uint32: - v.Object = v.Object.(uint32) + uint32(n) - case uint64: - v.Object = v.Object.(uint64) + uint64(n) - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to increment it by n. Pass a negative number to decrement the -// value. To retrieve the incremented value, use one of the specialized methods, -// e.g. IncrementFloat64. -func (c *cache) IncrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint8 by n. Returns an error if the item's value -// is not an uint8, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to decrement it by n. To retrieve the decremented value, use one -// of the specialized methods, e.g. DecrementInt64. -func (c *cache) Decrement(k string, n int64) error { - // TODO: Implement Increment and Decrement more cleanly. - // (Cannot do Increment(k, n*-1) for uints.) - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item not found") - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) - int(n) - case int8: - v.Object = v.Object.(int8) - int8(n) - case int16: - v.Object = v.Object.(int16) - int16(n) - case int32: - v.Object = v.Object.(int32) - int32(n) - case int64: - v.Object = v.Object.(int64) - n - case uint: - v.Object = v.Object.(uint) - uint(n) - case uintptr: - v.Object = v.Object.(uintptr) - uintptr(n) - case uint8: - v.Object = v.Object.(uint8) - uint8(n) - case uint16: - v.Object = v.Object.(uint16) - uint16(n) - case uint32: - v.Object = v.Object.(uint32) - uint32(n) - case uint64: - v.Object = v.Object.(uint64) - uint64(n) - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to decrement it by n. Pass a negative number to decrement the -// value. To retrieve the decremented value, use one of the specialized methods, -// e.g. DecrementFloat64. -func (c *cache) DecrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint8 by n. Returns an error if the item's value is -// not an uint8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Delete an item from the cache. Does nothing if the key is not in the cache. -func (c *cache) Delete(k string) { - c.mu.Lock() - v, evicted := c.delete(k) - c.mu.Unlock() - if evicted { - c.onEvicted(k, v) - } -} - -func (c *cache) delete(k string) (interface{}, bool) { - if c.onEvicted != nil { - if v, found := c.items[k]; found { - delete(c.items, k) - return v.Object, true - } - } - delete(c.items, k) - return nil, false -} - -type keyAndValue struct { - key string - value interface{} -} - -// Delete all expired items from the cache. -func (c *cache) DeleteExpired() { - var evictedItems []keyAndValue - now := time.Now().UnixNano() - c.mu.Lock() - for k, v := range c.items { - // "Inlining" of expired - if v.Expiration > 0 && now > v.Expiration { - ov, evicted := c.delete(k) - if evicted { - evictedItems = append(evictedItems, keyAndValue{k, ov}) - } - } - } - c.mu.Unlock() - for _, v := range evictedItems { - c.onEvicted(v.key, v.value) - } -} - -// Sets an (optional) function that is called with the key and value when an -// item is evicted from the cache. (Including when it is deleted manually, but -// not when it is overwritten.) Set to nil to disable. -func (c *cache) OnEvicted(f func(string, interface{})) { - c.mu.Lock() - c.onEvicted = f - c.mu.Unlock() -} - -// Write the cache's items (using Gob) to an io.Writer. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) Save(w io.Writer) (err error) { - enc := gob.NewEncoder(w) - defer func() { - if x := recover(); x != nil { - err = fmt.Errorf("Error registering item types with Gob library") - } - }() - c.mu.RLock() - defer c.mu.RUnlock() - for _, v := range c.items { - gob.Register(v.Object) - } - err = enc.Encode(&c.items) - return -} - -// Save the cache's items to the given filename, creating the file if it -// doesn't exist, and overwriting it if it does. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) SaveFile(fname string) error { - fp, err := os.Create(fname) - if err != nil { - return err - } - err = c.Save(fp) - if err != nil { - fp.Close() - return err - } - return fp.Close() -} - -// Add (Gob-serialized) cache items from an io.Reader, excluding any items with -// keys that already exist (and haven't expired) in the current cache. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) Load(r io.Reader) error { - dec := gob.NewDecoder(r) - items := map[string]Item{} - err := dec.Decode(&items) - if err == nil { - c.mu.Lock() - defer c.mu.Unlock() - for k, v := range items { - ov, found := c.items[k] - if !found || ov.Expired() { - c.items[k] = v - } - } - } - return err -} - -// Load and add cache items from the given filename, excluding any items with -// keys that already exist in the current cache. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) LoadFile(fname string) error { - fp, err := os.Open(fname) - if err != nil { - return err - } - err = c.Load(fp) - if err != nil { - fp.Close() - return err - } - return fp.Close() -} - -// Copies all unexpired items in the cache into a new map and returns it. -func (c *cache) Items() map[string]Item { - c.mu.RLock() - defer c.mu.RUnlock() - m := make(map[string]Item, len(c.items)) - now := time.Now().UnixNano() - for k, v := range c.items { - // "Inlining" of Expired - if v.Expiration > 0 { - if now > v.Expiration { - continue - } - } - m[k] = v - } - return m -} - -// Returns the number of items in the cache. This may include items that have -// expired, but have not yet been cleaned up. -func (c *cache) ItemCount() int { - c.mu.RLock() - n := len(c.items) - c.mu.RUnlock() - return n -} - -// Delete all items from the cache. -func (c *cache) Flush() { - c.mu.Lock() - c.items = map[string]Item{} - c.mu.Unlock() -} - -type janitor struct { - Interval time.Duration - stop chan bool -} - -func (j *janitor) Run(c *cache) { - ticker := time.NewTicker(j.Interval) - for { - select { - case <-ticker.C: - c.DeleteExpired() - case <-j.stop: - ticker.Stop() - return - } - } -} - -func stopJanitor(c *Cache) { - c.janitor.stop <- true -} - -func runJanitor(c *cache, ci time.Duration) { - j := &janitor{ - Interval: ci, - stop: make(chan bool), - } - c.janitor = j - go j.Run(c) -} - -func newCache(de time.Duration, m map[string]Item) *cache { - if de == 0 { - de = -1 - } - c := &cache{ - defaultExpiration: de, - items: m, - } - return c -} - -func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) *Cache { - c := newCache(de, m) - // This trick ensures that the janitor goroutine (which--granted it - // was enabled--is running DeleteExpired on c forever) does not keep - // the returned C object from being garbage collected. When it is - // garbage collected, the finalizer stops the janitor goroutine, after - // which c can be collected. - C := &Cache{c} - if ci > 0 { - runJanitor(c, ci) - runtime.SetFinalizer(C, stopJanitor) - } - return C -} - -// Return a new cache with a given default expiration duration and cleanup -// interval. If the expiration duration is less than one (or NoExpiration), -// the items in the cache never expire (by default), and must be deleted -// manually. If the cleanup interval is less than one, expired items are not -// deleted from the cache before calling c.DeleteExpired(). -func New(defaultExpiration, cleanupInterval time.Duration) *Cache { - items := make(map[string]Item) - return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) -} - -// Return a new cache with a given default expiration duration and cleanup -// interval. If the expiration duration is less than one (or NoExpiration), -// the items in the cache never expire (by default), and must be deleted -// manually. If the cleanup interval is less than one, expired items are not -// deleted from the cache before calling c.DeleteExpired(). -// -// NewFrom() also accepts an items map which will serve as the underlying map -// for the cache. This is useful for starting from a deserialized cache -// (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. -// make(map[string]Item, 500) to improve startup performance when the cache -// is expected to reach a certain minimum size. -// -// Only the cache's methods synchronize access to this map, so it is not -// recommended to keep any references to the map around after creating a cache. -// If need be, the map can be accessed at a later point using c.Items() (subject -// to the same caveat.) -// -// Note regarding serialization: When using e.g. gob, make sure to -// gob.Register() the individual types stored in the cache before encoding a -// map retrieved with c.Items(), and to register those same types before -// decoding a blob containing an items map. -func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache { - return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) -} diff --git a/vendor/github.com/patrickmn/go-cache/sharded.go b/vendor/github.com/patrickmn/go-cache/sharded.go deleted file mode 100644 index bcc0538b..00000000 --- a/vendor/github.com/patrickmn/go-cache/sharded.go +++ /dev/null @@ -1,192 +0,0 @@ -package cache - -import ( - "crypto/rand" - "math" - "math/big" - insecurerand "math/rand" - "os" - "runtime" - "time" -) - -// This is an experimental and unexported (for now) attempt at making a cache -// with better algorithmic complexity than the standard one, namely by -// preventing write locks of the entire cache when an item is added. As of the -// time of writing, the overhead of selecting buckets results in cache -// operations being about twice as slow as for the standard cache with small -// total cache sizes, and faster for larger ones. -// -// See cache_test.go for a few benchmarks. - -type unexportedShardedCache struct { - *shardedCache -} - -type shardedCache struct { - seed uint32 - m uint32 - cs []*cache - janitor *shardedJanitor -} - -// djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead. -func djb33(seed uint32, k string) uint32 { - var ( - l = uint32(len(k)) - d = 5381 + seed + l - i = uint32(0) - ) - // Why is all this 5x faster than a for loop? - if l >= 4 { - for i < l-4 { - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - d = (d * 33) ^ uint32(k[i+2]) - d = (d * 33) ^ uint32(k[i+3]) - i += 4 - } - } - switch l - i { - case 1: - case 2: - d = (d * 33) ^ uint32(k[i]) - case 3: - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - case 4: - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - d = (d * 33) ^ uint32(k[i+2]) - } - return d ^ (d >> 16) -} - -func (sc *shardedCache) bucket(k string) *cache { - return sc.cs[djb33(sc.seed, k)%sc.m] -} - -func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) { - sc.bucket(k).Set(k, x, d) -} - -func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error { - return sc.bucket(k).Add(k, x, d) -} - -func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error { - return sc.bucket(k).Replace(k, x, d) -} - -func (sc *shardedCache) Get(k string) (interface{}, bool) { - return sc.bucket(k).Get(k) -} - -func (sc *shardedCache) Increment(k string, n int64) error { - return sc.bucket(k).Increment(k, n) -} - -func (sc *shardedCache) IncrementFloat(k string, n float64) error { - return sc.bucket(k).IncrementFloat(k, n) -} - -func (sc *shardedCache) Decrement(k string, n int64) error { - return sc.bucket(k).Decrement(k, n) -} - -func (sc *shardedCache) Delete(k string) { - sc.bucket(k).Delete(k) -} - -func (sc *shardedCache) DeleteExpired() { - for _, v := range sc.cs { - v.DeleteExpired() - } -} - -// Returns the items in the cache. This may include items that have expired, -// but have not yet been cleaned up. If this is significant, the Expiration -// fields of the items should be checked. Note that explicit synchronization -// is needed to use a cache and its corresponding Items() return values at -// the same time, as the maps are shared. -func (sc *shardedCache) Items() []map[string]Item { - res := make([]map[string]Item, len(sc.cs)) - for i, v := range sc.cs { - res[i] = v.Items() - } - return res -} - -func (sc *shardedCache) Flush() { - for _, v := range sc.cs { - v.Flush() - } -} - -type shardedJanitor struct { - Interval time.Duration - stop chan bool -} - -func (j *shardedJanitor) Run(sc *shardedCache) { - j.stop = make(chan bool) - tick := time.Tick(j.Interval) - for { - select { - case <-tick: - sc.DeleteExpired() - case <-j.stop: - return - } - } -} - -func stopShardedJanitor(sc *unexportedShardedCache) { - sc.janitor.stop <- true -} - -func runShardedJanitor(sc *shardedCache, ci time.Duration) { - j := &shardedJanitor{ - Interval: ci, - } - sc.janitor = j - go j.Run(sc) -} - -func newShardedCache(n int, de time.Duration) *shardedCache { - max := big.NewInt(0).SetUint64(uint64(math.MaxUint32)) - rnd, err := rand.Int(rand.Reader, max) - var seed uint32 - if err != nil { - os.Stderr.Write([]byte("WARNING: go-cache's newShardedCache failed to read from the system CSPRNG (/dev/urandom or equivalent.) Your system's security may be compromised. Continuing with an insecure seed.\n")) - seed = insecurerand.Uint32() - } else { - seed = uint32(rnd.Uint64()) - } - sc := &shardedCache{ - seed: seed, - m: uint32(n), - cs: make([]*cache, n), - } - for i := 0; i < n; i++ { - c := &cache{ - defaultExpiration: de, - items: map[string]Item{}, - } - sc.cs[i] = c - } - return sc -} - -func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache { - if defaultExpiration == 0 { - defaultExpiration = -1 - } - sc := newShardedCache(shards, defaultExpiration) - SC := &unexportedShardedCache{sc} - if cleanupInterval > 0 { - runShardedJanitor(sc, cleanupInterval) - runtime.SetFinalizer(SC, stopShardedJanitor) - } - return SC -} diff --git a/vendor/github.com/pierrec/lz4/.gitignore b/vendor/github.com/pierrec/lz4/.gitignore deleted file mode 100644 index e48bab32..00000000 --- a/vendor/github.com/pierrec/lz4/.gitignore +++ /dev/null @@ -1,33 +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 - -lz4c/lz4c diff --git a/vendor/github.com/pierrec/lz4/.travis.yml b/vendor/github.com/pierrec/lz4/.travis.yml deleted file mode 100644 index b2c806d5..00000000 --- a/vendor/github.com/pierrec/lz4/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go - -go: - - 1.8.x - - 1.9.x - - 1.10.x - - master - -matrix: - fast_finish: true - allow_failures: - - go: master - -sudo: false - -script: - - go test -v -cpu=2 - - go test -v -cpu=2 -race diff --git a/vendor/github.com/pierrec/lz4/LICENSE b/vendor/github.com/pierrec/lz4/LICENSE deleted file mode 100644 index bd899d83..00000000 --- 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 50a10ee1..00000000 --- a/vendor/github.com/pierrec/lz4/README.md +++ /dev/null @@ -1,24 +0,0 @@ -[![godoc](https://godoc.org/github.com/pierrec/lz4?status.png)](https://godoc.org/github.com/pierrec/lz4) - -# lz4 -LZ4 compression and decompression in pure Go. - -## Usage - -```go -import "github.com/pierrec/lz4" -``` - -## Description -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. - -This package is **compatible with the LZ4 frame format** 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. - diff --git a/vendor/github.com/pierrec/lz4/block.go b/vendor/github.com/pierrec/lz4/block.go deleted file mode 100644 index ef24f17e..00000000 --- a/vendor/github.com/pierrec/lz4/block.go +++ /dev/null @@ -1,397 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "errors" -) - -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") -) - -// blockHash hashes 4 bytes into a value < winSize. -func blockHash(x uint32) uint32 { - const hasher uint32 = 2654435761 // Knuth multiplicative hash. - return x * hasher >> hashShift -} - -// 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) (si int, err error) { - defer func() { - // It is now faster to let the runtime panic and recover on out of bound slice access - // than checking indices as we go along. - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - sn := len(src) - if sn == 0 { - return 0, nil - } - var di int - - for { - // Literals and match lengths (token). - b := int(src[si]) - si++ - - // Literals. - if lLen := b >> 4; lLen > 0 { - if lLen == 0xF { - for src[si] == 0xFF { - lLen += 0xFF - si++ - } - lLen += int(src[si]) - si++ - } - i := si - si += lLen - di += copy(dst[di:], src[i:si]) - - if si >= sn { - return di, nil - } - } - - si++ - _ = src[si] // Bound check elimination. - offset := int(src[si-1]) | int(src[si])<<8 - si++ - - // Match. - mLen := b & 0xF - if mLen == 0xF { - for src[si] == 0xFF { - mLen += 0xFF - si++ - } - mLen += int(src[si]) - si++ - } - mLen += minMatch - - // Copy the match. - i := di - offset - if offset > 0 && mLen >= offset { - // Efficiently copy the match dst[di-offset:di] into the dst slice. - bytesToCopy := offset * (mLen / offset) - expanded := dst[i:] - for n := offset; n <= bytesToCopy+offset; n *= 2 { - copy(expanded[n:], expanded[:n]) - } - di += bytesToCopy - mLen -= bytesToCopy - } - di += copy(dst[di:], dst[i:i+mLen]) - } -} - -// CompressBlock compresses the source buffer into the destination one. -// This is the fast version of LZ4 compression and also the default one. -// The size of hashTable must be at least 64Kb. -// -// The size of the compressed data is returned. If it 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) (di int, err error) { - defer func() { - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - - sn, dn := len(src)-mfLimit, len(dst) - if sn <= 0 || dn == 0 { - return 0, nil - } - var si int - - // Fast scan strategy: the hash table only stores the last 4 bytes sequences. - // const accInit = 1 << skipStrength - - anchor := si // Position of the current literals. - // acc := accInit // Variable step: improves performance on non-compressible data. - - for si < sn { - // Hash the next 4 bytes (sequence)... - match := binary.LittleEndian.Uint32(src[si:]) - h := blockHash(match) - - ref := hashTable[h] - hashTable[h] = si - if ref >= sn { // Invalid reference (dirty hashtable). - si++ - continue - } - offset := si - ref - if offset <= 0 || offset >= winSize || // Out of window. - match != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches. - // si += acc >> skipStrength - // acc++ - si++ - continue - } - - // Match found. - // acc = accInit - lLen := si - anchor // Literal length. - - // Encode match length part 1. - si += minMatch - mLen := si // Match length has minMatch already. - // Find the longest match, first looking by batches of 8 bytes. - for si < sn && binary.LittleEndian.Uint64(src[si:]) == binary.LittleEndian.Uint64(src[si-offset:]) { - si += 8 - } - // Then byte by byte. - for si < sn && src[si] == src[si-offset] { - si++ - } - - 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:], 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++ - } - } - - if 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 di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:], src[anchor:]) - return di, nil -} - -// 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 it is 0 and no error, then the data is not compressible. -// -// An error is returned if the destination buffer is too small. -func CompressBlockHC(src, dst []byte, depth int) (di int, err error) { - defer func() { - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - - sn, dn := len(src)-mfLimit, len(dst) - if sn <= 0 || dn == 0 { - return 0, nil - } - var si int - - // hashTable: stores the last position found for a given hash - // chaingTable: stores previous positions for a given hash - var hashTable, chainTable [winSize]int - - if depth <= 0 { - depth = winSize - } - - anchor := si - for si < sn { - // Hash the next 4 bytes (sequence). - match := binary.LittleEndian.Uint32(src[si:]) - h := blockHash(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 && binary.LittleEndian.Uint64(src[next+ml:]) == binary.LittleEndian.Uint64(src[si+ml:]) { - ml += 8 - } - for ml < sn-si && src[next+ml] == src[si+ml] { - ml++ - } - if ml+1 < minMatch || ml <= mLen { - // Match too small ( winStart { - winStart = ws - } - for si, ml := winStart, si+mLen; si < ml; { - match >>= 8 - match |= uint32(src[si+3]) << 24 - h := blockHash(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:], 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 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++ - lLen -= 0xF - for ; lLen >= 0xFF; lLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(lLen) - } - di++ - - // Write the last literals. - if di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:], 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 bc5e78d4..00000000 --- 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 44211ad9..00000000 --- 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/internal/xxh32/xxh32zero.go b/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go deleted file mode 100644 index 850a6fdf..00000000 --- a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go +++ /dev/null @@ -1,222 +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 ( - prime32_1 uint32 = 2654435761 - prime32_2 uint32 = 2246822519 - prime32_3 uint32 = 3266489917 - prime32_4 uint32 = 668265263 - prime32_5 uint32 = 374761393 - - prime32_1plus2 uint32 = 606290984 - prime32_minus1 uint32 = 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 = prime32_1plus2 - xxh.v2 = prime32_2 - xxh.v3 = 0 - xxh.v4 = prime32_minus1 - 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[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime32_2) * prime32_1 - 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[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - 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 += prime32_5 - } - - p := 0 - n := xxh.bufused - buf := xxh.buf - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(buf[p:p+4]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for ; p < n; p++ { - h32 += uint32(buf[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - 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 += prime32_5 - } else { - v1 := prime32_1plus2 - v2 := prime32_2 - v3 := uint32(0) - v4 := prime32_minus1 - 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[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - 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]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for p < n { - h32 += uint32(input[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - p++ - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - h32 ^= h32 >> 16 - - return h32 -} - -// Uint32Zero hashes x with seed 0. -func Uint32Zero(x uint32) uint32 { - h := prime32_5 + 4 + x*prime32_3 - h = rol17(h) * prime32_4 - h ^= h >> 15 - h *= prime32_2 - h ^= h >> 13 - h *= prime32_3 - 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 35802756..00000000 --- a/vendor/github.com/pierrec/lz4/lz4.go +++ /dev/null @@ -1,68 +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 - -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 - - // 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. - hashLog = 16 - hashTableSize = 1 << hashLog - hashShift = uint((minMatch * 8) - hashLog) - - mfLimit = 8 + minMatch // The last match cannot start within the last 12 bytes. - skipStrength = 6 // variable step for fast scan -) - -// map the block max size id with its value in bytes: 64Kb, 256Kb, 1Mb and 4Mb. -var ( - bsMapID = map[byte]int{4: 64 << 10, 5: 256 << 10, 6: 1 << 20, 7: 4 << 20} - bsMapValue = make(map[int]byte, len(bsMapID)) -) - -// Reversed. -func init() { - for i, v := range bsMapID { - bsMapValue[v] = i - } -} - -// 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 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). -} 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 9a0fb007..00000000 --- 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 12c761a2..00000000 --- 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 f08db47d..00000000 --- a/vendor/github.com/pierrec/lz4/reader.go +++ /dev/null @@ -1,295 +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 - - 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. -} - -// 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 fmt.Errorf("lz4: block dependency not supported") - } - z.BlockChecksum = b>>4&1 > 0 - frameSize := b>>3&1 > 0 - z.NoChecksum = b>>2&1 == 0 - - bmsID := buf[1] >> 4 & 0x7 - bSize, ok := bsMapID[bmsID] - if !ok { - return fmt.Errorf("lz4: invalid block max size ID: %d", bmsID) - } - 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") - } - // 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.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.NoChecksum { - z.checksum.Write(z.data) - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - } - z.idx = 0 - } - - n := copy(buf, z.data[z.idx:]) - z.idx += n - if debugFlag { - debug("copied %d bytes to input", n) - } - - return n, 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/writer.go b/vendor/github.com/pierrec/lz4/writer.go deleted file mode 100644 index 01204380..00000000 --- a/vendor/github.com/pierrec/lz4/writer.go +++ /dev/null @@ -1,267 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" - - "github.com/pierrec/lz4/internal/xxh32" -) - -// Writer implements the LZ4 frame encoder. -type Writer struct { - Header - - 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. - zdata []byte // Compressed data. - data []byte // Data to be compressed. - idx int // Index into data. - hashtable [winSize]int // Hash table used in CompressBlock(). -} - -// 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 { - return &Writer{dst: dst} -} - -// 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 = bsMapID[7] - } - // The only option that needs to be validated. - bSize := z.Header.BlockMaxSize - bSizeID, ok := bsMapValue[bSize] - if !ok { - return fmt.Errorf("lz4: invalid block max size: %d", 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) - } - z.zdata = z.zdata[:bSize] - z.data = z.zdata[:cap(z.zdata)][bSize:] - 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] = bSizeID << 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) - } - - // The compressed block size cannot exceed the input's. - var zn int - var err error - - if level := z.Header.CompressionLevel; level != 0 { - zn, err = CompressBlockHC(data, z.zdata, level) - } else { - zn, err = CompressBlock(data, z.zdata, z.hashtable[:]) - } - - var zdata []byte - var bLen uint32 - if debugFlag { - debug("block compression %d => %d", len(data), zn) - } - if err == nil && zn > 0 && zn < len(data) { - // Compressible and compressed size smaller than uncompressed: ok! - bLen = uint32(zn) - zdata = z.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 - } - if _, err := z.dst.Write(zdata); err != nil { - return err - } - - if z.BlockChecksum { - checksum := xxh32.ChecksumZero(zdata) - if debugFlag { - debug("block checksum %x", checksum) - } - if err := z.writeUint32(checksum); err != nil { - return err - } - } - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - - 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 *Writer) Flush() error { - if debugFlag { - debug("flush with index %d", z.idx) - } - if z.idx == 0 { - return nil - } - - return z.compressBlock(z.data[:z.idx]) -} - -// 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 debugFlag { - debug("writing last empty block") - } - if err := z.writeUint32(0); err != nil { - return err - } - if !z.NoChecksum { - checksum := z.checksum.Sum32() - if debugFlag { - debug("stream checksum %x", checksum) - } - if err := z.writeUint32(checksum); err != nil { - return err - } - } - return nil -} - -// 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) { - z.Header = Header{} - z.dst = w - z.checksum.Reset() - z.zdata = z.zdata[:0] - z.data = z.data[:0] - z.idx = 0 -} - -// 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 -} diff --git a/vendor/github.com/rendon/testcli/LICENSE b/vendor/github.com/rendon/testcli/LICENSE deleted file mode 100644 index ffe70776..00000000 --- a/vendor/github.com/rendon/testcli/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016, Rafael Rendon Pablo - -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/rendon/testcli/README.md b/vendor/github.com/rendon/testcli/README.md deleted file mode 100644 index e754f969..00000000 --- a/vendor/github.com/rendon/testcli/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# testcli -CLI testing package for the Go language. - -Developing a command line application? Wanna be able to test your app from the outside? If the answer is Yes to at least one of the questions, keep reading. - -When using Ruby I use [aruba](https://github.com/cucumber/aruba) for testing command line applications, in Go I still can use aruba, but it"s awkward to bring Ruby and it's artillery only to test my app. - -`testcli` is a wrapper around [os.exec](https://golang.org/pkg/os/exec/) to test CLI apps in Go lang, minimalistic, so you can do your tests with [testing](https://golang.org/pkg/testing/) or any other testing framework. - - -## Greetings app -main\_test.go -```go -// make sure to execute `go install` before tests -package main - -import ( - "testing" - - "github.com/rendon/testcli" -) - -func TestGreetings(t *testing.T) { - // Using package functions - testcli.Run("greetings") - if !testcli.Success() { - t.Fatalf("Expected to succeed, but failed: %s", testcli.Error()) - } - - if !testcli.StdoutContains("Hello?") { - t.Fatalf("Expected %q to contain %q", testcli.Stdout(), "Hello?") - } -} - -func TestGreetingsWithName(t *testing.T) { - // Using the struct version, if you want to test multiple commands - c := testcli.Command("greetings", "--name", "John") - c.Run() - if !c.Success() { - t.Fatalf("Expected to succeed, but failed with error: %s", c.Error()) - } - - if !c.StdoutContains("Hello John!") { - t.Fatalf("Expected %q to contain %q", c.Stdout(), "Hello John!") - } -} -``` - - -main.go -```go -package main - -import ( - "fmt" - "os" - - "github.com/codegangsta/cli" -) - -func main() { - app := cli.NewApp() - app.Name = "cli" - app.Usage = "CLI app" - app.Flags = []cli.Flag{ - cli.StringFlag{ - Name: "name", - Usage: "User name", - }, - } - app.Action = func(c *cli.Context) { - if c.String("name") != "" { - fmt.Printf("Hello %s!\n", c.String("name")) - } else { - fmt.Printf("Hello? Anyone?\n") - } - } - - app.Run(os.Args) -} -``` diff --git a/vendor/github.com/rendon/testcli/main.go b/vendor/github.com/rendon/testcli/main.go deleted file mode 100644 index 839834de..00000000 --- a/vendor/github.com/rendon/testcli/main.go +++ /dev/null @@ -1,204 +0,0 @@ -// CLI testing package for the Go language. -// -// Developing a command line application? Wanna be able to test your app from the -// outside? If the answer is Yes to at least one of the questions, keep reading. -// -// `testcli` is a wrapper around os/exec to test CLI apps in Go lang, -// minimalistic, so you can do your tests with `testing` or any other testing -// framework. -package testcli - -import ( - "bytes" - "errors" - "io" - "log" - "os" - "os/exec" - "regexp" - "strings" -) - -// Cmd is typically constructed through the Command() call and provides state -// to the execution engine. -type Cmd struct { - cmd *exec.Cmd - env []string - exitError error - executed bool - stdout string - stderr string - stdin io.Reader -} - -// ErrUninitializedCmd is returned when members are accessed before a run, that -// can only be used after a command has been run. -var ErrUninitializedCmd = errors.New("You need to run this command first") -var pkgCmd = &Cmd{} - -// Command constructs a *Cmd. It is passed the command name and arguments. -func Command(name string, arg ...string) *Cmd { - return &Cmd{ - cmd: exec.Command(name, arg...), - } -} - -func (c *Cmd) validate() { - if !c.executed { - log.Fatal(ErrUninitializedCmd) - } -} - -// SetEnv overwrites the environment with the provided one. Otherwise, the -// parent environment will be supplied. -func (c *Cmd) SetEnv(env []string) { - c.env = env -} - -// SetStdin sets the stdin stream. It makes no attempt to determine if the -// command accepts anything over stdin. -func (c *Cmd) SetStdin(stdin io.Reader) { - c.stdin = stdin -} - -// Run runs the command. -func (c *Cmd) Run() { - if c.stdin != nil { - c.cmd.Stdin = c.stdin - } - - if c.env != nil { - c.cmd.Env = c.env - } else { - c.cmd.Env = os.Environ() - } - - var outBuf bytes.Buffer - c.cmd.Stdout = &outBuf - - var errBuf bytes.Buffer - c.cmd.Stderr = &errBuf - - if err := c.cmd.Run(); err != nil { - c.exitError = err - } - c.stdout = string(outBuf.Bytes()) - c.stderr = string(errBuf.Bytes()) - c.executed = true -} - -// Run runs a command with name and arguments. After this, package-level -// functions will return the data about the last command run. -func Run(name string, arg ...string) { - pkgCmd = Command(name, arg...) - pkgCmd.Run() -} - -// Error is the command's error, if any. -func (c *Cmd) Error() error { - c.validate() - return c.exitError -} - -// Error is the command's error, if any. -func Error() error { - return pkgCmd.Error() -} - -// Stdout stream for the command -func (c *Cmd) Stdout() string { - c.validate() - return c.stdout -} - -// Stdout stream for the command -func Stdout() string { - return pkgCmd.Stdout() -} - -// Stderr stream for the command -func (c *Cmd) Stderr() string { - c.validate() - return c.stderr -} - -// Stderr stream for the command -func Stderr() string { - return pkgCmd.Stderr() -} - -// StdoutContains determines if command's STDOUT contains `str`, this operation -// is case insensitive. -func (c *Cmd) StdoutContains(str string) bool { - c.validate() - str = strings.ToLower(str) - return strings.Contains(strings.ToLower(c.stdout), str) -} - -// StdoutContains determines if command's STDOUT contains `str`, this operation -// is case insensitive. -func StdoutContains(str string) bool { - return pkgCmd.StdoutContains(str) -} - -// StderrContains determines if command's STDERR contains `str`, this operation -// is case insensitive. -func (c *Cmd) StderrContains(str string) bool { - c.validate() - str = strings.ToLower(str) - return strings.Contains(strings.ToLower(c.stderr), str) -} - -// StderrContains determines if command's STDERR contains `str`, this operation -// is case insensitive. -func StderrContains(str string) bool { - return pkgCmd.StderrContains(str) -} - -// Success is a boolean status which indicates if the program exited non-zero -// or not. -func (c *Cmd) Success() bool { - c.validate() - return c.exitError == nil -} - -// Success is a boolean status which indicates if the program exited non-zero -// or not. -func Success() bool { - return pkgCmd.Success() -} - -// Failure is the inverse of Success(). -func (c *Cmd) Failure() bool { - c.validate() - return c.exitError != nil -} - -// Failure is the inverse of Success(). -func Failure() bool { - return pkgCmd.Failure() -} - -// StdoutMatches compares a regex to the stdout produced by the command. -func (c *Cmd) StdoutMatches(regex string) bool { - c.validate() - re := regexp.MustCompile(regex) - return re.MatchString(c.Stdout()) -} - -// StdoutMatches compares a regex to the stdout produced by the command. -func StdoutMatches(regex string) bool { - return pkgCmd.StdoutMatches(regex) -} - -// StderrMatches compares a regex to the stderr produced by the command. -func (c *Cmd) StderrMatches(regex string) bool { - c.validate() - re := regexp.MustCompile(regex) - return re.MatchString(c.Stderr()) -} - -// StderrMatches compares a regex to the stderr produced by the command. -func StderrMatches(regex string) bool { - return pkgCmd.StderrMatches(regex) -} diff --git a/vendor/github.com/ryanuber/go-glob/.travis.yml b/vendor/github.com/ryanuber/go-glob/.travis.yml deleted file mode 100644 index 9d1ca3c3..00000000 --- a/vendor/github.com/ryanuber/go-glob/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go -go: - - tip -script: - - go test -v ./... diff --git a/vendor/github.com/ryanuber/go-glob/LICENSE b/vendor/github.com/ryanuber/go-glob/LICENSE deleted file mode 100644 index bdfbd951..00000000 --- a/vendor/github.com/ryanuber/go-glob/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Ryan Uber - -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/ryanuber/go-glob/README.md b/vendor/github.com/ryanuber/go-glob/README.md deleted file mode 100644 index 48f7fcb0..00000000 --- a/vendor/github.com/ryanuber/go-glob/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# String globbing in golang [![Build Status](https://travis-ci.org/ryanuber/go-glob.svg)](https://travis-ci.org/ryanuber/go-glob) - -`go-glob` is a single-function library implementing basic string glob support. - -Globs are an extremely user-friendly way of supporting string matching without -requiring knowledge of regular expressions or Go's particular regex engine. Most -people understand that if you put a `*` character somewhere in a string, it is -treated as a wildcard. Surprisingly, this functionality isn't found in Go's -standard library, except for `path.Match`, which is intended to be used while -comparing paths (not arbitrary strings), and contains specialized logic for this -use case. A better solution might be a POSIX basic (non-ERE) regular expression -engine for Go, which doesn't exist currently. - -Example -======= - -``` -package main - -import "github.com/ryanuber/go-glob" - -func main() { - glob.Glob("*World!", "Hello, World!") // true - glob.Glob("Hello,*", "Hello, World!") // true - glob.Glob("*ello,*", "Hello, World!") // true - glob.Glob("World!", "Hello, World!") // false - glob.Glob("/home/*", "/home/ryanuber/.bashrc") // true -} -``` diff --git a/vendor/github.com/ryanuber/go-glob/glob.go b/vendor/github.com/ryanuber/go-glob/glob.go deleted file mode 100644 index d9d46379..00000000 --- a/vendor/github.com/ryanuber/go-glob/glob.go +++ /dev/null @@ -1,51 +0,0 @@ -package glob - -import "strings" - -// The character which is treated like a glob -const GLOB = "*" - -// Glob will test a string pattern, potentially containing globs, against a -// subject string. The result is a simple true/false, determining whether or -// not the glob pattern matched the subject text. -func Glob(pattern, subj string) bool { - // Empty pattern can only match empty subject - if pattern == "" { - return subj == pattern - } - - // If the pattern _is_ a glob, it matches everything - if pattern == GLOB { - return true - } - - parts := strings.Split(pattern, GLOB) - - if len(parts) == 1 { - // No globs in pattern, so test for equality - return subj == pattern - } - - leadingGlob := strings.HasPrefix(pattern, GLOB) - trailingGlob := strings.HasSuffix(pattern, GLOB) - end := len(parts) - 1 - - // Check the first section. Requires special handling. - if !leadingGlob && !strings.HasPrefix(subj, parts[0]) { - return false - } - - // Go over the middle parts and ensure they match. - for i := 1; i < end; i++ { - if !strings.Contains(subj, parts[i]) { - return false - } - - // Trim evaluated text from subj as we loop over the pattern. - idx := strings.Index(subj, parts[i]) + len(parts[i]) - subj = subj[idx:] - } - - // Reached the last section. Requires special handling. - return trailingGlob || strings.HasSuffix(subj, parts[end]) -} diff --git a/vendor/golang.org/x/crypto/AUTHORS b/vendor/golang.org/x/crypto/AUTHORS deleted file mode 100644 index 2b00ddba..00000000 --- a/vendor/golang.org/x/crypto/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at https://tip.golang.org/AUTHORS. diff --git a/vendor/golang.org/x/crypto/CONTRIBUTORS b/vendor/golang.org/x/crypto/CONTRIBUTORS deleted file mode 100644 index 1fbd3e97..00000000 --- a/vendor/golang.org/x/crypto/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at https://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/golang.org/x/crypto/LICENSE b/vendor/golang.org/x/crypto/LICENSE deleted file mode 100644 index 6a66aea5..00000000 --- a/vendor/golang.org/x/crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/crypto/PATENTS b/vendor/golang.org/x/crypto/PATENTS deleted file mode 100644 index 73309904..00000000 --- a/vendor/golang.org/x/crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.h b/vendor/golang.org/x/crypto/curve25519/const_amd64.h deleted file mode 100644 index b3f74162..00000000 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.h +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -#define REDMASK51 0x0007FFFFFFFFFFFF diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.s b/vendor/golang.org/x/crypto/curve25519/const_amd64.s deleted file mode 100644 index ee7b4bd5..00000000 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.s +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// These constants cannot be encoded in non-MOVQ immediates. -// We access them directly from memory instead. - -DATA ·_121666_213(SB)/8, $996687872 -GLOBL ·_121666_213(SB), 8, $8 - -DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA -GLOBL ·_2P0(SB), 8, $8 - -DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE -GLOBL ·_2P1234(SB), 8, $8 diff --git a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s deleted file mode 100644 index cd793a5b..00000000 --- a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -// func cswap(inout *[4][5]uint64, v uint64) -TEXT ·cswap(SB),7,$0 - MOVQ inout+0(FP),DI - MOVQ v+8(FP),SI - - SUBQ $1, SI - NOTQ SI - MOVQ SI, X15 - PSHUFD $0x44, X15, X15 - - MOVOU 0(DI), X0 - MOVOU 16(DI), X2 - MOVOU 32(DI), X4 - MOVOU 48(DI), X6 - MOVOU 64(DI), X8 - MOVOU 80(DI), X1 - MOVOU 96(DI), X3 - MOVOU 112(DI), X5 - MOVOU 128(DI), X7 - MOVOU 144(DI), X9 - - MOVO X1, X10 - MOVO X3, X11 - MOVO X5, X12 - MOVO X7, X13 - MOVO X9, X14 - - PXOR X0, X10 - PXOR X2, X11 - PXOR X4, X12 - PXOR X6, X13 - PXOR X8, X14 - PAND X15, X10 - PAND X15, X11 - PAND X15, X12 - PAND X15, X13 - PAND X15, X14 - PXOR X10, X0 - PXOR X10, X1 - PXOR X11, X2 - PXOR X11, X3 - PXOR X12, X4 - PXOR X12, X5 - PXOR X13, X6 - PXOR X13, X7 - PXOR X14, X8 - PXOR X14, X9 - - MOVOU X0, 0(DI) - MOVOU X2, 16(DI) - MOVOU X4, 32(DI) - MOVOU X6, 48(DI) - MOVOU X8, 64(DI) - MOVOU X1, 80(DI) - MOVOU X3, 96(DI) - MOVOU X5, 112(DI) - MOVOU X7, 128(DI) - MOVOU X9, 144(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go deleted file mode 100644 index 75f24bab..00000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright 2013 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. - -// We have an implementation in amd64 assembly so this code is only run on -// non-amd64 platforms. The amd64 assembly does not support gccgo. -// +build !amd64 gccgo appengine - -package curve25519 - -import ( - "encoding/binary" -) - -// This code is a port of the public domain, "ref10" implementation of -// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. - -// fieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type fieldElement [10]int32 - -func feZero(fe *fieldElement) { - for i := range fe { - fe[i] = 0 - } -} - -func feOne(fe *fieldElement) { - feZero(fe) - fe[0] = 1 -} - -func feAdd(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] + b[i] - } -} - -func feSub(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] - b[i] - } -} - -func feCopy(dst, src *fieldElement) { - for i := range dst { - dst[i] = src[i] - } -} - -// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func feCSwap(f, g *fieldElement, b int32) { - b = -b - for i := range f { - t := b & (f[i] ^ g[i]) - f[i] ^= t - g[i] ^= t - } -} - -// load3 reads a 24-bit, little-endian value from in. -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -// load4 reads a 32-bit, little-endian value from in. -func load4(in []byte) int64 { - return int64(binary.LittleEndian.Uint32(in)) -} - -func feFromBytes(dst *fieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 0x7fffff) << 2 - - var carry [10]int64 - carry[9] = (h9 + 1<<24) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + 1<<24) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + 1<<24) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + 1<<24) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + 1<<24) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + 1<<25) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + 1<<25) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + 1<<25) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + 1<<25) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + 1<<25) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - dst[0] = int32(h0) - dst[1] = int32(h1) - dst[2] = int32(h2) - dst[3] = int32(h3) - dst[4] = int32(h4) - dst[5] = int32(h5) - dst[6] = int32(h6) - dst[7] = int32(h7) - dst[8] = int32(h8) - dst[9] = int32(h9) -} - -// feToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -// feMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs can squeeze carries into int32. -func feMul(h, f, g *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - g0 := g[0] - g1 := g[1] - g2 := g[2] - g3 := g[3] - g4 := g[4] - g5 := g[5] - g6 := g[6] - g7 := g[7] - g8 := g[8] - g9 := g[9] - g1_19 := 19 * g1 // 1.4*2^29 - g2_19 := 19 * g2 // 1.4*2^30; still ok - g3_19 := 19 * g3 - g4_19 := 19 * g4 - g5_19 := 19 * g5 - g6_19 := 19 * g6 - g7_19 := 19 * g7 - g8_19 := 19 * g8 - g9_19 := 19 * g9 - f1_2 := 2 * f1 - f3_2 := 2 * f3 - f5_2 := 2 * f5 - f7_2 := 2 * f7 - f9_2 := 2 * f9 - f0g0 := int64(f0) * int64(g0) - f0g1 := int64(f0) * int64(g1) - f0g2 := int64(f0) * int64(g2) - f0g3 := int64(f0) * int64(g3) - f0g4 := int64(f0) * int64(g4) - f0g5 := int64(f0) * int64(g5) - f0g6 := int64(f0) * int64(g6) - f0g7 := int64(f0) * int64(g7) - f0g8 := int64(f0) * int64(g8) - f0g9 := int64(f0) * int64(g9) - f1g0 := int64(f1) * int64(g0) - f1g1_2 := int64(f1_2) * int64(g1) - f1g2 := int64(f1) * int64(g2) - f1g3_2 := int64(f1_2) * int64(g3) - f1g4 := int64(f1) * int64(g4) - f1g5_2 := int64(f1_2) * int64(g5) - f1g6 := int64(f1) * int64(g6) - f1g7_2 := int64(f1_2) * int64(g7) - f1g8 := int64(f1) * int64(g8) - f1g9_38 := int64(f1_2) * int64(g9_19) - f2g0 := int64(f2) * int64(g0) - f2g1 := int64(f2) * int64(g1) - f2g2 := int64(f2) * int64(g2) - f2g3 := int64(f2) * int64(g3) - f2g4 := int64(f2) * int64(g4) - f2g5 := int64(f2) * int64(g5) - f2g6 := int64(f2) * int64(g6) - f2g7 := int64(f2) * int64(g7) - f2g8_19 := int64(f2) * int64(g8_19) - f2g9_19 := int64(f2) * int64(g9_19) - f3g0 := int64(f3) * int64(g0) - f3g1_2 := int64(f3_2) * int64(g1) - f3g2 := int64(f3) * int64(g2) - f3g3_2 := int64(f3_2) * int64(g3) - f3g4 := int64(f3) * int64(g4) - f3g5_2 := int64(f3_2) * int64(g5) - f3g6 := int64(f3) * int64(g6) - f3g7_38 := int64(f3_2) * int64(g7_19) - f3g8_19 := int64(f3) * int64(g8_19) - f3g9_38 := int64(f3_2) * int64(g9_19) - f4g0 := int64(f4) * int64(g0) - f4g1 := int64(f4) * int64(g1) - f4g2 := int64(f4) * int64(g2) - f4g3 := int64(f4) * int64(g3) - f4g4 := int64(f4) * int64(g4) - f4g5 := int64(f4) * int64(g5) - f4g6_19 := int64(f4) * int64(g6_19) - f4g7_19 := int64(f4) * int64(g7_19) - f4g8_19 := int64(f4) * int64(g8_19) - f4g9_19 := int64(f4) * int64(g9_19) - f5g0 := int64(f5) * int64(g0) - f5g1_2 := int64(f5_2) * int64(g1) - f5g2 := int64(f5) * int64(g2) - f5g3_2 := int64(f5_2) * int64(g3) - f5g4 := int64(f5) * int64(g4) - f5g5_38 := int64(f5_2) * int64(g5_19) - f5g6_19 := int64(f5) * int64(g6_19) - f5g7_38 := int64(f5_2) * int64(g7_19) - f5g8_19 := int64(f5) * int64(g8_19) - f5g9_38 := int64(f5_2) * int64(g9_19) - f6g0 := int64(f6) * int64(g0) - f6g1 := int64(f6) * int64(g1) - f6g2 := int64(f6) * int64(g2) - f6g3 := int64(f6) * int64(g3) - f6g4_19 := int64(f6) * int64(g4_19) - f6g5_19 := int64(f6) * int64(g5_19) - f6g6_19 := int64(f6) * int64(g6_19) - f6g7_19 := int64(f6) * int64(g7_19) - f6g8_19 := int64(f6) * int64(g8_19) - f6g9_19 := int64(f6) * int64(g9_19) - f7g0 := int64(f7) * int64(g0) - f7g1_2 := int64(f7_2) * int64(g1) - f7g2 := int64(f7) * int64(g2) - f7g3_38 := int64(f7_2) * int64(g3_19) - f7g4_19 := int64(f7) * int64(g4_19) - f7g5_38 := int64(f7_2) * int64(g5_19) - f7g6_19 := int64(f7) * int64(g6_19) - f7g7_38 := int64(f7_2) * int64(g7_19) - f7g8_19 := int64(f7) * int64(g8_19) - f7g9_38 := int64(f7_2) * int64(g9_19) - f8g0 := int64(f8) * int64(g0) - f8g1 := int64(f8) * int64(g1) - f8g2_19 := int64(f8) * int64(g2_19) - f8g3_19 := int64(f8) * int64(g3_19) - f8g4_19 := int64(f8) * int64(g4_19) - f8g5_19 := int64(f8) * int64(g5_19) - f8g6_19 := int64(f8) * int64(g6_19) - f8g7_19 := int64(f8) * int64(g7_19) - f8g8_19 := int64(f8) * int64(g8_19) - f8g9_19 := int64(f8) * int64(g9_19) - f9g0 := int64(f9) * int64(g0) - f9g1_38 := int64(f9_2) * int64(g1_19) - f9g2_19 := int64(f9) * int64(g2_19) - f9g3_38 := int64(f9_2) * int64(g3_19) - f9g4_19 := int64(f9) * int64(g4_19) - f9g5_38 := int64(f9_2) * int64(g5_19) - f9g6_19 := int64(f9) * int64(g6_19) - f9g7_38 := int64(f9_2) * int64(g7_19) - f9g8_19 := int64(f9) * int64(g8_19) - f9g9_38 := int64(f9_2) * int64(g9_19) - h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 - h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 - h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 - h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 - h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 - h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 - h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 - h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 - h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 - h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 - var carry [10]int64 - - // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - // |h0| <= 2^25 - // |h4| <= 2^25 - // |h1| <= 1.51*2^58 - // |h5| <= 1.51*2^58 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - // |h1| <= 2^24; from now on fits into int32 - // |h5| <= 2^24; from now on fits into int32 - // |h2| <= 1.21*2^59 - // |h6| <= 1.21*2^59 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - // |h2| <= 2^25; from now on fits into int32 unchanged - // |h6| <= 2^25; from now on fits into int32 unchanged - // |h3| <= 1.51*2^58 - // |h7| <= 1.51*2^58 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - // |h3| <= 2^24; from now on fits into int32 unchanged - // |h7| <= 2^24; from now on fits into int32 unchanged - // |h4| <= 1.52*2^33 - // |h8| <= 1.52*2^33 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - // |h4| <= 2^25; from now on fits into int32 unchanged - // |h8| <= 2^25; from now on fits into int32 unchanged - // |h5| <= 1.01*2^24 - // |h9| <= 1.51*2^58 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - // |h9| <= 2^24; from now on fits into int32 unchanged - // |h0| <= 1.8*2^37 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - // |h0| <= 2^25; from now on fits into int32 unchanged - // |h1| <= 1.01*2^24 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feSquare(h, f *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feMul121666 calculates h = f * 121666. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feMul121666(h, f *fieldElement) { - h0 := int64(f[0]) * 121666 - h1 := int64(f[1]) * 121666 - h2 := int64(f[2]) * 121666 - h3 := int64(f[3]) * 121666 - h4 := int64(f[4]) * 121666 - h5 := int64(f[5]) * 121666 - h6 := int64(f[6]) * 121666 - h7 := int64(f[7]) * 121666 - h8 := int64(f[8]) * 121666 - h9 := int64(f[9]) * 121666 - var carry [10]int64 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feInvert sets out = z^-1. -func feInvert(out, z *fieldElement) { - var t0, t1, t2, t3 fieldElement - var i int - - feSquare(&t0, z) - for i = 1; i < 1; i++ { - feSquare(&t0, &t0) - } - feSquare(&t1, &t0) - for i = 1; i < 2; i++ { - feSquare(&t1, &t1) - } - feMul(&t1, z, &t1) - feMul(&t0, &t0, &t1) - feSquare(&t2, &t0) - for i = 1; i < 1; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t1, &t2) - feSquare(&t2, &t1) - for i = 1; i < 5; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 20; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 100; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t1, &t1) - for i = 1; i < 5; i++ { - feSquare(&t1, &t1) - } - feMul(out, &t1, &t0) -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - - copy(e[:], in[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement - feFromBytes(&x1, base) - feOne(&x2) - feCopy(&x3, &x1) - feOne(&z3) - - swap := int32(0) - for pos := 254; pos >= 0; pos-- { - b := e[pos/8] >> uint(pos&7) - b &= 1 - swap ^= int32(b) - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - swap = int32(b) - - feSub(&tmp0, &x3, &z3) - feSub(&tmp1, &x2, &z2) - feAdd(&x2, &x2, &z2) - feAdd(&z2, &x3, &z3) - feMul(&z3, &tmp0, &x2) - feMul(&z2, &z2, &tmp1) - feSquare(&tmp0, &tmp1) - feSquare(&tmp1, &x2) - feAdd(&x3, &z3, &z2) - feSub(&z2, &z3, &z2) - feMul(&x2, &tmp1, &tmp0) - feSub(&tmp1, &tmp1, &tmp0) - feSquare(&z2, &z2) - feMul121666(&z3, &tmp1) - feSquare(&x3, &x3) - feAdd(&tmp0, &tmp0, &z3) - feMul(&z3, &x1, &z2) - feMul(&z2, &tmp1, &tmp0) - } - - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - - feInvert(&z2, &z2) - feMul(&x2, &x2, &z2) - feToBytes(out, &x2) -} diff --git a/vendor/golang.org/x/crypto/curve25519/doc.go b/vendor/golang.org/x/crypto/curve25519/doc.go deleted file mode 100644 index da9b10d9..00000000 --- a/vendor/golang.org/x/crypto/curve25519/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 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 curve25519 provides an implementation of scalar multiplication on -// the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html -package curve25519 // import "golang.org/x/crypto/curve25519" - -// basePoint is the x coordinate of the generator of the curve. -var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - -// ScalarMult sets dst to the product in*base where dst and base are the x -// coordinates of group points and all values are in little-endian form. -func ScalarMult(dst, in, base *[32]byte) { - scalarMult(dst, in, base) -} - -// ScalarBaseMult sets dst to the product in*base where dst and base are the x -// coordinates of group points, base is the standard generator and all values -// are in little-endian form. -func ScalarBaseMult(dst, in *[32]byte) { - ScalarMult(dst, in, &basePoint) -} diff --git a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s deleted file mode 100644 index 39081610..00000000 --- a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func freeze(inout *[5]uint64) -TEXT ·freeze(SB),7,$0-8 - MOVQ inout+0(FP), DI - - MOVQ 0(DI),SI - MOVQ 8(DI),DX - MOVQ 16(DI),CX - MOVQ 24(DI),R8 - MOVQ 32(DI),R9 - MOVQ $REDMASK51,AX - MOVQ AX,R10 - SUBQ $18,R10 - MOVQ $3,R11 -REDUCELOOP: - MOVQ SI,R12 - SHRQ $51,R12 - ANDQ AX,SI - ADDQ R12,DX - MOVQ DX,R12 - SHRQ $51,R12 - ANDQ AX,DX - ADDQ R12,CX - MOVQ CX,R12 - SHRQ $51,R12 - ANDQ AX,CX - ADDQ R12,R8 - MOVQ R8,R12 - SHRQ $51,R12 - ANDQ AX,R8 - ADDQ R12,R9 - MOVQ R9,R12 - SHRQ $51,R12 - ANDQ AX,R9 - IMUL3Q $19,R12,R12 - ADDQ R12,SI - SUBQ $1,R11 - JA REDUCELOOP - MOVQ $1,R12 - CMPQ R10,SI - CMOVQLT R11,R12 - CMPQ AX,DX - CMOVQNE R11,R12 - CMPQ AX,CX - CMOVQNE R11,R12 - CMPQ AX,R8 - CMOVQNE R11,R12 - CMPQ AX,R9 - CMOVQNE R11,R12 - NEGQ R12 - ANDQ R12,AX - ANDQ R12,R10 - SUBQ R10,SI - SUBQ AX,DX - SUBQ AX,CX - SUBQ AX,R8 - SUBQ AX,R9 - MOVQ SI,0(DI) - MOVQ DX,8(DI) - MOVQ CX,16(DI) - MOVQ R8,24(DI) - MOVQ R9,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s deleted file mode 100644 index 9e9040b2..00000000 --- a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s +++ /dev/null @@ -1,1377 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func ladderstep(inout *[5][5]uint64) -TEXT ·ladderstep(SB),0,$296-8 - MOVQ inout+0(FP),DI - - MOVQ 40(DI),SI - MOVQ 48(DI),DX - MOVQ 56(DI),CX - MOVQ 64(DI),R8 - MOVQ 72(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 80(DI),SI - ADDQ 88(DI),DX - ADDQ 96(DI),CX - ADDQ 104(DI),R8 - ADDQ 112(DI),R9 - SUBQ 80(DI),AX - SUBQ 88(DI),R10 - SUBQ 96(DI),R11 - SUBQ 104(DI),R12 - SUBQ 112(DI),R13 - MOVQ SI,0(SP) - MOVQ DX,8(SP) - MOVQ CX,16(SP) - MOVQ R8,24(SP) - MOVQ R9,32(SP) - MOVQ AX,40(SP) - MOVQ R10,48(SP) - MOVQ R11,56(SP) - MOVQ R12,64(SP) - MOVQ R13,72(SP) - MOVQ 40(SP),AX - MULQ 40(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 48(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 48(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 72(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(SP) - MOVQ R8,88(SP) - MOVQ R9,96(SP) - MOVQ AX,104(SP) - MOVQ R10,112(SP) - MOVQ 0(SP),AX - MULQ 0(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 8(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 32(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(SP) - MOVQ R8,128(SP) - MOVQ R9,136(SP) - MOVQ AX,144(SP) - MOVQ R10,152(SP) - MOVQ SI,SI - MOVQ R8,DX - MOVQ R9,CX - MOVQ AX,R8 - MOVQ R10,R9 - ADDQ ·_2P0(SB),SI - ADDQ ·_2P1234(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R8 - ADDQ ·_2P1234(SB),R9 - SUBQ 80(SP),SI - SUBQ 88(SP),DX - SUBQ 96(SP),CX - SUBQ 104(SP),R8 - SUBQ 112(SP),R9 - MOVQ SI,160(SP) - MOVQ DX,168(SP) - MOVQ CX,176(SP) - MOVQ R8,184(SP) - MOVQ R9,192(SP) - MOVQ 120(DI),SI - MOVQ 128(DI),DX - MOVQ 136(DI),CX - MOVQ 144(DI),R8 - MOVQ 152(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 160(DI),SI - ADDQ 168(DI),DX - ADDQ 176(DI),CX - ADDQ 184(DI),R8 - ADDQ 192(DI),R9 - SUBQ 160(DI),AX - SUBQ 168(DI),R10 - SUBQ 176(DI),R11 - SUBQ 184(DI),R12 - SUBQ 192(DI),R13 - MOVQ SI,200(SP) - MOVQ DX,208(SP) - MOVQ CX,216(SP) - MOVQ R8,224(SP) - MOVQ R9,232(SP) - MOVQ AX,240(SP) - MOVQ R10,248(SP) - MOVQ R11,256(SP) - MOVQ R12,264(SP) - MOVQ R13,272(SP) - MOVQ 224(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,280(SP) - MULQ 56(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 232(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,288(SP) - MULQ 48(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 40(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 200(SP),AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 200(SP),AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 200(SP),AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 208(SP),AX - MULQ 40(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 208(SP),AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),AX - MULQ 40(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 216(SP),AX - MULQ 48(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 216(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 224(SP),AX - MULQ 40(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 224(SP),AX - MULQ 48(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 280(SP),AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 280(SP),AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 232(SP),AX - MULQ 40(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 288(SP),AX - MULQ 56(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 288(SP),AX - MULQ 64(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 288(SP),AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(SP) - MOVQ R8,48(SP) - MOVQ R9,56(SP) - MOVQ AX,64(SP) - MOVQ R10,72(SP) - MOVQ 264(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,200(SP) - MULQ 16(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 272(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,208(SP) - MULQ 8(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 0(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 240(SP),AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 240(SP),AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 240(SP),AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 248(SP),AX - MULQ 0(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 248(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 248(SP),AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 248(SP),AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 248(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),AX - MULQ 0(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 256(SP),AX - MULQ 8(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 256(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 264(SP),AX - MULQ 0(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 264(SP),AX - MULQ 8(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 200(SP),AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 200(SP),AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 272(SP),AX - MULQ 0(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),AX - MULQ 16(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 24(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,DX - MOVQ R8,CX - MOVQ R9,R11 - MOVQ AX,R12 - MOVQ R10,R13 - ADDQ ·_2P0(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 40(SP),SI - ADDQ 48(SP),R8 - ADDQ 56(SP),R9 - ADDQ 64(SP),AX - ADDQ 72(SP),R10 - SUBQ 40(SP),DX - SUBQ 48(SP),CX - SUBQ 56(SP),R11 - SUBQ 64(SP),R12 - SUBQ 72(SP),R13 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ DX,160(DI) - MOVQ CX,168(DI) - MOVQ R11,176(DI) - MOVQ R12,184(DI) - MOVQ R13,192(DI) - MOVQ 120(DI),AX - MULQ 120(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 128(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 136(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 144(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 152(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(DI),AX - MULQ 128(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 136(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 144(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),AX - MULQ 136(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 144(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $19,DX,AX - MULQ 144(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(DI),DX - IMUL3Q $19,DX,AX - MULQ 152(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ 160(DI),AX - MULQ 160(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 168(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 176(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 184(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 192(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 168(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 176(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 184(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 176(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 184(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 184(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 16(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 0(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 8(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - MULQ 16(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - MULQ 24(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - MULQ 32(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 0(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 168(DI),AX - MULQ 8(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - MULQ 16(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - MULQ 24(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 0(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 176(DI),AX - MULQ 8(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 176(DI),AX - MULQ 16(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 24(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),AX - MULQ 0(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 184(DI),AX - MULQ 8(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 24(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 32(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),AX - MULQ 0(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 16(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 24(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 32(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 144(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 96(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 152(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 88(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 80(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 88(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(SP),AX - MULQ 96(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(SP),AX - MULQ 104(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(SP),AX - MULQ 112(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(SP),AX - MULQ 80(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 128(SP),AX - MULQ 88(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(SP),AX - MULQ 96(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(SP),AX - MULQ 104(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),AX - MULQ 80(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 136(SP),AX - MULQ 88(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 136(SP),AX - MULQ 96(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 104(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(SP),AX - MULQ 80(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 144(SP),AX - MULQ 88(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 104(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 112(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(SP),AX - MULQ 80(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 96(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 104(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 112(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(DI) - MOVQ R8,48(DI) - MOVQ R9,56(DI) - MOVQ AX,64(DI) - MOVQ R10,72(DI) - MOVQ 160(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - MOVQ AX,SI - MOVQ DX,CX - MOVQ 168(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,CX - MOVQ DX,R8 - MOVQ 176(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R8 - MOVQ DX,R9 - MOVQ 184(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R9 - MOVQ DX,R10 - MOVQ 192(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R10 - IMUL3Q $19,DX,DX - ADDQ DX,SI - ADDQ 80(SP),SI - ADDQ 88(SP),CX - ADDQ 96(SP),R8 - ADDQ 104(SP),R9 - ADDQ 112(SP),R10 - MOVQ SI,80(DI) - MOVQ CX,88(DI) - MOVQ R8,96(DI) - MOVQ R9,104(DI) - MOVQ R10,112(DI) - MOVQ 104(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 176(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 112(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 168(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 160(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 168(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 80(DI),AX - MULQ 176(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 80(DI),AX - MULQ 184(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 80(DI),AX - MULQ 192(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 88(DI),AX - MULQ 160(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 88(DI),AX - MULQ 168(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 88(DI),AX - MULQ 176(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 88(DI),AX - MULQ 184(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 88(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),AX - MULQ 160(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 96(DI),AX - MULQ 168(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 96(DI),AX - MULQ 176(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 104(DI),AX - MULQ 160(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 104(DI),AX - MULQ 168(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 184(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 192(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 112(DI),AX - MULQ 160(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 176(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 184(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 192(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(DI) - MOVQ R8,88(DI) - MOVQ R9,96(DI) - MOVQ AX,104(DI) - MOVQ R10,112(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go b/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go deleted file mode 100644 index 5822bd53..00000000 --- a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -package curve25519 - -// These functions are implemented in the .s files. The names of the functions -// in the rest of the file are also taken from the SUPERCOP sources to help -// people following along. - -//go:noescape - -func cswap(inout *[5]uint64, v uint64) - -//go:noescape - -func ladderstep(inout *[5][5]uint64) - -//go:noescape - -func freeze(inout *[5]uint64) - -//go:noescape - -func mul(dest, a, b *[5]uint64) - -//go:noescape - -func square(out, in *[5]uint64) - -// mladder uses a Montgomery ladder to calculate (xr/zr) *= s. -func mladder(xr, zr *[5]uint64, s *[32]byte) { - var work [5][5]uint64 - - work[0] = *xr - setint(&work[1], 1) - setint(&work[2], 0) - work[3] = *xr - setint(&work[4], 1) - - j := uint(6) - var prevbit byte - - for i := 31; i >= 0; i-- { - for j < 8 { - bit := ((*s)[i] >> j) & 1 - swap := bit ^ prevbit - prevbit = bit - cswap(&work[1], uint64(swap)) - ladderstep(&work) - j-- - } - j = 7 - } - - *xr = work[1] - *zr = work[2] -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - copy(e[:], (*in)[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var t, z [5]uint64 - unpack(&t, base) - mladder(&t, &z, &e) - invert(&z, &z) - mul(&t, &t, &z) - pack(out, &t) -} - -func setint(r *[5]uint64, v uint64) { - r[0] = v - r[1] = 0 - r[2] = 0 - r[3] = 0 - r[4] = 0 -} - -// unpack sets r = x where r consists of 5, 51-bit limbs in little-endian -// order. -func unpack(r *[5]uint64, x *[32]byte) { - r[0] = uint64(x[0]) | - uint64(x[1])<<8 | - uint64(x[2])<<16 | - uint64(x[3])<<24 | - uint64(x[4])<<32 | - uint64(x[5])<<40 | - uint64(x[6]&7)<<48 - - r[1] = uint64(x[6])>>3 | - uint64(x[7])<<5 | - uint64(x[8])<<13 | - uint64(x[9])<<21 | - uint64(x[10])<<29 | - uint64(x[11])<<37 | - uint64(x[12]&63)<<45 - - r[2] = uint64(x[12])>>6 | - uint64(x[13])<<2 | - uint64(x[14])<<10 | - uint64(x[15])<<18 | - uint64(x[16])<<26 | - uint64(x[17])<<34 | - uint64(x[18])<<42 | - uint64(x[19]&1)<<50 - - r[3] = uint64(x[19])>>1 | - uint64(x[20])<<7 | - uint64(x[21])<<15 | - uint64(x[22])<<23 | - uint64(x[23])<<31 | - uint64(x[24])<<39 | - uint64(x[25]&15)<<47 - - r[4] = uint64(x[25])>>4 | - uint64(x[26])<<4 | - uint64(x[27])<<12 | - uint64(x[28])<<20 | - uint64(x[29])<<28 | - uint64(x[30])<<36 | - uint64(x[31]&127)<<44 -} - -// pack sets out = x where out is the usual, little-endian form of the 5, -// 51-bit limbs in x. -func pack(out *[32]byte, x *[5]uint64) { - t := *x - freeze(&t) - - out[0] = byte(t[0]) - out[1] = byte(t[0] >> 8) - out[2] = byte(t[0] >> 16) - out[3] = byte(t[0] >> 24) - out[4] = byte(t[0] >> 32) - out[5] = byte(t[0] >> 40) - out[6] = byte(t[0] >> 48) - - out[6] ^= byte(t[1]<<3) & 0xf8 - out[7] = byte(t[1] >> 5) - out[8] = byte(t[1] >> 13) - out[9] = byte(t[1] >> 21) - out[10] = byte(t[1] >> 29) - out[11] = byte(t[1] >> 37) - out[12] = byte(t[1] >> 45) - - out[12] ^= byte(t[2]<<6) & 0xc0 - out[13] = byte(t[2] >> 2) - out[14] = byte(t[2] >> 10) - out[15] = byte(t[2] >> 18) - out[16] = byte(t[2] >> 26) - out[17] = byte(t[2] >> 34) - out[18] = byte(t[2] >> 42) - out[19] = byte(t[2] >> 50) - - out[19] ^= byte(t[3]<<1) & 0xfe - out[20] = byte(t[3] >> 7) - out[21] = byte(t[3] >> 15) - out[22] = byte(t[3] >> 23) - out[23] = byte(t[3] >> 31) - out[24] = byte(t[3] >> 39) - out[25] = byte(t[3] >> 47) - - out[25] ^= byte(t[4]<<4) & 0xf0 - out[26] = byte(t[4] >> 4) - out[27] = byte(t[4] >> 12) - out[28] = byte(t[4] >> 20) - out[29] = byte(t[4] >> 28) - out[30] = byte(t[4] >> 36) - out[31] = byte(t[4] >> 44) -} - -// invert calculates r = x^-1 mod p using Fermat's little theorem. -func invert(r *[5]uint64, x *[5]uint64) { - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 - - square(&z2, x) /* 2 */ - square(&t, &z2) /* 4 */ - square(&t, &t) /* 8 */ - mul(&z9, &t, x) /* 9 */ - mul(&z11, &z9, &z2) /* 11 */ - square(&t, &z11) /* 22 */ - mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ - - square(&t, &z2_5_0) /* 2^6 - 2^1 */ - for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ - - square(&t, &z2_10_0) /* 2^11 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ - - square(&t, &z2_20_0) /* 2^21 - 2^1 */ - for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ - square(&t, &t) - } - mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ - - square(&t, &t) /* 2^41 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ - square(&t, &t) - } - mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ - - square(&t, &z2_50_0) /* 2^51 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ - square(&t, &t) - } - mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ - - square(&t, &z2_100_0) /* 2^101 - 2^1 */ - for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ - square(&t, &t) - } - mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ - - square(&t, &t) /* 2^201 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ - square(&t, &t) - } - mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ - - square(&t, &t) /* 2^251 - 2^1 */ - square(&t, &t) /* 2^252 - 2^2 */ - square(&t, &t) /* 2^253 - 2^3 */ - - square(&t, &t) /* 2^254 - 2^4 */ - - square(&t, &t) /* 2^255 - 2^5 */ - mul(r, &t, &z11) /* 2^255 - 21 */ -} diff --git a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s deleted file mode 100644 index 5ce80a2e..00000000 --- a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func mul(dest, a, b *[5]uint64) -TEXT ·mul(SB),0,$16-24 - MOVQ dest+0(FP), DI - MOVQ a+8(FP), SI - MOVQ b+16(FP), DX - - MOVQ DX,CX - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,0(SP) - MULQ 16(CX) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 0(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 8(CX) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SI),AX - MULQ 16(CX) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SI),AX - MULQ 24(CX) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 0(SI),AX - MULQ 32(CX) - MOVQ AX,BX - MOVQ DX,BP - MOVQ 8(SI),AX - MULQ 0(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SI),AX - MULQ 8(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SI),AX - MULQ 16(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SI),AX - MULQ 24(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),AX - MULQ 0(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 16(SI),AX - MULQ 8(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SI),AX - MULQ 16(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 24(SI),AX - MULQ 0(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 24(SI),AX - MULQ 8(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 0(SP),AX - MULQ 24(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 0(SP),AX - MULQ 32(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 32(SI),AX - MULQ 0(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SP),AX - MULQ 16(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 24(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - MULQ 32(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ $REDMASK51,SI - SHLQ $13,R9:R8 - ANDQ SI,R8 - SHLQ $13,R11:R10 - ANDQ SI,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ SI,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ SI,R14 - ADDQ R13,R14 - SHLQ $13,BP:BX - ANDQ SI,BX - ADDQ R15,BX - IMUL3Q $19,BP,DX - ADDQ DX,R8 - MOVQ R8,DX - SHRQ $51,DX - ADDQ R10,DX - MOVQ DX,CX - SHRQ $51,DX - ANDQ SI,R8 - ADDQ R12,DX - MOVQ DX,R9 - SHRQ $51,DX - ANDQ SI,CX - ADDQ R14,DX - MOVQ DX,AX - SHRQ $51,DX - ANDQ SI,R9 - ADDQ BX,DX - MOVQ DX,R10 - SHRQ $51,DX - ANDQ SI,AX - IMUL3Q $19,DX,DX - ADDQ DX,R8 - ANDQ SI,R10 - MOVQ R8,0(DI) - MOVQ CX,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/square_amd64.s b/vendor/golang.org/x/crypto/curve25519/square_amd64.s deleted file mode 100644 index 12f73734..00000000 --- a/vendor/golang.org/x/crypto/curve25519/square_amd64.s +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func square(out, in *[5]uint64) -TEXT ·square(SB),7,$0-16 - MOVQ out+0(FP), DI - MOVQ in+8(FP), SI - - MOVQ 0(SI),AX - MULQ 0(SI) - MOVQ AX,CX - MOVQ DX,R8 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 8(SI) - MOVQ AX,R9 - MOVQ DX,R10 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 16(SI) - MOVQ AX,R11 - MOVQ DX,R12 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 24(SI) - MOVQ AX,R13 - MOVQ DX,R14 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 32(SI) - MOVQ AX,R15 - MOVQ DX,BX - MOVQ 8(SI),AX - MULQ 8(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 16(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 24(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 8(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),AX - MULQ 16(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 24(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ $REDMASK51,SI - SHLQ $13,R8:CX - ANDQ SI,CX - SHLQ $13,R10:R9 - ANDQ SI,R9 - ADDQ R8,R9 - SHLQ $13,R12:R11 - ANDQ SI,R11 - ADDQ R10,R11 - SHLQ $13,R14:R13 - ANDQ SI,R13 - ADDQ R12,R13 - SHLQ $13,BX:R15 - ANDQ SI,R15 - ADDQ R14,R15 - IMUL3Q $19,BX,DX - ADDQ DX,CX - MOVQ CX,DX - SHRQ $51,DX - ADDQ R9,DX - ANDQ SI,CX - MOVQ DX,R8 - SHRQ $51,DX - ADDQ R11,DX - ANDQ SI,R8 - MOVQ DX,R9 - SHRQ $51,DX - ADDQ R13,DX - ANDQ SI,R9 - MOVQ DX,AX - SHRQ $51,DX - ADDQ R15,DX - ANDQ SI,AX - MOVQ DX,R10 - SHRQ $51,DX - IMUL3Q $19,DX,DX - ADDQ DX,CX - ANDQ SI,R10 - MOVQ CX,0(DI) - MOVQ R8,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go deleted file mode 100644 index d6f683ba..00000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ /dev/null @@ -1,217 +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 ed25519 implements the Ed25519 signature algorithm. See -// https://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the “seed”. -package ed25519 - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -import ( - "bytes" - "crypto" - cryptorand "crypto/rand" - "crypto/sha512" - "errors" - "io" - "strconv" - - "golang.org/x/crypto/ed25519/internal/edwards25519" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[32:]) - return PublicKey(publicKey) -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:32]) - return seed -} - -// Sign signs the given message with priv. -// Ed25519 performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to -// indicate the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, errors.New("ed25519: cannot sign hashed message") - } - - return Sign(priv, message), nil -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptorand.Reader - } - - seed := make([]byte, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey := NewKeyFromSeed(seed) - publicKey := make([]byte, PublicKeySize) - copy(publicKey, privateKey[32:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - if l := len(seed); l != SeedSize { - panic("ed25519: bad seed length: " + strconv.Itoa(l)) - } - - digest := sha512.Sum512(seed) - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - var A edwards25519.ExtendedGroupElement - var hBytes [32]byte - copy(hBytes[:], digest[:]) - edwards25519.GeScalarMultBase(&A, &hBytes) - var publicKeyBytes [32]byte - A.ToBytes(&publicKeyBytes) - - privateKey := make([]byte, PrivateKeySize) - copy(privateKey, seed) - copy(privateKey[32:], publicKeyBytes[:]) - - return privateKey -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) []byte { - if l := len(privateKey); l != PrivateKeySize { - panic("ed25519: bad private key length: " + strconv.Itoa(l)) - } - - h := sha512.New() - h.Write(privateKey[:32]) - - var digest1, messageDigest, hramDigest [64]byte - var expandedSecretKey [32]byte - h.Sum(digest1[:0]) - copy(expandedSecretKey[:], digest1[:]) - expandedSecretKey[0] &= 248 - expandedSecretKey[31] &= 63 - expandedSecretKey[31] |= 64 - - h.Reset() - h.Write(digest1[32:]) - h.Write(message) - h.Sum(messageDigest[:0]) - - var messageDigestReduced [32]byte - edwards25519.ScReduce(&messageDigestReduced, &messageDigest) - var R edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&R, &messageDigestReduced) - - var encodedR [32]byte - R.ToBytes(&encodedR) - - h.Reset() - h.Write(encodedR[:]) - h.Write(privateKey[32:]) - h.Write(message) - h.Sum(hramDigest[:0]) - var hramDigestReduced [32]byte - edwards25519.ScReduce(&hramDigestReduced, &hramDigest) - - var s [32]byte - edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) - - signature := make([]byte, SignatureSize) - copy(signature[:], encodedR[:]) - copy(signature[32:], s[:]) - - return signature -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -func Verify(publicKey PublicKey, message, sig []byte) bool { - if l := len(publicKey); l != PublicKeySize { - panic("ed25519: bad public key length: " + strconv.Itoa(l)) - } - - if len(sig) != SignatureSize || sig[63]&224 != 0 { - return false - } - - var A edwards25519.ExtendedGroupElement - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], publicKey) - if !A.FromBytes(&publicKeyBytes) { - return false - } - edwards25519.FeNeg(&A.X, &A.X) - edwards25519.FeNeg(&A.T, &A.T) - - h := sha512.New() - h.Write(sig[:32]) - h.Write(publicKey[:]) - h.Write(message) - var digest [64]byte - h.Sum(digest[:0]) - - var hReduced [32]byte - edwards25519.ScReduce(&hReduced, &digest) - - var R edwards25519.ProjectiveGroupElement - var s [32]byte - copy(s[:], sig[32:]) - - // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in - // the range [0, order) in order to prevent signature malleability. - if !edwards25519.ScMinimal(&s) { - return false - } - - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) - - var checkR [32]byte - R.ToBytes(&checkR) - return bytes.Equal(sig[:32], checkR[:]) -} diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go deleted file mode 100644 index e39f086c..00000000 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go +++ /dev/null @@ -1,1422 +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 edwards25519 - -// These values are from the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// d is a constant in the Edwards curve equation. -var d = FieldElement{ - -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, -} - -// d2 is 2*d. -var d2 = FieldElement{ - -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, -} - -// SqrtM1 is the square-root of -1 in the field. -var SqrtM1 = FieldElement{ - -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, -} - -// A is a constant in the Montgomery-form of curve25519. -var A = FieldElement{ - 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, -} - -// bi contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var bi = [8]PreComputedGroupElement{ - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877}, - FieldElement{-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951}, - FieldElement{4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784}, - }, - { - FieldElement{-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436}, - FieldElement{25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918}, - FieldElement{23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877}, - }, - { - FieldElement{-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800}, - FieldElement{-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305}, - FieldElement{-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300}, - }, - { - FieldElement{-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876}, - FieldElement{-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619}, - FieldElement{-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683}, - }, -} - -// base contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var base = [32][8]PreComputedGroupElement{ - { - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303}, - FieldElement{-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081}, - FieldElement{26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540}, - FieldElement{23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397}, - FieldElement{7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777}, - FieldElement{-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737}, - FieldElement{-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726}, - FieldElement{-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955}, - FieldElement{27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425}, - }, - }, - { - { - FieldElement{-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171}, - FieldElement{27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510}, - FieldElement{17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660}, - }, - { - FieldElement{-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639}, - FieldElement{29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963}, - FieldElement{5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950}, - }, - { - FieldElement{-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568}, - FieldElement{12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335}, - FieldElement{25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628}, - }, - { - FieldElement{-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007}, - FieldElement{-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772}, - FieldElement{-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653}, - }, - { - FieldElement{2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567}, - FieldElement{13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686}, - FieldElement{21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372}, - }, - { - FieldElement{-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887}, - FieldElement{-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954}, - FieldElement{-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953}, - }, - { - FieldElement{24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833}, - FieldElement{-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532}, - FieldElement{-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876}, - }, - { - FieldElement{2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268}, - FieldElement{33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214}, - FieldElement{1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038}, - }, - }, - { - { - FieldElement{6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800}, - FieldElement{4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645}, - FieldElement{-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664}, - }, - { - FieldElement{1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933}, - FieldElement{-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182}, - FieldElement{-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222}, - }, - { - FieldElement{-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991}, - FieldElement{20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880}, - FieldElement{9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092}, - }, - { - FieldElement{-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295}, - FieldElement{19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788}, - FieldElement{8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553}, - }, - { - FieldElement{-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026}, - FieldElement{11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347}, - FieldElement{-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033}, - }, - { - FieldElement{-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395}, - FieldElement{-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278}, - FieldElement{1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890}, - }, - { - FieldElement{32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995}, - FieldElement{-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596}, - FieldElement{-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891}, - }, - { - FieldElement{31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060}, - FieldElement{11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608}, - FieldElement{-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606}, - }, - }, - { - { - FieldElement{7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389}, - FieldElement{-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016}, - FieldElement{-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341}, - }, - { - FieldElement{-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505}, - FieldElement{14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553}, - FieldElement{-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655}, - }, - { - FieldElement{15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220}, - FieldElement{12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631}, - FieldElement{-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099}, - }, - { - FieldElement{26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556}, - FieldElement{14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749}, - FieldElement{236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930}, - }, - { - FieldElement{1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391}, - FieldElement{5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253}, - FieldElement{20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066}, - }, - { - FieldElement{24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958}, - FieldElement{-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082}, - FieldElement{-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383}, - }, - { - FieldElement{-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521}, - FieldElement{-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807}, - FieldElement{23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948}, - }, - { - FieldElement{9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134}, - FieldElement{-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455}, - FieldElement{27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629}, - }, - }, - { - { - FieldElement{-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069}, - FieldElement{-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746}, - FieldElement{24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919}, - }, - { - FieldElement{11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837}, - FieldElement{8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906}, - FieldElement{-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771}, - }, - { - FieldElement{-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817}, - FieldElement{10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098}, - FieldElement{10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409}, - }, - { - FieldElement{-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504}, - FieldElement{-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727}, - FieldElement{28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420}, - }, - { - FieldElement{-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003}, - FieldElement{-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605}, - FieldElement{-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384}, - }, - { - FieldElement{-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701}, - FieldElement{-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683}, - FieldElement{29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708}, - }, - { - FieldElement{-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563}, - FieldElement{-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260}, - FieldElement{-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387}, - }, - { - FieldElement{-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672}, - FieldElement{23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686}, - FieldElement{-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665}, - }, - }, - { - { - FieldElement{11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182}, - FieldElement{-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277}, - FieldElement{14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628}, - }, - { - FieldElement{-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474}, - FieldElement{-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539}, - FieldElement{-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822}, - }, - { - FieldElement{-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970}, - FieldElement{19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756}, - FieldElement{-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508}, - }, - { - FieldElement{-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683}, - FieldElement{-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655}, - FieldElement{-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158}, - }, - { - FieldElement{-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125}, - FieldElement{-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839}, - FieldElement{-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664}, - }, - { - FieldElement{27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294}, - FieldElement{-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899}, - FieldElement{-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070}, - }, - { - FieldElement{3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294}, - FieldElement{-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949}, - FieldElement{-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083}, - }, - { - FieldElement{31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420}, - FieldElement{-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940}, - FieldElement{29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396}, - }, - }, - { - { - FieldElement{-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567}, - FieldElement{20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127}, - FieldElement{-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294}, - }, - { - FieldElement{-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887}, - FieldElement{22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964}, - FieldElement{16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195}, - }, - { - FieldElement{9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244}, - FieldElement{24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999}, - FieldElement{-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762}, - }, - { - FieldElement{-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274}, - FieldElement{-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236}, - FieldElement{-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605}, - }, - { - FieldElement{-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761}, - FieldElement{-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884}, - FieldElement{-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482}, - }, - { - FieldElement{-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638}, - FieldElement{-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490}, - FieldElement{-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170}, - }, - { - FieldElement{5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736}, - FieldElement{10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124}, - FieldElement{-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392}, - }, - { - FieldElement{8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029}, - FieldElement{6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048}, - FieldElement{28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958}, - }, - }, - { - { - FieldElement{24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593}, - FieldElement{26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071}, - FieldElement{-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692}, - }, - { - FieldElement{11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687}, - FieldElement{-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441}, - FieldElement{-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001}, - }, - { - FieldElement{-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460}, - FieldElement{-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007}, - FieldElement{-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762}, - }, - { - FieldElement{15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005}, - FieldElement{-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674}, - FieldElement{4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035}, - }, - { - FieldElement{7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590}, - FieldElement{-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957}, - FieldElement{-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812}, - }, - { - FieldElement{33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740}, - FieldElement{-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122}, - FieldElement{-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158}, - }, - { - FieldElement{8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885}, - FieldElement{26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140}, - FieldElement{19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857}, - }, - { - FieldElement{801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155}, - FieldElement{19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260}, - FieldElement{19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483}, - }, - }, - { - { - FieldElement{-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677}, - FieldElement{32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815}, - FieldElement{22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751}, - }, - { - FieldElement{-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203}, - FieldElement{-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208}, - FieldElement{1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230}, - }, - { - FieldElement{16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850}, - FieldElement{-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389}, - FieldElement{-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968}, - }, - { - FieldElement{-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689}, - FieldElement{14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880}, - FieldElement{5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304}, - }, - { - FieldElement{30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632}, - FieldElement{-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412}, - FieldElement{20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566}, - }, - { - FieldElement{-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038}, - FieldElement{-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232}, - FieldElement{-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943}, - }, - { - FieldElement{17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856}, - FieldElement{23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738}, - FieldElement{15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971}, - }, - { - FieldElement{-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718}, - FieldElement{-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697}, - FieldElement{-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883}, - }, - }, - { - { - FieldElement{5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912}, - FieldElement{-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358}, - FieldElement{3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849}, - }, - { - FieldElement{29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307}, - FieldElement{-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977}, - FieldElement{-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335}, - }, - { - FieldElement{-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644}, - FieldElement{-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616}, - FieldElement{-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735}, - }, - { - FieldElement{-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099}, - FieldElement{29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341}, - FieldElement{-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336}, - }, - { - FieldElement{-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646}, - FieldElement{31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425}, - FieldElement{-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388}, - }, - { - FieldElement{-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743}, - FieldElement{-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822}, - FieldElement{-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462}, - }, - { - FieldElement{18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985}, - FieldElement{9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702}, - FieldElement{-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797}, - }, - { - FieldElement{21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293}, - FieldElement{27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100}, - FieldElement{19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688}, - }, - }, - { - { - FieldElement{12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186}, - FieldElement{2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610}, - FieldElement{-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707}, - }, - { - FieldElement{7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220}, - FieldElement{915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025}, - FieldElement{32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044}, - }, - { - FieldElement{32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992}, - FieldElement{-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027}, - FieldElement{21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197}, - }, - { - FieldElement{8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901}, - FieldElement{31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952}, - FieldElement{19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878}, - }, - { - FieldElement{-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390}, - FieldElement{32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730}, - FieldElement{2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730}, - }, - { - FieldElement{-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180}, - FieldElement{-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272}, - FieldElement{-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715}, - }, - { - FieldElement{-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970}, - FieldElement{-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772}, - FieldElement{-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865}, - }, - { - FieldElement{15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750}, - FieldElement{20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373}, - FieldElement{32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348}, - }, - }, - { - { - FieldElement{9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144}, - FieldElement{-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195}, - FieldElement{5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086}, - }, - { - FieldElement{-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684}, - FieldElement{-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518}, - FieldElement{-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233}, - }, - { - FieldElement{-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793}, - FieldElement{-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794}, - FieldElement{580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435}, - }, - { - FieldElement{23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921}, - FieldElement{13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518}, - FieldElement{2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563}, - }, - { - FieldElement{14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278}, - FieldElement{-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024}, - FieldElement{4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030}, - }, - { - FieldElement{10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783}, - FieldElement{27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717}, - FieldElement{6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844}, - }, - { - FieldElement{14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333}, - FieldElement{16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048}, - FieldElement{22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760}, - }, - { - FieldElement{-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760}, - FieldElement{-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757}, - FieldElement{-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112}, - }, - }, - { - { - FieldElement{-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468}, - FieldElement{3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184}, - FieldElement{10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289}, - }, - { - FieldElement{15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066}, - FieldElement{24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882}, - FieldElement{13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226}, - }, - { - FieldElement{16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101}, - FieldElement{29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279}, - FieldElement{-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811}, - }, - { - FieldElement{27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709}, - FieldElement{20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714}, - FieldElement{-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121}, - }, - { - FieldElement{9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464}, - FieldElement{12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847}, - FieldElement{13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400}, - }, - { - FieldElement{4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414}, - FieldElement{-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158}, - FieldElement{17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045}, - }, - { - FieldElement{-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415}, - FieldElement{-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459}, - FieldElement{-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079}, - }, - { - FieldElement{21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412}, - FieldElement{-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743}, - FieldElement{-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836}, - }, - }, - { - { - FieldElement{12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022}, - FieldElement{18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429}, - FieldElement{-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065}, - }, - { - FieldElement{30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861}, - FieldElement{10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000}, - FieldElement{-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101}, - }, - { - FieldElement{32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815}, - FieldElement{29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642}, - FieldElement{10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966}, - }, - { - FieldElement{25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574}, - FieldElement{-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742}, - FieldElement{-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689}, - }, - { - FieldElement{12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020}, - FieldElement{-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772}, - FieldElement{3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982}, - }, - { - FieldElement{-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953}, - FieldElement{-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218}, - FieldElement{-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265}, - }, - { - FieldElement{29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073}, - FieldElement{-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325}, - FieldElement{-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798}, - }, - { - FieldElement{-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870}, - FieldElement{-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863}, - FieldElement{-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927}, - }, - }, - { - { - FieldElement{-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267}, - FieldElement{-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663}, - FieldElement{22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862}, - }, - { - FieldElement{-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673}, - FieldElement{15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943}, - FieldElement{15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020}, - }, - { - FieldElement{-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238}, - FieldElement{11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064}, - FieldElement{14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795}, - }, - { - FieldElement{15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052}, - FieldElement{-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904}, - FieldElement{29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531}, - }, - { - FieldElement{-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979}, - FieldElement{-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841}, - FieldElement{10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431}, - }, - { - FieldElement{10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324}, - FieldElement{-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940}, - FieldElement{10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320}, - }, - { - FieldElement{-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184}, - FieldElement{14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114}, - FieldElement{30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878}, - }, - { - FieldElement{12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784}, - FieldElement{-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091}, - FieldElement{-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585}, - }, - }, - { - { - FieldElement{-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208}, - FieldElement{10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864}, - FieldElement{17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661}, - }, - { - FieldElement{7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233}, - FieldElement{26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212}, - FieldElement{-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525}, - }, - { - FieldElement{-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068}, - FieldElement{9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397}, - FieldElement{-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988}, - }, - { - FieldElement{5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889}, - FieldElement{32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038}, - FieldElement{14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697}, - }, - { - FieldElement{20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875}, - FieldElement{-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905}, - FieldElement{-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656}, - }, - { - FieldElement{11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818}, - FieldElement{27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714}, - FieldElement{10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203}, - }, - { - FieldElement{20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931}, - FieldElement{-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024}, - FieldElement{-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084}, - }, - { - FieldElement{-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204}, - FieldElement{20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817}, - FieldElement{27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667}, - }, - }, - { - { - FieldElement{11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504}, - FieldElement{-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768}, - FieldElement{-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255}, - }, - { - FieldElement{6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790}, - FieldElement{1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438}, - FieldElement{-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333}, - }, - { - FieldElement{17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971}, - FieldElement{31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905}, - FieldElement{29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409}, - }, - { - FieldElement{12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409}, - FieldElement{6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499}, - FieldElement{-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363}, - }, - { - FieldElement{28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664}, - FieldElement{-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324}, - FieldElement{-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940}, - }, - { - FieldElement{13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990}, - FieldElement{-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914}, - FieldElement{-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290}, - }, - { - FieldElement{24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257}, - FieldElement{-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433}, - FieldElement{-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236}, - }, - { - FieldElement{-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045}, - FieldElement{11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093}, - FieldElement{-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347}, - }, - }, - { - { - FieldElement{-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191}, - FieldElement{-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507}, - FieldElement{-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906}, - }, - { - FieldElement{3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018}, - FieldElement{-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109}, - FieldElement{-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926}, - }, - { - FieldElement{-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528}, - FieldElement{8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625}, - FieldElement{-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286}, - }, - { - FieldElement{2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033}, - FieldElement{27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866}, - FieldElement{21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896}, - }, - { - FieldElement{30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075}, - FieldElement{26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347}, - FieldElement{-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437}, - }, - { - FieldElement{-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165}, - FieldElement{-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588}, - FieldElement{-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193}, - }, - { - FieldElement{-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017}, - FieldElement{-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883}, - FieldElement{21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961}, - }, - { - FieldElement{8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043}, - FieldElement{29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663}, - FieldElement{-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362}, - }, - }, - { - { - FieldElement{-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860}, - FieldElement{2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466}, - FieldElement{-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063}, - }, - { - FieldElement{-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997}, - FieldElement{-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295}, - FieldElement{-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369}, - }, - { - FieldElement{9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385}, - FieldElement{18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109}, - FieldElement{2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906}, - }, - { - FieldElement{4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424}, - FieldElement{-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185}, - FieldElement{7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962}, - }, - { - FieldElement{-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325}, - FieldElement{10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593}, - FieldElement{696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404}, - }, - { - FieldElement{-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644}, - FieldElement{17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801}, - FieldElement{26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804}, - }, - { - FieldElement{-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884}, - FieldElement{-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577}, - FieldElement{-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849}, - }, - { - FieldElement{32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473}, - FieldElement{-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644}, - FieldElement{-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319}, - }, - }, - { - { - FieldElement{-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599}, - FieldElement{-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768}, - FieldElement{-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084}, - }, - { - FieldElement{-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328}, - FieldElement{-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369}, - FieldElement{20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920}, - }, - { - FieldElement{12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815}, - FieldElement{-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025}, - FieldElement{-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397}, - }, - { - FieldElement{-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448}, - FieldElement{6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981}, - FieldElement{30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165}, - }, - { - FieldElement{32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501}, - FieldElement{17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073}, - FieldElement{-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861}, - }, - { - FieldElement{14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845}, - FieldElement{-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211}, - FieldElement{18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870}, - }, - { - FieldElement{10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096}, - FieldElement{33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803}, - FieldElement{-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168}, - }, - { - FieldElement{30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965}, - FieldElement{-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505}, - FieldElement{18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598}, - }, - }, - { - { - FieldElement{5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782}, - FieldElement{5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900}, - FieldElement{-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479}, - }, - { - FieldElement{-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208}, - FieldElement{8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232}, - FieldElement{17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719}, - }, - { - FieldElement{16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271}, - FieldElement{-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326}, - FieldElement{-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132}, - }, - { - FieldElement{14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300}, - FieldElement{8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570}, - FieldElement{15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670}, - }, - { - FieldElement{-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994}, - FieldElement{-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913}, - FieldElement{31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317}, - }, - { - FieldElement{-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730}, - FieldElement{842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096}, - FieldElement{-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078}, - }, - { - FieldElement{-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411}, - FieldElement{-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905}, - FieldElement{-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654}, - }, - { - FieldElement{-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870}, - FieldElement{-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498}, - FieldElement{12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579}, - }, - }, - { - { - FieldElement{14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677}, - FieldElement{10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647}, - FieldElement{-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743}, - }, - { - FieldElement{-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468}, - FieldElement{21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375}, - FieldElement{-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155}, - }, - { - FieldElement{6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725}, - FieldElement{-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612}, - FieldElement{-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943}, - }, - { - FieldElement{-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944}, - FieldElement{30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928}, - FieldElement{9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406}, - }, - { - FieldElement{22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139}, - FieldElement{-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963}, - FieldElement{-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693}, - }, - { - FieldElement{1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734}, - FieldElement{-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680}, - FieldElement{-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410}, - }, - { - FieldElement{-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931}, - FieldElement{-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654}, - FieldElement{22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710}, - }, - { - FieldElement{29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180}, - FieldElement{-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684}, - FieldElement{-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895}, - }, - }, - { - { - FieldElement{22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501}, - FieldElement{-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413}, - FieldElement{6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880}, - }, - { - FieldElement{-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874}, - FieldElement{22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962}, - FieldElement{-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899}, - }, - { - FieldElement{21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152}, - FieldElement{9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063}, - FieldElement{7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080}, - }, - { - FieldElement{-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146}, - FieldElement{-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183}, - FieldElement{-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133}, - }, - { - FieldElement{-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421}, - FieldElement{-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622}, - FieldElement{-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197}, - }, - { - FieldElement{2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663}, - FieldElement{31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753}, - FieldElement{4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755}, - }, - { - FieldElement{-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862}, - FieldElement{-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118}, - FieldElement{26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171}, - }, - { - FieldElement{15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380}, - FieldElement{16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824}, - FieldElement{28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270}, - }, - }, - { - { - FieldElement{-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438}, - FieldElement{-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584}, - FieldElement{-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562}, - }, - { - FieldElement{30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471}, - FieldElement{18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610}, - FieldElement{19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269}, - }, - { - FieldElement{-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650}, - FieldElement{14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369}, - FieldElement{19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461}, - }, - { - FieldElement{30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462}, - FieldElement{-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793}, - FieldElement{-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218}, - }, - { - FieldElement{-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226}, - FieldElement{18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019}, - FieldElement{-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037}, - }, - { - FieldElement{31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171}, - FieldElement{-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132}, - FieldElement{-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841}, - }, - { - FieldElement{21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181}, - FieldElement{-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210}, - FieldElement{-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040}, - }, - { - FieldElement{3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935}, - FieldElement{24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105}, - FieldElement{-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814}, - }, - }, - { - { - FieldElement{793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852}, - FieldElement{5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581}, - FieldElement{-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646}, - }, - { - FieldElement{10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844}, - FieldElement{10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025}, - FieldElement{27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453}, - }, - { - FieldElement{-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068}, - FieldElement{4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192}, - FieldElement{-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921}, - }, - { - FieldElement{-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259}, - FieldElement{-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426}, - FieldElement{-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072}, - }, - { - FieldElement{-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305}, - FieldElement{13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832}, - FieldElement{28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943}, - }, - { - FieldElement{-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011}, - FieldElement{24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447}, - FieldElement{17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494}, - }, - { - FieldElement{-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245}, - FieldElement{-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859}, - FieldElement{28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915}, - }, - { - FieldElement{16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707}, - FieldElement{10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848}, - FieldElement{-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224}, - }, - }, - { - { - FieldElement{-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391}, - FieldElement{15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215}, - FieldElement{-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101}, - }, - { - FieldElement{23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713}, - FieldElement{21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849}, - FieldElement{-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930}, - }, - { - FieldElement{-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940}, - FieldElement{-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031}, - FieldElement{-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404}, - }, - { - FieldElement{-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243}, - FieldElement{-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116}, - FieldElement{-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525}, - }, - { - FieldElement{-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509}, - FieldElement{-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883}, - FieldElement{15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865}, - }, - { - FieldElement{-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660}, - FieldElement{4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273}, - FieldElement{-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138}, - }, - { - FieldElement{-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560}, - FieldElement{-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135}, - FieldElement{2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941}, - }, - { - FieldElement{-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739}, - FieldElement{18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756}, - FieldElement{-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819}, - }, - }, - { - { - FieldElement{-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347}, - FieldElement{-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028}, - FieldElement{21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075}, - }, - { - FieldElement{16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799}, - FieldElement{-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609}, - FieldElement{-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817}, - }, - { - FieldElement{-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989}, - FieldElement{-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523}, - FieldElement{4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278}, - }, - { - FieldElement{31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045}, - FieldElement{19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377}, - FieldElement{24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480}, - }, - { - FieldElement{17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016}, - FieldElement{510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426}, - FieldElement{18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525}, - }, - { - FieldElement{13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396}, - FieldElement{9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080}, - FieldElement{12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892}, - }, - { - FieldElement{15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275}, - FieldElement{11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074}, - FieldElement{20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140}, - }, - { - FieldElement{-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717}, - FieldElement{-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101}, - FieldElement{24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127}, - }, - }, - { - { - FieldElement{-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632}, - FieldElement{-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415}, - FieldElement{-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160}, - }, - { - FieldElement{31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876}, - FieldElement{22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625}, - FieldElement{-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478}, - }, - { - FieldElement{27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164}, - FieldElement{26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595}, - FieldElement{-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248}, - }, - { - FieldElement{-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858}, - FieldElement{15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193}, - FieldElement{8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184}, - }, - { - FieldElement{-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942}, - FieldElement{-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635}, - FieldElement{21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948}, - }, - { - FieldElement{11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935}, - FieldElement{-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415}, - FieldElement{-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416}, - }, - { - FieldElement{-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018}, - FieldElement{4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778}, - FieldElement{366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659}, - }, - { - FieldElement{-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385}, - FieldElement{18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503}, - FieldElement{476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329}, - }, - }, - { - { - FieldElement{20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056}, - FieldElement{-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838}, - FieldElement{24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948}, - }, - { - FieldElement{-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691}, - FieldElement{-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118}, - FieldElement{-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517}, - }, - { - FieldElement{-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269}, - FieldElement{-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904}, - FieldElement{-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589}, - }, - { - FieldElement{-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193}, - FieldElement{-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910}, - FieldElement{-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930}, - }, - { - FieldElement{-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667}, - FieldElement{25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481}, - FieldElement{-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876}, - }, - { - FieldElement{22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640}, - FieldElement{-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278}, - FieldElement{-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112}, - }, - { - FieldElement{26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272}, - FieldElement{17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012}, - FieldElement{-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221}, - }, - { - FieldElement{30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046}, - FieldElement{13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345}, - FieldElement{-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310}, - }, - }, - { - { - FieldElement{19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937}, - FieldElement{31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636}, - FieldElement{-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008}, - }, - { - FieldElement{-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429}, - FieldElement{-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576}, - FieldElement{31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066}, - }, - { - FieldElement{-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490}, - FieldElement{-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104}, - FieldElement{33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053}, - }, - { - FieldElement{31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275}, - FieldElement{-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511}, - FieldElement{22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095}, - }, - { - FieldElement{-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439}, - FieldElement{23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939}, - FieldElement{-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424}, - }, - { - FieldElement{2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310}, - FieldElement{3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608}, - FieldElement{-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079}, - }, - { - FieldElement{-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101}, - FieldElement{21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418}, - FieldElement{18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576}, - }, - { - FieldElement{30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356}, - FieldElement{9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996}, - FieldElement{-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099}, - }, - }, - { - { - FieldElement{-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728}, - FieldElement{-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658}, - FieldElement{-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242}, - }, - { - FieldElement{-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001}, - FieldElement{-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766}, - FieldElement{18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373}, - }, - { - FieldElement{26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458}, - FieldElement{-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628}, - FieldElement{-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657}, - }, - { - FieldElement{-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062}, - FieldElement{25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616}, - FieldElement{31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014}, - }, - { - FieldElement{24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383}, - FieldElement{-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814}, - FieldElement{-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718}, - }, - { - FieldElement{30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417}, - FieldElement{2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222}, - FieldElement{33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444}, - }, - { - FieldElement{-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597}, - FieldElement{23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970}, - FieldElement{1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799}, - }, - { - FieldElement{-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647}, - FieldElement{13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511}, - FieldElement{-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032}, - }, - }, - { - { - FieldElement{9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834}, - FieldElement{-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461}, - FieldElement{29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062}, - }, - { - FieldElement{-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516}, - FieldElement{-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547}, - FieldElement{-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240}, - }, - { - FieldElement{-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038}, - FieldElement{-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741}, - FieldElement{16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103}, - }, - { - FieldElement{-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747}, - FieldElement{-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323}, - FieldElement{31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016}, - }, - { - FieldElement{-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373}, - FieldElement{15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228}, - FieldElement{-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141}, - }, - { - FieldElement{16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399}, - FieldElement{11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831}, - FieldElement{-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376}, - }, - { - FieldElement{-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313}, - FieldElement{-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958}, - FieldElement{-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577}, - }, - { - FieldElement{-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743}, - FieldElement{29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684}, - FieldElement{-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476}, - }, - }, -} diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go deleted file mode 100644 index fd03c252..00000000 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go +++ /dev/null @@ -1,1793 +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 edwards25519 - -import "encoding/binary" - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// FieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type FieldElement [10]int32 - -var zero FieldElement - -func FeZero(fe *FieldElement) { - copy(fe[:], zero[:]) -} - -func FeOne(fe *FieldElement) { - FeZero(fe) - fe[0] = 1 -} - -func FeAdd(dst, a, b *FieldElement) { - dst[0] = a[0] + b[0] - dst[1] = a[1] + b[1] - dst[2] = a[2] + b[2] - dst[3] = a[3] + b[3] - dst[4] = a[4] + b[4] - dst[5] = a[5] + b[5] - dst[6] = a[6] + b[6] - dst[7] = a[7] + b[7] - dst[8] = a[8] + b[8] - dst[9] = a[9] + b[9] -} - -func FeSub(dst, a, b *FieldElement) { - dst[0] = a[0] - b[0] - dst[1] = a[1] - b[1] - dst[2] = a[2] - b[2] - dst[3] = a[3] - b[3] - dst[4] = a[4] - b[4] - dst[5] = a[5] - b[5] - dst[6] = a[6] - b[6] - dst[7] = a[7] - b[7] - dst[8] = a[8] - b[8] - dst[9] = a[9] - b[9] -} - -func FeCopy(dst, src *FieldElement) { - copy(dst[:], src[:]) -} - -// Replace (f,g) with (g,g) if b == 1; -// replace (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func FeCMove(f, g *FieldElement, b int32) { - b = -b - f[0] ^= b & (f[0] ^ g[0]) - f[1] ^= b & (f[1] ^ g[1]) - f[2] ^= b & (f[2] ^ g[2]) - f[3] ^= b & (f[3] ^ g[3]) - f[4] ^= b & (f[4] ^ g[4]) - f[5] ^= b & (f[5] ^ g[5]) - f[6] ^= b & (f[6] ^ g[6]) - f[7] ^= b & (f[7] ^ g[7]) - f[8] ^= b & (f[8] ^ g[8]) - f[9] ^= b & (f[9] ^ g[9]) -} - -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -func load4(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -func FeFromBytes(dst *FieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 8388607) << 2 - - FeCombine(dst, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -func FeIsNegative(f *FieldElement) byte { - var s [32]byte - FeToBytes(&s, f) - return s[0] & 1 -} - -func FeIsNonZero(f *FieldElement) int32 { - var s [32]byte - FeToBytes(&s, f) - var x uint8 - for _, b := range s { - x |= b - } - x |= x >> 4 - x |= x >> 2 - x |= x >> 1 - return int32(x & 1) -} - -// FeNeg sets h = -f -// -// Preconditions: -// |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeNeg(h, f *FieldElement) { - h[0] = -f[0] - h[1] = -f[1] - h[2] = -f[2] - h[3] = -f[3] - h[4] = -f[4] - h[5] = -f[5] - h[6] = -f[6] - h[7] = -f[7] - h[8] = -f[8] - h[9] = -f[9] -} - -func FeCombine(h *FieldElement, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - var c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 int64 - - /* - |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - /* |h0| <= 2^25 */ - /* |h4| <= 2^25 */ - /* |h1| <= 1.51*2^58 */ - /* |h5| <= 1.51*2^58 */ - - c1 = (h1 + (1 << 24)) >> 25 - h2 += c1 - h1 -= c1 << 25 - c5 = (h5 + (1 << 24)) >> 25 - h6 += c5 - h5 -= c5 << 25 - /* |h1| <= 2^24; from now on fits into int32 */ - /* |h5| <= 2^24; from now on fits into int32 */ - /* |h2| <= 1.21*2^59 */ - /* |h6| <= 1.21*2^59 */ - - c2 = (h2 + (1 << 25)) >> 26 - h3 += c2 - h2 -= c2 << 26 - c6 = (h6 + (1 << 25)) >> 26 - h7 += c6 - h6 -= c6 << 26 - /* |h2| <= 2^25; from now on fits into int32 unchanged */ - /* |h6| <= 2^25; from now on fits into int32 unchanged */ - /* |h3| <= 1.51*2^58 */ - /* |h7| <= 1.51*2^58 */ - - c3 = (h3 + (1 << 24)) >> 25 - h4 += c3 - h3 -= c3 << 25 - c7 = (h7 + (1 << 24)) >> 25 - h8 += c7 - h7 -= c7 << 25 - /* |h3| <= 2^24; from now on fits into int32 unchanged */ - /* |h7| <= 2^24; from now on fits into int32 unchanged */ - /* |h4| <= 1.52*2^33 */ - /* |h8| <= 1.52*2^33 */ - - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - c8 = (h8 + (1 << 25)) >> 26 - h9 += c8 - h8 -= c8 << 26 - /* |h4| <= 2^25; from now on fits into int32 unchanged */ - /* |h8| <= 2^25; from now on fits into int32 unchanged */ - /* |h5| <= 1.01*2^24 */ - /* |h9| <= 1.51*2^58 */ - - c9 = (h9 + (1 << 24)) >> 25 - h0 += c9 * 19 - h9 -= c9 << 25 - /* |h9| <= 2^24; from now on fits into int32 unchanged */ - /* |h0| <= 1.8*2^37 */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - /* |h0| <= 2^25; from now on fits into int32 unchanged */ - /* |h1| <= 1.01*2^24 */ - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// FeMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs, can squeeze carries into int32. -func FeMul(h, f, g *FieldElement) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - - f1_2 := int64(2 * f[1]) - f3_2 := int64(2 * f[3]) - f5_2 := int64(2 * f[5]) - f7_2 := int64(2 * f[7]) - f9_2 := int64(2 * f[9]) - - g0 := int64(g[0]) - g1 := int64(g[1]) - g2 := int64(g[2]) - g3 := int64(g[3]) - g4 := int64(g[4]) - g5 := int64(g[5]) - g6 := int64(g[6]) - g7 := int64(g[7]) - g8 := int64(g[8]) - g9 := int64(g[9]) - - g1_19 := int64(19 * g[1]) /* 1.4*2^29 */ - g2_19 := int64(19 * g[2]) /* 1.4*2^30; still ok */ - g3_19 := int64(19 * g[3]) - g4_19 := int64(19 * g[4]) - g5_19 := int64(19 * g[5]) - g6_19 := int64(19 * g[6]) - g7_19 := int64(19 * g[7]) - g8_19 := int64(19 * g[8]) - g9_19 := int64(19 * g[9]) - - h0 := f0*g0 + f1_2*g9_19 + f2*g8_19 + f3_2*g7_19 + f4*g6_19 + f5_2*g5_19 + f6*g4_19 + f7_2*g3_19 + f8*g2_19 + f9_2*g1_19 - h1 := f0*g1 + f1*g0 + f2*g9_19 + f3*g8_19 + f4*g7_19 + f5*g6_19 + f6*g5_19 + f7*g4_19 + f8*g3_19 + f9*g2_19 - h2 := f0*g2 + f1_2*g1 + f2*g0 + f3_2*g9_19 + f4*g8_19 + f5_2*g7_19 + f6*g6_19 + f7_2*g5_19 + f8*g4_19 + f9_2*g3_19 - h3 := f0*g3 + f1*g2 + f2*g1 + f3*g0 + f4*g9_19 + f5*g8_19 + f6*g7_19 + f7*g6_19 + f8*g5_19 + f9*g4_19 - h4 := f0*g4 + f1_2*g3 + f2*g2 + f3_2*g1 + f4*g0 + f5_2*g9_19 + f6*g8_19 + f7_2*g7_19 + f8*g6_19 + f9_2*g5_19 - h5 := f0*g5 + f1*g4 + f2*g3 + f3*g2 + f4*g1 + f5*g0 + f6*g9_19 + f7*g8_19 + f8*g7_19 + f9*g6_19 - h6 := f0*g6 + f1_2*g5 + f2*g4 + f3_2*g3 + f4*g2 + f5_2*g1 + f6*g0 + f7_2*g9_19 + f8*g8_19 + f9_2*g7_19 - h7 := f0*g7 + f1*g6 + f2*g5 + f3*g4 + f4*g3 + f5*g2 + f6*g1 + f7*g0 + f8*g9_19 + f9*g8_19 - h8 := f0*g8 + f1_2*g7 + f2*g6 + f3_2*g5 + f4*g4 + f5_2*g3 + f6*g2 + f7_2*g1 + f8*g0 + f9_2*g9_19 - h9 := f0*g9 + f1*g8 + f2*g7 + f3*g6 + f4*g5 + f5*g4 + f6*g3 + f7*g2 + f8*g1 + f9*g0 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func feSquare(f *FieldElement) (h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - f0_2 := int64(2 * f[0]) - f1_2 := int64(2 * f[1]) - f2_2 := int64(2 * f[2]) - f3_2 := int64(2 * f[3]) - f4_2 := int64(2 * f[4]) - f5_2 := int64(2 * f[5]) - f6_2 := int64(2 * f[6]) - f7_2 := int64(2 * f[7]) - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - - h0 = f0*f0 + f1_2*f9_38 + f2_2*f8_19 + f3_2*f7_38 + f4_2*f6_19 + f5*f5_38 - h1 = f0_2*f1 + f2*f9_38 + f3_2*f8_19 + f4*f7_38 + f5_2*f6_19 - h2 = f0_2*f2 + f1_2*f1 + f3_2*f9_38 + f4_2*f8_19 + f5_2*f7_38 + f6*f6_19 - h3 = f0_2*f3 + f1_2*f2 + f4*f9_38 + f5_2*f8_19 + f6*f7_38 - h4 = f0_2*f4 + f1_2*f3_2 + f2*f2 + f5_2*f9_38 + f6_2*f8_19 + f7*f7_38 - h5 = f0_2*f5 + f1_2*f4 + f2_2*f3 + f6*f9_38 + f7_2*f8_19 - h6 = f0_2*f6 + f1_2*f5_2 + f2_2*f4 + f3_2*f3 + f7_2*f9_38 + f8*f8_19 - h7 = f0_2*f7 + f1_2*f6 + f2_2*f5 + f3_2*f4 + f8*f9_38 - h8 = f0_2*f8 + f1_2*f7_2 + f2_2*f6 + f3_2*f5_2 + f4*f4 + f9*f9_38 - h9 = f0_2*f9 + f1_2*f8 + f2_2*f7 + f3_2*f6 + f4_2*f5 - - return -} - -// FeSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeSquare(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeSquare2 sets h = 2 * f * f -// -// Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. -// See fe_mul.c for discussion of implementation strategy. -func FeSquare2(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - - h0 += h0 - h1 += h1 - h2 += h2 - h3 += h3 - h4 += h4 - h5 += h5 - h6 += h6 - h7 += h7 - h8 += h8 - h9 += h9 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func FeInvert(out, z *FieldElement) { - var t0, t1, t2, t3 FieldElement - var i int - - FeSquare(&t0, z) // 2^1 - FeSquare(&t1, &t0) // 2^2 - for i = 1; i < 2; i++ { // 2^3 - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) // 2^3 + 2^0 - FeMul(&t0, &t0, &t1) // 2^3 + 2^1 + 2^0 - FeSquare(&t2, &t0) // 2^4 + 2^2 + 2^1 - FeMul(&t1, &t1, &t2) // 2^4 + 2^3 + 2^2 + 2^1 + 2^0 - FeSquare(&t2, &t1) // 5,4,3,2,1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 19..0 - FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 39..0 - FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 49..0 - FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 99..0 - FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 199..0 - FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 249..0 - FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 5; i++ { // 254..5 - FeSquare(&t1, &t1) - } - FeMul(out, &t1, &t0) // 254..5,3,1,0 -} - -func fePow22523(out, z *FieldElement) { - var t0, t1, t2 FieldElement - var i int - - FeSquare(&t0, z) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeSquare(&t1, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) - FeMul(&t0, &t0, &t1) - FeSquare(&t0, &t0) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 5; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 20; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 100; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t0, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t0, &t0) - } - FeMul(out, &t0, z) -} - -// Group elements are members of the elliptic curve -x^2 + y^2 = 1 + d * x^2 * -// y^2 where d = -121665/121666. -// -// Several representations are used: -// ProjectiveGroupElement: (X:Y:Z) satisfying x=X/Z, y=Y/Z -// ExtendedGroupElement: (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT -// CompletedGroupElement: ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T -// PreComputedGroupElement: (y+x,y-x,2dxy) - -type ProjectiveGroupElement struct { - X, Y, Z FieldElement -} - -type ExtendedGroupElement struct { - X, Y, Z, T FieldElement -} - -type CompletedGroupElement struct { - X, Y, Z, T FieldElement -} - -type PreComputedGroupElement struct { - yPlusX, yMinusX, xy2d FieldElement -} - -type CachedGroupElement struct { - yPlusX, yMinusX, Z, T2d FieldElement -} - -func (p *ProjectiveGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) -} - -func (p *ProjectiveGroupElement) Double(r *CompletedGroupElement) { - var t0 FieldElement - - FeSquare(&r.X, &p.X) - FeSquare(&r.Z, &p.Y) - FeSquare2(&r.T, &p.Z) - FeAdd(&r.Y, &p.X, &p.Y) - FeSquare(&t0, &r.Y) - FeAdd(&r.Y, &r.Z, &r.X) - FeSub(&r.Z, &r.Z, &r.X) - FeSub(&r.X, &t0, &r.Y) - FeSub(&r.T, &r.T, &r.Z) -} - -func (p *ProjectiveGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) - FeZero(&p.T) -} - -func (p *ExtendedGroupElement) Double(r *CompletedGroupElement) { - var q ProjectiveGroupElement - p.ToProjective(&q) - q.Double(r) -} - -func (p *ExtendedGroupElement) ToCached(r *CachedGroupElement) { - FeAdd(&r.yPlusX, &p.Y, &p.X) - FeSub(&r.yMinusX, &p.Y, &p.X) - FeCopy(&r.Z, &p.Z) - FeMul(&r.T2d, &p.T, &d2) -} - -func (p *ExtendedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeCopy(&r.X, &p.X) - FeCopy(&r.Y, &p.Y) - FeCopy(&r.Z, &p.Z) -} - -func (p *ExtendedGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) FromBytes(s *[32]byte) bool { - var u, v, v3, vxx, check FieldElement - - FeFromBytes(&p.Y, s) - FeOne(&p.Z) - FeSquare(&u, &p.Y) - FeMul(&v, &u, &d) - FeSub(&u, &u, &p.Z) // y = y^2-1 - FeAdd(&v, &v, &p.Z) // v = dy^2+1 - - FeSquare(&v3, &v) - FeMul(&v3, &v3, &v) // v3 = v^3 - FeSquare(&p.X, &v3) - FeMul(&p.X, &p.X, &v) - FeMul(&p.X, &p.X, &u) // x = uv^7 - - fePow22523(&p.X, &p.X) // x = (uv^7)^((q-5)/8) - FeMul(&p.X, &p.X, &v3) - FeMul(&p.X, &p.X, &u) // x = uv^3(uv^7)^((q-5)/8) - - var tmpX, tmp2 [32]byte - - FeSquare(&vxx, &p.X) - FeMul(&vxx, &vxx, &v) - FeSub(&check, &vxx, &u) // vx^2-u - if FeIsNonZero(&check) == 1 { - FeAdd(&check, &vxx, &u) // vx^2+u - if FeIsNonZero(&check) == 1 { - return false - } - FeMul(&p.X, &p.X, &SqrtM1) - - FeToBytes(&tmpX, &p.X) - for i, v := range tmpX { - tmp2[31-i] = v - } - } - - if FeIsNegative(&p.X) != (s[31] >> 7) { - FeNeg(&p.X, &p.X) - } - - FeMul(&p.T, &p.X, &p.Y) - return true -} - -func (p *CompletedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) -} - -func (p *CompletedGroupElement) ToExtended(r *ExtendedGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) - FeMul(&r.T, &p.X, &p.Y) -} - -func (p *PreComputedGroupElement) Zero() { - FeOne(&p.yPlusX) - FeOne(&p.yMinusX) - FeZero(&p.xy2d) -} - -func geAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func geMixedAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geMixedSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func slide(r *[256]int8, a *[32]byte) { - for i := range r { - r[i] = int8(1 & (a[i>>3] >> uint(i&7))) - } - - for i := range r { - if r[i] != 0 { - for b := 1; b <= 6 && i+b < 256; b++ { - if r[i+b] != 0 { - if r[i]+(r[i+b]<= -15 { - r[i] -= r[i+b] << uint(b) - for k := i + b; k < 256; k++ { - if r[k] == 0 { - r[k] = 1 - break - } - r[k] = 0 - } - } else { - break - } - } - } - } - } -} - -// GeDoubleScalarMultVartime sets r = a*A + b*B -// where a = a[0]+256*a[1]+...+256^31 a[31]. -// and b = b[0]+256*b[1]+...+256^31 b[31]. -// B is the Ed25519 base point (x,4/5) with x positive. -func GeDoubleScalarMultVartime(r *ProjectiveGroupElement, a *[32]byte, A *ExtendedGroupElement, b *[32]byte) { - var aSlide, bSlide [256]int8 - var Ai [8]CachedGroupElement // A,3A,5A,7A,9A,11A,13A,15A - var t CompletedGroupElement - var u, A2 ExtendedGroupElement - var i int - - slide(&aSlide, a) - slide(&bSlide, b) - - A.ToCached(&Ai[0]) - A.Double(&t) - t.ToExtended(&A2) - - for i := 0; i < 7; i++ { - geAdd(&t, &A2, &Ai[i]) - t.ToExtended(&u) - u.ToCached(&Ai[i+1]) - } - - r.Zero() - - for i = 255; i >= 0; i-- { - if aSlide[i] != 0 || bSlide[i] != 0 { - break - } - } - - for ; i >= 0; i-- { - r.Double(&t) - - if aSlide[i] > 0 { - t.ToExtended(&u) - geAdd(&t, &u, &Ai[aSlide[i]/2]) - } else if aSlide[i] < 0 { - t.ToExtended(&u) - geSub(&t, &u, &Ai[(-aSlide[i])/2]) - } - - if bSlide[i] > 0 { - t.ToExtended(&u) - geMixedAdd(&t, &u, &bi[bSlide[i]/2]) - } else if bSlide[i] < 0 { - t.ToExtended(&u) - geMixedSub(&t, &u, &bi[(-bSlide[i])/2]) - } - - t.ToProjective(r) - } -} - -// equal returns 1 if b == c and 0 otherwise, assuming that b and c are -// non-negative. -func equal(b, c int32) int32 { - x := uint32(b ^ c) - x-- - return int32(x >> 31) -} - -// negative returns 1 if b < 0 and 0 otherwise. -func negative(b int32) int32 { - return (b >> 31) & 1 -} - -func PreComputedGroupElementCMove(t, u *PreComputedGroupElement, b int32) { - FeCMove(&t.yPlusX, &u.yPlusX, b) - FeCMove(&t.yMinusX, &u.yMinusX, b) - FeCMove(&t.xy2d, &u.xy2d, b) -} - -func selectPoint(t *PreComputedGroupElement, pos int32, b int32) { - var minusT PreComputedGroupElement - bNegative := negative(b) - bAbs := b - (((-bNegative) & b) << 1) - - t.Zero() - for i := int32(0); i < 8; i++ { - PreComputedGroupElementCMove(t, &base[pos][i], equal(bAbs, i+1)) - } - FeCopy(&minusT.yPlusX, &t.yMinusX) - FeCopy(&minusT.yMinusX, &t.yPlusX) - FeNeg(&minusT.xy2d, &t.xy2d) - PreComputedGroupElementCMove(t, &minusT, bNegative) -} - -// GeScalarMultBase computes h = a*B, where -// a = a[0]+256*a[1]+...+256^31 a[31] -// B is the Ed25519 base point (x,4/5) with x positive. -// -// Preconditions: -// a[31] <= 127 -func GeScalarMultBase(h *ExtendedGroupElement, a *[32]byte) { - var e [64]int8 - - for i, v := range a { - e[2*i] = int8(v & 15) - e[2*i+1] = int8((v >> 4) & 15) - } - - // each e[i] is between 0 and 15 and e[63] is between 0 and 7. - - carry := int8(0) - for i := 0; i < 63; i++ { - e[i] += carry - carry = (e[i] + 8) >> 4 - e[i] -= carry << 4 - } - e[63] += carry - // each e[i] is between -8 and 8. - - h.Zero() - var t PreComputedGroupElement - var r CompletedGroupElement - for i := int32(1); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } - - var s ProjectiveGroupElement - - h.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToExtended(h) - - for i := int32(0); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } -} - -// The scalars are GF(2^252 + 27742317777372353535851937790883648493). - -// Input: -// a[0]+256*a[1]+...+256^31*a[31] = a -// b[0]+256*b[1]+...+256^31*b[31] = b -// c[0]+256*c[1]+...+256^31*c[31] = c -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScMulAdd(s, a, b, c *[32]byte) { - a0 := 2097151 & load3(a[:]) - a1 := 2097151 & (load4(a[2:]) >> 5) - a2 := 2097151 & (load3(a[5:]) >> 2) - a3 := 2097151 & (load4(a[7:]) >> 7) - a4 := 2097151 & (load4(a[10:]) >> 4) - a5 := 2097151 & (load3(a[13:]) >> 1) - a6 := 2097151 & (load4(a[15:]) >> 6) - a7 := 2097151 & (load3(a[18:]) >> 3) - a8 := 2097151 & load3(a[21:]) - a9 := 2097151 & (load4(a[23:]) >> 5) - a10 := 2097151 & (load3(a[26:]) >> 2) - a11 := (load4(a[28:]) >> 7) - b0 := 2097151 & load3(b[:]) - b1 := 2097151 & (load4(b[2:]) >> 5) - b2 := 2097151 & (load3(b[5:]) >> 2) - b3 := 2097151 & (load4(b[7:]) >> 7) - b4 := 2097151 & (load4(b[10:]) >> 4) - b5 := 2097151 & (load3(b[13:]) >> 1) - b6 := 2097151 & (load4(b[15:]) >> 6) - b7 := 2097151 & (load3(b[18:]) >> 3) - b8 := 2097151 & load3(b[21:]) - b9 := 2097151 & (load4(b[23:]) >> 5) - b10 := 2097151 & (load3(b[26:]) >> 2) - b11 := (load4(b[28:]) >> 7) - c0 := 2097151 & load3(c[:]) - c1 := 2097151 & (load4(c[2:]) >> 5) - c2 := 2097151 & (load3(c[5:]) >> 2) - c3 := 2097151 & (load4(c[7:]) >> 7) - c4 := 2097151 & (load4(c[10:]) >> 4) - c5 := 2097151 & (load3(c[13:]) >> 1) - c6 := 2097151 & (load4(c[15:]) >> 6) - c7 := 2097151 & (load3(c[18:]) >> 3) - c8 := 2097151 & load3(c[21:]) - c9 := 2097151 & (load4(c[23:]) >> 5) - c10 := 2097151 & (load3(c[26:]) >> 2) - c11 := (load4(c[28:]) >> 7) - var carry [23]int64 - - s0 := c0 + a0*b0 - s1 := c1 + a0*b1 + a1*b0 - s2 := c2 + a0*b2 + a1*b1 + a2*b0 - s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 - s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 - s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 - s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 - s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 - s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 - s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 - s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 - s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 - s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 - s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 - s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 - s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 - s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 - s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 - s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 - s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 - s20 := a9*b11 + a10*b10 + a11*b9 - s21 := a10*b11 + a11*b10 - s22 := a11 * b11 - s23 := int64(0) - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - carry[18] = (s18 + (1 << 20)) >> 21 - s19 += carry[18] - s18 -= carry[18] << 21 - carry[20] = (s20 + (1 << 20)) >> 21 - s21 += carry[20] - s20 -= carry[20] << 21 - carry[22] = (s22 + (1 << 20)) >> 21 - s23 += carry[22] - s22 -= carry[22] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - carry[17] = (s17 + (1 << 20)) >> 21 - s18 += carry[17] - s17 -= carry[17] << 21 - carry[19] = (s19 + (1 << 20)) >> 21 - s20 += carry[19] - s19 -= carry[19] << 21 - carry[21] = (s21 + (1 << 20)) >> 21 - s22 += carry[21] - s21 -= carry[21] << 21 - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - s[0] = byte(s0 >> 0) - s[1] = byte(s0 >> 8) - s[2] = byte((s0 >> 16) | (s1 << 5)) - s[3] = byte(s1 >> 3) - s[4] = byte(s1 >> 11) - s[5] = byte((s1 >> 19) | (s2 << 2)) - s[6] = byte(s2 >> 6) - s[7] = byte((s2 >> 14) | (s3 << 7)) - s[8] = byte(s3 >> 1) - s[9] = byte(s3 >> 9) - s[10] = byte((s3 >> 17) | (s4 << 4)) - s[11] = byte(s4 >> 4) - s[12] = byte(s4 >> 12) - s[13] = byte((s4 >> 20) | (s5 << 1)) - s[14] = byte(s5 >> 7) - s[15] = byte((s5 >> 15) | (s6 << 6)) - s[16] = byte(s6 >> 2) - s[17] = byte(s6 >> 10) - s[18] = byte((s6 >> 18) | (s7 << 3)) - s[19] = byte(s7 >> 5) - s[20] = byte(s7 >> 13) - s[21] = byte(s8 >> 0) - s[22] = byte(s8 >> 8) - s[23] = byte((s8 >> 16) | (s9 << 5)) - s[24] = byte(s9 >> 3) - s[25] = byte(s9 >> 11) - s[26] = byte((s9 >> 19) | (s10 << 2)) - s[27] = byte(s10 >> 6) - s[28] = byte((s10 >> 14) | (s11 << 7)) - s[29] = byte(s11 >> 1) - s[30] = byte(s11 >> 9) - s[31] = byte(s11 >> 17) -} - -// Input: -// s[0]+256*s[1]+...+256^63*s[63] = s -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = s mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScReduce(out *[32]byte, s *[64]byte) { - s0 := 2097151 & load3(s[:]) - s1 := 2097151 & (load4(s[2:]) >> 5) - s2 := 2097151 & (load3(s[5:]) >> 2) - s3 := 2097151 & (load4(s[7:]) >> 7) - s4 := 2097151 & (load4(s[10:]) >> 4) - s5 := 2097151 & (load3(s[13:]) >> 1) - s6 := 2097151 & (load4(s[15:]) >> 6) - s7 := 2097151 & (load3(s[18:]) >> 3) - s8 := 2097151 & load3(s[21:]) - s9 := 2097151 & (load4(s[23:]) >> 5) - s10 := 2097151 & (load3(s[26:]) >> 2) - s11 := 2097151 & (load4(s[28:]) >> 7) - s12 := 2097151 & (load4(s[31:]) >> 4) - s13 := 2097151 & (load3(s[34:]) >> 1) - s14 := 2097151 & (load4(s[36:]) >> 6) - s15 := 2097151 & (load3(s[39:]) >> 3) - s16 := 2097151 & load3(s[42:]) - s17 := 2097151 & (load4(s[44:]) >> 5) - s18 := 2097151 & (load3(s[47:]) >> 2) - s19 := 2097151 & (load4(s[49:]) >> 7) - s20 := 2097151 & (load4(s[52:]) >> 4) - s21 := 2097151 & (load3(s[55:]) >> 1) - s22 := 2097151 & (load4(s[57:]) >> 6) - s23 := (load4(s[60:]) >> 3) - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - var carry [17]int64 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - out[0] = byte(s0 >> 0) - out[1] = byte(s0 >> 8) - out[2] = byte((s0 >> 16) | (s1 << 5)) - out[3] = byte(s1 >> 3) - out[4] = byte(s1 >> 11) - out[5] = byte((s1 >> 19) | (s2 << 2)) - out[6] = byte(s2 >> 6) - out[7] = byte((s2 >> 14) | (s3 << 7)) - out[8] = byte(s3 >> 1) - out[9] = byte(s3 >> 9) - out[10] = byte((s3 >> 17) | (s4 << 4)) - out[11] = byte(s4 >> 4) - out[12] = byte(s4 >> 12) - out[13] = byte((s4 >> 20) | (s5 << 1)) - out[14] = byte(s5 >> 7) - out[15] = byte((s5 >> 15) | (s6 << 6)) - out[16] = byte(s6 >> 2) - out[17] = byte(s6 >> 10) - out[18] = byte((s6 >> 18) | (s7 << 3)) - out[19] = byte(s7 >> 5) - out[20] = byte(s7 >> 13) - out[21] = byte(s8 >> 0) - out[22] = byte(s8 >> 8) - out[23] = byte((s8 >> 16) | (s9 << 5)) - out[24] = byte(s9 >> 3) - out[25] = byte(s9 >> 11) - out[26] = byte((s9 >> 19) | (s10 << 2)) - out[27] = byte(s10 >> 6) - out[28] = byte((s10 >> 14) | (s11 << 7)) - out[29] = byte(s11 >> 1) - out[30] = byte(s11 >> 9) - out[31] = byte(s11 >> 17) -} - -// order is the order of Curve25519 in little-endian form. -var order = [4]uint64{0x5812631a5cf5d3ed, 0x14def9dea2f79cd6, 0, 0x1000000000000000} - -// ScMinimal returns true if the given scalar is less than the order of the -// curve. -func ScMinimal(scalar *[32]byte) bool { - for i := 3; ; i-- { - v := binary.LittleEndian.Uint64(scalar[i*8:]) - if v > order[i] { - return false - } else if v < order[i] { - break - } else if i == 0 { - return false - } - } - - return true -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s b/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s deleted file mode 100644 index b3a16ef7..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s +++ /dev/null @@ -1,308 +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. - -// +build go1.11 -// +build !gccgo,!appengine - -#include "textflag.h" - -#define NUM_ROUNDS 10 - -// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) -TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 - MOVD dst+0(FP), R1 - MOVD src+24(FP), R2 - MOVD src_len+32(FP), R3 - MOVD key+48(FP), R4 - MOVD nonce+56(FP), R6 - MOVD counter+64(FP), R7 - - MOVD $·constants(SB), R10 - MOVD $·incRotMatrix(SB), R11 - - MOVW (R7), R20 - - AND $~255, R3, R13 - ADD R2, R13, R12 // R12 for block end - AND $255, R3, R13 -loop: - MOVD $NUM_ROUNDS, R21 - VLD1 (R11), [V30.S4, V31.S4] - - // load contants - // VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4] - WORD $0x4D60E940 - - // load keys - // VLD4R 16(R4), [V4.S4, V5.S4, V6.S4, V7.S4] - WORD $0x4DFFE884 - // VLD4R 16(R4), [V8.S4, V9.S4, V10.S4, V11.S4] - WORD $0x4DFFE888 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V12.S4] - WORD $0x4D40C8EC - - // VLD3R (R6), [V13.S4, V14.S4, V15.S4] - WORD $0x4D40E8CD - - // update counter - VADD V30.S4, V12.S4, V12.S4 - -chacha: - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) - VADD V8.S4, V12.S4, V8.S4 - VADD V9.S4, V13.S4, V9.S4 - VADD V10.S4, V14.S4, V10.S4 - VADD V11.S4, V15.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $12, V16.S4, V4.S4 - VSHL $12, V17.S4, V5.S4 - VSHL $12, V18.S4, V6.S4 - VSHL $12, V19.S4, V7.S4 - VSRI $20, V16.S4, V4.S4 - VSRI $20, V17.S4, V5.S4 - VSRI $20, V18.S4, V6.S4 - VSRI $20, V19.S4, V7.S4 - - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) - VADD V12.S4, V8.S4, V8.S4 - VADD V13.S4, V9.S4, V9.S4 - VADD V14.S4, V10.S4, V10.S4 - VADD V15.S4, V11.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $7, V16.S4, V4.S4 - VSHL $7, V17.S4, V5.S4 - VSHL $7, V18.S4, V6.S4 - VSHL $7, V19.S4, V7.S4 - VSRI $25, V16.S4, V4.S4 - VSRI $25, V17.S4, V5.S4 - VSRI $25, V18.S4, V6.S4 - VSRI $25, V19.S4, V7.S4 - - // V0..V3 += V5..V7, V4 - // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) - VADD V0.S4, V5.S4, V0.S4 - VADD V1.S4, V6.S4, V1.S4 - VADD V2.S4, V7.S4, V2.S4 - VADD V3.S4, V4.S4, V3.S4 - VEOR V15.B16, V0.B16, V15.B16 - VEOR V12.B16, V1.B16, V12.B16 - VEOR V13.B16, V2.B16, V13.B16 - VEOR V14.B16, V3.B16, V14.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 12) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $12, V16.S4, V5.S4 - VSHL $12, V17.S4, V6.S4 - VSHL $12, V18.S4, V7.S4 - VSHL $12, V19.S4, V4.S4 - VSRI $20, V16.S4, V5.S4 - VSRI $20, V17.S4, V6.S4 - VSRI $20, V18.S4, V7.S4 - VSRI $20, V19.S4, V4.S4 - - // V0 += V5; V15 <<<= ((V0 XOR V15), 8) - // ... - VADD V5.S4, V0.S4, V0.S4 - VADD V6.S4, V1.S4, V1.S4 - VADD V7.S4, V2.S4, V2.S4 - VADD V4.S4, V3.S4, V3.S4 - VEOR V0.B16, V15.B16, V15.B16 - VEOR V1.B16, V12.B16, V12.B16 - VEOR V2.B16, V13.B16, V13.B16 - VEOR V3.B16, V14.B16, V14.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 7) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $7, V16.S4, V5.S4 - VSHL $7, V17.S4, V6.S4 - VSHL $7, V18.S4, V7.S4 - VSHL $7, V19.S4, V4.S4 - VSRI $25, V16.S4, V5.S4 - VSRI $25, V17.S4, V6.S4 - VSRI $25, V18.S4, V7.S4 - VSRI $25, V19.S4, V4.S4 - - SUB $1, R21 - CBNZ R21, chacha - - // VLD4R (R10), [V16.S4, V17.S4, V18.S4, V19.S4] - WORD $0x4D60E950 - - // VLD4R 16(R4), [V20.S4, V21.S4, V22.S4, V23.S4] - WORD $0x4DFFE894 - VADD V30.S4, V12.S4, V12.S4 - VADD V16.S4, V0.S4, V0.S4 - VADD V17.S4, V1.S4, V1.S4 - VADD V18.S4, V2.S4, V2.S4 - VADD V19.S4, V3.S4, V3.S4 - // VLD4R 16(R4), [V24.S4, V25.S4, V26.S4, V27.S4] - WORD $0x4DFFE898 - // restore R4 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V28.S4] - WORD $0x4D40C8FC - // VLD3R (R6), [V29.S4, V30.S4, V31.S4] - WORD $0x4D40E8DD - - VADD V20.S4, V4.S4, V4.S4 - VADD V21.S4, V5.S4, V5.S4 - VADD V22.S4, V6.S4, V6.S4 - VADD V23.S4, V7.S4, V7.S4 - VADD V24.S4, V8.S4, V8.S4 - VADD V25.S4, V9.S4, V9.S4 - VADD V26.S4, V10.S4, V10.S4 - VADD V27.S4, V11.S4, V11.S4 - VADD V28.S4, V12.S4, V12.S4 - VADD V29.S4, V13.S4, V13.S4 - VADD V30.S4, V14.S4, V14.S4 - VADD V31.S4, V15.S4, V15.S4 - - VZIP1 V1.S4, V0.S4, V16.S4 - VZIP2 V1.S4, V0.S4, V17.S4 - VZIP1 V3.S4, V2.S4, V18.S4 - VZIP2 V3.S4, V2.S4, V19.S4 - VZIP1 V5.S4, V4.S4, V20.S4 - VZIP2 V5.S4, V4.S4, V21.S4 - VZIP1 V7.S4, V6.S4, V22.S4 - VZIP2 V7.S4, V6.S4, V23.S4 - VZIP1 V9.S4, V8.S4, V24.S4 - VZIP2 V9.S4, V8.S4, V25.S4 - VZIP1 V11.S4, V10.S4, V26.S4 - VZIP2 V11.S4, V10.S4, V27.S4 - VZIP1 V13.S4, V12.S4, V28.S4 - VZIP2 V13.S4, V12.S4, V29.S4 - VZIP1 V15.S4, V14.S4, V30.S4 - VZIP2 V15.S4, V14.S4, V31.S4 - VZIP1 V18.D2, V16.D2, V0.D2 - VZIP2 V18.D2, V16.D2, V4.D2 - VZIP1 V19.D2, V17.D2, V8.D2 - VZIP2 V19.D2, V17.D2, V12.D2 - VLD1.P 64(R2), [V16.B16, V17.B16, V18.B16, V19.B16] - - VZIP1 V22.D2, V20.D2, V1.D2 - VZIP2 V22.D2, V20.D2, V5.D2 - VZIP1 V23.D2, V21.D2, V9.D2 - VZIP2 V23.D2, V21.D2, V13.D2 - VLD1.P 64(R2), [V20.B16, V21.B16, V22.B16, V23.B16] - VZIP1 V26.D2, V24.D2, V2.D2 - VZIP2 V26.D2, V24.D2, V6.D2 - VZIP1 V27.D2, V25.D2, V10.D2 - VZIP2 V27.D2, V25.D2, V14.D2 - VLD1.P 64(R2), [V24.B16, V25.B16, V26.B16, V27.B16] - VZIP1 V30.D2, V28.D2, V3.D2 - VZIP2 V30.D2, V28.D2, V7.D2 - VZIP1 V31.D2, V29.D2, V11.D2 - VZIP2 V31.D2, V29.D2, V15.D2 - VLD1.P 64(R2), [V28.B16, V29.B16, V30.B16, V31.B16] - VEOR V0.B16, V16.B16, V16.B16 - VEOR V1.B16, V17.B16, V17.B16 - VEOR V2.B16, V18.B16, V18.B16 - VEOR V3.B16, V19.B16, V19.B16 - VST1.P [V16.B16, V17.B16, V18.B16, V19.B16], 64(R1) - VEOR V4.B16, V20.B16, V20.B16 - VEOR V5.B16, V21.B16, V21.B16 - VEOR V6.B16, V22.B16, V22.B16 - VEOR V7.B16, V23.B16, V23.B16 - VST1.P [V20.B16, V21.B16, V22.B16, V23.B16], 64(R1) - VEOR V8.B16, V24.B16, V24.B16 - VEOR V9.B16, V25.B16, V25.B16 - VEOR V10.B16, V26.B16, V26.B16 - VEOR V11.B16, V27.B16, V27.B16 - VST1.P [V24.B16, V25.B16, V26.B16, V27.B16], 64(R1) - VEOR V12.B16, V28.B16, V28.B16 - VEOR V13.B16, V29.B16, V29.B16 - VEOR V14.B16, V30.B16, V30.B16 - VEOR V15.B16, V31.B16, V31.B16 - VST1.P [V28.B16, V29.B16, V30.B16, V31.B16], 64(R1) - - ADD $4, R20 - MOVW R20, (R7) // update counter - - CMP R2, R12 - BGT loop - - RET - - -DATA ·constants+0x00(SB)/4, $0x61707865 -DATA ·constants+0x04(SB)/4, $0x3320646e -DATA ·constants+0x08(SB)/4, $0x79622d32 -DATA ·constants+0x0c(SB)/4, $0x6b206574 -GLOBL ·constants(SB), NOPTR|RODATA, $32 - -DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 -DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 -DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 -DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 -DATA ·incRotMatrix+0x10(SB)/4, $0x02010003 -DATA ·incRotMatrix+0x14(SB)/4, $0x06050407 -DATA ·incRotMatrix+0x18(SB)/4, $0x0A09080B -DATA ·incRotMatrix+0x1c(SB)/4, $0x0E0D0C0F -GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go deleted file mode 100644 index ad74e23a..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go +++ /dev/null @@ -1,31 +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. - -// +build go1.11 -// +build !gccgo - -package chacha20 - -const ( - haveAsm = true - bufSize = 256 -) - -//go:noescape -func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - - if len(src) >= bufSize { - xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) - } - - if len(src)%bufSize != 0 { - i := len(src) - len(src)%bufSize - c.buf = [bufSize]byte{} - copy(c.buf[:], src[i:]) - xorKeyStreamVX(c.buf[:], c.buf[:], &c.key, &c.nonce, &c.counter) - c.len = bufSize - copy(dst[i:], c.buf[:len(src)%bufSize]) - } -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go deleted file mode 100644 index 6570847f..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go +++ /dev/null @@ -1,264 +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 ChaCha20 implements the core ChaCha20 function as specified -// in https://tools.ietf.org/html/rfc7539#section-2.3. -package chacha20 - -import ( - "crypto/cipher" - "encoding/binary" - - "golang.org/x/crypto/internal/subtle" -) - -// assert that *Cipher implements cipher.Stream -var _ cipher.Stream = (*Cipher)(nil) - -// Cipher is a stateful instance of ChaCha20 using a particular key -// and nonce. A *Cipher implements the cipher.Stream interface. -type Cipher struct { - key [8]uint32 - counter uint32 // incremented after each block - nonce [3]uint32 - buf [bufSize]byte // buffer for unused keystream bytes - len int // number of unused keystream bytes at end of buf -} - -// New creates a new ChaCha20 stream cipher with the given key and nonce. -// The initial counter value is set to 0. -func New(key [8]uint32, nonce [3]uint32) *Cipher { - return &Cipher{key: key, nonce: nonce} -} - -// ChaCha20 constants spelling "expand 32-byte k" -const ( - j0 uint32 = 0x61707865 - j1 uint32 = 0x3320646e - j2 uint32 = 0x79622d32 - j3 uint32 = 0x6b206574 -) - -func quarterRound(a, b, c, d uint32) (uint32, uint32, uint32, uint32) { - a += b - d ^= a - d = (d << 16) | (d >> 16) - c += d - b ^= c - b = (b << 12) | (b >> 20) - a += b - d ^= a - d = (d << 8) | (d >> 24) - c += d - b ^= c - b = (b << 7) | (b >> 25) - return a, b, c, d -} - -// XORKeyStream XORs each byte in the given slice with a byte from the -// cipher's key stream. Dst and src must overlap entirely or not at all. -// -// If len(dst) < len(src), XORKeyStream will panic. It is acceptable -// to pass a dst bigger than src, and in that case, XORKeyStream will -// only update dst[:len(src)] and will not touch the rest of dst. -// -// Multiple calls to XORKeyStream behave as if the concatenation of -// the src buffers was passed in a single run. That is, Cipher -// maintains state and does not reset at each XORKeyStream call. -func (s *Cipher) XORKeyStream(dst, src []byte) { - if len(dst) < len(src) { - panic("chacha20: output smaller than input") - } - if subtle.InexactOverlap(dst[:len(src)], src) { - panic("chacha20: invalid buffer overlap") - } - - // xor src with buffered keystream first - if s.len != 0 { - buf := s.buf[len(s.buf)-s.len:] - if len(src) < len(buf) { - buf = buf[:len(src)] - } - td, ts := dst[:len(buf)], src[:len(buf)] // BCE hint - for i, b := range buf { - td[i] = ts[i] ^ b - } - s.len -= len(buf) - if s.len != 0 { - return - } - s.buf = [len(s.buf)]byte{} // zero the empty buffer - src = src[len(buf):] - dst = dst[len(buf):] - } - - if len(src) == 0 { - return - } - if haveAsm { - if uint64(len(src))+uint64(s.counter)*64 > (1<<38)-64 { - panic("chacha20: counter overflow") - } - s.xorKeyStreamAsm(dst, src) - return - } - - // set up a 64-byte buffer to pad out the final block if needed - // (hoisted out of the main loop to avoid spills) - rem := len(src) % 64 // length of final block - fin := len(src) - rem // index of final block - if rem > 0 { - copy(s.buf[len(s.buf)-64:], src[fin:]) - } - - // pre-calculate most of the first round - s1, s5, s9, s13 := quarterRound(j1, s.key[1], s.key[5], s.nonce[0]) - s2, s6, s10, s14 := quarterRound(j2, s.key[2], s.key[6], s.nonce[1]) - s3, s7, s11, s15 := quarterRound(j3, s.key[3], s.key[7], s.nonce[2]) - - n := len(src) - src, dst = src[:n:n], dst[:n:n] // BCE hint - for i := 0; i < n; i += 64 { - // calculate the remainder of the first round - s0, s4, s8, s12 := quarterRound(j0, s.key[0], s.key[4], s.counter) - - // execute the second round - x0, x5, x10, x15 := quarterRound(s0, s5, s10, s15) - x1, x6, x11, x12 := quarterRound(s1, s6, s11, s12) - x2, x7, x8, x13 := quarterRound(s2, s7, s8, s13) - x3, x4, x9, x14 := quarterRound(s3, s4, s9, s14) - - // execute the remaining 18 rounds - for i := 0; i < 9; i++ { - x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) - x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) - x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) - x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) - - x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) - x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) - x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) - x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) - } - - x0 += j0 - x1 += j1 - x2 += j2 - x3 += j3 - - x4 += s.key[0] - x5 += s.key[1] - x6 += s.key[2] - x7 += s.key[3] - x8 += s.key[4] - x9 += s.key[5] - x10 += s.key[6] - x11 += s.key[7] - - x12 += s.counter - x13 += s.nonce[0] - x14 += s.nonce[1] - x15 += s.nonce[2] - - // increment the counter - s.counter += 1 - if s.counter == 0 { - panic("chacha20: counter overflow") - } - - // pad to 64 bytes if needed - in, out := src[i:], dst[i:] - if i == fin { - // src[fin:] has already been copied into s.buf before - // the main loop - in, out = s.buf[len(s.buf)-64:], s.buf[len(s.buf)-64:] - } - in, out = in[:64], out[:64] // BCE hint - - // XOR the key stream with the source and write out the result - xor(out[0:], in[0:], x0) - xor(out[4:], in[4:], x1) - xor(out[8:], in[8:], x2) - xor(out[12:], in[12:], x3) - xor(out[16:], in[16:], x4) - xor(out[20:], in[20:], x5) - xor(out[24:], in[24:], x6) - xor(out[28:], in[28:], x7) - xor(out[32:], in[32:], x8) - xor(out[36:], in[36:], x9) - xor(out[40:], in[40:], x10) - xor(out[44:], in[44:], x11) - xor(out[48:], in[48:], x12) - xor(out[52:], in[52:], x13) - xor(out[56:], in[56:], x14) - xor(out[60:], in[60:], x15) - } - // copy any trailing bytes out of the buffer and into dst - if rem != 0 { - s.len = 64 - rem - copy(dst[fin:], s.buf[len(s.buf)-64:]) - } -} - -// Advance discards bytes in the key stream until the next 64 byte block -// boundary is reached and updates the counter accordingly. If the key -// stream is already at a block boundary no bytes will be discarded and -// the counter will be unchanged. -func (s *Cipher) Advance() { - s.len -= s.len % 64 - if s.len == 0 { - s.buf = [len(s.buf)]byte{} - } -} - -// XORKeyStream crypts bytes from in to out using the given key and counters. -// In and out must overlap entirely or not at all. Counter contains the raw -// ChaCha20 counter bytes (i.e. block counter followed by nonce). -func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { - s := Cipher{ - key: [8]uint32{ - binary.LittleEndian.Uint32(key[0:4]), - binary.LittleEndian.Uint32(key[4:8]), - binary.LittleEndian.Uint32(key[8:12]), - binary.LittleEndian.Uint32(key[12:16]), - binary.LittleEndian.Uint32(key[16:20]), - binary.LittleEndian.Uint32(key[20:24]), - binary.LittleEndian.Uint32(key[24:28]), - binary.LittleEndian.Uint32(key[28:32]), - }, - nonce: [3]uint32{ - binary.LittleEndian.Uint32(counter[4:8]), - binary.LittleEndian.Uint32(counter[8:12]), - binary.LittleEndian.Uint32(counter[12:16]), - }, - counter: binary.LittleEndian.Uint32(counter[0:4]), - } - s.XORKeyStream(out, in) -} - -// HChaCha20 uses the ChaCha20 core to generate a derived key from a key and a -// nonce. It should only be used as part of the XChaCha20 construction. -func HChaCha20(key *[8]uint32, nonce *[4]uint32) [8]uint32 { - x0, x1, x2, x3 := j0, j1, j2, j3 - x4, x5, x6, x7 := key[0], key[1], key[2], key[3] - x8, x9, x10, x11 := key[4], key[5], key[6], key[7] - x12, x13, x14, x15 := nonce[0], nonce[1], nonce[2], nonce[3] - - for i := 0; i < 10; i++ { - x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) - x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) - x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) - x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) - - x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) - x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) - x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) - x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) - } - - var out [8]uint32 - out[0], out[1], out[2], out[3] = x0, x1, x2, x3 - out[4], out[5], out[6], out[7] = x12, x13, x14, x15 - return out -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go deleted file mode 100644 index 47eac031..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.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. - -// +build !arm64,!s390x arm64,!go1.11 gccgo appengine - -package chacha20 - -const ( - bufSize = 64 - haveAsm = false -) - -func (*Cipher) xorKeyStreamAsm(dst, src []byte) { - panic("not implemented") -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go deleted file mode 100644 index aad645b4..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go +++ /dev/null @@ -1,29 +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. - -// +build s390x,!gccgo,!appengine - -package chacha20 - -import ( - "golang.org/x/sys/cpu" -) - -var haveAsm = cpu.S390X.HasVX - -const bufSize = 256 - -// xorKeyStreamVX is an assembly implementation of XORKeyStream. It must only -// be called when the vector facility is available. -// Implementation in asm_s390x.s. -//go:noescape -func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter, &c.buf, &c.len) -} - -// EXRL targets, DO NOT CALL! -func mvcSrcToBuf() -func mvcBufToDst() diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s deleted file mode 100644 index 57df4044..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s +++ /dev/null @@ -1,260 +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. - -// +build s390x,!gccgo,!appengine - -#include "go_asm.h" -#include "textflag.h" - -// This is an implementation of the ChaCha20 encryption algorithm as -// specified in RFC 7539. It uses vector instructions to compute -// 4 keystream blocks in parallel (256 bytes) which are then XORed -// with the bytes in the input slice. - -GLOBL ·constants<>(SB), RODATA|NOPTR, $32 -// BSWAP: swap bytes in each 4-byte element -DATA ·constants<>+0x00(SB)/4, $0x03020100 -DATA ·constants<>+0x04(SB)/4, $0x07060504 -DATA ·constants<>+0x08(SB)/4, $0x0b0a0908 -DATA ·constants<>+0x0c(SB)/4, $0x0f0e0d0c -// J0: [j0, j1, j2, j3] -DATA ·constants<>+0x10(SB)/4, $0x61707865 -DATA ·constants<>+0x14(SB)/4, $0x3320646e -DATA ·constants<>+0x18(SB)/4, $0x79622d32 -DATA ·constants<>+0x1c(SB)/4, $0x6b206574 - -// EXRL targets: -TEXT ·mvcSrcToBuf(SB), NOFRAME|NOSPLIT, $0 - MVC $1, (R1), (R8) - RET - -TEXT ·mvcBufToDst(SB), NOFRAME|NOSPLIT, $0 - MVC $1, (R8), (R9) - RET - -#define BSWAP V5 -#define J0 V6 -#define KEY0 V7 -#define KEY1 V8 -#define NONCE V9 -#define CTR V10 -#define M0 V11 -#define M1 V12 -#define M2 V13 -#define M3 V14 -#define INC V15 -#define X0 V16 -#define X1 V17 -#define X2 V18 -#define X3 V19 -#define X4 V20 -#define X5 V21 -#define X6 V22 -#define X7 V23 -#define X8 V24 -#define X9 V25 -#define X10 V26 -#define X11 V27 -#define X12 V28 -#define X13 V29 -#define X14 V30 -#define X15 V31 - -#define NUM_ROUNDS 20 - -#define ROUND4(a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3, d0, d1, d2, d3) \ - VAF a1, a0, a0 \ - VAF b1, b0, b0 \ - VAF c1, c0, c0 \ - VAF d1, d0, d0 \ - VX a0, a2, a2 \ - VX b0, b2, b2 \ - VX c0, c2, c2 \ - VX d0, d2, d2 \ - VERLLF $16, a2, a2 \ - VERLLF $16, b2, b2 \ - VERLLF $16, c2, c2 \ - VERLLF $16, d2, d2 \ - VAF a2, a3, a3 \ - VAF b2, b3, b3 \ - VAF c2, c3, c3 \ - VAF d2, d3, d3 \ - VX a3, a1, a1 \ - VX b3, b1, b1 \ - VX c3, c1, c1 \ - VX d3, d1, d1 \ - VERLLF $12, a1, a1 \ - VERLLF $12, b1, b1 \ - VERLLF $12, c1, c1 \ - VERLLF $12, d1, d1 \ - VAF a1, a0, a0 \ - VAF b1, b0, b0 \ - VAF c1, c0, c0 \ - VAF d1, d0, d0 \ - VX a0, a2, a2 \ - VX b0, b2, b2 \ - VX c0, c2, c2 \ - VX d0, d2, d2 \ - VERLLF $8, a2, a2 \ - VERLLF $8, b2, b2 \ - VERLLF $8, c2, c2 \ - VERLLF $8, d2, d2 \ - VAF a2, a3, a3 \ - VAF b2, b3, b3 \ - VAF c2, c3, c3 \ - VAF d2, d3, d3 \ - VX a3, a1, a1 \ - VX b3, b1, b1 \ - VX c3, c1, c1 \ - VX d3, d1, d1 \ - VERLLF $7, a1, a1 \ - VERLLF $7, b1, b1 \ - VERLLF $7, c1, c1 \ - VERLLF $7, d1, d1 - -#define PERMUTE(mask, v0, v1, v2, v3) \ - VPERM v0, v0, mask, v0 \ - VPERM v1, v1, mask, v1 \ - VPERM v2, v2, mask, v2 \ - VPERM v3, v3, mask, v3 - -#define ADDV(x, v0, v1, v2, v3) \ - VAF x, v0, v0 \ - VAF x, v1, v1 \ - VAF x, v2, v2 \ - VAF x, v3, v3 - -#define XORV(off, dst, src, v0, v1, v2, v3) \ - VLM off(src), M0, M3 \ - PERMUTE(BSWAP, v0, v1, v2, v3) \ - VX v0, M0, M0 \ - VX v1, M1, M1 \ - VX v2, M2, M2 \ - VX v3, M3, M3 \ - VSTM M0, M3, off(dst) - -#define SHUFFLE(a, b, c, d, t, u, v, w) \ - VMRHF a, c, t \ // t = {a[0], c[0], a[1], c[1]} - VMRHF b, d, u \ // u = {b[0], d[0], b[1], d[1]} - VMRLF a, c, v \ // v = {a[2], c[2], a[3], c[3]} - VMRLF b, d, w \ // w = {b[2], d[2], b[3], d[3]} - VMRHF t, u, a \ // a = {a[0], b[0], c[0], d[0]} - VMRLF t, u, b \ // b = {a[1], b[1], c[1], d[1]} - VMRHF v, w, c \ // c = {a[2], b[2], c[2], d[2]} - VMRLF v, w, d // d = {a[3], b[3], c[3], d[3]} - -// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) -TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 - MOVD $·constants<>(SB), R1 - MOVD dst+0(FP), R2 // R2=&dst[0] - LMG src+24(FP), R3, R4 // R3=&src[0] R4=len(src) - MOVD key+48(FP), R5 // R5=key - MOVD nonce+56(FP), R6 // R6=nonce - MOVD counter+64(FP), R7 // R7=counter - MOVD buf+72(FP), R8 // R8=buf - MOVD len+80(FP), R9 // R9=len - - // load BSWAP and J0 - VLM (R1), BSWAP, J0 - - // set up tail buffer - ADD $-1, R4, R12 - MOVBZ R12, R12 - CMPUBEQ R12, $255, aligned - MOVD R4, R1 - AND $~255, R1 - MOVD $(R3)(R1*1), R1 - EXRL $·mvcSrcToBuf(SB), R12 - MOVD $255, R0 - SUB R12, R0 - MOVD R0, (R9) // update len - -aligned: - // setup - MOVD $95, R0 - VLM (R5), KEY0, KEY1 - VLL R0, (R6), NONCE - VZERO M0 - VLEIB $7, $32, M0 - VSRLB M0, NONCE, NONCE - - // initialize counter values - VLREPF (R7), CTR - VZERO INC - VLEIF $1, $1, INC - VLEIF $2, $2, INC - VLEIF $3, $3, INC - VAF INC, CTR, CTR - VREPIF $4, INC - -chacha: - VREPF $0, J0, X0 - VREPF $1, J0, X1 - VREPF $2, J0, X2 - VREPF $3, J0, X3 - VREPF $0, KEY0, X4 - VREPF $1, KEY0, X5 - VREPF $2, KEY0, X6 - VREPF $3, KEY0, X7 - VREPF $0, KEY1, X8 - VREPF $1, KEY1, X9 - VREPF $2, KEY1, X10 - VREPF $3, KEY1, X11 - VLR CTR, X12 - VREPF $1, NONCE, X13 - VREPF $2, NONCE, X14 - VREPF $3, NONCE, X15 - - MOVD $(NUM_ROUNDS/2), R1 - -loop: - ROUND4(X0, X4, X12, X8, X1, X5, X13, X9, X2, X6, X14, X10, X3, X7, X15, X11) - ROUND4(X0, X5, X15, X10, X1, X6, X12, X11, X2, X7, X13, X8, X3, X4, X14, X9) - - ADD $-1, R1 - BNE loop - - // decrement length - ADD $-256, R4 - BLT tail - -continue: - // rearrange vectors - SHUFFLE(X0, X1, X2, X3, M0, M1, M2, M3) - ADDV(J0, X0, X1, X2, X3) - SHUFFLE(X4, X5, X6, X7, M0, M1, M2, M3) - ADDV(KEY0, X4, X5, X6, X7) - SHUFFLE(X8, X9, X10, X11, M0, M1, M2, M3) - ADDV(KEY1, X8, X9, X10, X11) - VAF CTR, X12, X12 - SHUFFLE(X12, X13, X14, X15, M0, M1, M2, M3) - ADDV(NONCE, X12, X13, X14, X15) - - // increment counters - VAF INC, CTR, CTR - - // xor keystream with plaintext - XORV(0*64, R2, R3, X0, X4, X8, X12) - XORV(1*64, R2, R3, X1, X5, X9, X13) - XORV(2*64, R2, R3, X2, X6, X10, X14) - XORV(3*64, R2, R3, X3, X7, X11, X15) - - // increment pointers - MOVD $256(R2), R2 - MOVD $256(R3), R3 - - CMPBNE R4, $0, chacha - CMPUBEQ R12, $255, return - EXRL $·mvcBufToDst(SB), R12 // len was updated during setup - -return: - VSTEF $0, CTR, (R7) - RET - -tail: - MOVD R2, R9 - MOVD R8, R2 - MOVD R8, R3 - MOVD $0, R4 - JMP continue diff --git a/vendor/golang.org/x/crypto/internal/chacha20/xor.go b/vendor/golang.org/x/crypto/internal/chacha20/xor.go deleted file mode 100644 index 9c5ba0b3..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/xor.go +++ /dev/null @@ -1,43 +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 src the LICENSE file. - -package chacha20 - -import ( - "runtime" -) - -// Platforms that have fast unaligned 32-bit little endian accesses. -const unaligned = runtime.GOARCH == "386" || - runtime.GOARCH == "amd64" || - runtime.GOARCH == "arm64" || - runtime.GOARCH == "ppc64le" || - runtime.GOARCH == "s390x" - -// xor reads a little endian uint32 from src, XORs it with u and -// places the result in little endian byte order in dst. -func xor(dst, src []byte, u uint32) { - _, _ = src[3], dst[3] // eliminate bounds checks - if unaligned { - // The compiler should optimize this code into - // 32-bit unaligned little endian loads and stores. - // TODO: delete once the compiler does a reliably - // good job with the generic code below. - // See issue #25111 for more details. - v := uint32(src[0]) - v |= uint32(src[1]) << 8 - v |= uint32(src[2]) << 16 - v |= uint32(src[3]) << 24 - v ^= u - dst[0] = byte(v) - dst[1] = byte(v >> 8) - dst[2] = byte(v >> 16) - dst[3] = byte(v >> 24) - } else { - dst[0] = src[0] ^ byte(u) - dst[1] = src[1] ^ byte(u>>8) - dst[2] = src[2] ^ byte(u>>16) - dst[3] = src[3] ^ byte(u>>24) - } -} diff --git a/vendor/golang.org/x/crypto/internal/subtle/aliasing.go b/vendor/golang.org/x/crypto/internal/subtle/aliasing.go deleted file mode 100644 index f38797bf..00000000 --- a/vendor/golang.org/x/crypto/internal/subtle/aliasing.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. - -// +build !appengine - -// Package subtle implements functions that are often useful in cryptographic -// code but require careful thought to use correctly. -package subtle // import "golang.org/x/crypto/internal/subtle" - -import "unsafe" - -// AnyOverlap reports whether x and y share memory at any (not necessarily -// corresponding) index. The memory beyond the slice length is ignored. -func AnyOverlap(x, y []byte) bool { - return len(x) > 0 && len(y) > 0 && - uintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) && - uintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1])) -} - -// InexactOverlap reports whether x and y share memory at any non-corresponding -// index. The memory beyond the slice length is ignored. Note that x and y can -// have different lengths and still not have any inexact overlap. -// -// InexactOverlap can be used to implement the requirements of the crypto/cipher -// AEAD, Block, BlockMode and Stream interfaces. -func InexactOverlap(x, y []byte) bool { - if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] { - return false - } - return AnyOverlap(x, y) -} diff --git a/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go b/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go deleted file mode 100644 index 0cc4a8a6..00000000 --- a/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go +++ /dev/null @@ -1,35 +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. - -// +build appengine - -// Package subtle implements functions that are often useful in cryptographic -// code but require careful thought to use correctly. -package subtle // import "golang.org/x/crypto/internal/subtle" - -// This is the Google App Engine standard variant based on reflect -// because the unsafe package and cgo are disallowed. - -import "reflect" - -// AnyOverlap reports whether x and y share memory at any (not necessarily -// corresponding) index. The memory beyond the slice length is ignored. -func AnyOverlap(x, y []byte) bool { - return len(x) > 0 && len(y) > 0 && - reflect.ValueOf(&x[0]).Pointer() <= reflect.ValueOf(&y[len(y)-1]).Pointer() && - reflect.ValueOf(&y[0]).Pointer() <= reflect.ValueOf(&x[len(x)-1]).Pointer() -} - -// InexactOverlap reports whether x and y share memory at any non-corresponding -// index. The memory beyond the slice length is ignored. Note that x and y can -// have different lengths and still not have any inexact overlap. -// -// InexactOverlap can be used to implement the requirements of the crypto/cipher -// AEAD, Block, BlockMode and Stream interfaces. -func InexactOverlap(x, y []byte) bool { - if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] { - return false - } - return AnyOverlap(x, y) -} diff --git a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go deleted file mode 100644 index 8387d299..00000000 --- a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go +++ /dev/null @@ -1,11 +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. - -// +build !amd64 gccgo appengine - -package poly1305 - -type mac struct{ macGeneric } - -func newMAC(key *[32]byte) mac { return mac{newMACGeneric(key)} } diff --git a/vendor/golang.org/x/crypto/poly1305/poly1305.go b/vendor/golang.org/x/crypto/poly1305/poly1305.go deleted file mode 100644 index d076a562..00000000 --- a/vendor/golang.org/x/crypto/poly1305/poly1305.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2012 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 poly1305 implements Poly1305 one-time message authentication code as -// specified in https://cr.yp.to/mac/poly1305-20050329.pdf. -// -// Poly1305 is a fast, one-time authentication function. It is infeasible for an -// attacker to generate an authenticator for a message without the key. However, a -// key must only be used for a single message. Authenticating two different -// messages with the same key allows an attacker to forge authenticators for other -// messages with the same key. -// -// Poly1305 was originally coupled with AES in order to make Poly1305-AES. AES was -// used with a fixed key in order to generate one-time keys from an nonce. -// However, in this package AES isn't used and the one-time key is specified -// directly. -package poly1305 // import "golang.org/x/crypto/poly1305" - -import "crypto/subtle" - -// TagSize is the size, in bytes, of a poly1305 authenticator. -const TagSize = 16 - -// Verify returns true if mac is a valid authenticator for m with the given -// key. -func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { - var tmp [16]byte - Sum(&tmp, m, key) - return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1 -} - -// New returns a new MAC computing an authentication -// tag of all data written to it with the given key. -// This allows writing the message progressively instead -// of passing it as a single slice. Common users should use -// the Sum function instead. -// -// The key must be unique for each message, as authenticating -// two different messages with the same key allows an attacker -// to forge messages at will. -func New(key *[32]byte) *MAC { - return &MAC{ - mac: newMAC(key), - finalized: false, - } -} - -// MAC is an io.Writer computing an authentication tag -// of the data written to it. -// -// MAC cannot be used like common hash.Hash implementations, -// because using a poly1305 key twice breaks its security. -// Therefore writing data to a running MAC after calling -// Sum causes it to panic. -type MAC struct { - mac // platform-dependent implementation - - finalized bool -} - -// Size returns the number of bytes Sum will return. -func (h *MAC) Size() int { return TagSize } - -// Write adds more data to the running message authentication code. -// It never returns an error. -// -// It must not be called after the first call of Sum. -func (h *MAC) Write(p []byte) (n int, err error) { - if h.finalized { - panic("poly1305: write to MAC after Sum") - } - return h.mac.Write(p) -} - -// Sum computes the authenticator of all data written to the -// message authentication code. -func (h *MAC) Sum(b []byte) []byte { - var mac [TagSize]byte - h.mac.Sum(&mac) - h.finalized = true - return append(b, mac[:]...) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go deleted file mode 100644 index 2dbf42aa..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -package poly1305 - -//go:noescape -func initialize(state *[7]uint64, key *[32]byte) - -//go:noescape -func update(state *[7]uint64, msg []byte) - -//go:noescape -func finalize(tag *[TagSize]byte, state *[7]uint64) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - h := newMAC(key) - h.Write(m) - h.Sum(out) -} - -func newMAC(key *[32]byte) (h mac) { - initialize(&h.state, key) - return -} - -type mac struct { - state [7]uint64 // := uint64{ h0, h1, h2, r0, r1, pad0, pad1 } - - buffer [TagSize]byte - offset int -} - -func (h *mac) Write(p []byte) (n int, err error) { - n = len(p) - if h.offset > 0 { - remaining := TagSize - h.offset - if n < remaining { - h.offset += copy(h.buffer[h.offset:], p) - return n, nil - } - copy(h.buffer[h.offset:], p[:remaining]) - p = p[remaining:] - h.offset = 0 - update(&h.state, h.buffer[:]) - } - if nn := len(p) - (len(p) % TagSize); nn > 0 { - update(&h.state, p[:nn]) - p = p[nn:] - } - if len(p) > 0 { - h.offset += copy(h.buffer[h.offset:], p) - } - return n, nil -} - -func (h *mac) Sum(out *[16]byte) { - state := h.state - if h.offset > 0 { - update(&state, h.buffer[:h.offset]) - } - finalize(out, &state) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s deleted file mode 100644 index 7d600f13..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -#include "textflag.h" - -#define POLY1305_ADD(msg, h0, h1, h2) \ - ADDQ 0(msg), h0; \ - ADCQ 8(msg), h1; \ - ADCQ $1, h2; \ - LEAQ 16(msg), msg - -#define POLY1305_MUL(h0, h1, h2, r0, r1, t0, t1, t2, t3) \ - MOVQ r0, AX; \ - MULQ h0; \ - MOVQ AX, t0; \ - MOVQ DX, t1; \ - MOVQ r0, AX; \ - MULQ h1; \ - ADDQ AX, t1; \ - ADCQ $0, DX; \ - MOVQ r0, t2; \ - IMULQ h2, t2; \ - ADDQ DX, t2; \ - \ - MOVQ r1, AX; \ - MULQ h0; \ - ADDQ AX, t1; \ - ADCQ $0, DX; \ - MOVQ DX, h0; \ - MOVQ r1, t3; \ - IMULQ h2, t3; \ - MOVQ r1, AX; \ - MULQ h1; \ - ADDQ AX, t2; \ - ADCQ DX, t3; \ - ADDQ h0, t2; \ - ADCQ $0, t3; \ - \ - MOVQ t0, h0; \ - MOVQ t1, h1; \ - MOVQ t2, h2; \ - ANDQ $3, h2; \ - MOVQ t2, t0; \ - ANDQ $0xFFFFFFFFFFFFFFFC, t0; \ - ADDQ t0, h0; \ - ADCQ t3, h1; \ - ADCQ $0, h2; \ - SHRQ $2, t3, t2; \ - SHRQ $2, t3; \ - ADDQ t2, h0; \ - ADCQ t3, h1; \ - ADCQ $0, h2 - -DATA ·poly1305Mask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF -DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC -GLOBL ·poly1305Mask<>(SB), RODATA, $16 - -// func update(state *[7]uint64, msg []byte) -TEXT ·update(SB), $0-32 - MOVQ state+0(FP), DI - MOVQ msg_base+8(FP), SI - MOVQ msg_len+16(FP), R15 - - MOVQ 0(DI), R8 // h0 - MOVQ 8(DI), R9 // h1 - MOVQ 16(DI), R10 // h2 - MOVQ 24(DI), R11 // r0 - MOVQ 32(DI), R12 // r1 - - CMPQ R15, $16 - JB bytes_between_0_and_15 - -loop: - POLY1305_ADD(SI, R8, R9, R10) - -multiply: - POLY1305_MUL(R8, R9, R10, R11, R12, BX, CX, R13, R14) - SUBQ $16, R15 - CMPQ R15, $16 - JAE loop - -bytes_between_0_and_15: - TESTQ R15, R15 - JZ done - MOVQ $1, BX - XORQ CX, CX - XORQ R13, R13 - ADDQ R15, SI - -flush_buffer: - SHLQ $8, BX, CX - SHLQ $8, BX - MOVB -1(SI), R13 - XORQ R13, BX - DECQ SI - DECQ R15 - JNZ flush_buffer - - ADDQ BX, R8 - ADCQ CX, R9 - ADCQ $0, R10 - MOVQ $16, R15 - JMP multiply - -done: - MOVQ R8, 0(DI) - MOVQ R9, 8(DI) - MOVQ R10, 16(DI) - RET - -// func initialize(state *[7]uint64, key *[32]byte) -TEXT ·initialize(SB), $0-16 - MOVQ state+0(FP), DI - MOVQ key+8(FP), SI - - // state[0...7] is initialized with zero - MOVOU 0(SI), X0 - MOVOU 16(SI), X1 - MOVOU ·poly1305Mask<>(SB), X2 - PAND X2, X0 - MOVOU X0, 24(DI) - MOVOU X1, 40(DI) - RET - -// func finalize(tag *[TagSize]byte, state *[7]uint64) -TEXT ·finalize(SB), $0-16 - MOVQ tag+0(FP), DI - MOVQ state+8(FP), SI - - MOVQ 0(SI), AX - MOVQ 8(SI), BX - MOVQ 16(SI), CX - MOVQ AX, R8 - MOVQ BX, R9 - SUBQ $0xFFFFFFFFFFFFFFFB, AX - SBBQ $0xFFFFFFFFFFFFFFFF, BX - SBBQ $3, CX - CMOVQCS R8, AX - CMOVQCS R9, BX - ADDQ 40(SI), AX - ADCQ 48(SI), BX - - MOVQ AX, 0(DI) - MOVQ BX, 8(DI) - RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.go b/vendor/golang.org/x/crypto/poly1305/sum_arm.go deleted file mode 100644 index 5dc321c2..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_arm.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2015 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 arm,!gccgo,!appengine,!nacl - -package poly1305 - -// This function is implemented in sum_arm.s -//go:noescape -func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - var mPtr *byte - if len(m) > 0 { - mPtr = &m[0] - } - poly1305_auth_armv6(out, mPtr, uint32(len(m)), key) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.s b/vendor/golang.org/x/crypto/poly1305/sum_arm.s deleted file mode 100644 index f70b4ac4..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_arm.s +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright 2015 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 arm,!gccgo,!appengine,!nacl - -#include "textflag.h" - -// This code was translated into a form compatible with 5a from the public -// domain source by Andrew Moon: github.com/floodyberry/poly1305-opt/blob/master/app/extensions/poly1305. - -DATA ·poly1305_init_constants_armv6<>+0x00(SB)/4, $0x3ffffff -DATA ·poly1305_init_constants_armv6<>+0x04(SB)/4, $0x3ffff03 -DATA ·poly1305_init_constants_armv6<>+0x08(SB)/4, $0x3ffc0ff -DATA ·poly1305_init_constants_armv6<>+0x0c(SB)/4, $0x3f03fff -DATA ·poly1305_init_constants_armv6<>+0x10(SB)/4, $0x00fffff -GLOBL ·poly1305_init_constants_armv6<>(SB), 8, $20 - -// Warning: the linker may use R11 to synthesize certain instructions. Please -// take care and verify that no synthetic instructions use it. - -TEXT poly1305_init_ext_armv6<>(SB), NOSPLIT, $0 - // Needs 16 bytes of stack and 64 bytes of space pointed to by R0. (It - // might look like it's only 60 bytes of space but the final four bytes - // will be written by another function.) We need to skip over four - // bytes of stack because that's saving the value of 'g'. - ADD $4, R13, R8 - MOVM.IB [R4-R7], (R8) - MOVM.IA.W (R1), [R2-R5] - MOVW $·poly1305_init_constants_armv6<>(SB), R7 - MOVW R2, R8 - MOVW R2>>26, R9 - MOVW R3>>20, g - MOVW R4>>14, R11 - MOVW R5>>8, R12 - ORR R3<<6, R9, R9 - ORR R4<<12, g, g - ORR R5<<18, R11, R11 - MOVM.IA (R7), [R2-R6] - AND R8, R2, R2 - AND R9, R3, R3 - AND g, R4, R4 - AND R11, R5, R5 - AND R12, R6, R6 - MOVM.IA.W [R2-R6], (R0) - EOR R2, R2, R2 - EOR R3, R3, R3 - EOR R4, R4, R4 - EOR R5, R5, R5 - EOR R6, R6, R6 - MOVM.IA.W [R2-R6], (R0) - MOVM.IA.W (R1), [R2-R5] - MOVM.IA [R2-R6], (R0) - ADD $20, R13, R0 - MOVM.DA (R0), [R4-R7] - RET - -#define MOVW_UNALIGNED(Rsrc, Rdst, Rtmp, offset) \ - MOVBU (offset+0)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+0)(Rdst); \ - MOVBU (offset+1)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+1)(Rdst); \ - MOVBU (offset+2)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+2)(Rdst); \ - MOVBU (offset+3)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+3)(Rdst) - -TEXT poly1305_blocks_armv6<>(SB), NOSPLIT, $0 - // Needs 24 bytes of stack for saved registers and then 88 bytes of - // scratch space after that. We assume that 24 bytes at (R13) have - // already been used: four bytes for the link register saved in the - // prelude of poly1305_auth_armv6, four bytes for saving the value of g - // in that function and 16 bytes of scratch space used around - // poly1305_finish_ext_armv6_skip1. - ADD $24, R13, R12 - MOVM.IB [R4-R8, R14], (R12) - MOVW R0, 88(R13) - MOVW R1, 92(R13) - MOVW R2, 96(R13) - MOVW R1, R14 - MOVW R2, R12 - MOVW 56(R0), R8 - WORD $0xe1180008 // TST R8, R8 not working see issue 5921 - EOR R6, R6, R6 - MOVW.EQ $(1<<24), R6 - MOVW R6, 84(R13) - ADD $116, R13, g - MOVM.IA (R0), [R0-R9] - MOVM.IA [R0-R4], (g) - CMP $16, R12 - BLO poly1305_blocks_armv6_done - -poly1305_blocks_armv6_mainloop: - WORD $0xe31e0003 // TST R14, #3 not working see issue 5921 - BEQ poly1305_blocks_armv6_mainloop_aligned - ADD $100, R13, g - MOVW_UNALIGNED(R14, g, R0, 0) - MOVW_UNALIGNED(R14, g, R0, 4) - MOVW_UNALIGNED(R14, g, R0, 8) - MOVW_UNALIGNED(R14, g, R0, 12) - MOVM.IA (g), [R0-R3] - ADD $16, R14 - B poly1305_blocks_armv6_mainloop_loaded - -poly1305_blocks_armv6_mainloop_aligned: - MOVM.IA.W (R14), [R0-R3] - -poly1305_blocks_armv6_mainloop_loaded: - MOVW R0>>26, g - MOVW R1>>20, R11 - MOVW R2>>14, R12 - MOVW R14, 92(R13) - MOVW R3>>8, R4 - ORR R1<<6, g, g - ORR R2<<12, R11, R11 - ORR R3<<18, R12, R12 - BIC $0xfc000000, R0, R0 - BIC $0xfc000000, g, g - MOVW 84(R13), R3 - BIC $0xfc000000, R11, R11 - BIC $0xfc000000, R12, R12 - ADD R0, R5, R5 - ADD g, R6, R6 - ORR R3, R4, R4 - ADD R11, R7, R7 - ADD $116, R13, R14 - ADD R12, R8, R8 - ADD R4, R9, R9 - MOVM.IA (R14), [R0-R4] - MULLU R4, R5, (R11, g) - MULLU R3, R5, (R14, R12) - MULALU R3, R6, (R11, g) - MULALU R2, R6, (R14, R12) - MULALU R2, R7, (R11, g) - MULALU R1, R7, (R14, R12) - ADD R4<<2, R4, R4 - ADD R3<<2, R3, R3 - MULALU R1, R8, (R11, g) - MULALU R0, R8, (R14, R12) - MULALU R0, R9, (R11, g) - MULALU R4, R9, (R14, R12) - MOVW g, 76(R13) - MOVW R11, 80(R13) - MOVW R12, 68(R13) - MOVW R14, 72(R13) - MULLU R2, R5, (R11, g) - MULLU R1, R5, (R14, R12) - MULALU R1, R6, (R11, g) - MULALU R0, R6, (R14, R12) - MULALU R0, R7, (R11, g) - MULALU R4, R7, (R14, R12) - ADD R2<<2, R2, R2 - ADD R1<<2, R1, R1 - MULALU R4, R8, (R11, g) - MULALU R3, R8, (R14, R12) - MULALU R3, R9, (R11, g) - MULALU R2, R9, (R14, R12) - MOVW g, 60(R13) - MOVW R11, 64(R13) - MOVW R12, 52(R13) - MOVW R14, 56(R13) - MULLU R0, R5, (R11, g) - MULALU R4, R6, (R11, g) - MULALU R3, R7, (R11, g) - MULALU R2, R8, (R11, g) - MULALU R1, R9, (R11, g) - ADD $52, R13, R0 - MOVM.IA (R0), [R0-R7] - MOVW g>>26, R12 - MOVW R4>>26, R14 - ORR R11<<6, R12, R12 - ORR R5<<6, R14, R14 - BIC $0xfc000000, g, g - BIC $0xfc000000, R4, R4 - ADD.S R12, R0, R0 - ADC $0, R1, R1 - ADD.S R14, R6, R6 - ADC $0, R7, R7 - MOVW R0>>26, R12 - MOVW R6>>26, R14 - ORR R1<<6, R12, R12 - ORR R7<<6, R14, R14 - BIC $0xfc000000, R0, R0 - BIC $0xfc000000, R6, R6 - ADD R14<<2, R14, R14 - ADD.S R12, R2, R2 - ADC $0, R3, R3 - ADD R14, g, g - MOVW R2>>26, R12 - MOVW g>>26, R14 - ORR R3<<6, R12, R12 - BIC $0xfc000000, g, R5 - BIC $0xfc000000, R2, R7 - ADD R12, R4, R4 - ADD R14, R0, R0 - MOVW R4>>26, R12 - BIC $0xfc000000, R4, R8 - ADD R12, R6, R9 - MOVW 96(R13), R12 - MOVW 92(R13), R14 - MOVW R0, R6 - CMP $32, R12 - SUB $16, R12, R12 - MOVW R12, 96(R13) - BHS poly1305_blocks_armv6_mainloop - -poly1305_blocks_armv6_done: - MOVW 88(R13), R12 - MOVW R5, 20(R12) - MOVW R6, 24(R12) - MOVW R7, 28(R12) - MOVW R8, 32(R12) - MOVW R9, 36(R12) - ADD $48, R13, R0 - MOVM.DA (R0), [R4-R8, R14] - RET - -#define MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) \ - MOVBU.P 1(Rsrc), Rtmp; \ - MOVBU.P Rtmp, 1(Rdst); \ - MOVBU.P 1(Rsrc), Rtmp; \ - MOVBU.P Rtmp, 1(Rdst) - -#define MOVWP_UNALIGNED(Rsrc, Rdst, Rtmp) \ - MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp); \ - MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) - -// func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]key) -TEXT ·poly1305_auth_armv6(SB), $196-16 - // The value 196, just above, is the sum of 64 (the size of the context - // structure) and 132 (the amount of stack needed). - // - // At this point, the stack pointer (R13) has been moved down. It - // points to the saved link register and there's 196 bytes of free - // space above it. - // - // The stack for this function looks like: - // - // +--------------------- - // | - // | 64 bytes of context structure - // | - // +--------------------- - // | - // | 112 bytes for poly1305_blocks_armv6 - // | - // +--------------------- - // | 16 bytes of final block, constructed at - // | poly1305_finish_ext_armv6_skip8 - // +--------------------- - // | four bytes of saved 'g' - // +--------------------- - // | lr, saved by prelude <- R13 points here - // +--------------------- - MOVW g, 4(R13) - - MOVW out+0(FP), R4 - MOVW m+4(FP), R5 - MOVW mlen+8(FP), R6 - MOVW key+12(FP), R7 - - ADD $136, R13, R0 // 136 = 4 + 4 + 16 + 112 - MOVW R7, R1 - - // poly1305_init_ext_armv6 will write to the stack from R13+4, but - // that's ok because none of the other values have been written yet. - BL poly1305_init_ext_armv6<>(SB) - BIC.S $15, R6, R2 - BEQ poly1305_auth_armv6_noblocks - ADD $136, R13, R0 - MOVW R5, R1 - ADD R2, R5, R5 - SUB R2, R6, R6 - BL poly1305_blocks_armv6<>(SB) - -poly1305_auth_armv6_noblocks: - ADD $136, R13, R0 - MOVW R5, R1 - MOVW R6, R2 - MOVW R4, R3 - - MOVW R0, R5 - MOVW R1, R6 - MOVW R2, R7 - MOVW R3, R8 - AND.S R2, R2, R2 - BEQ poly1305_finish_ext_armv6_noremaining - EOR R0, R0 - ADD $8, R13, R9 // 8 = offset to 16 byte scratch space - MOVW R0, (R9) - MOVW R0, 4(R9) - MOVW R0, 8(R9) - MOVW R0, 12(R9) - WORD $0xe3110003 // TST R1, #3 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_aligned - WORD $0xe3120008 // TST R2, #8 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip8 - MOVWP_UNALIGNED(R1, R9, g) - MOVWP_UNALIGNED(R1, R9, g) - -poly1305_finish_ext_armv6_skip8: - WORD $0xe3120004 // TST $4, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip4 - MOVWP_UNALIGNED(R1, R9, g) - -poly1305_finish_ext_armv6_skip4: - WORD $0xe3120002 // TST $2, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip2 - MOVHUP_UNALIGNED(R1, R9, g) - B poly1305_finish_ext_armv6_skip2 - -poly1305_finish_ext_armv6_aligned: - WORD $0xe3120008 // TST R2, #8 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip8_aligned - MOVM.IA.W (R1), [g-R11] - MOVM.IA.W [g-R11], (R9) - -poly1305_finish_ext_armv6_skip8_aligned: - WORD $0xe3120004 // TST $4, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip4_aligned - MOVW.P 4(R1), g - MOVW.P g, 4(R9) - -poly1305_finish_ext_armv6_skip4_aligned: - WORD $0xe3120002 // TST $2, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip2 - MOVHU.P 2(R1), g - MOVH.P g, 2(R9) - -poly1305_finish_ext_armv6_skip2: - WORD $0xe3120001 // TST $1, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip1 - MOVBU.P 1(R1), g - MOVBU.P g, 1(R9) - -poly1305_finish_ext_armv6_skip1: - MOVW $1, R11 - MOVBU R11, 0(R9) - MOVW R11, 56(R5) - MOVW R5, R0 - ADD $8, R13, R1 - MOVW $16, R2 - BL poly1305_blocks_armv6<>(SB) - -poly1305_finish_ext_armv6_noremaining: - MOVW 20(R5), R0 - MOVW 24(R5), R1 - MOVW 28(R5), R2 - MOVW 32(R5), R3 - MOVW 36(R5), R4 - MOVW R4>>26, R12 - BIC $0xfc000000, R4, R4 - ADD R12<<2, R12, R12 - ADD R12, R0, R0 - MOVW R0>>26, R12 - BIC $0xfc000000, R0, R0 - ADD R12, R1, R1 - MOVW R1>>26, R12 - BIC $0xfc000000, R1, R1 - ADD R12, R2, R2 - MOVW R2>>26, R12 - BIC $0xfc000000, R2, R2 - ADD R12, R3, R3 - MOVW R3>>26, R12 - BIC $0xfc000000, R3, R3 - ADD R12, R4, R4 - ADD $5, R0, R6 - MOVW R6>>26, R12 - BIC $0xfc000000, R6, R6 - ADD R12, R1, R7 - MOVW R7>>26, R12 - BIC $0xfc000000, R7, R7 - ADD R12, R2, g - MOVW g>>26, R12 - BIC $0xfc000000, g, g - ADD R12, R3, R11 - MOVW $-(1<<26), R12 - ADD R11>>26, R12, R12 - BIC $0xfc000000, R11, R11 - ADD R12, R4, R9 - MOVW R9>>31, R12 - SUB $1, R12 - AND R12, R6, R6 - AND R12, R7, R7 - AND R12, g, g - AND R12, R11, R11 - AND R12, R9, R9 - MVN R12, R12 - AND R12, R0, R0 - AND R12, R1, R1 - AND R12, R2, R2 - AND R12, R3, R3 - AND R12, R4, R4 - ORR R6, R0, R0 - ORR R7, R1, R1 - ORR g, R2, R2 - ORR R11, R3, R3 - ORR R9, R4, R4 - ORR R1<<26, R0, R0 - MOVW R1>>6, R1 - ORR R2<<20, R1, R1 - MOVW R2>>12, R2 - ORR R3<<14, R2, R2 - MOVW R3>>18, R3 - ORR R4<<8, R3, R3 - MOVW 40(R5), R6 - MOVW 44(R5), R7 - MOVW 48(R5), g - MOVW 52(R5), R11 - ADD.S R6, R0, R0 - ADC.S R7, R1, R1 - ADC.S g, R2, R2 - ADC.S R11, R3, R3 - MOVM.IA [R0-R3], (R8) - MOVW R5, R12 - EOR R0, R0, R0 - EOR R1, R1, R1 - EOR R2, R2, R2 - EOR R3, R3, R3 - EOR R4, R4, R4 - EOR R5, R5, R5 - EOR R6, R6, R6 - EOR R7, R7, R7 - MOVM.IA.W [R0-R7], (R12) - MOVM.IA [R0-R7], (R12) - MOVW 4(R13), g - RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_generic.go b/vendor/golang.org/x/crypto/poly1305/sum_generic.go deleted file mode 100644 index bab76ef0..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_generic.go +++ /dev/null @@ -1,172 +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 poly1305 - -import "encoding/binary" - -const ( - msgBlock = uint32(1 << 24) - finalBlock = uint32(0) -) - -// sumGeneric generates an authenticator for msg using a one-time key and -// puts the 16-byte result into out. This is the generic implementation of -// Sum and should be called if no assembly implementation is available. -func sumGeneric(out *[TagSize]byte, msg []byte, key *[32]byte) { - h := newMACGeneric(key) - h.Write(msg) - h.Sum(out) -} - -func newMACGeneric(key *[32]byte) (h macGeneric) { - h.r[0] = binary.LittleEndian.Uint32(key[0:]) & 0x3ffffff - h.r[1] = (binary.LittleEndian.Uint32(key[3:]) >> 2) & 0x3ffff03 - h.r[2] = (binary.LittleEndian.Uint32(key[6:]) >> 4) & 0x3ffc0ff - h.r[3] = (binary.LittleEndian.Uint32(key[9:]) >> 6) & 0x3f03fff - h.r[4] = (binary.LittleEndian.Uint32(key[12:]) >> 8) & 0x00fffff - - h.s[0] = binary.LittleEndian.Uint32(key[16:]) - h.s[1] = binary.LittleEndian.Uint32(key[20:]) - h.s[2] = binary.LittleEndian.Uint32(key[24:]) - h.s[3] = binary.LittleEndian.Uint32(key[28:]) - return -} - -type macGeneric struct { - h, r [5]uint32 - s [4]uint32 - - buffer [TagSize]byte - offset int -} - -func (h *macGeneric) Write(p []byte) (n int, err error) { - n = len(p) - if h.offset > 0 { - remaining := TagSize - h.offset - if n < remaining { - h.offset += copy(h.buffer[h.offset:], p) - return n, nil - } - copy(h.buffer[h.offset:], p[:remaining]) - p = p[remaining:] - h.offset = 0 - updateGeneric(h.buffer[:], msgBlock, &(h.h), &(h.r)) - } - if nn := len(p) - (len(p) % TagSize); nn > 0 { - updateGeneric(p, msgBlock, &(h.h), &(h.r)) - p = p[nn:] - } - if len(p) > 0 { - h.offset += copy(h.buffer[h.offset:], p) - } - return n, nil -} - -func (h *macGeneric) Sum(out *[16]byte) { - H, R := h.h, h.r - if h.offset > 0 { - var buffer [TagSize]byte - copy(buffer[:], h.buffer[:h.offset]) - buffer[h.offset] = 1 // invariant: h.offset < TagSize - updateGeneric(buffer[:], finalBlock, &H, &R) - } - finalizeGeneric(out, &H, &(h.s)) -} - -func updateGeneric(msg []byte, flag uint32, h, r *[5]uint32) { - h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] - r0, r1, r2, r3, r4 := uint64(r[0]), uint64(r[1]), uint64(r[2]), uint64(r[3]), uint64(r[4]) - R1, R2, R3, R4 := r1*5, r2*5, r3*5, r4*5 - - for len(msg) >= TagSize { - // h += msg - h0 += binary.LittleEndian.Uint32(msg[0:]) & 0x3ffffff - h1 += (binary.LittleEndian.Uint32(msg[3:]) >> 2) & 0x3ffffff - h2 += (binary.LittleEndian.Uint32(msg[6:]) >> 4) & 0x3ffffff - h3 += (binary.LittleEndian.Uint32(msg[9:]) >> 6) & 0x3ffffff - h4 += (binary.LittleEndian.Uint32(msg[12:]) >> 8) | flag - - // h *= r - d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1) - d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2) - d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3) - d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4) - d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0) - - // h %= p - h0 = uint32(d0) & 0x3ffffff - h1 = uint32(d1) & 0x3ffffff - h2 = uint32(d2) & 0x3ffffff - h3 = uint32(d3) & 0x3ffffff - h4 = uint32(d4) & 0x3ffffff - - h0 += uint32(d4>>26) * 5 - h1 += h0 >> 26 - h0 = h0 & 0x3ffffff - - msg = msg[TagSize:] - } - - h[0], h[1], h[2], h[3], h[4] = h0, h1, h2, h3, h4 -} - -func finalizeGeneric(out *[TagSize]byte, h *[5]uint32, s *[4]uint32) { - h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] - - // h %= p reduction - h2 += h1 >> 26 - h1 &= 0x3ffffff - h3 += h2 >> 26 - h2 &= 0x3ffffff - h4 += h3 >> 26 - h3 &= 0x3ffffff - h0 += 5 * (h4 >> 26) - h4 &= 0x3ffffff - h1 += h0 >> 26 - h0 &= 0x3ffffff - - // h - p - t0 := h0 + 5 - t1 := h1 + (t0 >> 26) - t2 := h2 + (t1 >> 26) - t3 := h3 + (t2 >> 26) - t4 := h4 + (t3 >> 26) - (1 << 26) - t0 &= 0x3ffffff - t1 &= 0x3ffffff - t2 &= 0x3ffffff - t3 &= 0x3ffffff - - // select h if h < p else h - p - t_mask := (t4 >> 31) - 1 - h_mask := ^t_mask - h0 = (h0 & h_mask) | (t0 & t_mask) - h1 = (h1 & h_mask) | (t1 & t_mask) - h2 = (h2 & h_mask) | (t2 & t_mask) - h3 = (h3 & h_mask) | (t3 & t_mask) - h4 = (h4 & h_mask) | (t4 & t_mask) - - // h %= 2^128 - h0 |= h1 << 26 - h1 = ((h1 >> 6) | (h2 << 20)) - h2 = ((h2 >> 12) | (h3 << 14)) - h3 = ((h3 >> 18) | (h4 << 8)) - - // s: the s part of the key - // tag = (h + s) % (2^128) - t := uint64(h0) + uint64(s[0]) - h0 = uint32(t) - t = uint64(h1) + uint64(s[1]) + (t >> 32) - h1 = uint32(t) - t = uint64(h2) + uint64(s[2]) + (t >> 32) - h2 = uint32(t) - t = uint64(h3) + uint64(s[3]) + (t >> 32) - h3 = uint32(t) - - binary.LittleEndian.PutUint32(out[0:], h0) - binary.LittleEndian.PutUint32(out[4:], h1) - binary.LittleEndian.PutUint32(out[8:], h2) - binary.LittleEndian.PutUint32(out[12:], h3) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go deleted file mode 100644 index fcdef46a..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_noasm.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. - -// +build s390x,!go1.11 !arm,!amd64,!s390x gccgo appengine nacl - -package poly1305 - -// Sum generates an authenticator for msg using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) { - h := newMAC(key) - h.Write(msg) - h.Sum(out) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.go b/vendor/golang.org/x/crypto/poly1305/sum_s390x.go deleted file mode 100644 index ec99e07e..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_s390x.go +++ /dev/null @@ -1,42 +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. - -// +build s390x,go1.11,!gccgo,!appengine - -package poly1305 - -import ( - "golang.org/x/sys/cpu" -) - -// poly1305vx is an assembly implementation of Poly1305 that uses vector -// instructions. It must only be called if the vector facility (vx) is -// available. -//go:noescape -func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]byte) - -// poly1305vmsl is an assembly implementation of Poly1305 that uses vector -// instructions, including VMSL. It must only be called if the vector facility (vx) is -// available and if VMSL is supported. -//go:noescape -func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]byte) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - if cpu.S390X.HasVX { - var mPtr *byte - if len(m) > 0 { - mPtr = &m[0] - } - if cpu.S390X.HasVXE && len(m) > 256 { - poly1305vmsl(out, mPtr, uint64(len(m)), key) - } else { - poly1305vx(out, mPtr, uint64(len(m)), key) - } - } else { - sumGeneric(out, m, key) - } -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_s390x.s deleted file mode 100644 index ca5a309d..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_s390x.s +++ /dev/null @@ -1,378 +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. - -// +build s390x,go1.11,!gccgo,!appengine - -#include "textflag.h" - -// Implementation of Poly1305 using the vector facility (vx). - -// constants -#define MOD26 V0 -#define EX0 V1 -#define EX1 V2 -#define EX2 V3 - -// temporaries -#define T_0 V4 -#define T_1 V5 -#define T_2 V6 -#define T_3 V7 -#define T_4 V8 - -// key (r) -#define R_0 V9 -#define R_1 V10 -#define R_2 V11 -#define R_3 V12 -#define R_4 V13 -#define R5_1 V14 -#define R5_2 V15 -#define R5_3 V16 -#define R5_4 V17 -#define RSAVE_0 R5 -#define RSAVE_1 R6 -#define RSAVE_2 R7 -#define RSAVE_3 R8 -#define RSAVE_4 R9 -#define R5SAVE_1 V28 -#define R5SAVE_2 V29 -#define R5SAVE_3 V30 -#define R5SAVE_4 V31 - -// message block -#define F_0 V18 -#define F_1 V19 -#define F_2 V20 -#define F_3 V21 -#define F_4 V22 - -// accumulator -#define H_0 V23 -#define H_1 V24 -#define H_2 V25 -#define H_3 V26 -#define H_4 V27 - -GLOBL ·keyMask<>(SB), RODATA, $16 -DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f -DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f - -GLOBL ·bswapMask<>(SB), RODATA, $16 -DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 -DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 - -GLOBL ·constants<>(SB), RODATA, $64 -// MOD26 -DATA ·constants<>+0(SB)/8, $0x3ffffff -DATA ·constants<>+8(SB)/8, $0x3ffffff -// EX0 -DATA ·constants<>+16(SB)/8, $0x0006050403020100 -DATA ·constants<>+24(SB)/8, $0x1016151413121110 -// EX1 -DATA ·constants<>+32(SB)/8, $0x060c0b0a09080706 -DATA ·constants<>+40(SB)/8, $0x161c1b1a19181716 -// EX2 -DATA ·constants<>+48(SB)/8, $0x0d0d0d0d0d0f0e0d -DATA ·constants<>+56(SB)/8, $0x1d1d1d1d1d1f1e1d - -// h = (f*g) % (2**130-5) [partial reduction] -#define MULTIPLY(f0, f1, f2, f3, f4, g0, g1, g2, g3, g4, g51, g52, g53, g54, h0, h1, h2, h3, h4) \ - VMLOF f0, g0, h0 \ - VMLOF f0, g1, h1 \ - VMLOF f0, g2, h2 \ - VMLOF f0, g3, h3 \ - VMLOF f0, g4, h4 \ - VMLOF f1, g54, T_0 \ - VMLOF f1, g0, T_1 \ - VMLOF f1, g1, T_2 \ - VMLOF f1, g2, T_3 \ - VMLOF f1, g3, T_4 \ - VMALOF f2, g53, h0, h0 \ - VMALOF f2, g54, h1, h1 \ - VMALOF f2, g0, h2, h2 \ - VMALOF f2, g1, h3, h3 \ - VMALOF f2, g2, h4, h4 \ - VMALOF f3, g52, T_0, T_0 \ - VMALOF f3, g53, T_1, T_1 \ - VMALOF f3, g54, T_2, T_2 \ - VMALOF f3, g0, T_3, T_3 \ - VMALOF f3, g1, T_4, T_4 \ - VMALOF f4, g51, h0, h0 \ - VMALOF f4, g52, h1, h1 \ - VMALOF f4, g53, h2, h2 \ - VMALOF f4, g54, h3, h3 \ - VMALOF f4, g0, h4, h4 \ - VAG T_0, h0, h0 \ - VAG T_1, h1, h1 \ - VAG T_2, h2, h2 \ - VAG T_3, h3, h3 \ - VAG T_4, h4, h4 - -// carry h0->h1 h3->h4, h1->h2 h4->h0, h0->h1 h2->h3, h3->h4 -#define REDUCE(h0, h1, h2, h3, h4) \ - VESRLG $26, h0, T_0 \ - VESRLG $26, h3, T_1 \ - VN MOD26, h0, h0 \ - VN MOD26, h3, h3 \ - VAG T_0, h1, h1 \ - VAG T_1, h4, h4 \ - VESRLG $26, h1, T_2 \ - VESRLG $26, h4, T_3 \ - VN MOD26, h1, h1 \ - VN MOD26, h4, h4 \ - VESLG $2, T_3, T_4 \ - VAG T_3, T_4, T_4 \ - VAG T_2, h2, h2 \ - VAG T_4, h0, h0 \ - VESRLG $26, h2, T_0 \ - VESRLG $26, h0, T_1 \ - VN MOD26, h2, h2 \ - VN MOD26, h0, h0 \ - VAG T_0, h3, h3 \ - VAG T_1, h1, h1 \ - VESRLG $26, h3, T_2 \ - VN MOD26, h3, h3 \ - VAG T_2, h4, h4 - -// expand in0 into d[0] and in1 into d[1] -#define EXPAND(in0, in1, d0, d1, d2, d3, d4) \ - VGBM $0x0707, d1 \ // d1=tmp - VPERM in0, in1, EX2, d4 \ - VPERM in0, in1, EX0, d0 \ - VPERM in0, in1, EX1, d2 \ - VN d1, d4, d4 \ - VESRLG $26, d0, d1 \ - VESRLG $30, d2, d3 \ - VESRLG $4, d2, d2 \ - VN MOD26, d0, d0 \ - VN MOD26, d1, d1 \ - VN MOD26, d2, d2 \ - VN MOD26, d3, d3 - -// pack h4:h0 into h1:h0 (no carry) -#define PACK(h0, h1, h2, h3, h4) \ - VESLG $26, h1, h1 \ - VESLG $26, h3, h3 \ - VO h0, h1, h0 \ - VO h2, h3, h2 \ - VESLG $4, h2, h2 \ - VLEIB $7, $48, h1 \ - VSLB h1, h2, h2 \ - VO h0, h2, h0 \ - VLEIB $7, $104, h1 \ - VSLB h1, h4, h3 \ - VO h3, h0, h0 \ - VLEIB $7, $24, h1 \ - VSRLB h1, h4, h1 - -// if h > 2**130-5 then h -= 2**130-5 -#define MOD(h0, h1, t0, t1, t2) \ - VZERO t0 \ - VLEIG $1, $5, t0 \ - VACCQ h0, t0, t1 \ - VAQ h0, t0, t0 \ - VONE t2 \ - VLEIG $1, $-4, t2 \ - VAQ t2, t1, t1 \ - VACCQ h1, t1, t1 \ - VONE t2 \ - VAQ t2, t1, t1 \ - VN h0, t1, t2 \ - VNC t0, t1, t1 \ - VO t1, t2, h0 - -// func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]key) -TEXT ·poly1305vx(SB), $0-32 - // This code processes up to 2 blocks (32 bytes) per iteration - // using the algorithm described in: - // NEON crypto, Daniel J. Bernstein & Peter Schwabe - // https://cryptojedi.org/papers/neoncrypto-20120320.pdf - LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key - - // load MOD26, EX0, EX1 and EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), MOD26, EX2 - - // setup r - VL (R4), T_0 - MOVD $·keyMask<>(SB), R6 - VL (R6), T_1 - VN T_0, T_1, T_0 - EXPAND(T_0, T_0, R_0, R_1, R_2, R_3, R_4) - - // setup r*5 - VLEIG $0, $5, T_0 - VLEIG $1, $5, T_0 - - // store r (for final block) - VMLOF T_0, R_1, R5SAVE_1 - VMLOF T_0, R_2, R5SAVE_2 - VMLOF T_0, R_3, R5SAVE_3 - VMLOF T_0, R_4, R5SAVE_4 - VLGVG $0, R_0, RSAVE_0 - VLGVG $0, R_1, RSAVE_1 - VLGVG $0, R_2, RSAVE_2 - VLGVG $0, R_3, RSAVE_3 - VLGVG $0, R_4, RSAVE_4 - - // skip r**2 calculation - CMPBLE R3, $16, skip - - // calculate r**2 - MULTIPLY(R_0, R_1, R_2, R_3, R_4, R_0, R_1, R_2, R_3, R_4, R5SAVE_1, R5SAVE_2, R5SAVE_3, R5SAVE_4, H_0, H_1, H_2, H_3, H_4) - REDUCE(H_0, H_1, H_2, H_3, H_4) - VLEIG $0, $5, T_0 - VLEIG $1, $5, T_0 - VMLOF T_0, H_1, R5_1 - VMLOF T_0, H_2, R5_2 - VMLOF T_0, H_3, R5_3 - VMLOF T_0, H_4, R5_4 - VLR H_0, R_0 - VLR H_1, R_1 - VLR H_2, R_2 - VLR H_3, R_3 - VLR H_4, R_4 - - // initialize h - VZERO H_0 - VZERO H_1 - VZERO H_2 - VZERO H_3 - VZERO H_4 - -loop: - CMPBLE R3, $32, b2 - VLM (R2), T_0, T_1 - SUB $32, R3 - MOVD $32(R2), R2 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) - VLEIB $4, $1, F_4 - VLEIB $12, $1, F_4 - -multiply: - VAG H_0, F_0, F_0 - VAG H_1, F_1, F_1 - VAG H_2, F_2, F_2 - VAG H_3, F_3, F_3 - VAG H_4, F_4, F_4 - MULTIPLY(F_0, F_1, F_2, F_3, F_4, R_0, R_1, R_2, R_3, R_4, R5_1, R5_2, R5_3, R5_4, H_0, H_1, H_2, H_3, H_4) - REDUCE(H_0, H_1, H_2, H_3, H_4) - CMPBNE R3, $0, loop - -finish: - // sum vectors - VZERO T_0 - VSUMQG H_0, T_0, H_0 - VSUMQG H_1, T_0, H_1 - VSUMQG H_2, T_0, H_2 - VSUMQG H_3, T_0, H_3 - VSUMQG H_4, T_0, H_4 - - // h may be >= 2*(2**130-5) so we need to reduce it again - REDUCE(H_0, H_1, H_2, H_3, H_4) - - // carry h1->h4 - VESRLG $26, H_1, T_1 - VN MOD26, H_1, H_1 - VAQ T_1, H_2, H_2 - VESRLG $26, H_2, T_2 - VN MOD26, H_2, H_2 - VAQ T_2, H_3, H_3 - VESRLG $26, H_3, T_3 - VN MOD26, H_3, H_3 - VAQ T_3, H_4, H_4 - - // h is now < 2*(2**130-5) - // pack h into h1 (hi) and h0 (lo) - PACK(H_0, H_1, H_2, H_3, H_4) - - // if h > 2**130-5 then h -= 2**130-5 - MOD(H_0, H_1, T_0, T_1, T_2) - - // h += s - MOVD $·bswapMask<>(SB), R5 - VL (R5), T_1 - VL 16(R4), T_0 - VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) - VAQ T_0, H_0, H_0 - VPERM H_0, H_0, T_1, H_0 // reverse bytes (to little) - VST H_0, (R1) - - RET - -b2: - CMPBLE R3, $16, b1 - - // 2 blocks remaining - SUB $17, R3 - VL (R2), T_0 - VLL R3, 16(R2), T_1 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, T_1 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) - CMPBNE R3, $16, 2(PC) - VLEIB $12, $1, F_4 - VLEIB $4, $1, F_4 - - // setup [r²,r] - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, RSAVE_3, R_3 - VLVGG $1, RSAVE_4, R_4 - VPDI $0, R5_1, R5SAVE_1, R5_1 - VPDI $0, R5_2, R5SAVE_2, R5_2 - VPDI $0, R5_3, R5SAVE_3, R5_3 - VPDI $0, R5_4, R5SAVE_4, R5_4 - - MOVD $0, R3 - BR multiply - -skip: - VZERO H_0 - VZERO H_1 - VZERO H_2 - VZERO H_3 - VZERO H_4 - - CMPBEQ R3, $0, finish - -b1: - // 1 block remaining - SUB $1, R3 - VLL R3, (R2), T_0 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, T_0 - VZERO T_1 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) - CMPBNE R3, $16, 2(PC) - VLEIB $4, $1, F_4 - VLEIG $1, $1, R_0 - VZERO R_1 - VZERO R_2 - VZERO R_3 - VZERO R_4 - VZERO R5_1 - VZERO R5_2 - VZERO R5_3 - VZERO R5_4 - - // setup [r, 1] - VLVGG $0, RSAVE_0, R_0 - VLVGG $0, RSAVE_1, R_1 - VLVGG $0, RSAVE_2, R_2 - VLVGG $0, RSAVE_3, R_3 - VLVGG $0, RSAVE_4, R_4 - VPDI $0, R5SAVE_1, R5_1, R5_1 - VPDI $0, R5SAVE_2, R5_2, R5_2 - VPDI $0, R5SAVE_3, R5_3, R5_3 - VPDI $0, R5SAVE_4, R5_4, R5_4 - - MOVD $0, R3 - BR multiply diff --git a/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s deleted file mode 100644 index e60bbc1d..00000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s +++ /dev/null @@ -1,909 +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. - -// +build s390x,go1.11,!gccgo,!appengine - -#include "textflag.h" - -// Implementation of Poly1305 using the vector facility (vx) and the VMSL instruction. - -// constants -#define EX0 V1 -#define EX1 V2 -#define EX2 V3 - -// temporaries -#define T_0 V4 -#define T_1 V5 -#define T_2 V6 -#define T_3 V7 -#define T_4 V8 -#define T_5 V9 -#define T_6 V10 -#define T_7 V11 -#define T_8 V12 -#define T_9 V13 -#define T_10 V14 - -// r**2 & r**4 -#define R_0 V15 -#define R_1 V16 -#define R_2 V17 -#define R5_1 V18 -#define R5_2 V19 -// key (r) -#define RSAVE_0 R7 -#define RSAVE_1 R8 -#define RSAVE_2 R9 -#define R5SAVE_1 R10 -#define R5SAVE_2 R11 - -// message block -#define M0 V20 -#define M1 V21 -#define M2 V22 -#define M3 V23 -#define M4 V24 -#define M5 V25 - -// accumulator -#define H0_0 V26 -#define H1_0 V27 -#define H2_0 V28 -#define H0_1 V29 -#define H1_1 V30 -#define H2_1 V31 - -GLOBL ·keyMask<>(SB), RODATA, $16 -DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f -DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f - -GLOBL ·bswapMask<>(SB), RODATA, $16 -DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 -DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 - -GLOBL ·constants<>(SB), RODATA, $48 -// EX0 -DATA ·constants<>+0(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+8(SB)/8, $0x0000050403020100 -// EX1 -DATA ·constants<>+16(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+24(SB)/8, $0x00000a0908070605 -// EX2 -DATA ·constants<>+32(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+40(SB)/8, $0x0000000f0e0d0c0b - -GLOBL ·c<>(SB), RODATA, $48 -// EX0 -DATA ·c<>+0(SB)/8, $0x0000050403020100 -DATA ·c<>+8(SB)/8, $0x0000151413121110 -// EX1 -DATA ·c<>+16(SB)/8, $0x00000a0908070605 -DATA ·c<>+24(SB)/8, $0x00001a1918171615 -// EX2 -DATA ·c<>+32(SB)/8, $0x0000000f0e0d0c0b -DATA ·c<>+40(SB)/8, $0x0000001f1e1d1c1b - -GLOBL ·reduce<>(SB), RODATA, $32 -// 44 bit -DATA ·reduce<>+0(SB)/8, $0x0 -DATA ·reduce<>+8(SB)/8, $0xfffffffffff -// 42 bit -DATA ·reduce<>+16(SB)/8, $0x0 -DATA ·reduce<>+24(SB)/8, $0x3ffffffffff - -// h = (f*g) % (2**130-5) [partial reduction] -// uses T_0...T_9 temporary registers -// input: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9 -// output: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2 -#define MULTIPLY(m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9) \ - \ // Eliminate the dependency for the last 2 VMSLs - VMSLG m02_0, r_2, m4_2, m4_2 \ - VMSLG m13_0, r_2, m5_2, m5_2 \ // 8 VMSLs pipelined - VMSLG m02_0, r_0, m4_0, m4_0 \ - VMSLG m02_1, r5_2, V0, T_0 \ - VMSLG m02_0, r_1, m4_1, m4_1 \ - VMSLG m02_1, r_0, V0, T_1 \ - VMSLG m02_1, r_1, V0, T_2 \ - VMSLG m02_2, r5_1, V0, T_3 \ - VMSLG m02_2, r5_2, V0, T_4 \ - VMSLG m13_0, r_0, m5_0, m5_0 \ - VMSLG m13_1, r5_2, V0, T_5 \ - VMSLG m13_0, r_1, m5_1, m5_1 \ - VMSLG m13_1, r_0, V0, T_6 \ - VMSLG m13_1, r_1, V0, T_7 \ - VMSLG m13_2, r5_1, V0, T_8 \ - VMSLG m13_2, r5_2, V0, T_9 \ - VMSLG m02_2, r_0, m4_2, m4_2 \ - VMSLG m13_2, r_0, m5_2, m5_2 \ - VAQ m4_0, T_0, m02_0 \ - VAQ m4_1, T_1, m02_1 \ - VAQ m5_0, T_5, m13_0 \ - VAQ m5_1, T_6, m13_1 \ - VAQ m02_0, T_3, m02_0 \ - VAQ m02_1, T_4, m02_1 \ - VAQ m13_0, T_8, m13_0 \ - VAQ m13_1, T_9, m13_1 \ - VAQ m4_2, T_2, m02_2 \ - VAQ m5_2, T_7, m13_2 \ - -// SQUARE uses three limbs of r and r_2*5 to output square of r -// uses T_1, T_5 and T_7 temporary registers -// input: r_0, r_1, r_2, r5_2 -// temp: TEMP0, TEMP1, TEMP2 -// output: p0, p1, p2 -#define SQUARE(r_0, r_1, r_2, r5_2, p0, p1, p2, TEMP0, TEMP1, TEMP2) \ - VMSLG r_0, r_0, p0, p0 \ - VMSLG r_1, r5_2, V0, TEMP0 \ - VMSLG r_2, r5_2, p1, p1 \ - VMSLG r_0, r_1, V0, TEMP1 \ - VMSLG r_1, r_1, p2, p2 \ - VMSLG r_0, r_2, V0, TEMP2 \ - VAQ TEMP0, p0, p0 \ - VAQ TEMP1, p1, p1 \ - VAQ TEMP2, p2, p2 \ - VAQ TEMP0, p0, p0 \ - VAQ TEMP1, p1, p1 \ - VAQ TEMP2, p2, p2 \ - -// carry h0->h1->h2->h0 || h3->h4->h5->h3 -// uses T_2, T_4, T_5, T_7, T_8, T_9 -// t6, t7, t8, t9, t10, t11 -// input: h0, h1, h2, h3, h4, h5 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11 -// output: h0, h1, h2, h3, h4, h5 -#define REDUCE(h0, h1, h2, h3, h4, h5, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) \ - VLM (R12), t6, t7 \ // 44 and 42 bit clear mask - VLEIB $7, $0x28, t10 \ // 5 byte shift mask - VREPIB $4, t8 \ // 4 bit shift mask - VREPIB $2, t11 \ // 2 bit shift mask - VSRLB t10, h0, t0 \ // h0 byte shift - VSRLB t10, h1, t1 \ // h1 byte shift - VSRLB t10, h2, t2 \ // h2 byte shift - VSRLB t10, h3, t3 \ // h3 byte shift - VSRLB t10, h4, t4 \ // h4 byte shift - VSRLB t10, h5, t5 \ // h5 byte shift - VSRL t8, t0, t0 \ // h0 bit shift - VSRL t8, t1, t1 \ // h2 bit shift - VSRL t11, t2, t2 \ // h2 bit shift - VSRL t8, t3, t3 \ // h3 bit shift - VSRL t8, t4, t4 \ // h4 bit shift - VESLG $2, t2, t9 \ // h2 carry x5 - VSRL t11, t5, t5 \ // h5 bit shift - VN t6, h0, h0 \ // h0 clear carry - VAQ t2, t9, t2 \ // h2 carry x5 - VESLG $2, t5, t9 \ // h5 carry x5 - VN t6, h1, h1 \ // h1 clear carry - VN t7, h2, h2 \ // h2 clear carry - VAQ t5, t9, t5 \ // h5 carry x5 - VN t6, h3, h3 \ // h3 clear carry - VN t6, h4, h4 \ // h4 clear carry - VN t7, h5, h5 \ // h5 clear carry - VAQ t0, h1, h1 \ // h0->h1 - VAQ t3, h4, h4 \ // h3->h4 - VAQ t1, h2, h2 \ // h1->h2 - VAQ t4, h5, h5 \ // h4->h5 - VAQ t2, h0, h0 \ // h2->h0 - VAQ t5, h3, h3 \ // h5->h3 - VREPG $1, t6, t6 \ // 44 and 42 bit masks across both halves - VREPG $1, t7, t7 \ - VSLDB $8, h0, h0, h0 \ // set up [h0/1/2, h3/4/5] - VSLDB $8, h1, h1, h1 \ - VSLDB $8, h2, h2, h2 \ - VO h0, h3, h3 \ - VO h1, h4, h4 \ - VO h2, h5, h5 \ - VESRLG $44, h3, t0 \ // 44 bit shift right - VESRLG $44, h4, t1 \ - VESRLG $42, h5, t2 \ - VN t6, h3, h3 \ // clear carry bits - VN t6, h4, h4 \ - VN t7, h5, h5 \ - VESLG $2, t2, t9 \ // multiply carry by 5 - VAQ t9, t2, t2 \ - VAQ t0, h4, h4 \ - VAQ t1, h5, h5 \ - VAQ t2, h3, h3 \ - -// carry h0->h1->h2->h0 -// input: h0, h1, h2 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8 -// output: h0, h1, h2 -#define REDUCE2(h0, h1, h2, t0, t1, t2, t3, t4, t5, t6, t7, t8) \ - VLEIB $7, $0x28, t3 \ // 5 byte shift mask - VREPIB $4, t4 \ // 4 bit shift mask - VREPIB $2, t7 \ // 2 bit shift mask - VGBM $0x003F, t5 \ // mask to clear carry bits - VSRLB t3, h0, t0 \ - VSRLB t3, h1, t1 \ - VSRLB t3, h2, t2 \ - VESRLG $4, t5, t5 \ // 44 bit clear mask - VSRL t4, t0, t0 \ - VSRL t4, t1, t1 \ - VSRL t7, t2, t2 \ - VESRLG $2, t5, t6 \ // 42 bit clear mask - VESLG $2, t2, t8 \ - VAQ t8, t2, t2 \ - VN t5, h0, h0 \ - VN t5, h1, h1 \ - VN t6, h2, h2 \ - VAQ t0, h1, h1 \ - VAQ t1, h2, h2 \ - VAQ t2, h0, h0 \ - VSRLB t3, h0, t0 \ - VSRLB t3, h1, t1 \ - VSRLB t3, h2, t2 \ - VSRL t4, t0, t0 \ - VSRL t4, t1, t1 \ - VSRL t7, t2, t2 \ - VN t5, h0, h0 \ - VN t5, h1, h1 \ - VESLG $2, t2, t8 \ - VN t6, h2, h2 \ - VAQ t0, h1, h1 \ - VAQ t8, t2, t2 \ - VAQ t1, h2, h2 \ - VAQ t2, h0, h0 \ - -// expands two message blocks into the lower halfs of the d registers -// moves the contents of the d registers into upper halfs -// input: in1, in2, d0, d1, d2, d3, d4, d5 -// temp: TEMP0, TEMP1, TEMP2, TEMP3 -// output: d0, d1, d2, d3, d4, d5 -#define EXPACC(in1, in2, d0, d1, d2, d3, d4, d5, TEMP0, TEMP1, TEMP2, TEMP3) \ - VGBM $0xff3f, TEMP0 \ - VGBM $0xff1f, TEMP1 \ - VESLG $4, d1, TEMP2 \ - VESLG $4, d4, TEMP3 \ - VESRLG $4, TEMP0, TEMP0 \ - VPERM in1, d0, EX0, d0 \ - VPERM in2, d3, EX0, d3 \ - VPERM in1, d2, EX2, d2 \ - VPERM in2, d5, EX2, d5 \ - VPERM in1, TEMP2, EX1, d1 \ - VPERM in2, TEMP3, EX1, d4 \ - VN TEMP0, d0, d0 \ - VN TEMP0, d3, d3 \ - VESRLG $4, d1, d1 \ - VESRLG $4, d4, d4 \ - VN TEMP1, d2, d2 \ - VN TEMP1, d5, d5 \ - VN TEMP0, d1, d1 \ - VN TEMP0, d4, d4 \ - -// expands one message block into the lower halfs of the d registers -// moves the contents of the d registers into upper halfs -// input: in, d0, d1, d2 -// temp: TEMP0, TEMP1, TEMP2 -// output: d0, d1, d2 -#define EXPACC2(in, d0, d1, d2, TEMP0, TEMP1, TEMP2) \ - VGBM $0xff3f, TEMP0 \ - VESLG $4, d1, TEMP2 \ - VGBM $0xff1f, TEMP1 \ - VPERM in, d0, EX0, d0 \ - VESRLG $4, TEMP0, TEMP0 \ - VPERM in, d2, EX2, d2 \ - VPERM in, TEMP2, EX1, d1 \ - VN TEMP0, d0, d0 \ - VN TEMP1, d2, d2 \ - VESRLG $4, d1, d1 \ - VN TEMP0, d1, d1 \ - -// pack h2:h0 into h1:h0 (no carry) -// input: h0, h1, h2 -// output: h0, h1, h2 -#define PACK(h0, h1, h2) \ - VMRLG h1, h2, h2 \ // copy h1 to upper half h2 - VESLG $44, h1, h1 \ // shift limb 1 44 bits, leaving 20 - VO h0, h1, h0 \ // combine h0 with 20 bits from limb 1 - VESRLG $20, h2, h1 \ // put top 24 bits of limb 1 into h1 - VLEIG $1, $0, h1 \ // clear h2 stuff from lower half of h1 - VO h0, h1, h0 \ // h0 now has 88 bits (limb 0 and 1) - VLEIG $0, $0, h2 \ // clear upper half of h2 - VESRLG $40, h2, h1 \ // h1 now has upper two bits of result - VLEIB $7, $88, h1 \ // for byte shift (11 bytes) - VSLB h1, h2, h2 \ // shift h2 11 bytes to the left - VO h0, h2, h0 \ // combine h0 with 20 bits from limb 1 - VLEIG $0, $0, h1 \ // clear upper half of h1 - -// if h > 2**130-5 then h -= 2**130-5 -// input: h0, h1 -// temp: t0, t1, t2 -// output: h0 -#define MOD(h0, h1, t0, t1, t2) \ - VZERO t0 \ - VLEIG $1, $5, t0 \ - VACCQ h0, t0, t1 \ - VAQ h0, t0, t0 \ - VONE t2 \ - VLEIG $1, $-4, t2 \ - VAQ t2, t1, t1 \ - VACCQ h1, t1, t1 \ - VONE t2 \ - VAQ t2, t1, t1 \ - VN h0, t1, t2 \ - VNC t0, t1, t1 \ - VO t1, t2, h0 \ - -// func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]key) -TEXT ·poly1305vmsl(SB), $0-32 - // This code processes 6 + up to 4 blocks (32 bytes) per iteration - // using the algorithm described in: - // NEON crypto, Daniel J. Bernstein & Peter Schwabe - // https://cryptojedi.org/papers/neoncrypto-20120320.pdf - // And as moddified for VMSL as described in - // Accelerating Poly1305 Cryptographic Message Authentication on the z14 - // O'Farrell et al, CASCON 2017, p48-55 - // https://ibm.ent.box.com/s/jf9gedj0e9d2vjctfyh186shaztavnht - - LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key - VZERO V0 // c - - // load EX0, EX1 and EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 // c - - // setup r - VL (R4), T_0 - MOVD $·keyMask<>(SB), R6 - VL (R6), T_1 - VN T_0, T_1, T_0 - VZERO T_2 // limbs for r - VZERO T_3 - VZERO T_4 - EXPACC2(T_0, T_2, T_3, T_4, T_1, T_5, T_7) - - // T_2, T_3, T_4: [0, r] - - // setup r*20 - VLEIG $0, $0, T_0 - VLEIG $1, $20, T_0 // T_0: [0, 20] - VZERO T_5 - VZERO T_6 - VMSLG T_0, T_3, T_5, T_5 - VMSLG T_0, T_4, T_6, T_6 - - // store r for final block in GR - VLGVG $1, T_2, RSAVE_0 // c - VLGVG $1, T_3, RSAVE_1 // c - VLGVG $1, T_4, RSAVE_2 // c - VLGVG $1, T_5, R5SAVE_1 // c - VLGVG $1, T_6, R5SAVE_2 // c - - // initialize h - VZERO H0_0 - VZERO H1_0 - VZERO H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - // initialize pointer for reduce constants - MOVD $·reduce<>(SB), R12 - - // calculate r**2 and 20*(r**2) - VZERO R_0 - VZERO R_1 - VZERO R_2 - SQUARE(T_2, T_3, T_4, T_6, R_0, R_1, R_2, T_1, T_5, T_7) - REDUCE2(R_0, R_1, R_2, M0, M1, M2, M3, M4, R5_1, R5_2, M5, T_1) - VZERO R5_1 - VZERO R5_2 - VMSLG T_0, R_1, R5_1, R5_1 - VMSLG T_0, R_2, R5_2, R5_2 - - // skip r**4 calculation if 3 blocks or less - CMPBLE R3, $48, b4 - - // calculate r**4 and 20*(r**4) - VZERO T_8 - VZERO T_9 - VZERO T_10 - SQUARE(R_0, R_1, R_2, R5_2, T_8, T_9, T_10, T_1, T_5, T_7) - REDUCE2(T_8, T_9, T_10, M0, M1, M2, M3, M4, T_2, T_3, M5, T_1) - VZERO T_2 - VZERO T_3 - VMSLG T_0, T_9, T_2, T_2 - VMSLG T_0, T_10, T_3, T_3 - - // put r**2 to the right and r**4 to the left of R_0, R_1, R_2 - VSLDB $8, T_8, T_8, T_8 - VSLDB $8, T_9, T_9, T_9 - VSLDB $8, T_10, T_10, T_10 - VSLDB $8, T_2, T_2, T_2 - VSLDB $8, T_3, T_3, T_3 - - VO T_8, R_0, R_0 - VO T_9, R_1, R_1 - VO T_10, R_2, R_2 - VO T_2, R5_1, R5_1 - VO T_3, R5_2, R5_2 - - CMPBLE R3, $80, load // less than or equal to 5 blocks in message - - // 6(or 5+1) blocks - SUB $81, R3 - VLM (R2), M0, M4 - VLL R3, 80(R2), M5 - ADD $1, R3 - MOVBZ $1, R0 - CMPBGE R3, $16, 2(PC) - VLVGB R3, R0, M5 - MOVD $96(R2), R2 - EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - EXPACC(M2, M3, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - VLEIB $2, $1, H2_0 - VLEIB $2, $1, H2_1 - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO T_4 - VZERO T_10 - EXPACC(M4, M5, M0, M1, M2, M3, T_4, T_10, T_0, T_1, T_2, T_3) - VLR T_4, M4 - VLEIB $10, $1, M2 - CMPBLT R3, $16, 2(PC) - VLEIB $10, $1, T_10 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - SUB $16, R3 - CMPBLE R3, $0, square - -load: - // load EX0, EX1 and EX2 - MOVD $·c<>(SB), R5 - VLM (R5), EX0, EX2 - -loop: - CMPBLE R3, $64, add // b4 // last 4 or less blocks left - - // next 4 full blocks - VLM (R2), M2, M5 - SUB $64, R3 - MOVD $64(R2), R2 - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, T_0, T_1, T_3, T_4, T_5, T_2, T_7, T_8, T_9) - - // expacc in-lined to create [m2, m3] limbs - VGBM $0x3f3f, T_0 // 44 bit clear mask - VGBM $0x1f1f, T_1 // 40 bit clear mask - VPERM M2, M3, EX0, T_3 - VESRLG $4, T_0, T_0 // 44 bit clear mask ready - VPERM M2, M3, EX1, T_4 - VPERM M2, M3, EX2, T_5 - VN T_0, T_3, T_3 - VESRLG $4, T_4, T_4 - VN T_1, T_5, T_5 - VN T_0, T_4, T_4 - VMRHG H0_1, T_3, H0_0 - VMRHG H1_1, T_4, H1_0 - VMRHG H2_1, T_5, H2_0 - VMRLG H0_1, T_3, H0_1 - VMRLG H1_1, T_4, H1_1 - VMRLG H2_1, T_5, H2_1 - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - VPERM M4, M5, EX0, T_3 - VPERM M4, M5, EX1, T_4 - VPERM M4, M5, EX2, T_5 - VN T_0, T_3, T_3 - VESRLG $4, T_4, T_4 - VN T_1, T_5, T_5 - VN T_0, T_4, T_4 - VMRHG V0, T_3, M0 - VMRHG V0, T_4, M1 - VMRHG V0, T_5, M2 - VMRLG V0, T_3, M3 - VMRLG V0, T_4, M4 - VMRLG V0, T_5, M5 - VLEIB $10, $1, M2 - VLEIB $10, $1, M5 - - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - CMPBNE R3, $0, loop - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - // load EX0, EX1, EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 - - // sum vectors - VAQ H0_0, H0_1, H0_0 - VAQ H1_0, H1_1, H1_0 - VAQ H2_0, H2_1, H2_0 - - // h may be >= 2*(2**130-5) so we need to reduce it again - // M0...M4 are used as temps here - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - -next: // carry h1->h2 - VLEIB $7, $0x28, T_1 - VREPIB $4, T_2 - VGBM $0x003F, T_3 - VESRLG $4, T_3 - - // byte shift - VSRLB T_1, H1_0, T_4 - - // bit shift - VSRL T_2, T_4, T_4 - - // clear h1 carry bits - VN T_3, H1_0, H1_0 - - // add carry - VAQ T_4, H2_0, H2_0 - - // h is now < 2*(2**130-5) - // pack h into h1 (hi) and h0 (lo) - PACK(H0_0, H1_0, H2_0) - - // if h > 2**130-5 then h -= 2**130-5 - MOD(H0_0, H1_0, T_0, T_1, T_2) - - // h += s - MOVD $·bswapMask<>(SB), R5 - VL (R5), T_1 - VL 16(R4), T_0 - VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) - VAQ T_0, H0_0, H0_0 - VPERM H0_0, H0_0, T_1, H0_0 // reverse bytes (to little) - VST H0_0, (R1) - RET - -add: - // load EX0, EX1, EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 - - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - CMPBLE R3, $64, b4 - -b4: - CMPBLE R3, $48, b3 // 3 blocks or less - - // 4(3+1) blocks remaining - SUB $49, R3 - VLM (R2), M0, M2 - VLL R3, 48(R2), M3 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M3 - MOVD $64(R2), R2 - EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - VZERO M0 - VZERO M1 - VZERO M4 - VZERO M5 - VZERO T_4 - VZERO T_10 - EXPACC(M2, M3, M0, M1, M4, M5, T_4, T_10, T_0, T_1, T_2, T_3) - VLR T_4, M2 - VLEIB $10, $1, M4 - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_10 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M4, M5, M2, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - SUB $16, R3 - CMPBLE R3, $0, square // this condition must always hold true! - -b3: - CMPBLE R3, $32, b2 - - // 3 blocks remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, T_10, M5) - - SUB $33, R3 - VLM (R2), M0, M1 - VLL R3, 32(R2), M2 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M2 - - // H += m0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6) - VLEIB $10, $1, T_3 - VAG H0_0, T_1, H0_0 - VAG H1_0, T_2, H1_0 - VAG H2_0, T_3, H2_0 - - VZERO M0 - VZERO M3 - VZERO M4 - VZERO M5 - VZERO T_10 - - // (H+m0)*r - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M3, M4, M5, V0, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_10, H0_1, H1_1, H2_1, T_9) - - // H += m1 - VZERO V0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M1, T_1, T_2, T_3, T_4, T_5, T_6) - VLEIB $10, $1, T_3 - VAQ H0_0, T_1, H0_0 - VAQ H1_0, T_2, H1_0 - VAQ H2_0, T_3, H2_0 - REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) - - // [H, m2] * [r**2, r] - EXPACC2(M2, H0_0, H1_0, H2_0, T_1, T_2, T_3) - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, H2_0 - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, M5, T_10) - SUB $16, R3 - CMPBLE R3, $0, next // this condition must always hold true! - -b2: - CMPBLE R3, $16, b1 - - // 2 blocks remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - // move h to the left and 0s at the right - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - - // get message blocks and append 1 to start - SUB $17, R3 - VL (R2), M0 - VLL R3, 16(R2), M1 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M1 - VZERO T_6 - VZERO T_7 - VZERO T_8 - EXPACC2(M0, T_6, T_7, T_8, T_1, T_2, T_3) - EXPACC2(M1, T_6, T_7, T_8, T_1, T_2, T_3) - VLEIB $2, $1, T_8 - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_8 - - // add [m0, m1] to h - VAG H0_0, T_6, H0_0 - VAG H1_0, T_7, H1_0 - VAG H2_0, T_8, H2_0 - - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - VZERO T_10 - VZERO M0 - - // at this point R_0 .. R5_2 look like [r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M2, M3, M4, M5, T_10, M0, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M2, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) - SUB $16, R3, R3 - CMPBLE R3, $0, next - -b1: - CMPBLE R3, $0, next - - // 1 block remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - - // set up [0, m0] limbs - SUB $1, R3 - VLL R3, (R2), M0 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6)// limbs: [0, m] - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_3 - - // h+m0 - VAQ H0_0, T_1, H0_0 - VAQ H1_0, T_2, H1_0 - VAQ H2_0, T_3, H2_0 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - - BR next - -square: - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // (h0*r**2) + (h1*r) - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - BR next diff --git a/vendor/golang.org/x/crypto/ssh/buffer.go b/vendor/golang.org/x/crypto/ssh/buffer.go deleted file mode 100644 index 1ab07d07..00000000 --- a/vendor/golang.org/x/crypto/ssh/buffer.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "io" - "sync" -) - -// buffer provides a linked list buffer for data exchange -// between producer and consumer. Theoretically the buffer is -// of unlimited capacity as it does no allocation of its own. -type buffer struct { - // protects concurrent access to head, tail and closed - *sync.Cond - - head *element // the buffer that will be read first - tail *element // the buffer that will be read last - - closed bool -} - -// An element represents a single link in a linked list. -type element struct { - buf []byte - next *element -} - -// newBuffer returns an empty buffer that is not closed. -func newBuffer() *buffer { - e := new(element) - b := &buffer{ - Cond: newCond(), - head: e, - tail: e, - } - return b -} - -// write makes buf available for Read to receive. -// buf must not be modified after the call to write. -func (b *buffer) write(buf []byte) { - b.Cond.L.Lock() - e := &element{buf: buf} - b.tail.next = e - b.tail = e - b.Cond.Signal() - b.Cond.L.Unlock() -} - -// eof closes the buffer. Reads from the buffer once all -// the data has been consumed will receive io.EOF. -func (b *buffer) eof() { - b.Cond.L.Lock() - b.closed = true - b.Cond.Signal() - b.Cond.L.Unlock() -} - -// Read reads data from the internal buffer in buf. Reads will block -// if no data is available, or until the buffer is closed. -func (b *buffer) Read(buf []byte) (n int, err error) { - b.Cond.L.Lock() - defer b.Cond.L.Unlock() - - for len(buf) > 0 { - // if there is data in b.head, copy it - if len(b.head.buf) > 0 { - r := copy(buf, b.head.buf) - buf, b.head.buf = buf[r:], b.head.buf[r:] - n += r - continue - } - // if there is a next buffer, make it the head - if len(b.head.buf) == 0 && b.head != b.tail { - b.head = b.head.next - continue - } - - // if at least one byte has been copied, return - if n > 0 { - break - } - - // if nothing was read, and there is nothing outstanding - // check to see if the buffer is closed. - if b.closed { - err = io.EOF - break - } - // out of buffers, wait for producer - b.Cond.Wait() - } - return -} diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go deleted file mode 100644 index 00ed9923..00000000 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" - "net" - "sort" - "time" -) - -// These constants from [PROTOCOL.certkeys] represent the algorithm names -// for certificate types supported by this package. -const ( - CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" - CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" - CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" - CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" - CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" - CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" -) - -// Certificate types distinguish between host and user -// certificates. The values can be set in the CertType field of -// Certificate. -const ( - UserCert = 1 - HostCert = 2 -) - -// Signature represents a cryptographic signature. -type Signature struct { - Format string - Blob []byte -} - -// CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that -// a certificate does not expire. -const CertTimeInfinity = 1<<64 - 1 - -// An Certificate represents an OpenSSH certificate as defined in -// [PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the -// PublicKey interface, so it can be unmarshaled using -// ParsePublicKey. -type Certificate struct { - Nonce []byte - Key PublicKey - Serial uint64 - CertType uint32 - KeyId string - ValidPrincipals []string - ValidAfter uint64 - ValidBefore uint64 - Permissions - Reserved []byte - SignatureKey PublicKey - Signature *Signature -} - -// genericCertData holds the key-independent part of the certificate data. -// Overall, certificates contain an nonce, public key fields and -// key-independent fields. -type genericCertData struct { - Serial uint64 - CertType uint32 - KeyId string - ValidPrincipals []byte - ValidAfter uint64 - ValidBefore uint64 - CriticalOptions []byte - Extensions []byte - Reserved []byte - SignatureKey []byte - Signature []byte -} - -func marshalStringList(namelist []string) []byte { - var to []byte - for _, name := range namelist { - s := struct{ N string }{name} - to = append(to, Marshal(&s)...) - } - return to -} - -type optionsTuple struct { - Key string - Value []byte -} - -type optionsTupleValue struct { - Value string -} - -// serialize a map of critical options or extensions -// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, -// we need two length prefixes for a non-empty string value -func marshalTuples(tups map[string]string) []byte { - keys := make([]string, 0, len(tups)) - for key := range tups { - keys = append(keys, key) - } - sort.Strings(keys) - - var ret []byte - for _, key := range keys { - s := optionsTuple{Key: key} - if value := tups[key]; len(value) > 0 { - s.Value = Marshal(&optionsTupleValue{value}) - } - ret = append(ret, Marshal(&s)...) - } - return ret -} - -// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, -// we need two length prefixes for a non-empty option value -func parseTuples(in []byte) (map[string]string, error) { - tups := map[string]string{} - var lastKey string - var haveLastKey bool - - for len(in) > 0 { - var key, val, extra []byte - var ok bool - - if key, in, ok = parseString(in); !ok { - return nil, errShortRead - } - keyStr := string(key) - // according to [PROTOCOL.certkeys], the names must be in - // lexical order. - if haveLastKey && keyStr <= lastKey { - return nil, fmt.Errorf("ssh: certificate options are not in lexical order") - } - lastKey, haveLastKey = keyStr, true - // the next field is a data field, which if non-empty has a string embedded - if val, in, ok = parseString(in); !ok { - return nil, errShortRead - } - if len(val) > 0 { - val, extra, ok = parseString(val) - if !ok { - return nil, errShortRead - } - if len(extra) > 0 { - return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value") - } - tups[keyStr] = string(val) - } else { - tups[keyStr] = "" - } - } - return tups, nil -} - -func parseCert(in []byte, privAlgo string) (*Certificate, error) { - nonce, rest, ok := parseString(in) - if !ok { - return nil, errShortRead - } - - key, rest, err := parsePubKey(rest, privAlgo) - if err != nil { - return nil, err - } - - var g genericCertData - if err := Unmarshal(rest, &g); err != nil { - return nil, err - } - - c := &Certificate{ - Nonce: nonce, - Key: key, - Serial: g.Serial, - CertType: g.CertType, - KeyId: g.KeyId, - ValidAfter: g.ValidAfter, - ValidBefore: g.ValidBefore, - } - - for principals := g.ValidPrincipals; len(principals) > 0; { - principal, rest, ok := parseString(principals) - if !ok { - return nil, errShortRead - } - c.ValidPrincipals = append(c.ValidPrincipals, string(principal)) - principals = rest - } - - c.CriticalOptions, err = parseTuples(g.CriticalOptions) - if err != nil { - return nil, err - } - c.Extensions, err = parseTuples(g.Extensions) - if err != nil { - return nil, err - } - c.Reserved = g.Reserved - k, err := ParsePublicKey(g.SignatureKey) - if err != nil { - return nil, err - } - - c.SignatureKey = k - c.Signature, rest, ok = parseSignatureBody(g.Signature) - if !ok || len(rest) > 0 { - return nil, errors.New("ssh: signature parse error") - } - - return c, nil -} - -type openSSHCertSigner struct { - pub *Certificate - signer Signer -} - -type algorithmOpenSSHCertSigner struct { - *openSSHCertSigner - algorithmSigner AlgorithmSigner -} - -// NewCertSigner returns a Signer that signs with the given Certificate, whose -// private key is held by signer. It returns an error if the public key in cert -// doesn't match the key used by signer. -func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) { - if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 { - return nil, errors.New("ssh: signer and cert have different public key") - } - - if algorithmSigner, ok := signer.(AlgorithmSigner); ok { - return &algorithmOpenSSHCertSigner{ - &openSSHCertSigner{cert, signer}, algorithmSigner}, nil - } else { - return &openSSHCertSigner{cert, signer}, nil - } -} - -func (s *openSSHCertSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { - return s.signer.Sign(rand, data) -} - -func (s *openSSHCertSigner) PublicKey() PublicKey { - return s.pub -} - -func (s *algorithmOpenSSHCertSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { - return s.algorithmSigner.SignWithAlgorithm(rand, data, algorithm) -} - -const sourceAddressCriticalOption = "source-address" - -// CertChecker does the work of verifying a certificate. Its methods -// can be plugged into ClientConfig.HostKeyCallback and -// ServerConfig.PublicKeyCallback. For the CertChecker to work, -// minimally, the IsAuthority callback should be set. -type CertChecker struct { - // SupportedCriticalOptions lists the CriticalOptions that the - // server application layer understands. These are only used - // for user certificates. - SupportedCriticalOptions []string - - // IsUserAuthority should return true if the key is recognized as an - // authority for the given user certificate. This allows for - // certificates to be signed by other certificates. This must be set - // if this CertChecker will be checking user certificates. - IsUserAuthority func(auth PublicKey) bool - - // IsHostAuthority should report whether the key is recognized as - // an authority for this host. This allows for certificates to be - // signed by other keys, and for those other keys to only be valid - // signers for particular hostnames. This must be set if this - // CertChecker will be checking host certificates. - IsHostAuthority func(auth PublicKey, address string) bool - - // Clock is used for verifying time stamps. If nil, time.Now - // is used. - Clock func() time.Time - - // UserKeyFallback is called when CertChecker.Authenticate encounters a - // public key that is not a certificate. It must implement validation - // of user keys or else, if nil, all such keys are rejected. - UserKeyFallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) - - // HostKeyFallback is called when CertChecker.CheckHostKey encounters a - // public key that is not a certificate. It must implement host key - // validation or else, if nil, all such keys are rejected. - HostKeyFallback HostKeyCallback - - // IsRevoked is called for each certificate so that revocation checking - // can be implemented. It should return true if the given certificate - // is revoked and false otherwise. If nil, no certificates are - // considered to have been revoked. - IsRevoked func(cert *Certificate) bool -} - -// CheckHostKey checks a host key certificate. This method can be -// plugged into ClientConfig.HostKeyCallback. -func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error { - cert, ok := key.(*Certificate) - if !ok { - if c.HostKeyFallback != nil { - return c.HostKeyFallback(addr, remote, key) - } - return errors.New("ssh: non-certificate host key") - } - if cert.CertType != HostCert { - return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType) - } - if !c.IsHostAuthority(cert.SignatureKey, addr) { - return fmt.Errorf("ssh: no authorities for hostname: %v", addr) - } - - hostname, _, err := net.SplitHostPort(addr) - if err != nil { - return err - } - - // Pass hostname only as principal for host certificates (consistent with OpenSSH) - return c.CheckCert(hostname, cert) -} - -// Authenticate checks a user certificate. Authenticate can be used as -// a value for ServerConfig.PublicKeyCallback. -func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) { - cert, ok := pubKey.(*Certificate) - if !ok { - if c.UserKeyFallback != nil { - return c.UserKeyFallback(conn, pubKey) - } - return nil, errors.New("ssh: normal key pairs not accepted") - } - - if cert.CertType != UserCert { - return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType) - } - if !c.IsUserAuthority(cert.SignatureKey) { - return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority") - } - - if err := c.CheckCert(conn.User(), cert); err != nil { - return nil, err - } - - return &cert.Permissions, nil -} - -// CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and -// the signature of the certificate. -func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { - if c.IsRevoked != nil && c.IsRevoked(cert) { - return fmt.Errorf("ssh: certificate serial %d revoked", cert.Serial) - } - - for opt := range cert.CriticalOptions { - // sourceAddressCriticalOption will be enforced by - // serverAuthenticate - if opt == sourceAddressCriticalOption { - continue - } - - found := false - for _, supp := range c.SupportedCriticalOptions { - if supp == opt { - found = true - break - } - } - if !found { - return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt) - } - } - - if len(cert.ValidPrincipals) > 0 { - // By default, certs are valid for all users/hosts. - found := false - for _, p := range cert.ValidPrincipals { - if p == principal { - found = true - break - } - } - if !found { - return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals) - } - } - - clock := c.Clock - if clock == nil { - clock = time.Now - } - - unixNow := clock().Unix() - if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) { - return fmt.Errorf("ssh: cert is not yet valid") - } - if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) { - return fmt.Errorf("ssh: cert has expired") - } - if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil { - return fmt.Errorf("ssh: certificate signature does not verify") - } - - return nil -} - -// SignCert sets c.SignatureKey to the authority's public key and stores a -// Signature, by authority, in the certificate. -func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { - c.Nonce = make([]byte, 32) - if _, err := io.ReadFull(rand, c.Nonce); err != nil { - return err - } - c.SignatureKey = authority.PublicKey() - - sig, err := authority.Sign(rand, c.bytesForSigning()) - if err != nil { - return err - } - c.Signature = sig - return nil -} - -var certAlgoNames = map[string]string{ - KeyAlgoRSA: CertAlgoRSAv01, - KeyAlgoDSA: CertAlgoDSAv01, - KeyAlgoECDSA256: CertAlgoECDSA256v01, - KeyAlgoECDSA384: CertAlgoECDSA384v01, - KeyAlgoECDSA521: CertAlgoECDSA521v01, - KeyAlgoED25519: CertAlgoED25519v01, -} - -// certToPrivAlgo returns the underlying algorithm for a certificate algorithm. -// Panics if a non-certificate algorithm is passed. -func certToPrivAlgo(algo string) string { - for privAlgo, pubAlgo := range certAlgoNames { - if pubAlgo == algo { - return privAlgo - } - } - panic("unknown cert algorithm") -} - -func (cert *Certificate) bytesForSigning() []byte { - c2 := *cert - c2.Signature = nil - out := c2.Marshal() - // Drop trailing signature length. - return out[:len(out)-4] -} - -// Marshal serializes c into OpenSSH's wire format. It is part of the -// PublicKey interface. -func (c *Certificate) Marshal() []byte { - generic := genericCertData{ - Serial: c.Serial, - CertType: c.CertType, - KeyId: c.KeyId, - ValidPrincipals: marshalStringList(c.ValidPrincipals), - ValidAfter: uint64(c.ValidAfter), - ValidBefore: uint64(c.ValidBefore), - CriticalOptions: marshalTuples(c.CriticalOptions), - Extensions: marshalTuples(c.Extensions), - Reserved: c.Reserved, - SignatureKey: c.SignatureKey.Marshal(), - } - if c.Signature != nil { - generic.Signature = Marshal(c.Signature) - } - genericBytes := Marshal(&generic) - keyBytes := c.Key.Marshal() - _, keyBytes, _ = parseString(keyBytes) - prefix := Marshal(&struct { - Name string - Nonce []byte - Key []byte `ssh:"rest"` - }{c.Type(), c.Nonce, keyBytes}) - - result := make([]byte, 0, len(prefix)+len(genericBytes)) - result = append(result, prefix...) - result = append(result, genericBytes...) - return result -} - -// Type returns the key name. It is part of the PublicKey interface. -func (c *Certificate) Type() string { - algo, ok := certAlgoNames[c.Key.Type()] - if !ok { - panic("unknown cert key type " + c.Key.Type()) - } - return algo -} - -// Verify verifies a signature against the certificate's public -// key. It is part of the PublicKey interface. -func (c *Certificate) Verify(data []byte, sig *Signature) error { - return c.Key.Verify(data, sig) -} - -func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) { - format, in, ok := parseString(in) - if !ok { - return - } - - out = &Signature{ - Format: string(format), - } - - if out.Blob, in, ok = parseString(in); !ok { - return - } - - return out, in, ok -} - -func parseSignature(in []byte) (out *Signature, rest []byte, ok bool) { - sigBytes, rest, ok := parseString(in) - if !ok { - return - } - - out, trailing, ok := parseSignatureBody(sigBytes) - if !ok || len(trailing) > 0 { - return nil, nil, false - } - return -} diff --git a/vendor/golang.org/x/crypto/ssh/channel.go b/vendor/golang.org/x/crypto/ssh/channel.go deleted file mode 100644 index c0834c00..00000000 --- a/vendor/golang.org/x/crypto/ssh/channel.go +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "log" - "sync" -) - -const ( - minPacketLength = 9 - // channelMaxPacket contains the maximum number of bytes that will be - // sent in a single packet. As per RFC 4253, section 6.1, 32k is also - // the minimum. - channelMaxPacket = 1 << 15 - // We follow OpenSSH here. - channelWindowSize = 64 * channelMaxPacket -) - -// NewChannel represents an incoming request to a channel. It must either be -// accepted for use by calling Accept, or rejected by calling Reject. -type NewChannel interface { - // Accept accepts the channel creation request. It returns the Channel - // and a Go channel containing SSH requests. The Go channel must be - // serviced otherwise the Channel will hang. - Accept() (Channel, <-chan *Request, error) - - // Reject rejects the channel creation request. After calling - // this, no other methods on the Channel may be called. - Reject(reason RejectionReason, message string) error - - // ChannelType returns the type of the channel, as supplied by the - // client. - ChannelType() string - - // ExtraData returns the arbitrary payload for this channel, as supplied - // by the client. This data is specific to the channel type. - ExtraData() []byte -} - -// A Channel is an ordered, reliable, flow-controlled, duplex stream -// that is multiplexed over an SSH connection. -type Channel interface { - // Read reads up to len(data) bytes from the channel. - Read(data []byte) (int, error) - - // Write writes len(data) bytes to the channel. - Write(data []byte) (int, error) - - // Close signals end of channel use. No data may be sent after this - // call. - Close() error - - // CloseWrite signals the end of sending in-band - // data. Requests may still be sent, and the other side may - // still send data - CloseWrite() error - - // SendRequest sends a channel request. If wantReply is true, - // it will wait for a reply and return the result as a - // boolean, otherwise the return value will be false. Channel - // requests are out-of-band messages so they may be sent even - // if the data stream is closed or blocked by flow control. - // If the channel is closed before a reply is returned, io.EOF - // is returned. - SendRequest(name string, wantReply bool, payload []byte) (bool, error) - - // Stderr returns an io.ReadWriter that writes to this channel - // with the extended data type set to stderr. Stderr may - // safely be read and written from a different goroutine than - // Read and Write respectively. - Stderr() io.ReadWriter -} - -// Request is a request sent outside of the normal stream of -// data. Requests can either be specific to an SSH channel, or they -// can be global. -type Request struct { - Type string - WantReply bool - Payload []byte - - ch *channel - mux *mux -} - -// Reply sends a response to a request. It must be called for all requests -// where WantReply is true and is a no-op otherwise. The payload argument is -// ignored for replies to channel-specific requests. -func (r *Request) Reply(ok bool, payload []byte) error { - if !r.WantReply { - return nil - } - - if r.ch == nil { - return r.mux.ackRequest(ok, payload) - } - - return r.ch.ackRequest(ok) -} - -// RejectionReason is an enumeration used when rejecting channel creation -// requests. See RFC 4254, section 5.1. -type RejectionReason uint32 - -const ( - Prohibited RejectionReason = iota + 1 - ConnectionFailed - UnknownChannelType - ResourceShortage -) - -// String converts the rejection reason to human readable form. -func (r RejectionReason) String() string { - switch r { - case Prohibited: - return "administratively prohibited" - case ConnectionFailed: - return "connect failed" - case UnknownChannelType: - return "unknown channel type" - case ResourceShortage: - return "resource shortage" - } - return fmt.Sprintf("unknown reason %d", int(r)) -} - -func min(a uint32, b int) uint32 { - if a < uint32(b) { - return a - } - return uint32(b) -} - -type channelDirection uint8 - -const ( - channelInbound channelDirection = iota - channelOutbound -) - -// channel is an implementation of the Channel interface that works -// with the mux class. -type channel struct { - // R/O after creation - chanType string - extraData []byte - localId, remoteId uint32 - - // maxIncomingPayload and maxRemotePayload are the maximum - // payload sizes of normal and extended data packets for - // receiving and sending, respectively. The wire packet will - // be 9 or 13 bytes larger (excluding encryption overhead). - maxIncomingPayload uint32 - maxRemotePayload uint32 - - mux *mux - - // decided is set to true if an accept or reject message has been sent - // (for outbound channels) or received (for inbound channels). - decided bool - - // direction contains either channelOutbound, for channels created - // locally, or channelInbound, for channels created by the peer. - direction channelDirection - - // Pending internal channel messages. - msg chan interface{} - - // Since requests have no ID, there can be only one request - // with WantReply=true outstanding. This lock is held by a - // goroutine that has such an outgoing request pending. - sentRequestMu sync.Mutex - - incomingRequests chan *Request - - sentEOF bool - - // thread-safe data - remoteWin window - pending *buffer - extPending *buffer - - // windowMu protects myWindow, the flow-control window. - windowMu sync.Mutex - myWindow uint32 - - // writeMu serializes calls to mux.conn.writePacket() and - // protects sentClose and packetPool. This mutex must be - // different from windowMu, as writePacket can block if there - // is a key exchange pending. - writeMu sync.Mutex - sentClose bool - - // packetPool has a buffer for each extended channel ID to - // save allocations during writes. - packetPool map[uint32][]byte -} - -// writePacket sends a packet. If the packet is a channel close, it updates -// sentClose. This method takes the lock c.writeMu. -func (ch *channel) writePacket(packet []byte) error { - ch.writeMu.Lock() - if ch.sentClose { - ch.writeMu.Unlock() - return io.EOF - } - ch.sentClose = (packet[0] == msgChannelClose) - err := ch.mux.conn.writePacket(packet) - ch.writeMu.Unlock() - return err -} - -func (ch *channel) sendMessage(msg interface{}) error { - if debugMux { - log.Printf("send(%d): %#v", ch.mux.chanList.offset, msg) - } - - p := Marshal(msg) - binary.BigEndian.PutUint32(p[1:], ch.remoteId) - return ch.writePacket(p) -} - -// WriteExtended writes data to a specific extended stream. These streams are -// used, for example, for stderr. -func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { - if ch.sentEOF { - return 0, io.EOF - } - // 1 byte message type, 4 bytes remoteId, 4 bytes data length - opCode := byte(msgChannelData) - headerLength := uint32(9) - if extendedCode > 0 { - headerLength += 4 - opCode = msgChannelExtendedData - } - - ch.writeMu.Lock() - packet := ch.packetPool[extendedCode] - // We don't remove the buffer from packetPool, so - // WriteExtended calls from different goroutines will be - // flagged as errors by the race detector. - ch.writeMu.Unlock() - - for len(data) > 0 { - space := min(ch.maxRemotePayload, len(data)) - if space, err = ch.remoteWin.reserve(space); err != nil { - return n, err - } - if want := headerLength + space; uint32(cap(packet)) < want { - packet = make([]byte, want) - } else { - packet = packet[:want] - } - - todo := data[:space] - - packet[0] = opCode - binary.BigEndian.PutUint32(packet[1:], ch.remoteId) - if extendedCode > 0 { - binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode)) - } - binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo))) - copy(packet[headerLength:], todo) - if err = ch.writePacket(packet); err != nil { - return n, err - } - - n += len(todo) - data = data[len(todo):] - } - - ch.writeMu.Lock() - ch.packetPool[extendedCode] = packet - ch.writeMu.Unlock() - - return n, err -} - -func (ch *channel) handleData(packet []byte) error { - headerLen := 9 - isExtendedData := packet[0] == msgChannelExtendedData - if isExtendedData { - headerLen = 13 - } - if len(packet) < headerLen { - // malformed data packet - return parseError(packet[0]) - } - - var extended uint32 - if isExtendedData { - extended = binary.BigEndian.Uint32(packet[5:]) - } - - length := binary.BigEndian.Uint32(packet[headerLen-4 : headerLen]) - if length == 0 { - return nil - } - if length > ch.maxIncomingPayload { - // TODO(hanwen): should send Disconnect? - return errors.New("ssh: incoming packet exceeds maximum payload size") - } - - data := packet[headerLen:] - if length != uint32(len(data)) { - return errors.New("ssh: wrong packet length") - } - - ch.windowMu.Lock() - if ch.myWindow < length { - ch.windowMu.Unlock() - // TODO(hanwen): should send Disconnect with reason? - return errors.New("ssh: remote side wrote too much") - } - ch.myWindow -= length - ch.windowMu.Unlock() - - if extended == 1 { - ch.extPending.write(data) - } else if extended > 0 { - // discard other extended data. - } else { - ch.pending.write(data) - } - return nil -} - -func (c *channel) adjustWindow(n uint32) error { - c.windowMu.Lock() - // Since myWindow is managed on our side, and can never exceed - // the initial window setting, we don't worry about overflow. - c.myWindow += uint32(n) - c.windowMu.Unlock() - return c.sendMessage(windowAdjustMsg{ - AdditionalBytes: uint32(n), - }) -} - -func (c *channel) ReadExtended(data []byte, extended uint32) (n int, err error) { - switch extended { - case 1: - n, err = c.extPending.Read(data) - case 0: - n, err = c.pending.Read(data) - default: - return 0, fmt.Errorf("ssh: extended code %d unimplemented", extended) - } - - if n > 0 { - err = c.adjustWindow(uint32(n)) - // sendWindowAdjust can return io.EOF if the remote - // peer has closed the connection, however we want to - // defer forwarding io.EOF to the caller of Read until - // the buffer has been drained. - if n > 0 && err == io.EOF { - err = nil - } - } - - return n, err -} - -func (c *channel) close() { - c.pending.eof() - c.extPending.eof() - close(c.msg) - close(c.incomingRequests) - c.writeMu.Lock() - // This is not necessary for a normal channel teardown, but if - // there was another error, it is. - c.sentClose = true - c.writeMu.Unlock() - // Unblock writers. - c.remoteWin.close() -} - -// responseMessageReceived is called when a success or failure message is -// received on a channel to check that such a message is reasonable for the -// given channel. -func (ch *channel) responseMessageReceived() error { - if ch.direction == channelInbound { - return errors.New("ssh: channel response message received on inbound channel") - } - if ch.decided { - return errors.New("ssh: duplicate response received for channel") - } - ch.decided = true - return nil -} - -func (ch *channel) handlePacket(packet []byte) error { - switch packet[0] { - case msgChannelData, msgChannelExtendedData: - return ch.handleData(packet) - case msgChannelClose: - ch.sendMessage(channelCloseMsg{PeersID: ch.remoteId}) - ch.mux.chanList.remove(ch.localId) - ch.close() - return nil - case msgChannelEOF: - // RFC 4254 is mute on how EOF affects dataExt messages but - // it is logical to signal EOF at the same time. - ch.extPending.eof() - ch.pending.eof() - return nil - } - - decoded, err := decode(packet) - if err != nil { - return err - } - - switch msg := decoded.(type) { - case *channelOpenFailureMsg: - if err := ch.responseMessageReceived(); err != nil { - return err - } - ch.mux.chanList.remove(msg.PeersID) - ch.msg <- msg - case *channelOpenConfirmMsg: - if err := ch.responseMessageReceived(); err != nil { - return err - } - if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { - return fmt.Errorf("ssh: invalid MaxPacketSize %d from peer", msg.MaxPacketSize) - } - ch.remoteId = msg.MyID - ch.maxRemotePayload = msg.MaxPacketSize - ch.remoteWin.add(msg.MyWindow) - ch.msg <- msg - case *windowAdjustMsg: - if !ch.remoteWin.add(msg.AdditionalBytes) { - return fmt.Errorf("ssh: invalid window update for %d bytes", msg.AdditionalBytes) - } - case *channelRequestMsg: - req := Request{ - Type: msg.Request, - WantReply: msg.WantReply, - Payload: msg.RequestSpecificData, - ch: ch, - } - - ch.incomingRequests <- &req - default: - ch.msg <- msg - } - return nil -} - -func (m *mux) newChannel(chanType string, direction channelDirection, extraData []byte) *channel { - ch := &channel{ - remoteWin: window{Cond: newCond()}, - myWindow: channelWindowSize, - pending: newBuffer(), - extPending: newBuffer(), - direction: direction, - incomingRequests: make(chan *Request, chanSize), - msg: make(chan interface{}, chanSize), - chanType: chanType, - extraData: extraData, - mux: m, - packetPool: make(map[uint32][]byte), - } - ch.localId = m.chanList.add(ch) - return ch -} - -var errUndecided = errors.New("ssh: must Accept or Reject channel") -var errDecidedAlready = errors.New("ssh: can call Accept or Reject only once") - -type extChannel struct { - code uint32 - ch *channel -} - -func (e *extChannel) Write(data []byte) (n int, err error) { - return e.ch.WriteExtended(data, e.code) -} - -func (e *extChannel) Read(data []byte) (n int, err error) { - return e.ch.ReadExtended(data, e.code) -} - -func (ch *channel) Accept() (Channel, <-chan *Request, error) { - if ch.decided { - return nil, nil, errDecidedAlready - } - ch.maxIncomingPayload = channelMaxPacket - confirm := channelOpenConfirmMsg{ - PeersID: ch.remoteId, - MyID: ch.localId, - MyWindow: ch.myWindow, - MaxPacketSize: ch.maxIncomingPayload, - } - ch.decided = true - if err := ch.sendMessage(confirm); err != nil { - return nil, nil, err - } - - return ch, ch.incomingRequests, nil -} - -func (ch *channel) Reject(reason RejectionReason, message string) error { - if ch.decided { - return errDecidedAlready - } - reject := channelOpenFailureMsg{ - PeersID: ch.remoteId, - Reason: reason, - Message: message, - Language: "en", - } - ch.decided = true - return ch.sendMessage(reject) -} - -func (ch *channel) Read(data []byte) (int, error) { - if !ch.decided { - return 0, errUndecided - } - return ch.ReadExtended(data, 0) -} - -func (ch *channel) Write(data []byte) (int, error) { - if !ch.decided { - return 0, errUndecided - } - return ch.WriteExtended(data, 0) -} - -func (ch *channel) CloseWrite() error { - if !ch.decided { - return errUndecided - } - ch.sentEOF = true - return ch.sendMessage(channelEOFMsg{ - PeersID: ch.remoteId}) -} - -func (ch *channel) Close() error { - if !ch.decided { - return errUndecided - } - - return ch.sendMessage(channelCloseMsg{ - PeersID: ch.remoteId}) -} - -// Extended returns an io.ReadWriter that sends and receives data on the given, -// SSH extended stream. Such streams are used, for example, for stderr. -func (ch *channel) Extended(code uint32) io.ReadWriter { - if !ch.decided { - return nil - } - return &extChannel{code, ch} -} - -func (ch *channel) Stderr() io.ReadWriter { - return ch.Extended(1) -} - -func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { - if !ch.decided { - return false, errUndecided - } - - if wantReply { - ch.sentRequestMu.Lock() - defer ch.sentRequestMu.Unlock() - } - - msg := channelRequestMsg{ - PeersID: ch.remoteId, - Request: name, - WantReply: wantReply, - RequestSpecificData: payload, - } - - if err := ch.sendMessage(msg); err != nil { - return false, err - } - - if wantReply { - m, ok := (<-ch.msg) - if !ok { - return false, io.EOF - } - switch m.(type) { - case *channelRequestFailureMsg: - return false, nil - case *channelRequestSuccessMsg: - return true, nil - default: - return false, fmt.Errorf("ssh: unexpected response to channel request: %#v", m) - } - } - - return false, nil -} - -// ackRequest either sends an ack or nack to the channel request. -func (ch *channel) ackRequest(ok bool) error { - if !ch.decided { - return errUndecided - } - - var msg interface{} - if !ok { - msg = channelRequestFailureMsg{ - PeersID: ch.remoteId, - } - } else { - msg = channelRequestSuccessMsg{ - PeersID: ch.remoteId, - } - } - return ch.sendMessage(msg) -} - -func (ch *channel) ChannelType() string { - return ch.chanType -} - -func (ch *channel) ExtraData() []byte { - return ch.extraData -} diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go deleted file mode 100644 index 67b01261..00000000 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ /dev/null @@ -1,770 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/rc4" - "crypto/subtle" - "encoding/binary" - "errors" - "fmt" - "hash" - "io" - "io/ioutil" - "math/bits" - - "golang.org/x/crypto/internal/chacha20" - "golang.org/x/crypto/poly1305" -) - -const ( - packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher. - - // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations - // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC - // indicates implementations SHOULD be able to handle larger packet sizes, but then - // waffles on about reasonable limits. - // - // OpenSSH caps their maxPacket at 256kB so we choose to do - // the same. maxPacket is also used to ensure that uint32 - // length fields do not overflow, so it should remain well - // below 4G. - maxPacket = 256 * 1024 -) - -// noneCipher implements cipher.Stream and provides no encryption. It is used -// by the transport before the first key-exchange. -type noneCipher struct{} - -func (c noneCipher) XORKeyStream(dst, src []byte) { - copy(dst, src) -} - -func newAESCTR(key, iv []byte) (cipher.Stream, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - return cipher.NewCTR(c, iv), nil -} - -func newRC4(key, iv []byte) (cipher.Stream, error) { - return rc4.NewCipher(key) -} - -type cipherMode struct { - keySize int - ivSize int - create func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) -} - -func streamCipherMode(skip int, createFunc func(key, iv []byte) (cipher.Stream, error)) func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - return func(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - stream, err := createFunc(key, iv) - if err != nil { - return nil, err - } - - var streamDump []byte - if skip > 0 { - streamDump = make([]byte, 512) - } - - for remainingToDump := skip; remainingToDump > 0; { - dumpThisTime := remainingToDump - if dumpThisTime > len(streamDump) { - dumpThisTime = len(streamDump) - } - stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) - remainingToDump -= dumpThisTime - } - - mac := macModes[algs.MAC].new(macKey) - return &streamPacketCipher{ - mac: mac, - etm: macModes[algs.MAC].etm, - macResult: make([]byte, mac.Size()), - cipher: stream, - }, nil - } -} - -// cipherModes documents properties of supported ciphers. Ciphers not included -// are not supported and will not be negotiated, even if explicitly requested in -// ClientConfig.Crypto.Ciphers. -var cipherModes = map[string]*cipherMode{ - // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms - // are defined in the order specified in the RFC. - "aes128-ctr": {16, aes.BlockSize, streamCipherMode(0, newAESCTR)}, - "aes192-ctr": {24, aes.BlockSize, streamCipherMode(0, newAESCTR)}, - "aes256-ctr": {32, aes.BlockSize, streamCipherMode(0, newAESCTR)}, - - // Ciphers from RFC4345, which introduces security-improved arcfour ciphers. - // They are defined in the order specified in the RFC. - "arcfour128": {16, 0, streamCipherMode(1536, newRC4)}, - "arcfour256": {32, 0, streamCipherMode(1536, newRC4)}, - - // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol. - // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and - // RC4) has problems with weak keys, and should be used with caution." - // RFC4345 introduces improved versions of Arcfour. - "arcfour": {16, 0, streamCipherMode(0, newRC4)}, - - // AEAD ciphers - gcmCipherID: {16, 12, newGCMCipher}, - chacha20Poly1305ID: {64, 0, newChaCha20Cipher}, - - // CBC mode is insecure and so is not included in the default config. - // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely - // needed, it's possible to specify a custom Config to enable it. - // You should expect that an active attacker can recover plaintext if - // you do. - aes128cbcID: {16, aes.BlockSize, newAESCBCCipher}, - - // 3des-cbc is insecure and is not included in the default - // config. - tripledescbcID: {24, des.BlockSize, newTripleDESCBCCipher}, -} - -// prefixLen is the length of the packet prefix that contains the packet length -// and number of padding bytes. -const prefixLen = 5 - -// streamPacketCipher is a packetCipher using a stream cipher. -type streamPacketCipher struct { - mac hash.Hash - cipher cipher.Stream - etm bool - - // The following members are to avoid per-packet allocations. - prefix [prefixLen]byte - seqNumBytes [4]byte - padding [2 * packetSizeMultiple]byte - packetData []byte - macResult []byte -} - -// readPacket reads and decrypt a single packet from the reader argument. -func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - if _, err := io.ReadFull(r, s.prefix[:]); err != nil { - return nil, err - } - - var encryptedPaddingLength [1]byte - if s.mac != nil && s.etm { - copy(encryptedPaddingLength[:], s.prefix[4:5]) - s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5]) - } else { - s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) - } - - length := binary.BigEndian.Uint32(s.prefix[0:4]) - paddingLength := uint32(s.prefix[4]) - - var macSize uint32 - if s.mac != nil { - s.mac.Reset() - binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) - s.mac.Write(s.seqNumBytes[:]) - if s.etm { - s.mac.Write(s.prefix[:4]) - s.mac.Write(encryptedPaddingLength[:]) - } else { - s.mac.Write(s.prefix[:]) - } - macSize = uint32(s.mac.Size()) - } - - if length <= paddingLength+1 { - return nil, errors.New("ssh: invalid packet length, packet too small") - } - - if length > maxPacket { - return nil, errors.New("ssh: invalid packet length, packet too large") - } - - // the maxPacket check above ensures that length-1+macSize - // does not overflow. - if uint32(cap(s.packetData)) < length-1+macSize { - s.packetData = make([]byte, length-1+macSize) - } else { - s.packetData = s.packetData[:length-1+macSize] - } - - if _, err := io.ReadFull(r, s.packetData); err != nil { - return nil, err - } - mac := s.packetData[length-1:] - data := s.packetData[:length-1] - - if s.mac != nil && s.etm { - s.mac.Write(data) - } - - s.cipher.XORKeyStream(data, data) - - if s.mac != nil { - if !s.etm { - s.mac.Write(data) - } - s.macResult = s.mac.Sum(s.macResult[:0]) - if subtle.ConstantTimeCompare(s.macResult, mac) != 1 { - return nil, errors.New("ssh: MAC failure") - } - } - - return s.packetData[:length-paddingLength-1], nil -} - -// writePacket encrypts and sends a packet of data to the writer argument -func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - if len(packet) > maxPacket { - return errors.New("ssh: packet too large") - } - - aadlen := 0 - if s.mac != nil && s.etm { - // packet length is not encrypted for EtM modes - aadlen = 4 - } - - paddingLength := packetSizeMultiple - (prefixLen+len(packet)-aadlen)%packetSizeMultiple - if paddingLength < 4 { - paddingLength += packetSizeMultiple - } - - length := len(packet) + 1 + paddingLength - binary.BigEndian.PutUint32(s.prefix[:], uint32(length)) - s.prefix[4] = byte(paddingLength) - padding := s.padding[:paddingLength] - if _, err := io.ReadFull(rand, padding); err != nil { - return err - } - - if s.mac != nil { - s.mac.Reset() - binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) - s.mac.Write(s.seqNumBytes[:]) - - if s.etm { - // For EtM algorithms, the packet length must stay unencrypted, - // but the following data (padding length) must be encrypted - s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5]) - } - - s.mac.Write(s.prefix[:]) - - if !s.etm { - // For non-EtM algorithms, the algorithm is applied on unencrypted data - s.mac.Write(packet) - s.mac.Write(padding) - } - } - - if !(s.mac != nil && s.etm) { - // For EtM algorithms, the padding length has already been encrypted - // and the packet length must remain unencrypted - s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) - } - - s.cipher.XORKeyStream(packet, packet) - s.cipher.XORKeyStream(padding, padding) - - if s.mac != nil && s.etm { - // For EtM algorithms, packet and padding must be encrypted - s.mac.Write(packet) - s.mac.Write(padding) - } - - if _, err := w.Write(s.prefix[:]); err != nil { - return err - } - if _, err := w.Write(packet); err != nil { - return err - } - if _, err := w.Write(padding); err != nil { - return err - } - - if s.mac != nil { - s.macResult = s.mac.Sum(s.macResult[:0]) - if _, err := w.Write(s.macResult); err != nil { - return err - } - } - - return nil -} - -type gcmCipher struct { - aead cipher.AEAD - prefix [4]byte - iv []byte - buf []byte -} - -func newGCMCipher(key, iv, unusedMacKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - aead, err := cipher.NewGCM(c) - if err != nil { - return nil, err - } - - return &gcmCipher{ - aead: aead, - iv: iv, - }, nil -} - -const gcmTagSize = 16 - -func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - // Pad out to multiple of 16 bytes. This is different from the - // stream cipher because that encrypts the length too. - padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple) - if padding < 4 { - padding += packetSizeMultiple - } - - length := uint32(len(packet) + int(padding) + 1) - binary.BigEndian.PutUint32(c.prefix[:], length) - if _, err := w.Write(c.prefix[:]); err != nil { - return err - } - - if cap(c.buf) < int(length) { - c.buf = make([]byte, length) - } else { - c.buf = c.buf[:length] - } - - c.buf[0] = padding - copy(c.buf[1:], packet) - if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil { - return err - } - c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:]) - if _, err := w.Write(c.buf); err != nil { - return err - } - c.incIV() - - return nil -} - -func (c *gcmCipher) incIV() { - for i := 4 + 7; i >= 4; i-- { - c.iv[i]++ - if c.iv[i] != 0 { - break - } - } -} - -func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - if _, err := io.ReadFull(r, c.prefix[:]); err != nil { - return nil, err - } - length := binary.BigEndian.Uint32(c.prefix[:]) - if length > maxPacket { - return nil, errors.New("ssh: max packet length exceeded") - } - - if cap(c.buf) < int(length+gcmTagSize) { - c.buf = make([]byte, length+gcmTagSize) - } else { - c.buf = c.buf[:length+gcmTagSize] - } - - if _, err := io.ReadFull(r, c.buf); err != nil { - return nil, err - } - - plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:]) - if err != nil { - return nil, err - } - c.incIV() - - padding := plain[0] - if padding < 4 { - // padding is a byte, so it automatically satisfies - // the maximum size, which is 255. - return nil, fmt.Errorf("ssh: illegal padding %d", padding) - } - - if int(padding+1) >= len(plain) { - return nil, fmt.Errorf("ssh: padding %d too large", padding) - } - plain = plain[1 : length-uint32(padding)] - return plain, nil -} - -// cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1 -type cbcCipher struct { - mac hash.Hash - macSize uint32 - decrypter cipher.BlockMode - encrypter cipher.BlockMode - - // The following members are to avoid per-packet allocations. - seqNumBytes [4]byte - packetData []byte - macResult []byte - - // Amount of data we should still read to hide which - // verification error triggered. - oracleCamouflage uint32 -} - -func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - cbc := &cbcCipher{ - mac: macModes[algs.MAC].new(macKey), - decrypter: cipher.NewCBCDecrypter(c, iv), - encrypter: cipher.NewCBCEncrypter(c, iv), - packetData: make([]byte, 1024), - } - if cbc.mac != nil { - cbc.macSize = uint32(cbc.mac.Size()) - } - - return cbc, nil -} - -func newAESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - cbc, err := newCBCCipher(c, key, iv, macKey, algs) - if err != nil { - return nil, err - } - - return cbc, nil -} - -func newTripleDESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - c, err := des.NewTripleDESCipher(key) - if err != nil { - return nil, err - } - - cbc, err := newCBCCipher(c, key, iv, macKey, algs) - if err != nil { - return nil, err - } - - return cbc, nil -} - -func maxUInt32(a, b int) uint32 { - if a > b { - return uint32(a) - } - return uint32(b) -} - -const ( - cbcMinPacketSizeMultiple = 8 - cbcMinPacketSize = 16 - cbcMinPaddingSize = 4 -) - -// cbcError represents a verification error that may leak information. -type cbcError string - -func (e cbcError) Error() string { return string(e) } - -func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - p, err := c.readPacketLeaky(seqNum, r) - if err != nil { - if _, ok := err.(cbcError); ok { - // Verification error: read a fixed amount of - // data, to make distinguishing between - // failing MAC and failing length check more - // difficult. - io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage)) - } - } - return p, err -} - -func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) { - blockSize := c.decrypter.BlockSize() - - // Read the header, which will include some of the subsequent data in the - // case of block ciphers - this is copied back to the payload later. - // How many bytes of payload/padding will be read with this first read. - firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize) - firstBlock := c.packetData[:firstBlockLength] - if _, err := io.ReadFull(r, firstBlock); err != nil { - return nil, err - } - - c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength - - c.decrypter.CryptBlocks(firstBlock, firstBlock) - length := binary.BigEndian.Uint32(firstBlock[:4]) - if length > maxPacket { - return nil, cbcError("ssh: packet too large") - } - if length+4 < maxUInt32(cbcMinPacketSize, blockSize) { - // The minimum size of a packet is 16 (or the cipher block size, whichever - // is larger) bytes. - return nil, cbcError("ssh: packet too small") - } - // The length of the packet (including the length field but not the MAC) must - // be a multiple of the block size or 8, whichever is larger. - if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 { - return nil, cbcError("ssh: invalid packet length multiple") - } - - paddingLength := uint32(firstBlock[4]) - if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { - return nil, cbcError("ssh: invalid packet length") - } - - // Positions within the c.packetData buffer: - macStart := 4 + length - paddingStart := macStart - paddingLength - - // Entire packet size, starting before length, ending at end of mac. - entirePacketSize := macStart + c.macSize - - // Ensure c.packetData is large enough for the entire packet data. - if uint32(cap(c.packetData)) < entirePacketSize { - // Still need to upsize and copy, but this should be rare at runtime, only - // on upsizing the packetData buffer. - c.packetData = make([]byte, entirePacketSize) - copy(c.packetData, firstBlock) - } else { - c.packetData = c.packetData[:entirePacketSize] - } - - n, err := io.ReadFull(r, c.packetData[firstBlockLength:]) - if err != nil { - return nil, err - } - c.oracleCamouflage -= uint32(n) - - remainingCrypted := c.packetData[firstBlockLength:macStart] - c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) - - mac := c.packetData[macStart:] - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) - c.mac.Write(c.packetData[:macStart]) - c.macResult = c.mac.Sum(c.macResult[:0]) - if subtle.ConstantTimeCompare(c.macResult, mac) != 1 { - return nil, cbcError("ssh: MAC failure") - } - } - - return c.packetData[prefixLen:paddingStart], nil -} - -func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize()) - - // Length of encrypted portion of the packet (header, payload, padding). - // Enforce minimum padding and packet size. - encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize) - // Enforce block size. - encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize - - length := encLength - 4 - paddingLength := int(length) - (1 + len(packet)) - - // Overall buffer contains: header, payload, padding, mac. - // Space for the MAC is reserved in the capacity but not the slice length. - bufferSize := encLength + c.macSize - if uint32(cap(c.packetData)) < bufferSize { - c.packetData = make([]byte, encLength, bufferSize) - } else { - c.packetData = c.packetData[:encLength] - } - - p := c.packetData - - // Packet header. - binary.BigEndian.PutUint32(p, length) - p = p[4:] - p[0] = byte(paddingLength) - - // Payload. - p = p[1:] - copy(p, packet) - - // Padding. - p = p[len(packet):] - if _, err := io.ReadFull(rand, p); err != nil { - return err - } - - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) - c.mac.Write(c.packetData) - // The MAC is now appended into the capacity reserved for it earlier. - c.packetData = c.mac.Sum(c.packetData) - } - - c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength]) - - if _, err := w.Write(c.packetData); err != nil { - return err - } - - return nil -} - -const chacha20Poly1305ID = "chacha20-poly1305@openssh.com" - -// chacha20Poly1305Cipher implements the chacha20-poly1305@openssh.com -// AEAD, which is described here: -// -// https://tools.ietf.org/html/draft-josefsson-ssh-chacha20-poly1305-openssh-00 -// -// the methods here also implement padding, which RFC4253 Section 6 -// also requires of stream ciphers. -type chacha20Poly1305Cipher struct { - lengthKey [8]uint32 - contentKey [8]uint32 - buf []byte -} - -func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { - if len(key) != 64 { - panic(len(key)) - } - - c := &chacha20Poly1305Cipher{ - buf: make([]byte, 256), - } - - for i := range c.contentKey { - c.contentKey[i] = binary.LittleEndian.Uint32(key[i*4 : (i+1)*4]) - } - for i := range c.lengthKey { - c.lengthKey[i] = binary.LittleEndian.Uint32(key[(i+8)*4 : (i+9)*4]) - } - return c, nil -} - -func (c *chacha20Poly1305Cipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} - s := chacha20.New(c.contentKey, nonce) - var polyKey [32]byte - s.XORKeyStream(polyKey[:], polyKey[:]) - s.Advance() // skip next 32 bytes - - encryptedLength := c.buf[:4] - if _, err := io.ReadFull(r, encryptedLength); err != nil { - return nil, err - } - - var lenBytes [4]byte - chacha20.New(c.lengthKey, nonce).XORKeyStream(lenBytes[:], encryptedLength) - - length := binary.BigEndian.Uint32(lenBytes[:]) - if length > maxPacket { - return nil, errors.New("ssh: invalid packet length, packet too large") - } - - contentEnd := 4 + length - packetEnd := contentEnd + poly1305.TagSize - if uint32(cap(c.buf)) < packetEnd { - c.buf = make([]byte, packetEnd) - copy(c.buf[:], encryptedLength) - } else { - c.buf = c.buf[:packetEnd] - } - - if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil { - return nil, err - } - - var mac [poly1305.TagSize]byte - copy(mac[:], c.buf[contentEnd:packetEnd]) - if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) { - return nil, errors.New("ssh: MAC failure") - } - - plain := c.buf[4:contentEnd] - s.XORKeyStream(plain, plain) - - padding := plain[0] - if padding < 4 { - // padding is a byte, so it automatically satisfies - // the maximum size, which is 255. - return nil, fmt.Errorf("ssh: illegal padding %d", padding) - } - - if int(padding)+1 >= len(plain) { - return nil, fmt.Errorf("ssh: padding %d too large", padding) - } - - plain = plain[1 : len(plain)-int(padding)] - - return plain, nil -} - -func (c *chacha20Poly1305Cipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error { - nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} - s := chacha20.New(c.contentKey, nonce) - var polyKey [32]byte - s.XORKeyStream(polyKey[:], polyKey[:]) - s.Advance() // skip next 32 bytes - - // There is no blocksize, so fall back to multiple of 8 byte - // padding, as described in RFC 4253, Sec 6. - const packetSizeMultiple = 8 - - padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple - if padding < 4 { - padding += packetSizeMultiple - } - - // size (4 bytes), padding (1), payload, padding, tag. - totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize - if cap(c.buf) < totalLength { - c.buf = make([]byte, totalLength) - } else { - c.buf = c.buf[:totalLength] - } - - binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding)) - chacha20.New(c.lengthKey, nonce).XORKeyStream(c.buf, c.buf[:4]) - c.buf[4] = byte(padding) - copy(c.buf[5:], payload) - packetEnd := 5 + len(payload) + padding - if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil { - return err - } - - s.XORKeyStream(c.buf[4:], c.buf[4:packetEnd]) - - var mac [poly1305.TagSize]byte - poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey) - - copy(c.buf[packetEnd:], mac[:]) - - if _, err := w.Write(c.buf); err != nil { - return err - } - return nil -} diff --git a/vendor/golang.org/x/crypto/ssh/client.go b/vendor/golang.org/x/crypto/ssh/client.go deleted file mode 100644 index 7b00bff1..00000000 --- a/vendor/golang.org/x/crypto/ssh/client.go +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "net" - "os" - "sync" - "time" -) - -// Client implements a traditional SSH client that supports shells, -// subprocesses, TCP port/streamlocal forwarding and tunneled dialing. -type Client struct { - Conn - - handleForwardsOnce sync.Once // guards calling (*Client).handleForwards - - forwards forwardList // forwarded tcpip connections from the remote side - mu sync.Mutex - channelHandlers map[string]chan NewChannel -} - -// HandleChannelOpen returns a channel on which NewChannel requests -// for the given type are sent. If the type already is being handled, -// nil is returned. The channel is closed when the connection is closed. -func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel { - c.mu.Lock() - defer c.mu.Unlock() - if c.channelHandlers == nil { - // The SSH channel has been closed. - c := make(chan NewChannel) - close(c) - return c - } - - ch := c.channelHandlers[channelType] - if ch != nil { - return nil - } - - ch = make(chan NewChannel, chanSize) - c.channelHandlers[channelType] = ch - return ch -} - -// NewClient creates a Client on top of the given connection. -func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { - conn := &Client{ - Conn: c, - channelHandlers: make(map[string]chan NewChannel, 1), - } - - go conn.handleGlobalRequests(reqs) - go conn.handleChannelOpens(chans) - go func() { - conn.Wait() - conn.forwards.closeAll() - }() - return conn -} - -// NewClientConn establishes an authenticated SSH connection using c -// as the underlying transport. The Request and NewChannel channels -// must be serviced or the connection will hang. -func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) { - fullConf := *config - fullConf.SetDefaults() - if fullConf.HostKeyCallback == nil { - c.Close() - return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback") - } - - conn := &connection{ - sshConn: sshConn{conn: c}, - } - - if err := conn.clientHandshake(addr, &fullConf); err != nil { - c.Close() - return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err) - } - conn.mux = newMux(conn.transport) - return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil -} - -// clientHandshake performs the client side key exchange. See RFC 4253 Section -// 7. -func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error { - if config.ClientVersion != "" { - c.clientVersion = []byte(config.ClientVersion) - } else { - c.clientVersion = []byte(packageVersion) - } - var err error - c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion) - if err != nil { - return err - } - - c.transport = newClientTransport( - newTransport(c.sshConn.conn, config.Rand, true /* is client */), - c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr()) - if err := c.transport.waitSession(); err != nil { - return err - } - - c.sessionID = c.transport.getSessionID() - return c.clientAuthenticate(config) -} - -// verifyHostKeySignature verifies the host key obtained in the key -// exchange. -func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error { - sig, rest, ok := parseSignatureBody(result.Signature) - if len(rest) > 0 || !ok { - return errors.New("ssh: signature parse error") - } - - return hostKey.Verify(result.H, sig) -} - -// NewSession opens a new Session for this client. (A session is a remote -// execution of a program.) -func (c *Client) NewSession() (*Session, error) { - ch, in, err := c.OpenChannel("session", nil) - if err != nil { - return nil, err - } - return newSession(ch, in) -} - -func (c *Client) handleGlobalRequests(incoming <-chan *Request) { - for r := range incoming { - // This handles keepalive messages and matches - // the behaviour of OpenSSH. - r.Reply(false, nil) - } -} - -// handleChannelOpens channel open messages from the remote side. -func (c *Client) handleChannelOpens(in <-chan NewChannel) { - for ch := range in { - c.mu.Lock() - handler := c.channelHandlers[ch.ChannelType()] - c.mu.Unlock() - - if handler != nil { - handler <- ch - } else { - ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType())) - } - } - - c.mu.Lock() - for _, ch := range c.channelHandlers { - close(ch) - } - c.channelHandlers = nil - c.mu.Unlock() -} - -// Dial starts a client connection to the given SSH server. It is a -// convenience function that connects to the given network address, -// initiates the SSH handshake, and then sets up a Client. For access -// to incoming channels and requests, use net.Dial with NewClientConn -// instead. -func Dial(network, addr string, config *ClientConfig) (*Client, error) { - conn, err := net.DialTimeout(network, addr, config.Timeout) - if err != nil { - return nil, err - } - c, chans, reqs, err := NewClientConn(conn, addr, config) - if err != nil { - return nil, err - } - return NewClient(c, chans, reqs), nil -} - -// HostKeyCallback is the function type used for verifying server -// keys. A HostKeyCallback must return nil if the host key is OK, or -// an error to reject it. It receives the hostname as passed to Dial -// or NewClientConn. The remote address is the RemoteAddr of the -// net.Conn underlying the SSH connection. -type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error - -// BannerCallback is the function type used for treat the banner sent by -// the server. A BannerCallback receives the message sent by the remote server. -type BannerCallback func(message string) error - -// A ClientConfig structure is used to configure a Client. It must not be -// modified after having been passed to an SSH function. -type ClientConfig struct { - // Config contains configuration that is shared between clients and - // servers. - Config - - // User contains the username to authenticate as. - User string - - // Auth contains possible authentication methods to use with the - // server. Only the first instance of a particular RFC 4252 method will - // be used during authentication. - Auth []AuthMethod - - // HostKeyCallback is called during the cryptographic - // handshake to validate the server's host key. The client - // configuration must supply this callback for the connection - // to succeed. The functions InsecureIgnoreHostKey or - // FixedHostKey can be used for simplistic host key checks. - HostKeyCallback HostKeyCallback - - // BannerCallback is called during the SSH dance to display a custom - // server's message. The client configuration can supply this callback to - // handle it as wished. The function BannerDisplayStderr can be used for - // simplistic display on Stderr. - BannerCallback BannerCallback - - // ClientVersion contains the version identification string that will - // be used for the connection. If empty, a reasonable default is used. - ClientVersion string - - // HostKeyAlgorithms lists the key types that the client will - // accept from the server as host key, in order of - // preference. If empty, a reasonable default is used. Any - // string returned from PublicKey.Type method may be used, or - // any of the CertAlgoXxxx and KeyAlgoXxxx constants. - HostKeyAlgorithms []string - - // Timeout is the maximum amount of time for the TCP connection to establish. - // - // A Timeout of zero means no timeout. - Timeout time.Duration -} - -// InsecureIgnoreHostKey returns a function that can be used for -// ClientConfig.HostKeyCallback to accept any host key. It should -// not be used for production code. -func InsecureIgnoreHostKey() HostKeyCallback { - return func(hostname string, remote net.Addr, key PublicKey) error { - return nil - } -} - -type fixedHostKey struct { - key PublicKey -} - -func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error { - if f.key == nil { - return fmt.Errorf("ssh: required host key was nil") - } - if !bytes.Equal(key.Marshal(), f.key.Marshal()) { - return fmt.Errorf("ssh: host key mismatch") - } - return nil -} - -// FixedHostKey returns a function for use in -// ClientConfig.HostKeyCallback to accept only a specific host key. -func FixedHostKey(key PublicKey) HostKeyCallback { - hk := &fixedHostKey{key} - return hk.check -} - -// BannerDisplayStderr returns a function that can be used for -// ClientConfig.BannerCallback to display banners on os.Stderr. -func BannerDisplayStderr() BannerCallback { - return func(banner string) error { - _, err := os.Stderr.WriteString(banner) - - return err - } -} diff --git a/vendor/golang.org/x/crypto/ssh/client_auth.go b/vendor/golang.org/x/crypto/ssh/client_auth.go deleted file mode 100644 index 5f44b774..00000000 --- a/vendor/golang.org/x/crypto/ssh/client_auth.go +++ /dev/null @@ -1,525 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" -) - -type authResult int - -const ( - authFailure authResult = iota - authPartialSuccess - authSuccess -) - -// clientAuthenticate authenticates with the remote server. See RFC 4252. -func (c *connection) clientAuthenticate(config *ClientConfig) error { - // initiate user auth session - if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil { - return err - } - packet, err := c.transport.readPacket() - if err != nil { - return err - } - var serviceAccept serviceAcceptMsg - if err := Unmarshal(packet, &serviceAccept); err != nil { - return err - } - - // during the authentication phase the client first attempts the "none" method - // then any untried methods suggested by the server. - tried := make(map[string]bool) - var lastMethods []string - - sessionID := c.transport.getSessionID() - for auth := AuthMethod(new(noneAuth)); auth != nil; { - ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand) - if err != nil { - return err - } - if ok == authSuccess { - // success - return nil - } else if ok == authFailure { - tried[auth.method()] = true - } - if methods == nil { - methods = lastMethods - } - lastMethods = methods - - auth = nil - - findNext: - for _, a := range config.Auth { - candidateMethod := a.method() - if tried[candidateMethod] { - continue - } - for _, meth := range methods { - if meth == candidateMethod { - auth = a - break findNext - } - } - } - } - return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried)) -} - -func keys(m map[string]bool) []string { - s := make([]string, 0, len(m)) - - for key := range m { - s = append(s, key) - } - return s -} - -// An AuthMethod represents an instance of an RFC 4252 authentication method. -type AuthMethod interface { - // auth authenticates user over transport t. - // Returns true if authentication is successful. - // If authentication is not successful, a []string of alternative - // method names is returned. If the slice is nil, it will be ignored - // and the previous set of possible methods will be reused. - auth(session []byte, user string, p packetConn, rand io.Reader) (authResult, []string, error) - - // method returns the RFC 4252 method name. - method() string -} - -// "none" authentication, RFC 4252 section 5.2. -type noneAuth int - -func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { - if err := c.writePacket(Marshal(&userAuthRequestMsg{ - User: user, - Service: serviceSSH, - Method: "none", - })); err != nil { - return authFailure, nil, err - } - - return handleAuthResponse(c) -} - -func (n *noneAuth) method() string { - return "none" -} - -// passwordCallback is an AuthMethod that fetches the password through -// a function call, e.g. by prompting the user. -type passwordCallback func() (password string, err error) - -func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { - type passwordAuthMsg struct { - User string `sshtype:"50"` - Service string - Method string - Reply bool - Password string - } - - pw, err := cb() - // REVIEW NOTE: is there a need to support skipping a password attempt? - // The program may only find out that the user doesn't have a password - // when prompting. - if err != nil { - return authFailure, nil, err - } - - if err := c.writePacket(Marshal(&passwordAuthMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - Reply: false, - Password: pw, - })); err != nil { - return authFailure, nil, err - } - - return handleAuthResponse(c) -} - -func (cb passwordCallback) method() string { - return "password" -} - -// Password returns an AuthMethod using the given password. -func Password(secret string) AuthMethod { - return passwordCallback(func() (string, error) { return secret, nil }) -} - -// PasswordCallback returns an AuthMethod that uses a callback for -// fetching a password. -func PasswordCallback(prompt func() (secret string, err error)) AuthMethod { - return passwordCallback(prompt) -} - -type publickeyAuthMsg struct { - User string `sshtype:"50"` - Service string - Method string - // HasSig indicates to the receiver packet that the auth request is signed and - // should be used for authentication of the request. - HasSig bool - Algoname string - PubKey []byte - // Sig is tagged with "rest" so Marshal will exclude it during - // validateKey - Sig []byte `ssh:"rest"` -} - -// publicKeyCallback is an AuthMethod that uses a set of key -// pairs for authentication. -type publicKeyCallback func() ([]Signer, error) - -func (cb publicKeyCallback) method() string { - return "publickey" -} - -func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { - // Authentication is performed by sending an enquiry to test if a key is - // acceptable to the remote. If the key is acceptable, the client will - // attempt to authenticate with the valid key. If not the client will repeat - // the process with the remaining keys. - - signers, err := cb() - if err != nil { - return authFailure, nil, err - } - var methods []string - for _, signer := range signers { - ok, err := validateKey(signer.PublicKey(), user, c) - if err != nil { - return authFailure, nil, err - } - if !ok { - continue - } - - pub := signer.PublicKey() - pubKey := pub.Marshal() - sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - }, []byte(pub.Type()), pubKey)) - if err != nil { - return authFailure, nil, err - } - - // manually wrap the serialized signature in a string - s := Marshal(sign) - sig := make([]byte, stringLength(len(s))) - marshalString(sig, s) - msg := publickeyAuthMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - HasSig: true, - Algoname: pub.Type(), - PubKey: pubKey, - Sig: sig, - } - p := Marshal(&msg) - if err := c.writePacket(p); err != nil { - return authFailure, nil, err - } - var success authResult - success, methods, err = handleAuthResponse(c) - if err != nil { - return authFailure, nil, err - } - - // If authentication succeeds or the list of available methods does not - // contain the "publickey" method, do not attempt to authenticate with any - // other keys. According to RFC 4252 Section 7, the latter can occur when - // additional authentication methods are required. - if success == authSuccess || !containsMethod(methods, cb.method()) { - return success, methods, err - } - } - - return authFailure, methods, nil -} - -func containsMethod(methods []string, method string) bool { - for _, m := range methods { - if m == method { - return true - } - } - - return false -} - -// validateKey validates the key provided is acceptable to the server. -func validateKey(key PublicKey, user string, c packetConn) (bool, error) { - pubKey := key.Marshal() - msg := publickeyAuthMsg{ - User: user, - Service: serviceSSH, - Method: "publickey", - HasSig: false, - Algoname: key.Type(), - PubKey: pubKey, - } - if err := c.writePacket(Marshal(&msg)); err != nil { - return false, err - } - - return confirmKeyAck(key, c) -} - -func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { - pubKey := key.Marshal() - algoname := key.Type() - - for { - packet, err := c.readPacket() - if err != nil { - return false, err - } - switch packet[0] { - case msgUserAuthBanner: - if err := handleBannerResponse(c, packet); err != nil { - return false, err - } - case msgUserAuthPubKeyOk: - var msg userAuthPubKeyOkMsg - if err := Unmarshal(packet, &msg); err != nil { - return false, err - } - if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) { - return false, nil - } - return true, nil - case msgUserAuthFailure: - return false, nil - default: - return false, unexpectedMessageError(msgUserAuthSuccess, packet[0]) - } - } -} - -// PublicKeys returns an AuthMethod that uses the given key -// pairs. -func PublicKeys(signers ...Signer) AuthMethod { - return publicKeyCallback(func() ([]Signer, error) { return signers, nil }) -} - -// PublicKeysCallback returns an AuthMethod that runs the given -// function to obtain a list of key pairs. -func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod { - return publicKeyCallback(getSigners) -} - -// handleAuthResponse returns whether the preceding authentication request succeeded -// along with a list of remaining authentication methods to try next and -// an error if an unexpected response was received. -func handleAuthResponse(c packetConn) (authResult, []string, error) { - for { - packet, err := c.readPacket() - if err != nil { - return authFailure, nil, err - } - - switch packet[0] { - case msgUserAuthBanner: - if err := handleBannerResponse(c, packet); err != nil { - return authFailure, nil, err - } - case msgUserAuthFailure: - var msg userAuthFailureMsg - if err := Unmarshal(packet, &msg); err != nil { - return authFailure, nil, err - } - if msg.PartialSuccess { - return authPartialSuccess, msg.Methods, nil - } - return authFailure, msg.Methods, nil - case msgUserAuthSuccess: - return authSuccess, nil, nil - default: - return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) - } - } -} - -func handleBannerResponse(c packetConn, packet []byte) error { - var msg userAuthBannerMsg - if err := Unmarshal(packet, &msg); err != nil { - return err - } - - transport, ok := c.(*handshakeTransport) - if !ok { - return nil - } - - if transport.bannerCallback != nil { - return transport.bannerCallback(msg.Message) - } - - return nil -} - -// KeyboardInteractiveChallenge should print questions, optionally -// disabling echoing (e.g. for passwords), and return all the answers. -// Challenge may be called multiple times in a single session. After -// successful authentication, the server may send a challenge with no -// questions, for which the user and instruction messages should be -// printed. RFC 4256 section 3.3 details how the UI should behave for -// both CLI and GUI environments. -type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error) - -// KeyboardInteractive returns an AuthMethod using a prompt/response -// sequence controlled by the server. -func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { - return challenge -} - -func (cb KeyboardInteractiveChallenge) method() string { - return "keyboard-interactive" -} - -func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { - type initiateMsg struct { - User string `sshtype:"50"` - Service string - Method string - Language string - Submethods string - } - - if err := c.writePacket(Marshal(&initiateMsg{ - User: user, - Service: serviceSSH, - Method: "keyboard-interactive", - })); err != nil { - return authFailure, nil, err - } - - for { - packet, err := c.readPacket() - if err != nil { - return authFailure, nil, err - } - - // like handleAuthResponse, but with less options. - switch packet[0] { - case msgUserAuthBanner: - if err := handleBannerResponse(c, packet); err != nil { - return authFailure, nil, err - } - continue - case msgUserAuthInfoRequest: - // OK - case msgUserAuthFailure: - var msg userAuthFailureMsg - if err := Unmarshal(packet, &msg); err != nil { - return authFailure, nil, err - } - if msg.PartialSuccess { - return authPartialSuccess, msg.Methods, nil - } - return authFailure, msg.Methods, nil - case msgUserAuthSuccess: - return authSuccess, nil, nil - default: - return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) - } - - var msg userAuthInfoRequestMsg - if err := Unmarshal(packet, &msg); err != nil { - return authFailure, nil, err - } - - // Manually unpack the prompt/echo pairs. - rest := msg.Prompts - var prompts []string - var echos []bool - for i := 0; i < int(msg.NumPrompts); i++ { - prompt, r, ok := parseString(rest) - if !ok || len(r) == 0 { - return authFailure, nil, errors.New("ssh: prompt format error") - } - prompts = append(prompts, string(prompt)) - echos = append(echos, r[0] != 0) - rest = r[1:] - } - - if len(rest) != 0 { - return authFailure, nil, errors.New("ssh: extra data following keyboard-interactive pairs") - } - - answers, err := cb(msg.User, msg.Instruction, prompts, echos) - if err != nil { - return authFailure, nil, err - } - - if len(answers) != len(prompts) { - return authFailure, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") - } - responseLength := 1 + 4 - for _, a := range answers { - responseLength += stringLength(len(a)) - } - serialized := make([]byte, responseLength) - p := serialized - p[0] = msgUserAuthInfoResponse - p = p[1:] - p = marshalUint32(p, uint32(len(answers))) - for _, a := range answers { - p = marshalString(p, []byte(a)) - } - - if err := c.writePacket(serialized); err != nil { - return authFailure, nil, err - } - } -} - -type retryableAuthMethod struct { - authMethod AuthMethod - maxTries int -} - -func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok authResult, methods []string, err error) { - for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { - ok, methods, err = r.authMethod.auth(session, user, c, rand) - if ok != authFailure || err != nil { // either success, partial success or error terminate - return ok, methods, err - } - } - return ok, methods, err -} - -func (r *retryableAuthMethod) method() string { - return r.authMethod.method() -} - -// RetryableAuthMethod is a decorator for other auth methods enabling them to -// be retried up to maxTries before considering that AuthMethod itself failed. -// If maxTries is <= 0, will retry indefinitely -// -// This is useful for interactive clients using challenge/response type -// authentication (e.g. Keyboard-Interactive, Password, etc) where the user -// could mistype their response resulting in the server issuing a -// SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4 -// [keyboard-interactive]); Without this decorator, the non-retryable -// AuthMethod would be removed from future consideration, and never tried again -// (and so the user would never be able to retry their entry). -func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod { - return &retryableAuthMethod{authMethod: auth, maxTries: maxTries} -} diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go deleted file mode 100644 index 04f3620b..00000000 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "crypto" - "crypto/rand" - "fmt" - "io" - "math" - "sync" - - _ "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" -) - -// These are string constants in the SSH protocol. -const ( - compressionNone = "none" - serviceUserAuth = "ssh-userauth" - serviceSSH = "ssh-connection" -) - -// supportedCiphers lists ciphers we support but might not recommend. -var supportedCiphers = []string{ - "aes128-ctr", "aes192-ctr", "aes256-ctr", - "aes128-gcm@openssh.com", - chacha20Poly1305ID, - "arcfour256", "arcfour128", "arcfour", - aes128cbcID, - tripledescbcID, -} - -// preferredCiphers specifies the default preference for ciphers. -var preferredCiphers = []string{ - "aes128-gcm@openssh.com", - chacha20Poly1305ID, - "aes128-ctr", "aes192-ctr", "aes256-ctr", -} - -// supportedKexAlgos specifies the supported key-exchange algorithms in -// preference order. -var supportedKexAlgos = []string{ - kexAlgoCurve25519SHA256, - // P384 and P521 are not constant-time yet, but since we don't - // reuse ephemeral keys, using them for ECDH should be OK. - kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521, - kexAlgoDH14SHA1, kexAlgoDH1SHA1, -} - -// supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods -// of authenticating servers) in preference order. -var supportedHostKeyAlgos = []string{ - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, - CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01, - - KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, - KeyAlgoRSA, KeyAlgoDSA, - - KeyAlgoED25519, -} - -// supportedMACs specifies a default set of MAC algorithms in preference order. -// This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed -// because they have reached the end of their useful life. -var supportedMACs = []string{ - "hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96", -} - -var supportedCompressions = []string{compressionNone} - -// hashFuncs keeps the mapping of supported algorithms to their respective -// hashes needed for signature verification. -var hashFuncs = map[string]crypto.Hash{ - KeyAlgoRSA: crypto.SHA1, - KeyAlgoDSA: crypto.SHA1, - KeyAlgoECDSA256: crypto.SHA256, - KeyAlgoECDSA384: crypto.SHA384, - KeyAlgoECDSA521: crypto.SHA512, - CertAlgoRSAv01: crypto.SHA1, - CertAlgoDSAv01: crypto.SHA1, - CertAlgoECDSA256v01: crypto.SHA256, - CertAlgoECDSA384v01: crypto.SHA384, - CertAlgoECDSA521v01: crypto.SHA512, -} - -// unexpectedMessageError results when the SSH message that we received didn't -// match what we wanted. -func unexpectedMessageError(expected, got uint8) error { - return fmt.Errorf("ssh: unexpected message type %d (expected %d)", got, expected) -} - -// parseError results from a malformed SSH message. -func parseError(tag uint8) error { - return fmt.Errorf("ssh: parse error in message type %d", tag) -} - -func findCommon(what string, client []string, server []string) (common string, err error) { - for _, c := range client { - for _, s := range server { - if c == s { - return c, nil - } - } - } - return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server) -} - -type directionAlgorithms struct { - Cipher string - MAC string - Compression string -} - -// rekeyBytes returns a rekeying intervals in bytes. -func (a *directionAlgorithms) rekeyBytes() int64 { - // According to RFC4344 block ciphers should rekey after - // 2^(BLOCKSIZE/4) blocks. For all AES flavors BLOCKSIZE is - // 128. - switch a.Cipher { - case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcmCipherID, aes128cbcID: - return 16 * (1 << 32) - - } - - // For others, stick with RFC4253 recommendation to rekey after 1 Gb of data. - return 1 << 30 -} - -type algorithms struct { - kex string - hostKey string - w directionAlgorithms - r directionAlgorithms -} - -func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) { - result := &algorithms{} - - result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos) - if err != nil { - return - } - - result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) - if err != nil { - return - } - - result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) - if err != nil { - return - } - - result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) - if err != nil { - return - } - - result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) - if err != nil { - return - } - - result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) - if err != nil { - return - } - - result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) - if err != nil { - return - } - - result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) - if err != nil { - return - } - - return result, nil -} - -// If rekeythreshold is too small, we can't make any progress sending -// stuff. -const minRekeyThreshold uint64 = 256 - -// Config contains configuration data common to both ServerConfig and -// ClientConfig. -type Config struct { - // Rand provides the source of entropy for cryptographic - // primitives. If Rand is nil, the cryptographic random reader - // in package crypto/rand will be used. - Rand io.Reader - - // The maximum number of bytes sent or received after which a - // new key is negotiated. It must be at least 256. If - // unspecified, a size suitable for the chosen cipher is used. - RekeyThreshold uint64 - - // The allowed key exchanges algorithms. If unspecified then a - // default set of algorithms is used. - KeyExchanges []string - - // The allowed cipher algorithms. If unspecified then a sensible - // default is used. - Ciphers []string - - // The allowed MAC algorithms. If unspecified then a sensible default - // is used. - MACs []string -} - -// SetDefaults sets sensible values for unset fields in config. This is -// exported for testing: Configs passed to SSH functions are copied and have -// default values set automatically. -func (c *Config) SetDefaults() { - if c.Rand == nil { - c.Rand = rand.Reader - } - if c.Ciphers == nil { - c.Ciphers = preferredCiphers - } - var ciphers []string - for _, c := range c.Ciphers { - if cipherModes[c] != nil { - // reject the cipher if we have no cipherModes definition - ciphers = append(ciphers, c) - } - } - c.Ciphers = ciphers - - if c.KeyExchanges == nil { - c.KeyExchanges = supportedKexAlgos - } - - if c.MACs == nil { - c.MACs = supportedMACs - } - - if c.RekeyThreshold == 0 { - // cipher specific default - } else if c.RekeyThreshold < minRekeyThreshold { - c.RekeyThreshold = minRekeyThreshold - } else if c.RekeyThreshold >= math.MaxInt64 { - // Avoid weirdness if somebody uses -1 as a threshold. - c.RekeyThreshold = math.MaxInt64 - } -} - -// buildDataSignedForAuth returns the data that is signed in order to prove -// possession of a private key. See RFC 4252, section 7. -func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { - data := struct { - Session []byte - Type byte - User string - Service string - Method string - Sign bool - Algo []byte - PubKey []byte - }{ - sessionID, - msgUserAuthRequest, - req.User, - req.Service, - req.Method, - true, - algo, - pubKey, - } - return Marshal(data) -} - -func appendU16(buf []byte, n uint16) []byte { - return append(buf, byte(n>>8), byte(n)) -} - -func appendU32(buf []byte, n uint32) []byte { - return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) -} - -func appendU64(buf []byte, n uint64) []byte { - return append(buf, - byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32), - byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) -} - -func appendInt(buf []byte, n int) []byte { - return appendU32(buf, uint32(n)) -} - -func appendString(buf []byte, s string) []byte { - buf = appendU32(buf, uint32(len(s))) - buf = append(buf, s...) - return buf -} - -func appendBool(buf []byte, b bool) []byte { - if b { - return append(buf, 1) - } - return append(buf, 0) -} - -// newCond is a helper to hide the fact that there is no usable zero -// value for sync.Cond. -func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) } - -// window represents the buffer available to clients -// wishing to write to a channel. -type window struct { - *sync.Cond - win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1 - writeWaiters int - closed bool -} - -// add adds win to the amount of window available -// for consumers. -func (w *window) add(win uint32) bool { - // a zero sized window adjust is a noop. - if win == 0 { - return true - } - w.L.Lock() - if w.win+win < win { - w.L.Unlock() - return false - } - w.win += win - // It is unusual that multiple goroutines would be attempting to reserve - // window space, but not guaranteed. Use broadcast to notify all waiters - // that additional window is available. - w.Broadcast() - w.L.Unlock() - return true -} - -// close sets the window to closed, so all reservations fail -// immediately. -func (w *window) close() { - w.L.Lock() - w.closed = true - w.Broadcast() - w.L.Unlock() -} - -// reserve reserves win from the available window capacity. -// If no capacity remains, reserve will block. reserve may -// return less than requested. -func (w *window) reserve(win uint32) (uint32, error) { - var err error - w.L.Lock() - w.writeWaiters++ - w.Broadcast() - for w.win == 0 && !w.closed { - w.Wait() - } - w.writeWaiters-- - if w.win < win { - win = w.win - } - w.win -= win - if w.closed { - err = io.EOF - } - w.L.Unlock() - return win, err -} - -// waitWriterBlocked waits until some goroutine is blocked for further -// writes. It is used in tests only. -func (w *window) waitWriterBlocked() { - w.Cond.L.Lock() - for w.writeWaiters == 0 { - w.Cond.Wait() - } - w.Cond.L.Unlock() -} diff --git a/vendor/golang.org/x/crypto/ssh/connection.go b/vendor/golang.org/x/crypto/ssh/connection.go deleted file mode 100644 index fd6b0681..00000000 --- a/vendor/golang.org/x/crypto/ssh/connection.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "fmt" - "net" -) - -// OpenChannelError is returned if the other side rejects an -// OpenChannel request. -type OpenChannelError struct { - Reason RejectionReason - Message string -} - -func (e *OpenChannelError) Error() string { - return fmt.Sprintf("ssh: rejected: %s (%s)", e.Reason, e.Message) -} - -// ConnMetadata holds metadata for the connection. -type ConnMetadata interface { - // User returns the user ID for this connection. - User() string - - // SessionID returns the session hash, also denoted by H. - SessionID() []byte - - // ClientVersion returns the client's version string as hashed - // into the session ID. - ClientVersion() []byte - - // ServerVersion returns the server's version string as hashed - // into the session ID. - ServerVersion() []byte - - // RemoteAddr returns the remote address for this connection. - RemoteAddr() net.Addr - - // LocalAddr returns the local address for this connection. - LocalAddr() net.Addr -} - -// Conn represents an SSH connection for both server and client roles. -// Conn is the basis for implementing an application layer, such -// as ClientConn, which implements the traditional shell access for -// clients. -type Conn interface { - ConnMetadata - - // SendRequest sends a global request, and returns the - // reply. If wantReply is true, it returns the response status - // and payload. See also RFC4254, section 4. - SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) - - // OpenChannel tries to open an channel. If the request is - // rejected, it returns *OpenChannelError. On success it returns - // the SSH Channel and a Go channel for incoming, out-of-band - // requests. The Go channel must be serviced, or the - // connection will hang. - OpenChannel(name string, data []byte) (Channel, <-chan *Request, error) - - // Close closes the underlying network connection - Close() error - - // Wait blocks until the connection has shut down, and returns the - // error causing the shutdown. - Wait() error - - // TODO(hanwen): consider exposing: - // RequestKeyChange - // Disconnect -} - -// DiscardRequests consumes and rejects all requests from the -// passed-in channel. -func DiscardRequests(in <-chan *Request) { - for req := range in { - if req.WantReply { - req.Reply(false, nil) - } - } -} - -// A connection represents an incoming connection. -type connection struct { - transport *handshakeTransport - sshConn - - // The connection protocol. - *mux -} - -func (c *connection) Close() error { - return c.sshConn.conn.Close() -} - -// sshconn provides net.Conn metadata, but disallows direct reads and -// writes. -type sshConn struct { - conn net.Conn - - user string - sessionID []byte - clientVersion []byte - serverVersion []byte -} - -func dup(src []byte) []byte { - dst := make([]byte, len(src)) - copy(dst, src) - return dst -} - -func (c *sshConn) User() string { - return c.user -} - -func (c *sshConn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -func (c *sshConn) Close() error { - return c.conn.Close() -} - -func (c *sshConn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -func (c *sshConn) SessionID() []byte { - return dup(c.sessionID) -} - -func (c *sshConn) ClientVersion() []byte { - return dup(c.clientVersion) -} - -func (c *sshConn) ServerVersion() []byte { - return dup(c.serverVersion) -} diff --git a/vendor/golang.org/x/crypto/ssh/doc.go b/vendor/golang.org/x/crypto/ssh/doc.go deleted file mode 100644 index 67b7322c..00000000 --- a/vendor/golang.org/x/crypto/ssh/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2011 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 ssh implements an SSH client and server. - -SSH is a transport security protocol, an authentication protocol and a -family of application protocols. The most typical application level -protocol is a remote shell and this is specifically implemented. However, -the multiplexed nature of SSH is exposed to users that wish to support -others. - -References: - [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD - [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 - -This package does not fall under the stability promise of the Go language itself, -so its API may be changed when pressing needs arise. -*/ -package ssh // import "golang.org/x/crypto/ssh" diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go deleted file mode 100644 index 4f7912ec..00000000 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "crypto/rand" - "errors" - "fmt" - "io" - "log" - "net" - "sync" -) - -// debugHandshake, if set, prints messages sent and received. Key -// exchange messages are printed as if DH were used, so the debug -// messages are wrong when using ECDH. -const debugHandshake = false - -// chanSize sets the amount of buffering SSH connections. This is -// primarily for testing: setting chanSize=0 uncovers deadlocks more -// quickly. -const chanSize = 16 - -// keyingTransport is a packet based transport that supports key -// changes. It need not be thread-safe. It should pass through -// msgNewKeys in both directions. -type keyingTransport interface { - packetConn - - // prepareKeyChange sets up a key change. The key change for a - // direction will be effected if a msgNewKeys message is sent - // or received. - prepareKeyChange(*algorithms, *kexResult) error -} - -// handshakeTransport implements rekeying on top of a keyingTransport -// and offers a thread-safe writePacket() interface. -type handshakeTransport struct { - conn keyingTransport - config *Config - - serverVersion []byte - clientVersion []byte - - // hostKeys is non-empty if we are the server. In that case, - // it contains all host keys that can be used to sign the - // connection. - hostKeys []Signer - - // hostKeyAlgorithms is non-empty if we are the client. In that case, - // we accept these key types from the server as host key. - hostKeyAlgorithms []string - - // On read error, incoming is closed, and readError is set. - incoming chan []byte - readError error - - mu sync.Mutex - writeError error - sentInitPacket []byte - sentInitMsg *kexInitMsg - pendingPackets [][]byte // Used when a key exchange is in progress. - - // If the read loop wants to schedule a kex, it pings this - // channel, and the write loop will send out a kex - // message. - requestKex chan struct{} - - // If the other side requests or confirms a kex, its kexInit - // packet is sent here for the write loop to find it. - startKex chan *pendingKex - - // data for host key checking - hostKeyCallback HostKeyCallback - dialAddress string - remoteAddr net.Addr - - // bannerCallback is non-empty if we are the client and it has been set in - // ClientConfig. In that case it is called during the user authentication - // dance to handle a custom server's message. - bannerCallback BannerCallback - - // Algorithms agreed in the last key exchange. - algorithms *algorithms - - readPacketsLeft uint32 - readBytesLeft int64 - - writePacketsLeft uint32 - writeBytesLeft int64 - - // The session ID or nil if first kex did not complete yet. - sessionID []byte -} - -type pendingKex struct { - otherInit []byte - done chan error -} - -func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport { - t := &handshakeTransport{ - conn: conn, - serverVersion: serverVersion, - clientVersion: clientVersion, - incoming: make(chan []byte, chanSize), - requestKex: make(chan struct{}, 1), - startKex: make(chan *pendingKex, 1), - - config: config, - } - t.resetReadThresholds() - t.resetWriteThresholds() - - // We always start with a mandatory key exchange. - t.requestKex <- struct{}{} - return t -} - -func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport { - t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) - t.dialAddress = dialAddr - t.remoteAddr = addr - t.hostKeyCallback = config.HostKeyCallback - t.bannerCallback = config.BannerCallback - if config.HostKeyAlgorithms != nil { - t.hostKeyAlgorithms = config.HostKeyAlgorithms - } else { - t.hostKeyAlgorithms = supportedHostKeyAlgos - } - go t.readLoop() - go t.kexLoop() - return t -} - -func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport { - t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) - t.hostKeys = config.hostKeys - go t.readLoop() - go t.kexLoop() - return t -} - -func (t *handshakeTransport) getSessionID() []byte { - return t.sessionID -} - -// waitSession waits for the session to be established. This should be -// the first thing to call after instantiating handshakeTransport. -func (t *handshakeTransport) waitSession() error { - p, err := t.readPacket() - if err != nil { - return err - } - if p[0] != msgNewKeys { - return fmt.Errorf("ssh: first packet should be msgNewKeys") - } - - return nil -} - -func (t *handshakeTransport) id() string { - if len(t.hostKeys) > 0 { - return "server" - } - return "client" -} - -func (t *handshakeTransport) printPacket(p []byte, write bool) { - action := "got" - if write { - action = "sent" - } - - if p[0] == msgChannelData || p[0] == msgChannelExtendedData { - log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p)) - } else { - msg, err := decode(p) - log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err) - } -} - -func (t *handshakeTransport) readPacket() ([]byte, error) { - p, ok := <-t.incoming - if !ok { - return nil, t.readError - } - return p, nil -} - -func (t *handshakeTransport) readLoop() { - first := true - for { - p, err := t.readOnePacket(first) - first = false - if err != nil { - t.readError = err - close(t.incoming) - break - } - if p[0] == msgIgnore || p[0] == msgDebug { - continue - } - t.incoming <- p - } - - // Stop writers too. - t.recordWriteError(t.readError) - - // Unblock the writer should it wait for this. - close(t.startKex) - - // Don't close t.requestKex; it's also written to from writePacket. -} - -func (t *handshakeTransport) pushPacket(p []byte) error { - if debugHandshake { - t.printPacket(p, true) - } - return t.conn.writePacket(p) -} - -func (t *handshakeTransport) getWriteError() error { - t.mu.Lock() - defer t.mu.Unlock() - return t.writeError -} - -func (t *handshakeTransport) recordWriteError(err error) { - t.mu.Lock() - defer t.mu.Unlock() - if t.writeError == nil && err != nil { - t.writeError = err - } -} - -func (t *handshakeTransport) requestKeyExchange() { - select { - case t.requestKex <- struct{}{}: - default: - // something already requested a kex, so do nothing. - } -} - -func (t *handshakeTransport) resetWriteThresholds() { - t.writePacketsLeft = packetRekeyThreshold - if t.config.RekeyThreshold > 0 { - t.writeBytesLeft = int64(t.config.RekeyThreshold) - } else if t.algorithms != nil { - t.writeBytesLeft = t.algorithms.w.rekeyBytes() - } else { - t.writeBytesLeft = 1 << 30 - } -} - -func (t *handshakeTransport) kexLoop() { - -write: - for t.getWriteError() == nil { - var request *pendingKex - var sent bool - - for request == nil || !sent { - var ok bool - select { - case request, ok = <-t.startKex: - if !ok { - break write - } - case <-t.requestKex: - break - } - - if !sent { - if err := t.sendKexInit(); err != nil { - t.recordWriteError(err) - break - } - sent = true - } - } - - if err := t.getWriteError(); err != nil { - if request != nil { - request.done <- err - } - break - } - - // We're not servicing t.requestKex, but that is OK: - // we never block on sending to t.requestKex. - - // We're not servicing t.startKex, but the remote end - // has just sent us a kexInitMsg, so it can't send - // another key change request, until we close the done - // channel on the pendingKex request. - - err := t.enterKeyExchange(request.otherInit) - - t.mu.Lock() - t.writeError = err - t.sentInitPacket = nil - t.sentInitMsg = nil - - t.resetWriteThresholds() - - // we have completed the key exchange. Since the - // reader is still blocked, it is safe to clear out - // the requestKex channel. This avoids the situation - // where: 1) we consumed our own request for the - // initial kex, and 2) the kex from the remote side - // caused another send on the requestKex channel, - clear: - for { - select { - case <-t.requestKex: - // - default: - break clear - } - } - - request.done <- t.writeError - - // kex finished. Push packets that we received while - // the kex was in progress. Don't look at t.startKex - // and don't increment writtenSinceKex: if we trigger - // another kex while we are still busy with the last - // one, things will become very confusing. - for _, p := range t.pendingPackets { - t.writeError = t.pushPacket(p) - if t.writeError != nil { - break - } - } - t.pendingPackets = t.pendingPackets[:0] - t.mu.Unlock() - } - - // drain startKex channel. We don't service t.requestKex - // because nobody does blocking sends there. - go func() { - for init := range t.startKex { - init.done <- t.writeError - } - }() - - // Unblock reader. - t.conn.Close() -} - -// The protocol uses uint32 for packet counters, so we can't let them -// reach 1<<32. We will actually read and write more packets than -// this, though: the other side may send more packets, and after we -// hit this limit on writing we will send a few more packets for the -// key exchange itself. -const packetRekeyThreshold = (1 << 31) - -func (t *handshakeTransport) resetReadThresholds() { - t.readPacketsLeft = packetRekeyThreshold - if t.config.RekeyThreshold > 0 { - t.readBytesLeft = int64(t.config.RekeyThreshold) - } else if t.algorithms != nil { - t.readBytesLeft = t.algorithms.r.rekeyBytes() - } else { - t.readBytesLeft = 1 << 30 - } -} - -func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) { - p, err := t.conn.readPacket() - if err != nil { - return nil, err - } - - if t.readPacketsLeft > 0 { - t.readPacketsLeft-- - } else { - t.requestKeyExchange() - } - - if t.readBytesLeft > 0 { - t.readBytesLeft -= int64(len(p)) - } else { - t.requestKeyExchange() - } - - if debugHandshake { - t.printPacket(p, false) - } - - if first && p[0] != msgKexInit { - return nil, fmt.Errorf("ssh: first packet should be msgKexInit") - } - - if p[0] != msgKexInit { - return p, nil - } - - firstKex := t.sessionID == nil - - kex := pendingKex{ - done: make(chan error, 1), - otherInit: p, - } - t.startKex <- &kex - err = <-kex.done - - if debugHandshake { - log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err) - } - - if err != nil { - return nil, err - } - - t.resetReadThresholds() - - // By default, a key exchange is hidden from higher layers by - // translating it into msgIgnore. - successPacket := []byte{msgIgnore} - if firstKex { - // sendKexInit() for the first kex waits for - // msgNewKeys so the authentication process is - // guaranteed to happen over an encrypted transport. - successPacket = []byte{msgNewKeys} - } - - return successPacket, nil -} - -// sendKexInit sends a key change message. -func (t *handshakeTransport) sendKexInit() error { - t.mu.Lock() - defer t.mu.Unlock() - if t.sentInitMsg != nil { - // kexInits may be sent either in response to the other side, - // or because our side wants to initiate a key change, so we - // may have already sent a kexInit. In that case, don't send a - // second kexInit. - return nil - } - - msg := &kexInitMsg{ - KexAlgos: t.config.KeyExchanges, - CiphersClientServer: t.config.Ciphers, - CiphersServerClient: t.config.Ciphers, - MACsClientServer: t.config.MACs, - MACsServerClient: t.config.MACs, - CompressionClientServer: supportedCompressions, - CompressionServerClient: supportedCompressions, - } - io.ReadFull(rand.Reader, msg.Cookie[:]) - - if len(t.hostKeys) > 0 { - for _, k := range t.hostKeys { - msg.ServerHostKeyAlgos = append( - msg.ServerHostKeyAlgos, k.PublicKey().Type()) - } - } else { - msg.ServerHostKeyAlgos = t.hostKeyAlgorithms - } - packet := Marshal(msg) - - // writePacket destroys the contents, so save a copy. - packetCopy := make([]byte, len(packet)) - copy(packetCopy, packet) - - if err := t.pushPacket(packetCopy); err != nil { - return err - } - - t.sentInitMsg = msg - t.sentInitPacket = packet - - return nil -} - -func (t *handshakeTransport) writePacket(p []byte) error { - switch p[0] { - case msgKexInit: - return errors.New("ssh: only handshakeTransport can send kexInit") - case msgNewKeys: - return errors.New("ssh: only handshakeTransport can send newKeys") - } - - t.mu.Lock() - defer t.mu.Unlock() - if t.writeError != nil { - return t.writeError - } - - if t.sentInitMsg != nil { - // Copy the packet so the writer can reuse the buffer. - cp := make([]byte, len(p)) - copy(cp, p) - t.pendingPackets = append(t.pendingPackets, cp) - return nil - } - - if t.writeBytesLeft > 0 { - t.writeBytesLeft -= int64(len(p)) - } else { - t.requestKeyExchange() - } - - if t.writePacketsLeft > 0 { - t.writePacketsLeft-- - } else { - t.requestKeyExchange() - } - - if err := t.pushPacket(p); err != nil { - t.writeError = err - } - - return nil -} - -func (t *handshakeTransport) Close() error { - return t.conn.Close() -} - -func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { - if debugHandshake { - log.Printf("%s entered key exchange", t.id()) - } - - otherInit := &kexInitMsg{} - if err := Unmarshal(otherInitPacket, otherInit); err != nil { - return err - } - - magics := handshakeMagics{ - clientVersion: t.clientVersion, - serverVersion: t.serverVersion, - clientKexInit: otherInitPacket, - serverKexInit: t.sentInitPacket, - } - - clientInit := otherInit - serverInit := t.sentInitMsg - if len(t.hostKeys) == 0 { - clientInit, serverInit = serverInit, clientInit - - magics.clientKexInit = t.sentInitPacket - magics.serverKexInit = otherInitPacket - } - - var err error - t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit) - if err != nil { - return err - } - - // We don't send FirstKexFollows, but we handle receiving it. - // - // RFC 4253 section 7 defines the kex and the agreement method for - // first_kex_packet_follows. It states that the guessed packet - // should be ignored if the "kex algorithm and/or the host - // key algorithm is guessed wrong (server and client have - // different preferred algorithm), or if any of the other - // algorithms cannot be agreed upon". The other algorithms have - // already been checked above so the kex algorithm and host key - // algorithm are checked here. - if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) { - // other side sent a kex message for the wrong algorithm, - // which we have to ignore. - if _, err := t.conn.readPacket(); err != nil { - return err - } - } - - kex, ok := kexAlgoMap[t.algorithms.kex] - if !ok { - return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex) - } - - var result *kexResult - if len(t.hostKeys) > 0 { - result, err = t.server(kex, t.algorithms, &magics) - } else { - result, err = t.client(kex, t.algorithms, &magics) - } - - if err != nil { - return err - } - - if t.sessionID == nil { - t.sessionID = result.H - } - result.SessionID = t.sessionID - - if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil { - return err - } - if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil { - return err - } - if packet, err := t.conn.readPacket(); err != nil { - return err - } else if packet[0] != msgNewKeys { - return unexpectedMessageError(msgNewKeys, packet[0]) - } - - return nil -} - -func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { - var hostKey Signer - for _, k := range t.hostKeys { - if algs.hostKey == k.PublicKey().Type() { - hostKey = k - } - } - - r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey) - return r, err -} - -func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { - result, err := kex.Client(t.conn, t.config.Rand, magics) - if err != nil { - return nil, err - } - - hostKey, err := ParsePublicKey(result.HostKey) - if err != nil { - return nil, err - } - - if err := verifyHostKeySignature(hostKey, result); err != nil { - return nil, err - } - - err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) - if err != nil { - return nil, err - } - - return result, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go deleted file mode 100644 index f34bcc01..00000000 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ /dev/null @@ -1,540 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/subtle" - "errors" - "io" - "math/big" - - "golang.org/x/crypto/curve25519" -) - -const ( - kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" - kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" - kexAlgoECDH256 = "ecdh-sha2-nistp256" - kexAlgoECDH384 = "ecdh-sha2-nistp384" - kexAlgoECDH521 = "ecdh-sha2-nistp521" - kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org" -) - -// kexResult captures the outcome of a key exchange. -type kexResult struct { - // Session hash. See also RFC 4253, section 8. - H []byte - - // Shared secret. See also RFC 4253, section 8. - K []byte - - // Host key as hashed into H. - HostKey []byte - - // Signature of H. - Signature []byte - - // A cryptographic hash function that matches the security - // level of the key exchange algorithm. It is used for - // calculating H, and for deriving keys from H and K. - Hash crypto.Hash - - // The session ID, which is the first H computed. This is used - // to derive key material inside the transport. - SessionID []byte -} - -// handshakeMagics contains data that is always included in the -// session hash. -type handshakeMagics struct { - clientVersion, serverVersion []byte - clientKexInit, serverKexInit []byte -} - -func (m *handshakeMagics) write(w io.Writer) { - writeString(w, m.clientVersion) - writeString(w, m.serverVersion) - writeString(w, m.clientKexInit) - writeString(w, m.serverKexInit) -} - -// kexAlgorithm abstracts different key exchange algorithms. -type kexAlgorithm interface { - // Server runs server-side key agreement, signing the result - // with a hostkey. - Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error) - - // Client runs the client-side key agreement. Caller is - // responsible for verifying the host key signature. - Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) -} - -// dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement. -type dhGroup struct { - g, p, pMinus1 *big.Int -} - -func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) { - if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 { - return nil, errors.New("ssh: DH parameter out of bounds") - } - return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil -} - -func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { - hashFunc := crypto.SHA1 - - var x *big.Int - for { - var err error - if x, err = rand.Int(randSource, group.pMinus1); err != nil { - return nil, err - } - if x.Sign() > 0 { - break - } - } - - X := new(big.Int).Exp(group.g, x, group.p) - kexDHInit := kexDHInitMsg{ - X: X, - } - if err := c.writePacket(Marshal(&kexDHInit)); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var kexDHReply kexDHReplyMsg - if err = Unmarshal(packet, &kexDHReply); err != nil { - return nil, err - } - - ki, err := group.diffieHellman(kexDHReply.Y, x) - if err != nil { - return nil, err - } - - h := hashFunc.New() - magics.write(h) - writeString(h, kexDHReply.HostKey) - writeInt(h, X) - writeInt(h, kexDHReply.Y) - K := make([]byte, intLength(ki)) - marshalInt(K, ki) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: kexDHReply.HostKey, - Signature: kexDHReply.Signature, - Hash: crypto.SHA1, - }, nil -} - -func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - hashFunc := crypto.SHA1 - packet, err := c.readPacket() - if err != nil { - return - } - var kexDHInit kexDHInitMsg - if err = Unmarshal(packet, &kexDHInit); err != nil { - return - } - - var y *big.Int - for { - if y, err = rand.Int(randSource, group.pMinus1); err != nil { - return - } - if y.Sign() > 0 { - break - } - } - - Y := new(big.Int).Exp(group.g, y, group.p) - ki, err := group.diffieHellman(kexDHInit.X, y) - if err != nil { - return nil, err - } - - hostKeyBytes := priv.PublicKey().Marshal() - - h := hashFunc.New() - magics.write(h) - writeString(h, hostKeyBytes) - writeInt(h, kexDHInit.X) - writeInt(h, Y) - - K := make([]byte, intLength(ki)) - marshalInt(K, ki) - h.Write(K) - - H := h.Sum(nil) - - // H is already a hash, but the hostkey signing will apply its - // own key-specific hash algorithm. - sig, err := signAndMarshal(priv, randSource, H) - if err != nil { - return nil, err - } - - kexDHReply := kexDHReplyMsg{ - HostKey: hostKeyBytes, - Y: Y, - Signature: sig, - } - packet = Marshal(&kexDHReply) - - err = c.writePacket(packet) - return &kexResult{ - H: H, - K: K, - HostKey: hostKeyBytes, - Signature: sig, - Hash: crypto.SHA1, - }, nil -} - -// ecdh performs Elliptic Curve Diffie-Hellman key exchange as -// described in RFC 5656, section 4. -type ecdh struct { - curve elliptic.Curve -} - -func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { - ephKey, err := ecdsa.GenerateKey(kex.curve, rand) - if err != nil { - return nil, err - } - - kexInit := kexECDHInitMsg{ - ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y), - } - - serialized := Marshal(&kexInit) - if err := c.writePacket(serialized); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var reply kexECDHReplyMsg - if err = Unmarshal(packet, &reply); err != nil { - return nil, err - } - - x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey) - if err != nil { - return nil, err - } - - // generate shared secret - secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes()) - - h := ecHash(kex.curve).New() - magics.write(h) - writeString(h, reply.HostKey) - writeString(h, kexInit.ClientPubKey) - writeString(h, reply.EphemeralPubKey) - K := make([]byte, intLength(secret)) - marshalInt(K, secret) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: reply.HostKey, - Signature: reply.Signature, - Hash: ecHash(kex.curve), - }, nil -} - -// unmarshalECKey parses and checks an EC key. -func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) { - x, y = elliptic.Unmarshal(curve, pubkey) - if x == nil { - return nil, nil, errors.New("ssh: elliptic.Unmarshal failure") - } - if !validateECPublicKey(curve, x, y) { - return nil, nil, errors.New("ssh: public key not on curve") - } - return x, y, nil -} - -// validateECPublicKey checks that the point is a valid public key for -// the given curve. See [SEC1], 3.2.2 -func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool { - if x.Sign() == 0 && y.Sign() == 0 { - return false - } - - if x.Cmp(curve.Params().P) >= 0 { - return false - } - - if y.Cmp(curve.Params().P) >= 0 { - return false - } - - if !curve.IsOnCurve(x, y) { - return false - } - - // We don't check if N * PubKey == 0, since - // - // - the NIST curves have cofactor = 1, so this is implicit. - // (We don't foresee an implementation that supports non NIST - // curves) - // - // - for ephemeral keys, we don't need to worry about small - // subgroup attacks. - return true -} - -func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var kexECDHInit kexECDHInitMsg - if err = Unmarshal(packet, &kexECDHInit); err != nil { - return nil, err - } - - clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey) - if err != nil { - return nil, err - } - - // We could cache this key across multiple users/multiple - // connection attempts, but the benefit is small. OpenSSH - // generates a new key for each incoming connection. - ephKey, err := ecdsa.GenerateKey(kex.curve, rand) - if err != nil { - return nil, err - } - - hostKeyBytes := priv.PublicKey().Marshal() - - serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y) - - // generate shared secret - secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes()) - - h := ecHash(kex.curve).New() - magics.write(h) - writeString(h, hostKeyBytes) - writeString(h, kexECDHInit.ClientPubKey) - writeString(h, serializedEphKey) - - K := make([]byte, intLength(secret)) - marshalInt(K, secret) - h.Write(K) - - H := h.Sum(nil) - - // H is already a hash, but the hostkey signing will apply its - // own key-specific hash algorithm. - sig, err := signAndMarshal(priv, rand, H) - if err != nil { - return nil, err - } - - reply := kexECDHReplyMsg{ - EphemeralPubKey: serializedEphKey, - HostKey: hostKeyBytes, - Signature: sig, - } - - serialized := Marshal(&reply) - if err := c.writePacket(serialized); err != nil { - return nil, err - } - - return &kexResult{ - H: H, - K: K, - HostKey: reply.HostKey, - Signature: sig, - Hash: ecHash(kex.curve), - }, nil -} - -var kexAlgoMap = map[string]kexAlgorithm{} - -func init() { - // This is the group called diffie-hellman-group1-sha1 in RFC - // 4253 and Oakley Group 2 in RFC 2409. - p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) - kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, - pMinus1: new(big.Int).Sub(p, bigOne), - } - - // This is the group called diffie-hellman-group14-sha1 in RFC - // 4253 and Oakley Group 14 in RFC 3526. - p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) - - kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, - pMinus1: new(big.Int).Sub(p, bigOne), - } - - kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} - kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} - kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} - kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} -} - -// curve25519sha256 implements the curve25519-sha256@libssh.org key -// agreement protocol, as described in -// https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt -type curve25519sha256 struct{} - -type curve25519KeyPair struct { - priv [32]byte - pub [32]byte -} - -func (kp *curve25519KeyPair) generate(rand io.Reader) error { - if _, err := io.ReadFull(rand, kp.priv[:]); err != nil { - return err - } - curve25519.ScalarBaseMult(&kp.pub, &kp.priv) - return nil -} - -// curve25519Zeros is just an array of 32 zero bytes so that we have something -// convenient to compare against in order to reject curve25519 points with the -// wrong order. -var curve25519Zeros [32]byte - -func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { - var kp curve25519KeyPair - if err := kp.generate(rand); err != nil { - return nil, err - } - if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var reply kexECDHReplyMsg - if err = Unmarshal(packet, &reply); err != nil { - return nil, err - } - if len(reply.EphemeralPubKey) != 32 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong length") - } - - var servPub, secret [32]byte - copy(servPub[:], reply.EphemeralPubKey) - curve25519.ScalarMult(&secret, &kp.priv, &servPub) - if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong order") - } - - h := crypto.SHA256.New() - magics.write(h) - writeString(h, reply.HostKey) - writeString(h, kp.pub[:]) - writeString(h, reply.EphemeralPubKey) - - ki := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(ki)) - marshalInt(K, ki) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: reply.HostKey, - Signature: reply.Signature, - Hash: crypto.SHA256, - }, nil -} - -func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - packet, err := c.readPacket() - if err != nil { - return - } - var kexInit kexECDHInitMsg - if err = Unmarshal(packet, &kexInit); err != nil { - return - } - - if len(kexInit.ClientPubKey) != 32 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong length") - } - - var kp curve25519KeyPair - if err := kp.generate(rand); err != nil { - return nil, err - } - - var clientPub, secret [32]byte - copy(clientPub[:], kexInit.ClientPubKey) - curve25519.ScalarMult(&secret, &kp.priv, &clientPub) - if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong order") - } - - hostKeyBytes := priv.PublicKey().Marshal() - - h := crypto.SHA256.New() - magics.write(h) - writeString(h, hostKeyBytes) - writeString(h, kexInit.ClientPubKey) - writeString(h, kp.pub[:]) - - ki := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(ki)) - marshalInt(K, ki) - h.Write(K) - - H := h.Sum(nil) - - sig, err := signAndMarshal(priv, rand, H) - if err != nil { - return nil, err - } - - reply := kexECDHReplyMsg{ - EphemeralPubKey: kp.pub[:], - HostKey: hostKeyBytes, - Signature: sig, - } - if err := c.writePacket(Marshal(&reply)); err != nil { - return nil, err - } - return &kexResult{ - H: H, - K: K, - HostKey: hostKeyBytes, - Signature: sig, - Hash: crypto.SHA256, - }, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go deleted file mode 100644 index 96980479..00000000 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ /dev/null @@ -1,1100 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/md5" - "crypto/rsa" - "crypto/sha256" - "crypto/x509" - "encoding/asn1" - "encoding/base64" - "encoding/hex" - "encoding/pem" - "errors" - "fmt" - "io" - "math/big" - "strings" - - "golang.org/x/crypto/ed25519" -) - -// These constants represent the algorithm names for key types supported by this -// package. -const ( - KeyAlgoRSA = "ssh-rsa" - KeyAlgoDSA = "ssh-dss" - KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" - KeyAlgoECDSA384 = "ecdsa-sha2-nistp384" - KeyAlgoECDSA521 = "ecdsa-sha2-nistp521" - KeyAlgoED25519 = "ssh-ed25519" -) - -// These constants represent non-default signature algorithms that are supported -// as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See -// [PROTOCOL.agent] section 4.5.1 and -// https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10 -const ( - SigAlgoRSA = "ssh-rsa" - SigAlgoRSASHA2256 = "rsa-sha2-256" - SigAlgoRSASHA2512 = "rsa-sha2-512" -) - -// parsePubKey parses a public key of the given algorithm. -// Use ParsePublicKey for keys with prepended algorithm. -func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) { - switch algo { - case KeyAlgoRSA: - return parseRSA(in) - case KeyAlgoDSA: - return parseDSA(in) - case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521: - return parseECDSA(in) - case KeyAlgoED25519: - return parseED25519(in) - case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: - cert, err := parseCert(in, certToPrivAlgo(algo)) - if err != nil { - return nil, nil, err - } - return cert, nil, nil - } - return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo) -} - -// parseAuthorizedKey parses a public key in OpenSSH authorized_keys format -// (see sshd(8) manual page) once the options and key type fields have been -// removed. -func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { - in = bytes.TrimSpace(in) - - i := bytes.IndexAny(in, " \t") - if i == -1 { - i = len(in) - } - base64Key := in[:i] - - key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key))) - n, err := base64.StdEncoding.Decode(key, base64Key) - if err != nil { - return nil, "", err - } - key = key[:n] - out, err = ParsePublicKey(key) - if err != nil { - return nil, "", err - } - comment = string(bytes.TrimSpace(in[i:])) - return out, comment, nil -} - -// ParseKnownHosts parses an entry in the format of the known_hosts file. -// -// The known_hosts format is documented in the sshd(8) manual page. This -// function will parse a single entry from in. On successful return, marker -// will contain the optional marker value (i.e. "cert-authority" or "revoked") -// or else be empty, hosts will contain the hosts that this entry matches, -// pubKey will contain the public key and comment will contain any trailing -// comment at the end of the line. See the sshd(8) manual page for the various -// forms that a host string can take. -// -// The unparsed remainder of the input will be returned in rest. This function -// can be called repeatedly to parse multiple entries. -// -// If no entries were found in the input then err will be io.EOF. Otherwise a -// non-nil err value indicates a parse error. -func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) { - for len(in) > 0 { - end := bytes.IndexByte(in, '\n') - if end != -1 { - rest = in[end+1:] - in = in[:end] - } else { - rest = nil - } - - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } - - in = bytes.TrimSpace(in) - if len(in) == 0 || in[0] == '#' { - in = rest - continue - } - - i := bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - // Strip out the beginning of the known_host key. - // This is either an optional marker or a (set of) hostname(s). - keyFields := bytes.Fields(in) - if len(keyFields) < 3 || len(keyFields) > 5 { - return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data") - } - - // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated - // list of hosts - marker := "" - if keyFields[0][0] == '@' { - marker = string(keyFields[0][1:]) - keyFields = keyFields[1:] - } - - hosts := string(keyFields[0]) - // keyFields[1] contains the key type (e.g. “ssh-rsa”). - // However, that information is duplicated inside the - // base64-encoded key and so is ignored here. - - key := bytes.Join(keyFields[2:], []byte(" ")) - if pubKey, comment, err = parseAuthorizedKey(key); err != nil { - return "", nil, nil, "", nil, err - } - - return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil - } - - return "", nil, nil, "", nil, io.EOF -} - -// ParseAuthorizedKeys parses a public key from an authorized_keys -// file used in OpenSSH according to the sshd(8) manual page. -func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) { - for len(in) > 0 { - end := bytes.IndexByte(in, '\n') - if end != -1 { - rest = in[end+1:] - in = in[:end] - } else { - rest = nil - } - - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } - - in = bytes.TrimSpace(in) - if len(in) == 0 || in[0] == '#' { - in = rest - continue - } - - i := bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { - return out, comment, options, rest, nil - } - - // No key type recognised. Maybe there's an options field at - // the beginning. - var b byte - inQuote := false - var candidateOptions []string - optionStart := 0 - for i, b = range in { - isEnd := !inQuote && (b == ' ' || b == '\t') - if (b == ',' && !inQuote) || isEnd { - if i-optionStart > 0 { - candidateOptions = append(candidateOptions, string(in[optionStart:i])) - } - optionStart = i + 1 - } - if isEnd { - break - } - if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) { - inQuote = !inQuote - } - } - for i < len(in) && (in[i] == ' ' || in[i] == '\t') { - i++ - } - if i == len(in) { - // Invalid line: unmatched quote - in = rest - continue - } - - in = in[i:] - i = bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { - options = candidateOptions - return out, comment, options, rest, nil - } - - in = rest - continue - } - - return nil, "", nil, nil, errors.New("ssh: no key found") -} - -// ParsePublicKey parses an SSH public key formatted for use in -// the SSH wire protocol according to RFC 4253, section 6.6. -func ParsePublicKey(in []byte) (out PublicKey, err error) { - algo, in, ok := parseString(in) - if !ok { - return nil, errShortRead - } - var rest []byte - out, rest, err = parsePubKey(in, string(algo)) - if len(rest) > 0 { - return nil, errors.New("ssh: trailing junk in public key") - } - - return out, err -} - -// MarshalAuthorizedKey serializes key for inclusion in an OpenSSH -// authorized_keys file. The return value ends with newline. -func MarshalAuthorizedKey(key PublicKey) []byte { - b := &bytes.Buffer{} - b.WriteString(key.Type()) - b.WriteByte(' ') - e := base64.NewEncoder(base64.StdEncoding, b) - e.Write(key.Marshal()) - e.Close() - b.WriteByte('\n') - return b.Bytes() -} - -// PublicKey is an abstraction of different types of public keys. -type PublicKey interface { - // Type returns the key's type, e.g. "ssh-rsa". - Type() string - - // Marshal returns the serialized key data in SSH wire format, - // with the name prefix. To unmarshal the returned data, use - // the ParsePublicKey function. - Marshal() []byte - - // Verify that sig is a signature on the given data using this - // key. This function will hash the data appropriately first. - Verify(data []byte, sig *Signature) error -} - -// CryptoPublicKey, if implemented by a PublicKey, -// returns the underlying crypto.PublicKey form of the key. -type CryptoPublicKey interface { - CryptoPublicKey() crypto.PublicKey -} - -// A Signer can create signatures that verify against a public key. -type Signer interface { - // PublicKey returns an associated PublicKey instance. - PublicKey() PublicKey - - // Sign returns raw signature for the given data. This method - // will apply the hash specified for the keytype to the data. - Sign(rand io.Reader, data []byte) (*Signature, error) -} - -// A AlgorithmSigner is a Signer that also supports specifying a specific -// algorithm to use for signing. -type AlgorithmSigner interface { - Signer - - // SignWithAlgorithm is like Signer.Sign, but allows specification of a - // non-default signing algorithm. See the SigAlgo* constants in this - // package for signature algorithms supported by this package. Callers may - // pass an empty string for the algorithm in which case the AlgorithmSigner - // will use its default algorithm. - SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) -} - -type rsaPublicKey rsa.PublicKey - -func (r *rsaPublicKey) Type() string { - return "ssh-rsa" -} - -// parseRSA parses an RSA key according to RFC 4253, section 6.6. -func parseRSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - E *big.Int - N *big.Int - Rest []byte `ssh:"rest"` - } - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - if w.E.BitLen() > 24 { - return nil, nil, errors.New("ssh: exponent too large") - } - e := w.E.Int64() - if e < 3 || e&1 == 0 { - return nil, nil, errors.New("ssh: incorrect exponent") - } - - var key rsa.PublicKey - key.E = int(e) - key.N = w.N - return (*rsaPublicKey)(&key), w.Rest, nil -} - -func (r *rsaPublicKey) Marshal() []byte { - e := new(big.Int).SetInt64(int64(r.E)) - // RSA publickey struct layout should match the struct used by - // parseRSACert in the x/crypto/ssh/agent package. - wirekey := struct { - Name string - E *big.Int - N *big.Int - }{ - KeyAlgoRSA, - e, - r.N, - } - return Marshal(&wirekey) -} - -func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error { - var hash crypto.Hash - switch sig.Format { - case SigAlgoRSA: - hash = crypto.SHA1 - case SigAlgoRSASHA2256: - hash = crypto.SHA256 - case SigAlgoRSASHA2512: - hash = crypto.SHA512 - default: - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type()) - } - h := hash.New() - h.Write(data) - digest := h.Sum(nil) - return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, sig.Blob) -} - -func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*rsa.PublicKey)(r) -} - -type dsaPublicKey dsa.PublicKey - -func (k *dsaPublicKey) Type() string { - return "ssh-dss" -} - -func checkDSAParams(param *dsa.Parameters) error { - // SSH specifies FIPS 186-2, which only provided a single size - // (1024 bits) DSA key. FIPS 186-3 allows for larger key - // sizes, which would confuse SSH. - if l := param.P.BitLen(); l != 1024 { - return fmt.Errorf("ssh: unsupported DSA key size %d", l) - } - - return nil -} - -// parseDSA parses an DSA key according to RFC 4253, section 6.6. -func parseDSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - P, Q, G, Y *big.Int - Rest []byte `ssh:"rest"` - } - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - param := dsa.Parameters{ - P: w.P, - Q: w.Q, - G: w.G, - } - if err := checkDSAParams(¶m); err != nil { - return nil, nil, err - } - - key := &dsaPublicKey{ - Parameters: param, - Y: w.Y, - } - return key, w.Rest, nil -} - -func (k *dsaPublicKey) Marshal() []byte { - // DSA publickey struct layout should match the struct used by - // parseDSACert in the x/crypto/ssh/agent package. - w := struct { - Name string - P, Q, G, Y *big.Int - }{ - k.Type(), - k.P, - k.Q, - k.G, - k.Y, - } - - return Marshal(&w) -} - -func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != k.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) - } - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - - // Per RFC 4253, section 6.6, - // The value for 'dss_signature_blob' is encoded as a string containing - // r, followed by s (which are 160-bit integers, without lengths or - // padding, unsigned, and in network byte order). - // For DSS purposes, sig.Blob should be exactly 40 bytes in length. - if len(sig.Blob) != 40 { - return errors.New("ssh: DSA signature parse error") - } - r := new(big.Int).SetBytes(sig.Blob[:20]) - s := new(big.Int).SetBytes(sig.Blob[20:]) - if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) { - return nil - } - return errors.New("ssh: signature did not verify") -} - -func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*dsa.PublicKey)(k) -} - -type dsaPrivateKey struct { - *dsa.PrivateKey -} - -func (k *dsaPrivateKey) PublicKey() PublicKey { - return (*dsaPublicKey)(&k.PrivateKey.PublicKey) -} - -func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { - return k.SignWithAlgorithm(rand, data, "") -} - -func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { - if algorithm != "" && algorithm != k.PublicKey().Type() { - return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) - } - - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - r, s, err := dsa.Sign(rand, k.PrivateKey, digest) - if err != nil { - return nil, err - } - - sig := make([]byte, 40) - rb := r.Bytes() - sb := s.Bytes() - - copy(sig[20-len(rb):20], rb) - copy(sig[40-len(sb):], sb) - - return &Signature{ - Format: k.PublicKey().Type(), - Blob: sig, - }, nil -} - -type ecdsaPublicKey ecdsa.PublicKey - -func (k *ecdsaPublicKey) Type() string { - return "ecdsa-sha2-" + k.nistID() -} - -func (k *ecdsaPublicKey) nistID() string { - switch k.Params().BitSize { - case 256: - return "nistp256" - case 384: - return "nistp384" - case 521: - return "nistp521" - } - panic("ssh: unsupported ecdsa key size") -} - -type ed25519PublicKey ed25519.PublicKey - -func (k ed25519PublicKey) Type() string { - return KeyAlgoED25519 -} - -func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - KeyBytes []byte - Rest []byte `ssh:"rest"` - } - - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - key := ed25519.PublicKey(w.KeyBytes) - - return (ed25519PublicKey)(key), w.Rest, nil -} - -func (k ed25519PublicKey) Marshal() []byte { - w := struct { - Name string - KeyBytes []byte - }{ - KeyAlgoED25519, - []byte(k), - } - return Marshal(&w) -} - -func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error { - if sig.Format != k.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) - } - - edKey := (ed25519.PublicKey)(k) - if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { - return errors.New("ssh: signature did not verify") - } - - return nil -} - -func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey { - return ed25519.PublicKey(k) -} - -func supportedEllipticCurve(curve elliptic.Curve) bool { - return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521() -} - -// ecHash returns the hash to match the given elliptic curve, see RFC -// 5656, section 6.2.1 -func ecHash(curve elliptic.Curve) crypto.Hash { - bitSize := curve.Params().BitSize - switch { - case bitSize <= 256: - return crypto.SHA256 - case bitSize <= 384: - return crypto.SHA384 - } - return crypto.SHA512 -} - -// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. -func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - Curve string - KeyBytes []byte - Rest []byte `ssh:"rest"` - } - - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - key := new(ecdsa.PublicKey) - - switch w.Curve { - case "nistp256": - key.Curve = elliptic.P256() - case "nistp384": - key.Curve = elliptic.P384() - case "nistp521": - key.Curve = elliptic.P521() - default: - return nil, nil, errors.New("ssh: unsupported curve") - } - - key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) - if key.X == nil || key.Y == nil { - return nil, nil, errors.New("ssh: invalid curve point") - } - return (*ecdsaPublicKey)(key), w.Rest, nil -} - -func (k *ecdsaPublicKey) Marshal() []byte { - // See RFC 5656, section 3.1. - keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y) - // ECDSA publickey struct layout should match the struct used by - // parseECDSACert in the x/crypto/ssh/agent package. - w := struct { - Name string - ID string - Key []byte - }{ - k.Type(), - k.nistID(), - keyBytes, - } - - return Marshal(&w) -} - -func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != k.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) - } - - h := ecHash(k.Curve).New() - h.Write(data) - digest := h.Sum(nil) - - // Per RFC 5656, section 3.1.2, - // The ecdsa_signature_blob value has the following specific encoding: - // mpint r - // mpint s - var ecSig struct { - R *big.Int - S *big.Int - } - - if err := Unmarshal(sig.Blob, &ecSig); err != nil { - return err - } - - if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) { - return nil - } - return errors.New("ssh: signature did not verify") -} - -func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*ecdsa.PublicKey)(k) -} - -// NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, -// *ecdsa.PrivateKey or any other crypto.Signer and returns a -// corresponding Signer instance. ECDSA keys must use P-256, P-384 or -// P-521. DSA keys must use parameter size L1024N160. -func NewSignerFromKey(key interface{}) (Signer, error) { - switch key := key.(type) { - case crypto.Signer: - return NewSignerFromSigner(key) - case *dsa.PrivateKey: - return newDSAPrivateKey(key) - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } -} - -func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) { - if err := checkDSAParams(&key.PublicKey.Parameters); err != nil { - return nil, err - } - - return &dsaPrivateKey{key}, nil -} - -type wrappedSigner struct { - signer crypto.Signer - pubKey PublicKey -} - -// NewSignerFromSigner takes any crypto.Signer implementation and -// returns a corresponding Signer interface. This can be used, for -// example, with keys kept in hardware modules. -func NewSignerFromSigner(signer crypto.Signer) (Signer, error) { - pubKey, err := NewPublicKey(signer.Public()) - if err != nil { - return nil, err - } - - return &wrappedSigner{signer, pubKey}, nil -} - -func (s *wrappedSigner) PublicKey() PublicKey { - return s.pubKey -} - -func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { - return s.SignWithAlgorithm(rand, data, "") -} - -func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { - var hashFunc crypto.Hash - - if _, ok := s.pubKey.(*rsaPublicKey); ok { - // RSA keys support a few hash functions determined by the requested signature algorithm - switch algorithm { - case "", SigAlgoRSA: - algorithm = SigAlgoRSA - hashFunc = crypto.SHA1 - case SigAlgoRSASHA2256: - hashFunc = crypto.SHA256 - case SigAlgoRSASHA2512: - hashFunc = crypto.SHA512 - default: - return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) - } - } else { - // The only supported algorithm for all other key types is the same as the type of the key - if algorithm == "" { - algorithm = s.pubKey.Type() - } else if algorithm != s.pubKey.Type() { - return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) - } - - switch key := s.pubKey.(type) { - case *dsaPublicKey: - hashFunc = crypto.SHA1 - case *ecdsaPublicKey: - hashFunc = ecHash(key.Curve) - case ed25519PublicKey: - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } - } - - var digest []byte - if hashFunc != 0 { - h := hashFunc.New() - h.Write(data) - digest = h.Sum(nil) - } else { - digest = data - } - - signature, err := s.signer.Sign(rand, digest, hashFunc) - if err != nil { - return nil, err - } - - // crypto.Signer.Sign is expected to return an ASN.1-encoded signature - // for ECDSA and DSA, but that's not the encoding expected by SSH, so - // re-encode. - switch s.pubKey.(type) { - case *ecdsaPublicKey, *dsaPublicKey: - type asn1Signature struct { - R, S *big.Int - } - asn1Sig := new(asn1Signature) - _, err := asn1.Unmarshal(signature, asn1Sig) - if err != nil { - return nil, err - } - - switch s.pubKey.(type) { - case *ecdsaPublicKey: - signature = Marshal(asn1Sig) - - case *dsaPublicKey: - signature = make([]byte, 40) - r := asn1Sig.R.Bytes() - s := asn1Sig.S.Bytes() - copy(signature[20-len(r):20], r) - copy(signature[40-len(s):40], s) - } - } - - return &Signature{ - Format: algorithm, - Blob: signature, - }, nil -} - -// NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, -// or ed25519.PublicKey returns a corresponding PublicKey instance. -// ECDSA keys must use P-256, P-384 or P-521. -func NewPublicKey(key interface{}) (PublicKey, error) { - switch key := key.(type) { - case *rsa.PublicKey: - return (*rsaPublicKey)(key), nil - case *ecdsa.PublicKey: - if !supportedEllipticCurve(key.Curve) { - return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported") - } - return (*ecdsaPublicKey)(key), nil - case *dsa.PublicKey: - return (*dsaPublicKey)(key), nil - case ed25519.PublicKey: - return (ed25519PublicKey)(key), nil - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } -} - -// ParsePrivateKey returns a Signer from a PEM encoded private key. It supports -// the same keys as ParseRawPrivateKey. -func ParsePrivateKey(pemBytes []byte) (Signer, error) { - key, err := ParseRawPrivateKey(pemBytes) - if err != nil { - return nil, err - } - - return NewSignerFromKey(key) -} - -// ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private -// key and passphrase. It supports the same keys as -// ParseRawPrivateKeyWithPassphrase. -func ParsePrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (Signer, error) { - key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase) - if err != nil { - return nil, err - } - - return NewSignerFromKey(key) -} - -// encryptedBlock tells whether a private key is -// encrypted by examining its Proc-Type header -// for a mention of ENCRYPTED -// according to RFC 1421 Section 4.6.1.1. -func encryptedBlock(block *pem.Block) bool { - return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") -} - -// ParseRawPrivateKey returns a private key from a PEM encoded private key. It -// supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. -func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { - block, _ := pem.Decode(pemBytes) - if block == nil { - return nil, errors.New("ssh: no key found") - } - - if encryptedBlock(block) { - return nil, errors.New("ssh: cannot decode encrypted private keys") - } - - switch block.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(block.Bytes) - // RFC5208 - https://tools.ietf.org/html/rfc5208 - case "PRIVATE KEY": - return x509.ParsePKCS8PrivateKey(block.Bytes) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(block.Bytes) - case "DSA PRIVATE KEY": - return ParseDSAPrivateKey(block.Bytes) - case "OPENSSH PRIVATE KEY": - return parseOpenSSHPrivateKey(block.Bytes) - default: - return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) - } -} - -// ParseRawPrivateKeyWithPassphrase returns a private key decrypted with -// passphrase from a PEM encoded private key. If wrong passphrase, return -// x509.IncorrectPasswordError. -func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) { - block, _ := pem.Decode(pemBytes) - if block == nil { - return nil, errors.New("ssh: no key found") - } - buf := block.Bytes - - if encryptedBlock(block) { - if x509.IsEncryptedPEMBlock(block) { - var err error - buf, err = x509.DecryptPEMBlock(block, passPhrase) - if err != nil { - if err == x509.IncorrectPasswordError { - return nil, err - } - return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) - } - } - } - - switch block.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(buf) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(buf) - case "DSA PRIVATE KEY": - return ParseDSAPrivateKey(buf) - case "OPENSSH PRIVATE KEY": - return parseOpenSSHPrivateKey(buf) - default: - return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) - } -} - -// ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as -// specified by the OpenSSL DSA man page. -func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { - var k struct { - Version int - P *big.Int - Q *big.Int - G *big.Int - Pub *big.Int - Priv *big.Int - } - rest, err := asn1.Unmarshal(der, &k) - if err != nil { - return nil, errors.New("ssh: failed to parse DSA key: " + err.Error()) - } - if len(rest) > 0 { - return nil, errors.New("ssh: garbage after DSA key") - } - - return &dsa.PrivateKey{ - PublicKey: dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: k.P, - Q: k.Q, - G: k.G, - }, - Y: k.Pub, - }, - X: k.Priv, - }, nil -} - -// Implemented based on the documentation at -// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key -func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { - const magic = "openssh-key-v1\x00" - if len(key) < len(magic) || string(key[:len(magic)]) != magic { - return nil, errors.New("ssh: invalid openssh private key format") - } - remaining := key[len(magic):] - - var w struct { - CipherName string - KdfName string - KdfOpts string - NumKeys uint32 - PubKey []byte - PrivKeyBlock []byte - } - - if err := Unmarshal(remaining, &w); err != nil { - return nil, err - } - - if w.KdfName != "none" || w.CipherName != "none" { - return nil, errors.New("ssh: cannot decode encrypted private keys") - } - - pk1 := struct { - Check1 uint32 - Check2 uint32 - Keytype string - Rest []byte `ssh:"rest"` - }{} - - if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil { - return nil, err - } - - if pk1.Check1 != pk1.Check2 { - return nil, errors.New("ssh: checkint mismatch") - } - - // we only handle ed25519 and rsa keys currently - switch pk1.Keytype { - case KeyAlgoRSA: - // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773 - key := struct { - N *big.Int - E *big.Int - D *big.Int - Iqmp *big.Int - P *big.Int - Q *big.Int - Comment string - Pad []byte `ssh:"rest"` - }{} - - if err := Unmarshal(pk1.Rest, &key); err != nil { - return nil, err - } - - for i, b := range key.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") - } - } - - pk := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: key.N, - E: int(key.E.Int64()), - }, - D: key.D, - Primes: []*big.Int{key.P, key.Q}, - } - - if err := pk.Validate(); err != nil { - return nil, err - } - - pk.Precompute() - - return pk, nil - case KeyAlgoED25519: - key := struct { - Pub []byte - Priv []byte - Comment string - Pad []byte `ssh:"rest"` - }{} - - if err := Unmarshal(pk1.Rest, &key); err != nil { - return nil, err - } - - if len(key.Priv) != ed25519.PrivateKeySize { - return nil, errors.New("ssh: private key unexpected length") - } - - for i, b := range key.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") - } - } - - pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) - copy(pk, key.Priv) - return &pk, nil - default: - return nil, errors.New("ssh: unhandled key type") - } -} - -// FingerprintLegacyMD5 returns the user presentation of the key's -// fingerprint as described by RFC 4716 section 4. -func FingerprintLegacyMD5(pubKey PublicKey) string { - md5sum := md5.Sum(pubKey.Marshal()) - hexarray := make([]string, len(md5sum)) - for i, c := range md5sum { - hexarray[i] = hex.EncodeToString([]byte{c}) - } - return strings.Join(hexarray, ":") -} - -// FingerprintSHA256 returns the user presentation of the key's -// fingerprint as unpadded base64 encoded sha256 hash. -// This format was introduced from OpenSSH 6.8. -// https://www.openssh.com/txt/release-6.8 -// https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding) -func FingerprintSHA256(pubKey PublicKey) string { - sha256sum := sha256.Sum256(pubKey.Marshal()) - hash := base64.RawStdEncoding.EncodeToString(sha256sum[:]) - return "SHA256:" + hash -} diff --git a/vendor/golang.org/x/crypto/ssh/mac.go b/vendor/golang.org/x/crypto/ssh/mac.go deleted file mode 100644 index c07a0628..00000000 --- a/vendor/golang.org/x/crypto/ssh/mac.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 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 ssh - -// Message authentication support - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "hash" -) - -type macMode struct { - keySize int - etm bool - new func(key []byte) hash.Hash -} - -// truncatingMAC wraps around a hash.Hash and truncates the output digest to -// a given size. -type truncatingMAC struct { - length int - hmac hash.Hash -} - -func (t truncatingMAC) Write(data []byte) (int, error) { - return t.hmac.Write(data) -} - -func (t truncatingMAC) Sum(in []byte) []byte { - out := t.hmac.Sum(in) - return out[:len(in)+t.length] -} - -func (t truncatingMAC) Reset() { - t.hmac.Reset() -} - -func (t truncatingMAC) Size() int { - return t.length -} - -func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } - -var macModes = map[string]*macMode{ - "hmac-sha2-256-etm@openssh.com": {32, true, func(key []byte) hash.Hash { - return hmac.New(sha256.New, key) - }}, - "hmac-sha2-256": {32, false, func(key []byte) hash.Hash { - return hmac.New(sha256.New, key) - }}, - "hmac-sha1": {20, false, func(key []byte) hash.Hash { - return hmac.New(sha1.New, key) - }}, - "hmac-sha1-96": {20, false, func(key []byte) hash.Hash { - return truncatingMAC{12, hmac.New(sha1.New, key)} - }}, -} diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go deleted file mode 100644 index 08d28117..00000000 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ /dev/null @@ -1,766 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math/big" - "reflect" - "strconv" - "strings" -) - -// These are SSH message type numbers. They are scattered around several -// documents but many were taken from [SSH-PARAMETERS]. -const ( - msgIgnore = 2 - msgUnimplemented = 3 - msgDebug = 4 - msgNewKeys = 21 -) - -// SSH messages: -// -// These structures mirror the wire format of the corresponding SSH messages. -// They are marshaled using reflection with the marshal and unmarshal functions -// in this file. The only wrinkle is that a final member of type []byte with a -// ssh tag of "rest" receives the remainder of a packet when unmarshaling. - -// See RFC 4253, section 11.1. -const msgDisconnect = 1 - -// disconnectMsg is the message that signals a disconnect. It is also -// the error type returned from mux.Wait() -type disconnectMsg struct { - Reason uint32 `sshtype:"1"` - Message string - Language string -} - -func (d *disconnectMsg) Error() string { - return fmt.Sprintf("ssh: disconnect, reason %d: %s", d.Reason, d.Message) -} - -// See RFC 4253, section 7.1. -const msgKexInit = 20 - -type kexInitMsg struct { - Cookie [16]byte `sshtype:"20"` - KexAlgos []string - ServerHostKeyAlgos []string - CiphersClientServer []string - CiphersServerClient []string - MACsClientServer []string - MACsServerClient []string - CompressionClientServer []string - CompressionServerClient []string - LanguagesClientServer []string - LanguagesServerClient []string - FirstKexFollows bool - Reserved uint32 -} - -// See RFC 4253, section 8. - -// Diffie-Helman -const msgKexDHInit = 30 - -type kexDHInitMsg struct { - X *big.Int `sshtype:"30"` -} - -const msgKexECDHInit = 30 - -type kexECDHInitMsg struct { - ClientPubKey []byte `sshtype:"30"` -} - -const msgKexECDHReply = 31 - -type kexECDHReplyMsg struct { - HostKey []byte `sshtype:"31"` - EphemeralPubKey []byte - Signature []byte -} - -const msgKexDHReply = 31 - -type kexDHReplyMsg struct { - HostKey []byte `sshtype:"31"` - Y *big.Int - Signature []byte -} - -// See RFC 4253, section 10. -const msgServiceRequest = 5 - -type serviceRequestMsg struct { - Service string `sshtype:"5"` -} - -// See RFC 4253, section 10. -const msgServiceAccept = 6 - -type serviceAcceptMsg struct { - Service string `sshtype:"6"` -} - -// See RFC 4252, section 5. -const msgUserAuthRequest = 50 - -type userAuthRequestMsg struct { - User string `sshtype:"50"` - Service string - Method string - Payload []byte `ssh:"rest"` -} - -// Used for debug printouts of packets. -type userAuthSuccessMsg struct { -} - -// See RFC 4252, section 5.1 -const msgUserAuthFailure = 51 - -type userAuthFailureMsg struct { - Methods []string `sshtype:"51"` - PartialSuccess bool -} - -// See RFC 4252, section 5.1 -const msgUserAuthSuccess = 52 - -// See RFC 4252, section 5.4 -const msgUserAuthBanner = 53 - -type userAuthBannerMsg struct { - Message string `sshtype:"53"` - // unused, but required to allow message parsing - Language string -} - -// See RFC 4256, section 3.2 -const msgUserAuthInfoRequest = 60 -const msgUserAuthInfoResponse = 61 - -type userAuthInfoRequestMsg struct { - User string `sshtype:"60"` - Instruction string - DeprecatedLanguage string - NumPrompts uint32 - Prompts []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpen = 90 - -type channelOpenMsg struct { - ChanType string `sshtype:"90"` - PeersID uint32 - PeersWindow uint32 - MaxPacketSize uint32 - TypeSpecificData []byte `ssh:"rest"` -} - -const msgChannelExtendedData = 95 -const msgChannelData = 94 - -// Used for debug print outs of packets. -type channelDataMsg struct { - PeersID uint32 `sshtype:"94"` - Length uint32 - Rest []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpenConfirm = 91 - -type channelOpenConfirmMsg struct { - PeersID uint32 `sshtype:"91"` - MyID uint32 - MyWindow uint32 - MaxPacketSize uint32 - TypeSpecificData []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpenFailure = 92 - -type channelOpenFailureMsg struct { - PeersID uint32 `sshtype:"92"` - Reason RejectionReason - Message string - Language string -} - -const msgChannelRequest = 98 - -type channelRequestMsg struct { - PeersID uint32 `sshtype:"98"` - Request string - WantReply bool - RequestSpecificData []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.4. -const msgChannelSuccess = 99 - -type channelRequestSuccessMsg struct { - PeersID uint32 `sshtype:"99"` -} - -// See RFC 4254, section 5.4. -const msgChannelFailure = 100 - -type channelRequestFailureMsg struct { - PeersID uint32 `sshtype:"100"` -} - -// See RFC 4254, section 5.3 -const msgChannelClose = 97 - -type channelCloseMsg struct { - PeersID uint32 `sshtype:"97"` -} - -// See RFC 4254, section 5.3 -const msgChannelEOF = 96 - -type channelEOFMsg struct { - PeersID uint32 `sshtype:"96"` -} - -// See RFC 4254, section 4 -const msgGlobalRequest = 80 - -type globalRequestMsg struct { - Type string `sshtype:"80"` - WantReply bool - Data []byte `ssh:"rest"` -} - -// See RFC 4254, section 4 -const msgRequestSuccess = 81 - -type globalRequestSuccessMsg struct { - Data []byte `ssh:"rest" sshtype:"81"` -} - -// See RFC 4254, section 4 -const msgRequestFailure = 82 - -type globalRequestFailureMsg struct { - Data []byte `ssh:"rest" sshtype:"82"` -} - -// See RFC 4254, section 5.2 -const msgChannelWindowAdjust = 93 - -type windowAdjustMsg struct { - PeersID uint32 `sshtype:"93"` - AdditionalBytes uint32 -} - -// See RFC 4252, section 7 -const msgUserAuthPubKeyOk = 60 - -type userAuthPubKeyOkMsg struct { - Algo string `sshtype:"60"` - PubKey []byte -} - -// typeTags returns the possible type bytes for the given reflect.Type, which -// should be a struct. The possible values are separated by a '|' character. -func typeTags(structType reflect.Type) (tags []byte) { - tagStr := structType.Field(0).Tag.Get("sshtype") - - for _, tag := range strings.Split(tagStr, "|") { - i, err := strconv.Atoi(tag) - if err == nil { - tags = append(tags, byte(i)) - } - } - - return tags -} - -func fieldError(t reflect.Type, field int, problem string) error { - if problem != "" { - problem = ": " + problem - } - return fmt.Errorf("ssh: unmarshal error for field %s of type %s%s", t.Field(field).Name, t.Name(), problem) -} - -var errShortRead = errors.New("ssh: short read") - -// Unmarshal parses data in SSH wire format into a structure. The out -// argument should be a pointer to struct. If the first member of the -// struct has the "sshtype" tag set to a '|'-separated set of numbers -// in decimal, the packet must start with one of those numbers. In -// case of error, Unmarshal returns a ParseError or -// UnexpectedMessageError. -func Unmarshal(data []byte, out interface{}) error { - v := reflect.ValueOf(out).Elem() - structType := v.Type() - expectedTypes := typeTags(structType) - - var expectedType byte - if len(expectedTypes) > 0 { - expectedType = expectedTypes[0] - } - - if len(data) == 0 { - return parseError(expectedType) - } - - if len(expectedTypes) > 0 { - goodType := false - for _, e := range expectedTypes { - if e > 0 && data[0] == e { - goodType = true - break - } - } - if !goodType { - return fmt.Errorf("ssh: unexpected message type %d (expected one of %v)", data[0], expectedTypes) - } - data = data[1:] - } - - var ok bool - for i := 0; i < v.NumField(); i++ { - field := v.Field(i) - t := field.Type() - switch t.Kind() { - case reflect.Bool: - if len(data) < 1 { - return errShortRead - } - field.SetBool(data[0] != 0) - data = data[1:] - case reflect.Array: - if t.Elem().Kind() != reflect.Uint8 { - return fieldError(structType, i, "array of unsupported type") - } - if len(data) < t.Len() { - return errShortRead - } - for j, n := 0, t.Len(); j < n; j++ { - field.Index(j).Set(reflect.ValueOf(data[j])) - } - data = data[t.Len():] - case reflect.Uint64: - var u64 uint64 - if u64, data, ok = parseUint64(data); !ok { - return errShortRead - } - field.SetUint(u64) - case reflect.Uint32: - var u32 uint32 - if u32, data, ok = parseUint32(data); !ok { - return errShortRead - } - field.SetUint(uint64(u32)) - case reflect.Uint8: - if len(data) < 1 { - return errShortRead - } - field.SetUint(uint64(data[0])) - data = data[1:] - case reflect.String: - var s []byte - if s, data, ok = parseString(data); !ok { - return fieldError(structType, i, "") - } - field.SetString(string(s)) - case reflect.Slice: - switch t.Elem().Kind() { - case reflect.Uint8: - if structType.Field(i).Tag.Get("ssh") == "rest" { - field.Set(reflect.ValueOf(data)) - data = nil - } else { - var s []byte - if s, data, ok = parseString(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(s)) - } - case reflect.String: - var nl []string - if nl, data, ok = parseNameList(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(nl)) - default: - return fieldError(structType, i, "slice of unsupported type") - } - case reflect.Ptr: - if t == bigIntType { - var n *big.Int - if n, data, ok = parseInt(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(n)) - } else { - return fieldError(structType, i, "pointer to unsupported type") - } - default: - return fieldError(structType, i, fmt.Sprintf("unsupported type: %v", t)) - } - } - - if len(data) != 0 { - return parseError(expectedType) - } - - return nil -} - -// Marshal serializes the message in msg to SSH wire format. The msg -// argument should be a struct or pointer to struct. If the first -// member has the "sshtype" tag set to a number in decimal, that -// number is prepended to the result. If the last of member has the -// "ssh" tag set to "rest", its contents are appended to the output. -func Marshal(msg interface{}) []byte { - out := make([]byte, 0, 64) - return marshalStruct(out, msg) -} - -func marshalStruct(out []byte, msg interface{}) []byte { - v := reflect.Indirect(reflect.ValueOf(msg)) - msgTypes := typeTags(v.Type()) - if len(msgTypes) > 0 { - out = append(out, msgTypes[0]) - } - - for i, n := 0, v.NumField(); i < n; i++ { - field := v.Field(i) - switch t := field.Type(); t.Kind() { - case reflect.Bool: - var v uint8 - if field.Bool() { - v = 1 - } - out = append(out, v) - case reflect.Array: - if t.Elem().Kind() != reflect.Uint8 { - panic(fmt.Sprintf("array of non-uint8 in field %d: %T", i, field.Interface())) - } - for j, l := 0, t.Len(); j < l; j++ { - out = append(out, uint8(field.Index(j).Uint())) - } - case reflect.Uint32: - out = appendU32(out, uint32(field.Uint())) - case reflect.Uint64: - out = appendU64(out, uint64(field.Uint())) - case reflect.Uint8: - out = append(out, uint8(field.Uint())) - case reflect.String: - s := field.String() - out = appendInt(out, len(s)) - out = append(out, s...) - case reflect.Slice: - switch t.Elem().Kind() { - case reflect.Uint8: - if v.Type().Field(i).Tag.Get("ssh") != "rest" { - out = appendInt(out, field.Len()) - } - out = append(out, field.Bytes()...) - case reflect.String: - offset := len(out) - out = appendU32(out, 0) - if n := field.Len(); n > 0 { - for j := 0; j < n; j++ { - f := field.Index(j) - if j != 0 { - out = append(out, ',') - } - out = append(out, f.String()...) - } - // overwrite length value - binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4)) - } - default: - panic(fmt.Sprintf("slice of unknown type in field %d: %T", i, field.Interface())) - } - case reflect.Ptr: - if t == bigIntType { - var n *big.Int - nValue := reflect.ValueOf(&n) - nValue.Elem().Set(field) - needed := intLength(n) - oldLength := len(out) - - if cap(out)-len(out) < needed { - newOut := make([]byte, len(out), 2*(len(out)+needed)) - copy(newOut, out) - out = newOut - } - out = out[:oldLength+needed] - marshalInt(out[oldLength:], n) - } else { - panic(fmt.Sprintf("pointer to unknown type in field %d: %T", i, field.Interface())) - } - } - } - - return out -} - -var bigOne = big.NewInt(1) - -func parseString(in []byte) (out, rest []byte, ok bool) { - if len(in) < 4 { - return - } - length := binary.BigEndian.Uint32(in) - in = in[4:] - if uint32(len(in)) < length { - return - } - out = in[:length] - rest = in[length:] - ok = true - return -} - -var ( - comma = []byte{','} - emptyNameList = []string{} -) - -func parseNameList(in []byte) (out []string, rest []byte, ok bool) { - contents, rest, ok := parseString(in) - if !ok { - return - } - if len(contents) == 0 { - out = emptyNameList - return - } - parts := bytes.Split(contents, comma) - out = make([]string, len(parts)) - for i, part := range parts { - out[i] = string(part) - } - return -} - -func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) { - contents, rest, ok := parseString(in) - if !ok { - return - } - out = new(big.Int) - - if len(contents) > 0 && contents[0]&0x80 == 0x80 { - // This is a negative number - notBytes := make([]byte, len(contents)) - for i := range notBytes { - notBytes[i] = ^contents[i] - } - out.SetBytes(notBytes) - out.Add(out, bigOne) - out.Neg(out) - } else { - // Positive number - out.SetBytes(contents) - } - ok = true - return -} - -func parseUint32(in []byte) (uint32, []byte, bool) { - if len(in) < 4 { - return 0, nil, false - } - return binary.BigEndian.Uint32(in), in[4:], true -} - -func parseUint64(in []byte) (uint64, []byte, bool) { - if len(in) < 8 { - return 0, nil, false - } - return binary.BigEndian.Uint64(in), in[8:], true -} - -func intLength(n *big.Int) int { - length := 4 /* length bytes */ - if n.Sign() < 0 { - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bitLen := nMinus1.BitLen() - if bitLen%8 == 0 { - // The number will need 0xff padding - length++ - } - length += (bitLen + 7) / 8 - } else if n.Sign() == 0 { - // A zero is the zero length string - } else { - bitLen := n.BitLen() - if bitLen%8 == 0 { - // The number will need 0x00 padding - length++ - } - length += (bitLen + 7) / 8 - } - - return length -} - -func marshalUint32(to []byte, n uint32) []byte { - binary.BigEndian.PutUint32(to, n) - return to[4:] -} - -func marshalUint64(to []byte, n uint64) []byte { - binary.BigEndian.PutUint64(to, n) - return to[8:] -} - -func marshalInt(to []byte, n *big.Int) []byte { - lengthBytes := to - to = to[4:] - length := 0 - - if n.Sign() < 0 { - // A negative number has to be converted to two's-complement - // form. So we'll subtract 1 and invert. 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 { - to[0] = 0xff - to = to[1:] - length++ - } - nBytes := copy(to, bytes) - to = to[nBytes:] - length += nBytes - } else if n.Sign() == 0 { - // A zero is the zero length string - } else { - bytes := n.Bytes() - if len(bytes) > 0 && bytes[0]&0x80 != 0 { - // We'll have to pad this with a 0x00 in order to - // stop it looking like a negative number. - to[0] = 0 - to = to[1:] - length++ - } - nBytes := copy(to, bytes) - to = to[nBytes:] - length += nBytes - } - - lengthBytes[0] = byte(length >> 24) - lengthBytes[1] = byte(length >> 16) - lengthBytes[2] = byte(length >> 8) - lengthBytes[3] = byte(length) - return to -} - -func writeInt(w io.Writer, n *big.Int) { - length := intLength(n) - buf := make([]byte, length) - marshalInt(buf, n) - w.Write(buf) -} - -func writeString(w io.Writer, s []byte) { - var lengthBytes [4]byte - lengthBytes[0] = byte(len(s) >> 24) - lengthBytes[1] = byte(len(s) >> 16) - lengthBytes[2] = byte(len(s) >> 8) - lengthBytes[3] = byte(len(s)) - w.Write(lengthBytes[:]) - w.Write(s) -} - -func stringLength(n int) int { - return 4 + n -} - -func marshalString(to []byte, s []byte) []byte { - to[0] = byte(len(s) >> 24) - to[1] = byte(len(s) >> 16) - to[2] = byte(len(s) >> 8) - to[3] = byte(len(s)) - to = to[4:] - copy(to, s) - return to[len(s):] -} - -var bigIntType = reflect.TypeOf((*big.Int)(nil)) - -// Decode a packet into its corresponding message. -func decode(packet []byte) (interface{}, error) { - var msg interface{} - switch packet[0] { - case msgDisconnect: - msg = new(disconnectMsg) - case msgServiceRequest: - msg = new(serviceRequestMsg) - case msgServiceAccept: - msg = new(serviceAcceptMsg) - case msgKexInit: - msg = new(kexInitMsg) - case msgKexDHInit: - msg = new(kexDHInitMsg) - case msgKexDHReply: - msg = new(kexDHReplyMsg) - case msgUserAuthRequest: - msg = new(userAuthRequestMsg) - case msgUserAuthSuccess: - return new(userAuthSuccessMsg), nil - case msgUserAuthFailure: - msg = new(userAuthFailureMsg) - case msgUserAuthPubKeyOk: - msg = new(userAuthPubKeyOkMsg) - case msgGlobalRequest: - msg = new(globalRequestMsg) - case msgRequestSuccess: - msg = new(globalRequestSuccessMsg) - case msgRequestFailure: - msg = new(globalRequestFailureMsg) - case msgChannelOpen: - msg = new(channelOpenMsg) - case msgChannelData: - msg = new(channelDataMsg) - case msgChannelOpenConfirm: - msg = new(channelOpenConfirmMsg) - case msgChannelOpenFailure: - msg = new(channelOpenFailureMsg) - case msgChannelWindowAdjust: - msg = new(windowAdjustMsg) - case msgChannelEOF: - msg = new(channelEOFMsg) - case msgChannelClose: - msg = new(channelCloseMsg) - case msgChannelRequest: - msg = new(channelRequestMsg) - case msgChannelSuccess: - msg = new(channelRequestSuccessMsg) - case msgChannelFailure: - msg = new(channelRequestFailureMsg) - default: - return nil, unexpectedMessageError(0, packet[0]) - } - if err := Unmarshal(packet, msg); err != nil { - return nil, err - } - return msg, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/mux.go b/vendor/golang.org/x/crypto/ssh/mux.go deleted file mode 100644 index f1901627..00000000 --- a/vendor/golang.org/x/crypto/ssh/mux.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "encoding/binary" - "fmt" - "io" - "log" - "sync" - "sync/atomic" -) - -// debugMux, if set, causes messages in the connection protocol to be -// logged. -const debugMux = false - -// chanList is a thread safe channel list. -type chanList struct { - // protects concurrent access to chans - sync.Mutex - - // chans are indexed by the local id of the channel, which the - // other side should send in the PeersId field. - chans []*channel - - // This is a debugging aid: it offsets all IDs by this - // amount. This helps distinguish otherwise identical - // server/client muxes - offset uint32 -} - -// Assigns a channel ID to the given channel. -func (c *chanList) add(ch *channel) uint32 { - c.Lock() - defer c.Unlock() - for i := range c.chans { - if c.chans[i] == nil { - c.chans[i] = ch - return uint32(i) + c.offset - } - } - c.chans = append(c.chans, ch) - return uint32(len(c.chans)-1) + c.offset -} - -// getChan returns the channel for the given ID. -func (c *chanList) getChan(id uint32) *channel { - id -= c.offset - - c.Lock() - defer c.Unlock() - if id < uint32(len(c.chans)) { - return c.chans[id] - } - return nil -} - -func (c *chanList) remove(id uint32) { - id -= c.offset - c.Lock() - if id < uint32(len(c.chans)) { - c.chans[id] = nil - } - c.Unlock() -} - -// dropAll forgets all channels it knows, returning them in a slice. -func (c *chanList) dropAll() []*channel { - c.Lock() - defer c.Unlock() - var r []*channel - - for _, ch := range c.chans { - if ch == nil { - continue - } - r = append(r, ch) - } - c.chans = nil - return r -} - -// mux represents the state for the SSH connection protocol, which -// multiplexes many channels onto a single packet transport. -type mux struct { - conn packetConn - chanList chanList - - incomingChannels chan NewChannel - - globalSentMu sync.Mutex - globalResponses chan interface{} - incomingRequests chan *Request - - errCond *sync.Cond - err error -} - -// When debugging, each new chanList instantiation has a different -// offset. -var globalOff uint32 - -func (m *mux) Wait() error { - m.errCond.L.Lock() - defer m.errCond.L.Unlock() - for m.err == nil { - m.errCond.Wait() - } - return m.err -} - -// newMux returns a mux that runs over the given connection. -func newMux(p packetConn) *mux { - m := &mux{ - conn: p, - incomingChannels: make(chan NewChannel, chanSize), - globalResponses: make(chan interface{}, 1), - incomingRequests: make(chan *Request, chanSize), - errCond: newCond(), - } - if debugMux { - m.chanList.offset = atomic.AddUint32(&globalOff, 1) - } - - go m.loop() - return m -} - -func (m *mux) sendMessage(msg interface{}) error { - p := Marshal(msg) - if debugMux { - log.Printf("send global(%d): %#v", m.chanList.offset, msg) - } - return m.conn.writePacket(p) -} - -func (m *mux) SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) { - if wantReply { - m.globalSentMu.Lock() - defer m.globalSentMu.Unlock() - } - - if err := m.sendMessage(globalRequestMsg{ - Type: name, - WantReply: wantReply, - Data: payload, - }); err != nil { - return false, nil, err - } - - if !wantReply { - return false, nil, nil - } - - msg, ok := <-m.globalResponses - if !ok { - return false, nil, io.EOF - } - switch msg := msg.(type) { - case *globalRequestFailureMsg: - return false, msg.Data, nil - case *globalRequestSuccessMsg: - return true, msg.Data, nil - default: - return false, nil, fmt.Errorf("ssh: unexpected response to request: %#v", msg) - } -} - -// ackRequest must be called after processing a global request that -// has WantReply set. -func (m *mux) ackRequest(ok bool, data []byte) error { - if ok { - return m.sendMessage(globalRequestSuccessMsg{Data: data}) - } - return m.sendMessage(globalRequestFailureMsg{Data: data}) -} - -func (m *mux) Close() error { - return m.conn.Close() -} - -// loop runs the connection machine. It will process packets until an -// error is encountered. To synchronize on loop exit, use mux.Wait. -func (m *mux) loop() { - var err error - for err == nil { - err = m.onePacket() - } - - for _, ch := range m.chanList.dropAll() { - ch.close() - } - - close(m.incomingChannels) - close(m.incomingRequests) - close(m.globalResponses) - - m.conn.Close() - - m.errCond.L.Lock() - m.err = err - m.errCond.Broadcast() - m.errCond.L.Unlock() - - if debugMux { - log.Println("loop exit", err) - } -} - -// onePacket reads and processes one packet. -func (m *mux) onePacket() error { - packet, err := m.conn.readPacket() - if err != nil { - return err - } - - if debugMux { - if packet[0] == msgChannelData || packet[0] == msgChannelExtendedData { - log.Printf("decoding(%d): data packet - %d bytes", m.chanList.offset, len(packet)) - } else { - p, _ := decode(packet) - log.Printf("decoding(%d): %d %#v - %d bytes", m.chanList.offset, packet[0], p, len(packet)) - } - } - - switch packet[0] { - case msgChannelOpen: - return m.handleChannelOpen(packet) - case msgGlobalRequest, msgRequestSuccess, msgRequestFailure: - return m.handleGlobalPacket(packet) - } - - // assume a channel packet. - if len(packet) < 5 { - return parseError(packet[0]) - } - id := binary.BigEndian.Uint32(packet[1:]) - ch := m.chanList.getChan(id) - if ch == nil { - return fmt.Errorf("ssh: invalid channel %d", id) - } - - return ch.handlePacket(packet) -} - -func (m *mux) handleGlobalPacket(packet []byte) error { - msg, err := decode(packet) - if err != nil { - return err - } - - switch msg := msg.(type) { - case *globalRequestMsg: - m.incomingRequests <- &Request{ - Type: msg.Type, - WantReply: msg.WantReply, - Payload: msg.Data, - mux: m, - } - case *globalRequestSuccessMsg, *globalRequestFailureMsg: - m.globalResponses <- msg - default: - panic(fmt.Sprintf("not a global message %#v", msg)) - } - - return nil -} - -// handleChannelOpen schedules a channel to be Accept()ed. -func (m *mux) handleChannelOpen(packet []byte) error { - var msg channelOpenMsg - if err := Unmarshal(packet, &msg); err != nil { - return err - } - - if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { - failMsg := channelOpenFailureMsg{ - PeersID: msg.PeersID, - Reason: ConnectionFailed, - Message: "invalid request", - Language: "en_US.UTF-8", - } - return m.sendMessage(failMsg) - } - - c := m.newChannel(msg.ChanType, channelInbound, msg.TypeSpecificData) - c.remoteId = msg.PeersID - c.maxRemotePayload = msg.MaxPacketSize - c.remoteWin.add(msg.PeersWindow) - m.incomingChannels <- c - return nil -} - -func (m *mux) OpenChannel(chanType string, extra []byte) (Channel, <-chan *Request, error) { - ch, err := m.openChannel(chanType, extra) - if err != nil { - return nil, nil, err - } - - return ch, ch.incomingRequests, nil -} - -func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { - ch := m.newChannel(chanType, channelOutbound, extra) - - ch.maxIncomingPayload = channelMaxPacket - - open := channelOpenMsg{ - ChanType: chanType, - PeersWindow: ch.myWindow, - MaxPacketSize: ch.maxIncomingPayload, - TypeSpecificData: extra, - PeersID: ch.localId, - } - if err := m.sendMessage(open); err != nil { - return nil, err - } - - switch msg := (<-ch.msg).(type) { - case *channelOpenConfirmMsg: - return ch, nil - case *channelOpenFailureMsg: - return nil, &OpenChannelError{msg.Reason, msg.Message} - default: - return nil, fmt.Errorf("ssh: unexpected packet in response to channel open: %T", msg) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go deleted file mode 100644 index e86e8966..00000000 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ /dev/null @@ -1,594 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" - "net" - "strings" -) - -// The Permissions type holds fine-grained permissions that are -// specific to a user or a specific authentication method for a user. -// The Permissions value for a successful authentication attempt is -// available in ServerConn, so it can be used to pass information from -// the user-authentication phase to the application layer. -type Permissions struct { - // CriticalOptions indicate restrictions to the default - // permissions, and are typically used in conjunction with - // user certificates. The standard for SSH certificates - // defines "force-command" (only allow the given command to - // execute) and "source-address" (only allow connections from - // the given address). The SSH package currently only enforces - // the "source-address" critical option. It is up to server - // implementations to enforce other critical options, such as - // "force-command", by checking them after the SSH handshake - // is successful. In general, SSH servers should reject - // connections that specify critical options that are unknown - // or not supported. - CriticalOptions map[string]string - - // Extensions are extra functionality that the server may - // offer on authenticated connections. Lack of support for an - // extension does not preclude authenticating a user. Common - // extensions are "permit-agent-forwarding", - // "permit-X11-forwarding". The Go SSH library currently does - // not act on any extension, and it is up to server - // implementations to honor them. Extensions can be used to - // pass data from the authentication callbacks to the server - // application layer. - Extensions map[string]string -} - -// ServerConfig holds server specific configuration data. -type ServerConfig struct { - // Config contains configuration shared between client and server. - Config - - hostKeys []Signer - - // NoClientAuth is true if clients are allowed to connect without - // authenticating. - NoClientAuth bool - - // MaxAuthTries specifies the maximum number of authentication attempts - // permitted per connection. If set to a negative number, the number of - // attempts are unlimited. If set to zero, the number of attempts are limited - // to 6. - MaxAuthTries int - - // PasswordCallback, if non-nil, is called when a user - // attempts to authenticate using a password. - PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) - - // PublicKeyCallback, if non-nil, is called when a client - // offers a public key for authentication. It must return a nil error - // if the given public key can be used to authenticate the - // given user. For example, see CertChecker.Authenticate. A - // call to this function does not guarantee that the key - // offered is in fact used to authenticate. To record any data - // depending on the public key, store it inside a - // Permissions.Extensions entry. - PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) - - // KeyboardInteractiveCallback, if non-nil, is called when - // keyboard-interactive authentication is selected (RFC - // 4256). The client object's Challenge function should be - // used to query the user. The callback may offer multiple - // Challenge rounds. To avoid information leaks, the client - // should be presented a challenge even if the user is - // unknown. - KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) - - // AuthLogCallback, if non-nil, is called to log all authentication - // attempts. - AuthLogCallback func(conn ConnMetadata, method string, err error) - - // ServerVersion is the version identification string to announce in - // the public handshake. - // If empty, a reasonable default is used. - // Note that RFC 4253 section 4.2 requires that this string start with - // "SSH-2.0-". - ServerVersion string - - // BannerCallback, if present, is called and the return string is sent to - // the client after key exchange completed but before authentication. - BannerCallback func(conn ConnMetadata) string -} - -// AddHostKey adds a private key as a host key. If an existing host -// key exists with the same algorithm, it is overwritten. Each server -// config must have at least one host key. -func (s *ServerConfig) AddHostKey(key Signer) { - for i, k := range s.hostKeys { - if k.PublicKey().Type() == key.PublicKey().Type() { - s.hostKeys[i] = key - return - } - } - - s.hostKeys = append(s.hostKeys, key) -} - -// cachedPubKey contains the results of querying whether a public key is -// acceptable for a user. -type cachedPubKey struct { - user string - pubKeyData []byte - result error - perms *Permissions -} - -const maxCachedPubKeys = 16 - -// pubKeyCache caches tests for public keys. Since SSH clients -// will query whether a public key is acceptable before attempting to -// authenticate with it, we end up with duplicate queries for public -// key validity. The cache only applies to a single ServerConn. -type pubKeyCache struct { - keys []cachedPubKey -} - -// get returns the result for a given user/algo/key tuple. -func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) { - for _, k := range c.keys { - if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) { - return k, true - } - } - return cachedPubKey{}, false -} - -// add adds the given tuple to the cache. -func (c *pubKeyCache) add(candidate cachedPubKey) { - if len(c.keys) < maxCachedPubKeys { - c.keys = append(c.keys, candidate) - } -} - -// ServerConn is an authenticated SSH connection, as seen from the -// server -type ServerConn struct { - Conn - - // If the succeeding authentication callback returned a - // non-nil Permissions pointer, it is stored here. - Permissions *Permissions -} - -// NewServerConn starts a new SSH server with c as the underlying -// transport. It starts with a handshake and, if the handshake is -// unsuccessful, it closes the connection and returns an error. The -// Request and NewChannel channels must be serviced, or the connection -// will hang. -// -// The returned error may be of type *ServerAuthError for -// authentication errors. -func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) { - fullConf := *config - fullConf.SetDefaults() - if fullConf.MaxAuthTries == 0 { - fullConf.MaxAuthTries = 6 - } - - s := &connection{ - sshConn: sshConn{conn: c}, - } - perms, err := s.serverHandshake(&fullConf) - if err != nil { - c.Close() - return nil, nil, nil, err - } - return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil -} - -// signAndMarshal signs the data with the appropriate algorithm, -// and serializes the result in SSH wire format. -func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) { - sig, err := k.Sign(rand, data) - if err != nil { - return nil, err - } - - return Marshal(sig), nil -} - -// handshake performs key exchange and user authentication. -func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) { - if len(config.hostKeys) == 0 { - return nil, errors.New("ssh: server has no host keys") - } - - if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil { - return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") - } - - if config.ServerVersion != "" { - s.serverVersion = []byte(config.ServerVersion) - } else { - s.serverVersion = []byte(packageVersion) - } - var err error - s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion) - if err != nil { - return nil, err - } - - tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */) - s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config) - - if err := s.transport.waitSession(); err != nil { - return nil, err - } - - // We just did the key change, so the session ID is established. - s.sessionID = s.transport.getSessionID() - - var packet []byte - if packet, err = s.transport.readPacket(); err != nil { - return nil, err - } - - var serviceRequest serviceRequestMsg - if err = Unmarshal(packet, &serviceRequest); err != nil { - return nil, err - } - if serviceRequest.Service != serviceUserAuth { - return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating") - } - serviceAccept := serviceAcceptMsg{ - Service: serviceUserAuth, - } - if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil { - return nil, err - } - - perms, err := s.serverAuthenticate(config) - if err != nil { - return nil, err - } - s.mux = newMux(s.transport) - return perms, err -} - -func isAcceptableAlgo(algo string) bool { - switch algo { - case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: - return true - } - return false -} - -func checkSourceAddress(addr net.Addr, sourceAddrs string) error { - if addr == nil { - return errors.New("ssh: no address known for client, but source-address match required") - } - - tcpAddr, ok := addr.(*net.TCPAddr) - if !ok { - return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr) - } - - for _, sourceAddr := range strings.Split(sourceAddrs, ",") { - if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil { - if allowedIP.Equal(tcpAddr.IP) { - return nil - } - } else { - _, ipNet, err := net.ParseCIDR(sourceAddr) - if err != nil { - return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err) - } - - if ipNet.Contains(tcpAddr.IP) { - return nil - } - } - } - - return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr) -} - -// ServerAuthError represents server authentication errors and is -// sometimes returned by NewServerConn. It appends any authentication -// errors that may occur, and is returned if all of the authentication -// methods provided by the user failed to authenticate. -type ServerAuthError struct { - // Errors contains authentication errors returned by the authentication - // callback methods. The first entry is typically ErrNoAuth. - Errors []error -} - -func (l ServerAuthError) Error() string { - var errs []string - for _, err := range l.Errors { - errs = append(errs, err.Error()) - } - return "[" + strings.Join(errs, ", ") + "]" -} - -// ErrNoAuth is the error value returned if no -// authentication method has been passed yet. This happens as a normal -// part of the authentication loop, since the client first tries -// 'none' authentication to discover available methods. -// It is returned in ServerAuthError.Errors from NewServerConn. -var ErrNoAuth = errors.New("ssh: no auth passed yet") - -func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) { - sessionID := s.transport.getSessionID() - var cache pubKeyCache - var perms *Permissions - - authFailures := 0 - var authErrs []error - var displayedBanner bool - -userAuthLoop: - for { - if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 { - discMsg := &disconnectMsg{ - Reason: 2, - Message: "too many authentication failures", - } - - if err := s.transport.writePacket(Marshal(discMsg)); err != nil { - return nil, err - } - - return nil, discMsg - } - - var userAuthReq userAuthRequestMsg - if packet, err := s.transport.readPacket(); err != nil { - if err == io.EOF { - return nil, &ServerAuthError{Errors: authErrs} - } - return nil, err - } else if err = Unmarshal(packet, &userAuthReq); err != nil { - return nil, err - } - - if userAuthReq.Service != serviceSSH { - return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) - } - - s.user = userAuthReq.User - - if !displayedBanner && config.BannerCallback != nil { - displayedBanner = true - msg := config.BannerCallback(s) - if msg != "" { - bannerMsg := &userAuthBannerMsg{ - Message: msg, - } - if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil { - return nil, err - } - } - } - - perms = nil - authErr := ErrNoAuth - - switch userAuthReq.Method { - case "none": - if config.NoClientAuth { - authErr = nil - } - - // allow initial attempt of 'none' without penalty - if authFailures == 0 { - authFailures-- - } - case "password": - if config.PasswordCallback == nil { - authErr = errors.New("ssh: password auth not configured") - break - } - payload := userAuthReq.Payload - if len(payload) < 1 || payload[0] != 0 { - return nil, parseError(msgUserAuthRequest) - } - payload = payload[1:] - password, payload, ok := parseString(payload) - if !ok || len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - - perms, authErr = config.PasswordCallback(s, password) - case "keyboard-interactive": - if config.KeyboardInteractiveCallback == nil { - authErr = errors.New("ssh: keyboard-interactive auth not configured") - break - } - - prompter := &sshClientKeyboardInteractive{s} - perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge) - case "publickey": - if config.PublicKeyCallback == nil { - authErr = errors.New("ssh: publickey auth not configured") - break - } - payload := userAuthReq.Payload - if len(payload) < 1 { - return nil, parseError(msgUserAuthRequest) - } - isQuery := payload[0] == 0 - payload = payload[1:] - algoBytes, payload, ok := parseString(payload) - if !ok { - return nil, parseError(msgUserAuthRequest) - } - algo := string(algoBytes) - if !isAcceptableAlgo(algo) { - authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo) - break - } - - pubKeyData, payload, ok := parseString(payload) - if !ok { - return nil, parseError(msgUserAuthRequest) - } - - pubKey, err := ParsePublicKey(pubKeyData) - if err != nil { - return nil, err - } - - candidate, ok := cache.get(s.user, pubKeyData) - if !ok { - candidate.user = s.user - candidate.pubKeyData = pubKeyData - candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey) - if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" { - candidate.result = checkSourceAddress( - s.RemoteAddr(), - candidate.perms.CriticalOptions[sourceAddressCriticalOption]) - } - cache.add(candidate) - } - - if isQuery { - // The client can query if the given public key - // would be okay. - - if len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - - if candidate.result == nil { - okMsg := userAuthPubKeyOkMsg{ - Algo: algo, - PubKey: pubKeyData, - } - if err = s.transport.writePacket(Marshal(&okMsg)); err != nil { - return nil, err - } - continue userAuthLoop - } - authErr = candidate.result - } else { - sig, payload, ok := parseSignature(payload) - if !ok || len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - // Ensure the public key algo and signature algo - // are supported. Compare the private key - // algorithm name that corresponds to algo with - // sig.Format. This is usually the same, but - // for certs, the names differ. - if !isAcceptableAlgo(sig.Format) { - authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format) - break - } - signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData) - - if err := pubKey.Verify(signedData, sig); err != nil { - return nil, err - } - - authErr = candidate.result - perms = candidate.perms - } - default: - authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method) - } - - authErrs = append(authErrs, authErr) - - if config.AuthLogCallback != nil { - config.AuthLogCallback(s, userAuthReq.Method, authErr) - } - - if authErr == nil { - break userAuthLoop - } - - authFailures++ - - var failureMsg userAuthFailureMsg - if config.PasswordCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "password") - } - if config.PublicKeyCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "publickey") - } - if config.KeyboardInteractiveCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive") - } - - if len(failureMsg.Methods) == 0 { - return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") - } - - if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil { - return nil, err - } - } - - if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil { - return nil, err - } - return perms, nil -} - -// sshClientKeyboardInteractive implements a ClientKeyboardInteractive by -// asking the client on the other side of a ServerConn. -type sshClientKeyboardInteractive struct { - *connection -} - -func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) { - if len(questions) != len(echos) { - return nil, errors.New("ssh: echos and questions must have equal length") - } - - var prompts []byte - for i := range questions { - prompts = appendString(prompts, questions[i]) - prompts = appendBool(prompts, echos[i]) - } - - if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{ - Instruction: instruction, - NumPrompts: uint32(len(questions)), - Prompts: prompts, - })); err != nil { - return nil, err - } - - packet, err := c.transport.readPacket() - if err != nil { - return nil, err - } - if packet[0] != msgUserAuthInfoResponse { - return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0]) - } - packet = packet[1:] - - n, packet, ok := parseUint32(packet) - if !ok || int(n) != len(questions) { - return nil, parseError(msgUserAuthInfoResponse) - } - - for i := uint32(0); i < n; i++ { - ans, rest, ok := parseString(packet) - if !ok { - return nil, parseError(msgUserAuthInfoResponse) - } - - answers = append(answers, string(ans)) - packet = rest - } - if len(packet) != 0 { - return nil, errors.New("ssh: junk at end of message") - } - - return answers, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/session.go b/vendor/golang.org/x/crypto/ssh/session.go deleted file mode 100644 index d3321f6b..00000000 --- a/vendor/golang.org/x/crypto/ssh/session.go +++ /dev/null @@ -1,647 +0,0 @@ -// Copyright 2011 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 ssh - -// Session implements an interactive session described in -// "RFC 4254, section 6". - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "sync" -) - -type Signal string - -// POSIX signals as listed in RFC 4254 Section 6.10. -const ( - SIGABRT Signal = "ABRT" - SIGALRM Signal = "ALRM" - SIGFPE Signal = "FPE" - SIGHUP Signal = "HUP" - SIGILL Signal = "ILL" - SIGINT Signal = "INT" - SIGKILL Signal = "KILL" - SIGPIPE Signal = "PIPE" - SIGQUIT Signal = "QUIT" - SIGSEGV Signal = "SEGV" - SIGTERM Signal = "TERM" - SIGUSR1 Signal = "USR1" - SIGUSR2 Signal = "USR2" -) - -var signals = map[Signal]int{ - SIGABRT: 6, - SIGALRM: 14, - SIGFPE: 8, - SIGHUP: 1, - SIGILL: 4, - SIGINT: 2, - SIGKILL: 9, - SIGPIPE: 13, - SIGQUIT: 3, - SIGSEGV: 11, - SIGTERM: 15, -} - -type TerminalModes map[uint8]uint32 - -// POSIX terminal mode flags as listed in RFC 4254 Section 8. -const ( - tty_OP_END = 0 - VINTR = 1 - VQUIT = 2 - VERASE = 3 - VKILL = 4 - VEOF = 5 - VEOL = 6 - VEOL2 = 7 - VSTART = 8 - VSTOP = 9 - VSUSP = 10 - VDSUSP = 11 - VREPRINT = 12 - VWERASE = 13 - VLNEXT = 14 - VFLUSH = 15 - VSWTCH = 16 - VSTATUS = 17 - VDISCARD = 18 - IGNPAR = 30 - PARMRK = 31 - INPCK = 32 - ISTRIP = 33 - INLCR = 34 - IGNCR = 35 - ICRNL = 36 - IUCLC = 37 - IXON = 38 - IXANY = 39 - IXOFF = 40 - IMAXBEL = 41 - ISIG = 50 - ICANON = 51 - XCASE = 52 - ECHO = 53 - ECHOE = 54 - ECHOK = 55 - ECHONL = 56 - NOFLSH = 57 - TOSTOP = 58 - IEXTEN = 59 - ECHOCTL = 60 - ECHOKE = 61 - PENDIN = 62 - OPOST = 70 - OLCUC = 71 - ONLCR = 72 - OCRNL = 73 - ONOCR = 74 - ONLRET = 75 - CS7 = 90 - CS8 = 91 - PARENB = 92 - PARODD = 93 - TTY_OP_ISPEED = 128 - TTY_OP_OSPEED = 129 -) - -// A Session represents a connection to a remote command or shell. -type Session struct { - // Stdin specifies the remote process's standard input. - // If Stdin is nil, the remote process reads from an empty - // bytes.Buffer. - Stdin io.Reader - - // Stdout and Stderr specify the remote process's standard - // output and error. - // - // If either is nil, Run connects the corresponding file - // descriptor to an instance of ioutil.Discard. There is a - // fixed amount of buffering that is shared for the two streams. - // If either blocks it may eventually cause the remote - // command to block. - Stdout io.Writer - Stderr io.Writer - - ch Channel // the channel backing this session - started bool // true once Start, Run or Shell is invoked. - copyFuncs []func() error - errors chan error // one send per copyFunc - - // true if pipe method is active - stdinpipe, stdoutpipe, stderrpipe bool - - // stdinPipeWriter is non-nil if StdinPipe has not been called - // and Stdin was specified by the user; it is the write end of - // a pipe connecting Session.Stdin to the stdin channel. - stdinPipeWriter io.WriteCloser - - exitStatus chan error -} - -// SendRequest sends an out-of-band channel request on the SSH channel -// underlying the session. -func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { - return s.ch.SendRequest(name, wantReply, payload) -} - -func (s *Session) Close() error { - return s.ch.Close() -} - -// RFC 4254 Section 6.4. -type setenvRequest struct { - Name string - Value string -} - -// Setenv sets an environment variable that will be applied to any -// command executed by Shell or Run. -func (s *Session) Setenv(name, value string) error { - msg := setenvRequest{ - Name: name, - Value: value, - } - ok, err := s.ch.SendRequest("env", true, Marshal(&msg)) - if err == nil && !ok { - err = errors.New("ssh: setenv failed") - } - return err -} - -// RFC 4254 Section 6.2. -type ptyRequestMsg struct { - Term string - Columns uint32 - Rows uint32 - Width uint32 - Height uint32 - Modelist string -} - -// RequestPty requests the association of a pty with the session on the remote host. -func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error { - var tm []byte - for k, v := range termmodes { - kv := struct { - Key byte - Val uint32 - }{k, v} - - tm = append(tm, Marshal(&kv)...) - } - tm = append(tm, tty_OP_END) - req := ptyRequestMsg{ - Term: term, - Columns: uint32(w), - Rows: uint32(h), - Width: uint32(w * 8), - Height: uint32(h * 8), - Modelist: string(tm), - } - ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req)) - if err == nil && !ok { - err = errors.New("ssh: pty-req failed") - } - return err -} - -// RFC 4254 Section 6.5. -type subsystemRequestMsg struct { - Subsystem string -} - -// RequestSubsystem requests the association of a subsystem with the session on the remote host. -// A subsystem is a predefined command that runs in the background when the ssh session is initiated -func (s *Session) RequestSubsystem(subsystem string) error { - msg := subsystemRequestMsg{ - Subsystem: subsystem, - } - ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg)) - if err == nil && !ok { - err = errors.New("ssh: subsystem request failed") - } - return err -} - -// RFC 4254 Section 6.7. -type ptyWindowChangeMsg struct { - Columns uint32 - Rows uint32 - Width uint32 - Height uint32 -} - -// WindowChange informs the remote host about a terminal window dimension change to h rows and w columns. -func (s *Session) WindowChange(h, w int) error { - req := ptyWindowChangeMsg{ - Columns: uint32(w), - Rows: uint32(h), - Width: uint32(w * 8), - Height: uint32(h * 8), - } - _, err := s.ch.SendRequest("window-change", false, Marshal(&req)) - return err -} - -// RFC 4254 Section 6.9. -type signalMsg struct { - Signal string -} - -// Signal sends the given signal to the remote process. -// sig is one of the SIG* constants. -func (s *Session) Signal(sig Signal) error { - msg := signalMsg{ - Signal: string(sig), - } - - _, err := s.ch.SendRequest("signal", false, Marshal(&msg)) - return err -} - -// RFC 4254 Section 6.5. -type execMsg struct { - Command string -} - -// Start runs cmd on the remote host. Typically, the remote -// server passes cmd to the shell for interpretation. -// A Session only accepts one call to Run, Start or Shell. -func (s *Session) Start(cmd string) error { - if s.started { - return errors.New("ssh: session already started") - } - req := execMsg{ - Command: cmd, - } - - ok, err := s.ch.SendRequest("exec", true, Marshal(&req)) - if err == nil && !ok { - err = fmt.Errorf("ssh: command %v failed", cmd) - } - if err != nil { - return err - } - return s.start() -} - -// Run runs cmd on the remote host. Typically, the remote -// server passes cmd to the shell for interpretation. -// A Session only accepts one call to Run, Start, Shell, Output, -// or CombinedOutput. -// -// The returned error is nil if the command runs, has no problems -// copying stdin, stdout, and stderr, and exits with a zero exit -// status. -// -// If the remote server does not send an exit status, an error of type -// *ExitMissingError is returned. If the command completes -// unsuccessfully or is interrupted by a signal, the error is of type -// *ExitError. Other error types may be returned for I/O problems. -func (s *Session) Run(cmd string) error { - err := s.Start(cmd) - if err != nil { - return err - } - return s.Wait() -} - -// Output runs cmd on the remote host and returns its standard output. -func (s *Session) Output(cmd string) ([]byte, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - var b bytes.Buffer - s.Stdout = &b - err := s.Run(cmd) - return b.Bytes(), err -} - -type singleWriter struct { - b bytes.Buffer - mu sync.Mutex -} - -func (w *singleWriter) Write(p []byte) (int, error) { - w.mu.Lock() - defer w.mu.Unlock() - return w.b.Write(p) -} - -// CombinedOutput runs cmd on the remote host and returns its combined -// standard output and standard error. -func (s *Session) CombinedOutput(cmd string) ([]byte, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - if s.Stderr != nil { - return nil, errors.New("ssh: Stderr already set") - } - var b singleWriter - s.Stdout = &b - s.Stderr = &b - err := s.Run(cmd) - return b.b.Bytes(), err -} - -// Shell starts a login shell on the remote host. A Session only -// accepts one call to Run, Start, Shell, Output, or CombinedOutput. -func (s *Session) Shell() error { - if s.started { - return errors.New("ssh: session already started") - } - - ok, err := s.ch.SendRequest("shell", true, nil) - if err == nil && !ok { - return errors.New("ssh: could not start shell") - } - if err != nil { - return err - } - return s.start() -} - -func (s *Session) start() error { - s.started = true - - type F func(*Session) - for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} { - setupFd(s) - } - - s.errors = make(chan error, len(s.copyFuncs)) - for _, fn := range s.copyFuncs { - go func(fn func() error) { - s.errors <- fn() - }(fn) - } - return nil -} - -// Wait waits for the remote command to exit. -// -// The returned error is nil if the command runs, has no problems -// copying stdin, stdout, and stderr, and exits with a zero exit -// status. -// -// If the remote server does not send an exit status, an error of type -// *ExitMissingError is returned. If the command completes -// unsuccessfully or is interrupted by a signal, the error is of type -// *ExitError. Other error types may be returned for I/O problems. -func (s *Session) Wait() error { - if !s.started { - return errors.New("ssh: session not started") - } - waitErr := <-s.exitStatus - - if s.stdinPipeWriter != nil { - s.stdinPipeWriter.Close() - } - var copyError error - for range s.copyFuncs { - if err := <-s.errors; err != nil && copyError == nil { - copyError = err - } - } - if waitErr != nil { - return waitErr - } - return copyError -} - -func (s *Session) wait(reqs <-chan *Request) error { - wm := Waitmsg{status: -1} - // Wait for msg channel to be closed before returning. - for msg := range reqs { - switch msg.Type { - case "exit-status": - wm.status = int(binary.BigEndian.Uint32(msg.Payload)) - case "exit-signal": - var sigval struct { - Signal string - CoreDumped bool - Error string - Lang string - } - if err := Unmarshal(msg.Payload, &sigval); err != nil { - return err - } - - // Must sanitize strings? - wm.signal = sigval.Signal - wm.msg = sigval.Error - wm.lang = sigval.Lang - default: - // This handles keepalives and matches - // OpenSSH's behaviour. - if msg.WantReply { - msg.Reply(false, nil) - } - } - } - if wm.status == 0 { - return nil - } - if wm.status == -1 { - // exit-status was never sent from server - if wm.signal == "" { - // signal was not sent either. RFC 4254 - // section 6.10 recommends against this - // behavior, but it is allowed, so we let - // clients handle it. - return &ExitMissingError{} - } - wm.status = 128 - if _, ok := signals[Signal(wm.signal)]; ok { - wm.status += signals[Signal(wm.signal)] - } - } - - return &ExitError{wm} -} - -// ExitMissingError is returned if a session is torn down cleanly, but -// the server sends no confirmation of the exit status. -type ExitMissingError struct{} - -func (e *ExitMissingError) Error() string { - return "wait: remote command exited without exit status or exit signal" -} - -func (s *Session) stdin() { - if s.stdinpipe { - return - } - var stdin io.Reader - if s.Stdin == nil { - stdin = new(bytes.Buffer) - } else { - r, w := io.Pipe() - go func() { - _, err := io.Copy(w, s.Stdin) - w.CloseWithError(err) - }() - stdin, s.stdinPipeWriter = r, w - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.ch, stdin) - if err1 := s.ch.CloseWrite(); err == nil && err1 != io.EOF { - err = err1 - } - return err - }) -} - -func (s *Session) stdout() { - if s.stdoutpipe { - return - } - if s.Stdout == nil { - s.Stdout = ioutil.Discard - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.Stdout, s.ch) - return err - }) -} - -func (s *Session) stderr() { - if s.stderrpipe { - return - } - if s.Stderr == nil { - s.Stderr = ioutil.Discard - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.Stderr, s.ch.Stderr()) - return err - }) -} - -// sessionStdin reroutes Close to CloseWrite. -type sessionStdin struct { - io.Writer - ch Channel -} - -func (s *sessionStdin) Close() error { - return s.ch.CloseWrite() -} - -// StdinPipe returns a pipe that will be connected to the -// remote command's standard input when the command starts. -func (s *Session) StdinPipe() (io.WriteCloser, error) { - if s.Stdin != nil { - return nil, errors.New("ssh: Stdin already set") - } - if s.started { - return nil, errors.New("ssh: StdinPipe after process started") - } - s.stdinpipe = true - return &sessionStdin{s.ch, s.ch}, nil -} - -// StdoutPipe returns a pipe that will be connected to the -// remote command's standard output when the command starts. -// There is a fixed amount of buffering that is shared between -// stdout and stderr streams. If the StdoutPipe reader is -// not serviced fast enough it may eventually cause the -// remote command to block. -func (s *Session) StdoutPipe() (io.Reader, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - if s.started { - return nil, errors.New("ssh: StdoutPipe after process started") - } - s.stdoutpipe = true - return s.ch, nil -} - -// StderrPipe returns a pipe that will be connected to the -// remote command's standard error when the command starts. -// There is a fixed amount of buffering that is shared between -// stdout and stderr streams. If the StderrPipe reader is -// not serviced fast enough it may eventually cause the -// remote command to block. -func (s *Session) StderrPipe() (io.Reader, error) { - if s.Stderr != nil { - return nil, errors.New("ssh: Stderr already set") - } - if s.started { - return nil, errors.New("ssh: StderrPipe after process started") - } - s.stderrpipe = true - return s.ch.Stderr(), nil -} - -// newSession returns a new interactive session on the remote host. -func newSession(ch Channel, reqs <-chan *Request) (*Session, error) { - s := &Session{ - ch: ch, - } - s.exitStatus = make(chan error, 1) - go func() { - s.exitStatus <- s.wait(reqs) - }() - - return s, nil -} - -// An ExitError reports unsuccessful completion of a remote command. -type ExitError struct { - Waitmsg -} - -func (e *ExitError) Error() string { - return e.Waitmsg.String() -} - -// Waitmsg stores the information about an exited remote command -// as reported by Wait. -type Waitmsg struct { - status int - signal string - msg string - lang string -} - -// ExitStatus returns the exit status of the remote command. -func (w Waitmsg) ExitStatus() int { - return w.status -} - -// Signal returns the exit signal of the remote command if -// it was terminated violently. -func (w Waitmsg) Signal() string { - return w.signal -} - -// Msg returns the exit message given by the remote command -func (w Waitmsg) Msg() string { - return w.msg -} - -// Lang returns the language tag. See RFC 3066 -func (w Waitmsg) Lang() string { - return w.lang -} - -func (w Waitmsg) String() string { - str := fmt.Sprintf("Process exited with status %v", w.status) - if w.signal != "" { - str += fmt.Sprintf(" from signal %v", w.signal) - } - if w.msg != "" { - str += fmt.Sprintf(". Reason was: %v", w.msg) - } - return str -} diff --git a/vendor/golang.org/x/crypto/ssh/streamlocal.go b/vendor/golang.org/x/crypto/ssh/streamlocal.go deleted file mode 100644 index b171b330..00000000 --- a/vendor/golang.org/x/crypto/ssh/streamlocal.go +++ /dev/null @@ -1,116 +0,0 @@ -package ssh - -import ( - "errors" - "io" - "net" -) - -// streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message -// with "direct-streamlocal@openssh.com" string. -// -// See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding -// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235 -type streamLocalChannelOpenDirectMsg struct { - socketPath string - reserved0 string - reserved1 uint32 -} - -// forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message -// with "forwarded-streamlocal@openssh.com" string. -type forwardedStreamLocalPayload struct { - SocketPath string - Reserved0 string -} - -// streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message -// with "streamlocal-forward@openssh.com"/"cancel-streamlocal-forward@openssh.com" string. -type streamLocalChannelForwardMsg struct { - socketPath string -} - -// ListenUnix is similar to ListenTCP but uses a Unix domain socket. -func (c *Client) ListenUnix(socketPath string) (net.Listener, error) { - c.handleForwardsOnce.Do(c.handleForwards) - m := streamLocalChannelForwardMsg{ - socketPath, - } - // send message - ok, _, err := c.SendRequest("streamlocal-forward@openssh.com", true, Marshal(&m)) - if err != nil { - return nil, err - } - if !ok { - return nil, errors.New("ssh: streamlocal-forward@openssh.com request denied by peer") - } - ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"}) - - return &unixListener{socketPath, c, ch}, nil -} - -func (c *Client) dialStreamLocal(socketPath string) (Channel, error) { - msg := streamLocalChannelOpenDirectMsg{ - socketPath: socketPath, - } - ch, in, err := c.OpenChannel("direct-streamlocal@openssh.com", Marshal(&msg)) - if err != nil { - return nil, err - } - go DiscardRequests(in) - return ch, err -} - -type unixListener struct { - socketPath string - - conn *Client - in <-chan forward -} - -// Accept waits for and returns the next connection to the listener. -func (l *unixListener) Accept() (net.Conn, error) { - s, ok := <-l.in - if !ok { - return nil, io.EOF - } - ch, incoming, err := s.newCh.Accept() - if err != nil { - return nil, err - } - go DiscardRequests(incoming) - - return &chanConn{ - Channel: ch, - laddr: &net.UnixAddr{ - Name: l.socketPath, - Net: "unix", - }, - raddr: &net.UnixAddr{ - Name: "@", - Net: "unix", - }, - }, nil -} - -// Close closes the listener. -func (l *unixListener) Close() error { - // this also closes the listener. - l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"}) - m := streamLocalChannelForwardMsg{ - l.socketPath, - } - ok, _, err := l.conn.SendRequest("cancel-streamlocal-forward@openssh.com", true, Marshal(&m)) - if err == nil && !ok { - err = errors.New("ssh: cancel-streamlocal-forward@openssh.com failed") - } - return err -} - -// Addr returns the listener's network address. -func (l *unixListener) Addr() net.Addr { - return &net.UnixAddr{ - Name: l.socketPath, - Net: "unix", - } -} diff --git a/vendor/golang.org/x/crypto/ssh/tcpip.go b/vendor/golang.org/x/crypto/ssh/tcpip.go deleted file mode 100644 index 80d35f5e..00000000 --- a/vendor/golang.org/x/crypto/ssh/tcpip.go +++ /dev/null @@ -1,474 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "errors" - "fmt" - "io" - "math/rand" - "net" - "strconv" - "strings" - "sync" - "time" -) - -// Listen requests the remote peer open a listening socket on -// addr. Incoming connections will be available by calling Accept on -// the returned net.Listener. The listener must be serviced, or the -// SSH connection may hang. -// N must be "tcp", "tcp4", "tcp6", or "unix". -func (c *Client) Listen(n, addr string) (net.Listener, error) { - switch n { - case "tcp", "tcp4", "tcp6": - laddr, err := net.ResolveTCPAddr(n, addr) - if err != nil { - return nil, err - } - return c.ListenTCP(laddr) - case "unix": - return c.ListenUnix(addr) - default: - return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) - } -} - -// Automatic port allocation is broken with OpenSSH before 6.0. See -// also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In -// particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0, -// rather than the actual port number. This means you can never open -// two different listeners with auto allocated ports. We work around -// this by trying explicit ports until we succeed. - -const openSSHPrefix = "OpenSSH_" - -var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano())) - -// isBrokenOpenSSHVersion returns true if the given version string -// specifies a version of OpenSSH that is known to have a bug in port -// forwarding. -func isBrokenOpenSSHVersion(versionStr string) bool { - i := strings.Index(versionStr, openSSHPrefix) - if i < 0 { - return false - } - i += len(openSSHPrefix) - j := i - for ; j < len(versionStr); j++ { - if versionStr[j] < '0' || versionStr[j] > '9' { - break - } - } - version, _ := strconv.Atoi(versionStr[i:j]) - return version < 6 -} - -// autoPortListenWorkaround simulates automatic port allocation by -// trying random ports repeatedly. -func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) { - var sshListener net.Listener - var err error - const tries = 10 - for i := 0; i < tries; i++ { - addr := *laddr - addr.Port = 1024 + portRandomizer.Intn(60000) - sshListener, err = c.ListenTCP(&addr) - if err == nil { - laddr.Port = addr.Port - return sshListener, err - } - } - return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err) -} - -// RFC 4254 7.1 -type channelForwardMsg struct { - addr string - rport uint32 -} - -// handleForwards starts goroutines handling forwarded connections. -// It's called on first use by (*Client).ListenTCP to not launch -// goroutines until needed. -func (c *Client) handleForwards() { - go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-tcpip")) - go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-streamlocal@openssh.com")) -} - -// ListenTCP requests the remote peer open a listening socket -// on laddr. Incoming connections will be available by calling -// Accept on the returned net.Listener. -func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { - c.handleForwardsOnce.Do(c.handleForwards) - if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { - return c.autoPortListenWorkaround(laddr) - } - - m := channelForwardMsg{ - laddr.IP.String(), - uint32(laddr.Port), - } - // send message - ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m)) - if err != nil { - return nil, err - } - if !ok { - return nil, errors.New("ssh: tcpip-forward request denied by peer") - } - - // If the original port was 0, then the remote side will - // supply a real port number in the response. - if laddr.Port == 0 { - var p struct { - Port uint32 - } - if err := Unmarshal(resp, &p); err != nil { - return nil, err - } - laddr.Port = int(p.Port) - } - - // Register this forward, using the port number we obtained. - ch := c.forwards.add(laddr) - - return &tcpListener{laddr, c, ch}, nil -} - -// forwardList stores a mapping between remote -// forward requests and the tcpListeners. -type forwardList struct { - sync.Mutex - entries []forwardEntry -} - -// forwardEntry represents an established mapping of a laddr on a -// remote ssh server to a channel connected to a tcpListener. -type forwardEntry struct { - laddr net.Addr - c chan forward -} - -// forward represents an incoming forwarded tcpip connection. The -// arguments to add/remove/lookup should be address as specified in -// the original forward-request. -type forward struct { - newCh NewChannel // the ssh client channel underlying this forward - raddr net.Addr // the raddr of the incoming connection -} - -func (l *forwardList) add(addr net.Addr) chan forward { - l.Lock() - defer l.Unlock() - f := forwardEntry{ - laddr: addr, - c: make(chan forward, 1), - } - l.entries = append(l.entries, f) - return f.c -} - -// See RFC 4254, section 7.2 -type forwardedTCPPayload struct { - Addr string - Port uint32 - OriginAddr string - OriginPort uint32 -} - -// parseTCPAddr parses the originating address from the remote into a *net.TCPAddr. -func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) { - if port == 0 || port > 65535 { - return nil, fmt.Errorf("ssh: port number out of range: %d", port) - } - ip := net.ParseIP(string(addr)) - if ip == nil { - return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr) - } - return &net.TCPAddr{IP: ip, Port: int(port)}, nil -} - -func (l *forwardList) handleChannels(in <-chan NewChannel) { - for ch := range in { - var ( - laddr net.Addr - raddr net.Addr - err error - ) - switch channelType := ch.ChannelType(); channelType { - case "forwarded-tcpip": - var payload forwardedTCPPayload - if err = Unmarshal(ch.ExtraData(), &payload); err != nil { - ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) - continue - } - - // RFC 4254 section 7.2 specifies that incoming - // addresses should list the address, in string - // format. It is implied that this should be an IP - // address, as it would be impossible to connect to it - // otherwise. - laddr, err = parseTCPAddr(payload.Addr, payload.Port) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue - } - raddr, err = parseTCPAddr(payload.OriginAddr, payload.OriginPort) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue - } - - case "forwarded-streamlocal@openssh.com": - var payload forwardedStreamLocalPayload - if err = Unmarshal(ch.ExtraData(), &payload); err != nil { - ch.Reject(ConnectionFailed, "could not parse forwarded-streamlocal@openssh.com payload: "+err.Error()) - continue - } - laddr = &net.UnixAddr{ - Name: payload.SocketPath, - Net: "unix", - } - raddr = &net.UnixAddr{ - Name: "@", - Net: "unix", - } - default: - panic(fmt.Errorf("ssh: unknown channel type %s", channelType)) - } - if ok := l.forward(laddr, raddr, ch); !ok { - // Section 7.2, implementations MUST reject spurious incoming - // connections. - ch.Reject(Prohibited, "no forward for address") - continue - } - - } -} - -// remove removes the forward entry, and the channel feeding its -// listener. -func (l *forwardList) remove(addr net.Addr) { - l.Lock() - defer l.Unlock() - for i, f := range l.entries { - if addr.Network() == f.laddr.Network() && addr.String() == f.laddr.String() { - l.entries = append(l.entries[:i], l.entries[i+1:]...) - close(f.c) - return - } - } -} - -// closeAll closes and clears all forwards. -func (l *forwardList) closeAll() { - l.Lock() - defer l.Unlock() - for _, f := range l.entries { - close(f.c) - } - l.entries = nil -} - -func (l *forwardList) forward(laddr, raddr net.Addr, ch NewChannel) bool { - l.Lock() - defer l.Unlock() - for _, f := range l.entries { - if laddr.Network() == f.laddr.Network() && laddr.String() == f.laddr.String() { - f.c <- forward{newCh: ch, raddr: raddr} - return true - } - } - return false -} - -type tcpListener struct { - laddr *net.TCPAddr - - conn *Client - in <-chan forward -} - -// Accept waits for and returns the next connection to the listener. -func (l *tcpListener) Accept() (net.Conn, error) { - s, ok := <-l.in - if !ok { - return nil, io.EOF - } - ch, incoming, err := s.newCh.Accept() - if err != nil { - return nil, err - } - go DiscardRequests(incoming) - - return &chanConn{ - Channel: ch, - laddr: l.laddr, - raddr: s.raddr, - }, nil -} - -// Close closes the listener. -func (l *tcpListener) Close() error { - m := channelForwardMsg{ - l.laddr.IP.String(), - uint32(l.laddr.Port), - } - - // this also closes the listener. - l.conn.forwards.remove(l.laddr) - ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m)) - if err == nil && !ok { - err = errors.New("ssh: cancel-tcpip-forward failed") - } - return err -} - -// Addr returns the listener's network address. -func (l *tcpListener) Addr() net.Addr { - return l.laddr -} - -// Dial initiates a connection to the addr from the remote host. -// The resulting connection has a zero LocalAddr() and RemoteAddr(). -func (c *Client) Dial(n, addr string) (net.Conn, error) { - var ch Channel - switch n { - case "tcp", "tcp4", "tcp6": - // Parse the address into host and numeric port. - host, portString, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - port, err := strconv.ParseUint(portString, 10, 16) - if err != nil { - return nil, err - } - ch, err = c.dial(net.IPv4zero.String(), 0, host, int(port)) - if err != nil { - return nil, err - } - // Use a zero address for local and remote address. - zeroAddr := &net.TCPAddr{ - IP: net.IPv4zero, - Port: 0, - } - return &chanConn{ - Channel: ch, - laddr: zeroAddr, - raddr: zeroAddr, - }, nil - case "unix": - var err error - ch, err = c.dialStreamLocal(addr) - if err != nil { - return nil, err - } - return &chanConn{ - Channel: ch, - laddr: &net.UnixAddr{ - Name: "@", - Net: "unix", - }, - raddr: &net.UnixAddr{ - Name: addr, - Net: "unix", - }, - }, nil - default: - return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) - } -} - -// DialTCP connects to the remote address raddr on the network net, -// which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used -// as the local address for the connection. -func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) { - if laddr == nil { - laddr = &net.TCPAddr{ - IP: net.IPv4zero, - Port: 0, - } - } - ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port) - if err != nil { - return nil, err - } - return &chanConn{ - Channel: ch, - laddr: laddr, - raddr: raddr, - }, nil -} - -// RFC 4254 7.2 -type channelOpenDirectMsg struct { - raddr string - rport uint32 - laddr string - lport uint32 -} - -func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) { - msg := channelOpenDirectMsg{ - raddr: raddr, - rport: uint32(rport), - laddr: laddr, - lport: uint32(lport), - } - ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg)) - if err != nil { - return nil, err - } - go DiscardRequests(in) - return ch, err -} - -type tcpChan struct { - Channel // the backing channel -} - -// chanConn fulfills the net.Conn interface without -// the tcpChan having to hold laddr or raddr directly. -type chanConn struct { - Channel - laddr, raddr net.Addr -} - -// LocalAddr returns the local network address. -func (t *chanConn) LocalAddr() net.Addr { - return t.laddr -} - -// RemoteAddr returns the remote network address. -func (t *chanConn) RemoteAddr() net.Addr { - return t.raddr -} - -// SetDeadline sets the read and write deadlines associated -// with the connection. -func (t *chanConn) SetDeadline(deadline time.Time) error { - if err := t.SetReadDeadline(deadline); err != nil { - return err - } - return t.SetWriteDeadline(deadline) -} - -// SetReadDeadline sets the read deadline. -// A zero value for t means Read will not time out. -// After the deadline, the error from Read will implement net.Error -// with Timeout() == true. -func (t *chanConn) SetReadDeadline(deadline time.Time) error { - // for compatibility with previous version, - // the error message contains "tcpChan" - return errors.New("ssh: tcpChan: deadline not supported") -} - -// SetWriteDeadline exists to satisfy the net.Conn interface -// but is not implemented by this type. It always returns an error. -func (t *chanConn) SetWriteDeadline(deadline time.Time) error { - return errors.New("ssh: tcpChan: deadline not supported") -} diff --git a/vendor/golang.org/x/crypto/ssh/transport.go b/vendor/golang.org/x/crypto/ssh/transport.go deleted file mode 100644 index f6fae1db..00000000 --- a/vendor/golang.org/x/crypto/ssh/transport.go +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bufio" - "bytes" - "errors" - "io" - "log" -) - -// debugTransport if set, will print packet types as they go over the -// wire. No message decoding is done, to minimize the impact on timing. -const debugTransport = false - -const ( - gcmCipherID = "aes128-gcm@openssh.com" - aes128cbcID = "aes128-cbc" - tripledescbcID = "3des-cbc" -) - -// packetConn represents a transport that implements packet based -// operations. -type packetConn interface { - // Encrypt and send a packet of data to the remote peer. - writePacket(packet []byte) error - - // Read a packet from the connection. The read is blocking, - // i.e. if error is nil, then the returned byte slice is - // always non-empty. - readPacket() ([]byte, error) - - // Close closes the write-side of the connection. - Close() error -} - -// transport is the keyingTransport that implements the SSH packet -// protocol. -type transport struct { - reader connectionState - writer connectionState - - bufReader *bufio.Reader - bufWriter *bufio.Writer - rand io.Reader - isClient bool - io.Closer -} - -// packetCipher represents a combination of SSH encryption/MAC -// protocol. A single instance should be used for one direction only. -type packetCipher interface { - // writePacket encrypts the packet and writes it to w. The - // contents of the packet are generally scrambled. - writePacket(seqnum uint32, w io.Writer, rand io.Reader, packet []byte) error - - // readPacket reads and decrypts a packet of data. The - // returned packet may be overwritten by future calls of - // readPacket. - readPacket(seqnum uint32, r io.Reader) ([]byte, error) -} - -// connectionState represents one side (read or write) of the -// connection. This is necessary because each direction has its own -// keys, and can even have its own algorithms -type connectionState struct { - packetCipher - seqNum uint32 - dir direction - pendingKeyChange chan packetCipher -} - -// prepareKeyChange sets up key material for a keychange. The key changes in -// both directions are triggered by reading and writing a msgNewKey packet -// respectively. -func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error { - ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult) - if err != nil { - return err - } - t.reader.pendingKeyChange <- ciph - - ciph, err = newPacketCipher(t.writer.dir, algs.w, kexResult) - if err != nil { - return err - } - t.writer.pendingKeyChange <- ciph - - return nil -} - -func (t *transport) printPacket(p []byte, write bool) { - if len(p) == 0 { - return - } - who := "server" - if t.isClient { - who = "client" - } - what := "read" - if write { - what = "write" - } - - log.Println(what, who, p[0]) -} - -// Read and decrypt next packet. -func (t *transport) readPacket() (p []byte, err error) { - for { - p, err = t.reader.readPacket(t.bufReader) - if err != nil { - break - } - if len(p) == 0 || (p[0] != msgIgnore && p[0] != msgDebug) { - break - } - } - if debugTransport { - t.printPacket(p, false) - } - - return p, err -} - -func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) { - packet, err := s.packetCipher.readPacket(s.seqNum, r) - s.seqNum++ - if err == nil && len(packet) == 0 { - err = errors.New("ssh: zero length packet") - } - - if len(packet) > 0 { - switch packet[0] { - case msgNewKeys: - select { - case cipher := <-s.pendingKeyChange: - s.packetCipher = cipher - default: - return nil, errors.New("ssh: got bogus newkeys message") - } - - case msgDisconnect: - // Transform a disconnect message into an - // error. Since this is lowest level at which - // we interpret message types, doing it here - // ensures that we don't have to handle it - // elsewhere. - var msg disconnectMsg - if err := Unmarshal(packet, &msg); err != nil { - return nil, err - } - return nil, &msg - } - } - - // The packet may point to an internal buffer, so copy the - // packet out here. - fresh := make([]byte, len(packet)) - copy(fresh, packet) - - return fresh, err -} - -func (t *transport) writePacket(packet []byte) error { - if debugTransport { - t.printPacket(packet, true) - } - return t.writer.writePacket(t.bufWriter, t.rand, packet) -} - -func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error { - changeKeys := len(packet) > 0 && packet[0] == msgNewKeys - - err := s.packetCipher.writePacket(s.seqNum, w, rand, packet) - if err != nil { - return err - } - if err = w.Flush(); err != nil { - return err - } - s.seqNum++ - if changeKeys { - select { - case cipher := <-s.pendingKeyChange: - s.packetCipher = cipher - default: - panic("ssh: no key material for msgNewKeys") - } - } - return err -} - -func newTransport(rwc io.ReadWriteCloser, rand io.Reader, isClient bool) *transport { - t := &transport{ - bufReader: bufio.NewReader(rwc), - bufWriter: bufio.NewWriter(rwc), - rand: rand, - reader: connectionState{ - packetCipher: &streamPacketCipher{cipher: noneCipher{}}, - pendingKeyChange: make(chan packetCipher, 1), - }, - writer: connectionState{ - packetCipher: &streamPacketCipher{cipher: noneCipher{}}, - pendingKeyChange: make(chan packetCipher, 1), - }, - Closer: rwc, - } - t.isClient = isClient - - if isClient { - t.reader.dir = serverKeys - t.writer.dir = clientKeys - } else { - t.reader.dir = clientKeys - t.writer.dir = serverKeys - } - - return t -} - -type direction struct { - ivTag []byte - keyTag []byte - macKeyTag []byte -} - -var ( - serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}} - clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}} -) - -// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as -// described in RFC 4253, section 6.4. direction should either be serverKeys -// (to setup server->client keys) or clientKeys (for client->server keys). -func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { - cipherMode := cipherModes[algs.Cipher] - macMode := macModes[algs.MAC] - - iv := make([]byte, cipherMode.ivSize) - key := make([]byte, cipherMode.keySize) - macKey := make([]byte, macMode.keySize) - - generateKeyMaterial(iv, d.ivTag, kex) - generateKeyMaterial(key, d.keyTag, kex) - generateKeyMaterial(macKey, d.macKeyTag, kex) - - return cipherModes[algs.Cipher].create(key, iv, macKey, algs) -} - -// generateKeyMaterial fills out with key material generated from tag, K, H -// and sessionId, as specified in RFC 4253, section 7.2. -func generateKeyMaterial(out, tag []byte, r *kexResult) { - var digestsSoFar []byte - - h := r.Hash.New() - for len(out) > 0 { - h.Reset() - h.Write(r.K) - h.Write(r.H) - - if len(digestsSoFar) == 0 { - h.Write(tag) - h.Write(r.SessionID) - } else { - h.Write(digestsSoFar) - } - - digest := h.Sum(nil) - n := copy(out, digest) - out = out[n:] - if len(out) > 0 { - digestsSoFar = append(digestsSoFar, digest...) - } - } -} - -const packageVersion = "SSH-2.0-Go" - -// Sends and receives a version line. The versionLine string should -// be US ASCII, start with "SSH-2.0-", and should not include a -// newline. exchangeVersions returns the other side's version line. -func exchangeVersions(rw io.ReadWriter, versionLine []byte) (them []byte, err error) { - // Contrary to the RFC, we do not ignore lines that don't - // start with "SSH-2.0-" to make the library usable with - // nonconforming servers. - for _, c := range versionLine { - // The spec disallows non US-ASCII chars, and - // specifically forbids null chars. - if c < 32 { - return nil, errors.New("ssh: junk character in version line") - } - } - if _, err = rw.Write(append(versionLine, '\r', '\n')); err != nil { - return - } - - them, err = readVersion(rw) - return them, err -} - -// maxVersionStringBytes is the maximum number of bytes that we'll -// accept as a version string. RFC 4253 section 4.2 limits this at 255 -// chars -const maxVersionStringBytes = 255 - -// Read version string as specified by RFC 4253, section 4.2. -func readVersion(r io.Reader) ([]byte, error) { - versionString := make([]byte, 0, 64) - var ok bool - var buf [1]byte - - for length := 0; length < maxVersionStringBytes; length++ { - _, err := io.ReadFull(r, buf[:]) - if err != nil { - return nil, err - } - // The RFC says that the version should be terminated with \r\n - // but several SSH servers actually only send a \n. - if buf[0] == '\n' { - if !bytes.HasPrefix(versionString, []byte("SSH-")) { - // RFC 4253 says we need to ignore all version string lines - // except the one containing the SSH version (provided that - // all the lines do not exceed 255 bytes in total). - versionString = versionString[:0] - continue - } - ok = true - break - } - - // non ASCII chars are disallowed, but we are lenient, - // since Go doesn't use null-terminated strings. - - // The RFC allows a comment after a space, however, - // all of it (version and comments) goes into the - // session hash. - versionString = append(versionString, buf[0]) - } - - if !ok { - return nil, errors.New("ssh: overflow reading version string") - } - - // There might be a '\r' on the end which we should remove. - if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' { - versionString = versionString[:len(versionString)-1] - } - return versionString, nil -} diff --git a/vendor/golang.org/x/net/AUTHORS b/vendor/golang.org/x/net/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/vendor/golang.org/x/net/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/golang.org/x/net/CONTRIBUTORS b/vendor/golang.org/x/net/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/vendor/golang.org/x/net/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE deleted file mode 100644 index 6a66aea5..00000000 --- a/vendor/golang.org/x/net/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/net/PATENTS b/vendor/golang.org/x/net/PATENTS deleted file mode 100644 index 73309904..00000000 --- a/vendor/golang.org/x/net/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. 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 a3c021d3..00000000 --- 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 d20f52b7..00000000 --- a/vendor/golang.org/x/net/context/go17.go +++ /dev/null @@ -1,72 +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 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, CancelFunc(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, CancelFunc(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 d88bd1db..00000000 --- a/vendor/golang.org/x/net/context/go19.go +++ /dev/null @@ -1,20 +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. - -// +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 0f35592d..00000000 --- a/vendor/golang.org/x/net/context/pre_go17.go +++ /dev/null @@ -1,300 +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. - -// +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 b105f80b..00000000 --- a/vendor/golang.org/x/net/context/pre_go19.go +++ /dev/null @@ -1,109 +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. - -// +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/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go deleted file mode 100644 index cd0a8ac1..00000000 --- a/vendor/golang.org/x/net/html/atom/atom.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2012 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 atom provides integer codes (also known as atoms) for a fixed set of -// frequently occurring HTML strings: tag names and attribute keys such as "p" -// and "id". -// -// Sharing an atom's name between all elements with the same tag can result in -// fewer string allocations when tokenizing and parsing HTML. Integer -// comparisons are also generally faster than string comparisons. -// -// The value of an atom's particular code is not guaranteed to stay the same -// between versions of this package. Neither is any ordering guaranteed: -// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to -// be dense. The only guarantees are that e.g. looking up "div" will yield -// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. -package atom // import "golang.org/x/net/html/atom" - -// Atom is an integer code for a string. The zero value maps to "". -type Atom uint32 - -// String returns the atom's name. -func (a Atom) String() string { - start := uint32(a >> 8) - n := uint32(a & 0xff) - if start+n > uint32(len(atomText)) { - return "" - } - return atomText[start : start+n] -} - -func (a Atom) string() string { - return atomText[a>>8 : a>>8+a&0xff] -} - -// fnv computes the FNV hash with an arbitrary starting value h. -func fnv(h uint32, s []byte) uint32 { - for i := range s { - h ^= uint32(s[i]) - h *= 16777619 - } - return h -} - -func match(s string, t []byte) bool { - for i, c := range t { - if s[i] != c { - return false - } - } - return true -} - -// Lookup returns the atom whose name is s. It returns zero if there is no -// such atom. The lookup is case sensitive. -func Lookup(s []byte) Atom { - if len(s) == 0 || len(s) > maxAtomLen { - return 0 - } - h := fnv(hash0, s) - if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - return 0 -} - -// String returns a string whose contents are equal to s. In that sense, it is -// equivalent to string(s) but may be more efficient. -func String(s []byte) string { - if a := Lookup(s); a != 0 { - return a.String() - } - return string(s) -} diff --git a/vendor/golang.org/x/net/html/atom/gen.go b/vendor/golang.org/x/net/html/atom/gen.go deleted file mode 100644 index 5d052781..00000000 --- a/vendor/golang.org/x/net/html/atom/gen.go +++ /dev/null @@ -1,712 +0,0 @@ -// Copyright 2012 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 ignore - -//go:generate go run gen.go -//go:generate go run gen.go -test - -package main - -import ( - "bytes" - "flag" - "fmt" - "go/format" - "io/ioutil" - "math/rand" - "os" - "sort" - "strings" -) - -// identifier converts s to a Go exported identifier. -// It converts "div" to "Div" and "accept-charset" to "AcceptCharset". -func identifier(s string) string { - b := make([]byte, 0, len(s)) - cap := true - for _, c := range s { - if c == '-' { - cap = true - continue - } - if cap && 'a' <= c && c <= 'z' { - c -= 'a' - 'A' - } - cap = false - b = append(b, byte(c)) - } - return string(b) -} - -var test = flag.Bool("test", false, "generate table_test.go") - -func genFile(name string, buf *bytes.Buffer) { - b, err := format.Source(buf.Bytes()) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - if err := ioutil.WriteFile(name, b, 0644); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func main() { - flag.Parse() - - var all []string - all = append(all, elements...) - all = append(all, attributes...) - all = append(all, eventHandlers...) - all = append(all, extra...) - sort.Strings(all) - - // uniq - lists have dups - w := 0 - for _, s := range all { - if w == 0 || all[w-1] != s { - all[w] = s - w++ - } - } - all = all[:w] - - if *test { - var buf bytes.Buffer - fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") - fmt.Fprintln(&buf, "//go:generate go run gen.go -test\n") - fmt.Fprintln(&buf, "package atom\n") - fmt.Fprintln(&buf, "var testAtomList = []string{") - for _, s := range all { - fmt.Fprintf(&buf, "\t%q,\n", s) - } - fmt.Fprintln(&buf, "}") - - genFile("table_test.go", &buf) - return - } - - // Find hash that minimizes table size. - var best *table - for i := 0; i < 1000000; i++ { - if best != nil && 1<<(best.k-1) < len(all) { - break - } - h := rand.Uint32() - for k := uint(0); k <= 16; k++ { - if best != nil && k >= best.k { - break - } - var t table - if t.init(h, k, all) { - best = &t - break - } - } - } - if best == nil { - fmt.Fprintf(os.Stderr, "failed to construct string table\n") - os.Exit(1) - } - - // Lay out strings, using overlaps when possible. - layout := append([]string{}, all...) - - // Remove strings that are substrings of other strings - for changed := true; changed; { - changed = false - for i, s := range layout { - if s == "" { - continue - } - for j, t := range layout { - if i != j && t != "" && strings.Contains(s, t) { - changed = true - layout[j] = "" - } - } - } - } - - // Join strings where one suffix matches another prefix. - for { - // Find best i, j, k such that layout[i][len-k:] == layout[j][:k], - // maximizing overlap length k. - besti := -1 - bestj := -1 - bestk := 0 - for i, s := range layout { - if s == "" { - continue - } - for j, t := range layout { - if i == j { - continue - } - for k := bestk + 1; k <= len(s) && k <= len(t); k++ { - if s[len(s)-k:] == t[:k] { - besti = i - bestj = j - bestk = k - } - } - } - } - if bestk > 0 { - layout[besti] += layout[bestj][bestk:] - layout[bestj] = "" - continue - } - break - } - - text := strings.Join(layout, "") - - atom := map[string]uint32{} - for _, s := range all { - off := strings.Index(text, s) - if off < 0 { - panic("lost string " + s) - } - atom[s] = uint32(off<<8 | len(s)) - } - - var buf bytes.Buffer - // Generate the Go code. - fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") - fmt.Fprintln(&buf, "//go:generate go run gen.go\n") - fmt.Fprintln(&buf, "package atom\n\nconst (") - - // compute max len - maxLen := 0 - for _, s := range all { - if maxLen < len(s) { - maxLen = len(s) - } - fmt.Fprintf(&buf, "\t%s Atom = %#x\n", identifier(s), atom[s]) - } - fmt.Fprintln(&buf, ")\n") - - fmt.Fprintf(&buf, "const hash0 = %#x\n\n", best.h0) - fmt.Fprintf(&buf, "const maxAtomLen = %d\n\n", maxLen) - - fmt.Fprintf(&buf, "var table = [1<<%d]Atom{\n", best.k) - for i, s := range best.tab { - if s == "" { - continue - } - fmt.Fprintf(&buf, "\t%#x: %#x, // %s\n", i, atom[s], s) - } - fmt.Fprintf(&buf, "}\n") - datasize := (1 << best.k) * 4 - - fmt.Fprintln(&buf, "const atomText =") - textsize := len(text) - for len(text) > 60 { - fmt.Fprintf(&buf, "\t%q +\n", text[:60]) - text = text[60:] - } - fmt.Fprintf(&buf, "\t%q\n\n", text) - - genFile("table.go", &buf) - - fmt.Fprintf(os.Stdout, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize) -} - -type byLen []string - -func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) } -func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x byLen) Len() int { return len(x) } - -// fnv computes the FNV hash with an arbitrary starting value h. -func fnv(h uint32, s string) uint32 { - for i := 0; i < len(s); i++ { - h ^= uint32(s[i]) - h *= 16777619 - } - return h -} - -// A table represents an attempt at constructing the lookup table. -// The lookup table uses cuckoo hashing, meaning that each string -// can be found in one of two positions. -type table struct { - h0 uint32 - k uint - mask uint32 - tab []string -} - -// hash returns the two hashes for s. -func (t *table) hash(s string) (h1, h2 uint32) { - h := fnv(t.h0, s) - h1 = h & t.mask - h2 = (h >> 16) & t.mask - return -} - -// init initializes the table with the given parameters. -// h0 is the initial hash value, -// k is the number of bits of hash value to use, and -// x is the list of strings to store in the table. -// init returns false if the table cannot be constructed. -func (t *table) init(h0 uint32, k uint, x []string) bool { - t.h0 = h0 - t.k = k - t.tab = make([]string, 1< len(t.tab) { - return false - } - s := t.tab[i] - h1, h2 := t.hash(s) - j := h1 + h2 - i - if t.tab[j] != "" && !t.push(j, depth+1) { - return false - } - t.tab[j] = s - return true -} - -// The lists of element names and attribute keys were taken from -// https://html.spec.whatwg.org/multipage/indices.html#index -// as of the "HTML Living Standard - Last Updated 16 April 2018" version. - -// "command", "keygen" and "menuitem" have been removed from the spec, -// but are kept here for backwards compatibility. -var elements = []string{ - "a", - "abbr", - "address", - "area", - "article", - "aside", - "audio", - "b", - "base", - "bdi", - "bdo", - "blockquote", - "body", - "br", - "button", - "canvas", - "caption", - "cite", - "code", - "col", - "colgroup", - "command", - "data", - "datalist", - "dd", - "del", - "details", - "dfn", - "dialog", - "div", - "dl", - "dt", - "em", - "embed", - "fieldset", - "figcaption", - "figure", - "footer", - "form", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "head", - "header", - "hgroup", - "hr", - "html", - "i", - "iframe", - "img", - "input", - "ins", - "kbd", - "keygen", - "label", - "legend", - "li", - "link", - "main", - "map", - "mark", - "menu", - "menuitem", - "meta", - "meter", - "nav", - "noscript", - "object", - "ol", - "optgroup", - "option", - "output", - "p", - "param", - "picture", - "pre", - "progress", - "q", - "rp", - "rt", - "ruby", - "s", - "samp", - "script", - "section", - "select", - "slot", - "small", - "source", - "span", - "strong", - "style", - "sub", - "summary", - "sup", - "table", - "tbody", - "td", - "template", - "textarea", - "tfoot", - "th", - "thead", - "time", - "title", - "tr", - "track", - "u", - "ul", - "var", - "video", - "wbr", -} - -// https://html.spec.whatwg.org/multipage/indices.html#attributes-3 -// -// "challenge", "command", "contextmenu", "dropzone", "icon", "keytype", "mediagroup", -// "radiogroup", "spellcheck", "scoped", "seamless", "sortable" and "sorted" have been removed from the spec, -// but are kept here for backwards compatibility. -var attributes = []string{ - "abbr", - "accept", - "accept-charset", - "accesskey", - "action", - "allowfullscreen", - "allowpaymentrequest", - "allowusermedia", - "alt", - "as", - "async", - "autocomplete", - "autofocus", - "autoplay", - "challenge", - "charset", - "checked", - "cite", - "class", - "color", - "cols", - "colspan", - "command", - "content", - "contenteditable", - "contextmenu", - "controls", - "coords", - "crossorigin", - "data", - "datetime", - "default", - "defer", - "dir", - "dirname", - "disabled", - "download", - "draggable", - "dropzone", - "enctype", - "for", - "form", - "formaction", - "formenctype", - "formmethod", - "formnovalidate", - "formtarget", - "headers", - "height", - "hidden", - "high", - "href", - "hreflang", - "http-equiv", - "icon", - "id", - "inputmode", - "integrity", - "is", - "ismap", - "itemid", - "itemprop", - "itemref", - "itemscope", - "itemtype", - "keytype", - "kind", - "label", - "lang", - "list", - "loop", - "low", - "manifest", - "max", - "maxlength", - "media", - "mediagroup", - "method", - "min", - "minlength", - "multiple", - "muted", - "name", - "nomodule", - "nonce", - "novalidate", - "open", - "optimum", - "pattern", - "ping", - "placeholder", - "playsinline", - "poster", - "preload", - "radiogroup", - "readonly", - "referrerpolicy", - "rel", - "required", - "reversed", - "rows", - "rowspan", - "sandbox", - "spellcheck", - "scope", - "scoped", - "seamless", - "selected", - "shape", - "size", - "sizes", - "sortable", - "sorted", - "slot", - "span", - "spellcheck", - "src", - "srcdoc", - "srclang", - "srcset", - "start", - "step", - "style", - "tabindex", - "target", - "title", - "translate", - "type", - "typemustmatch", - "updateviacache", - "usemap", - "value", - "width", - "workertype", - "wrap", -} - -// "onautocomplete", "onautocompleteerror", "onmousewheel", -// "onshow" and "onsort" have been removed from the spec, -// but are kept here for backwards compatibility. -var eventHandlers = []string{ - "onabort", - "onautocomplete", - "onautocompleteerror", - "onauxclick", - "onafterprint", - "onbeforeprint", - "onbeforeunload", - "onblur", - "oncancel", - "oncanplay", - "oncanplaythrough", - "onchange", - "onclick", - "onclose", - "oncontextmenu", - "oncopy", - "oncuechange", - "oncut", - "ondblclick", - "ondrag", - "ondragend", - "ondragenter", - "ondragexit", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onended", - "onerror", - "onfocus", - "onhashchange", - "oninput", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeyup", - "onlanguagechange", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadend", - "onloadstart", - "onmessage", - "onmessageerror", - "onmousedown", - "onmouseenter", - "onmouseleave", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onwheel", - "onoffline", - "ononline", - "onpagehide", - "onpageshow", - "onpaste", - "onpause", - "onplay", - "onplaying", - "onpopstate", - "onprogress", - "onratechange", - "onreset", - "onresize", - "onrejectionhandled", - "onscroll", - "onsecuritypolicyviolation", - "onseeked", - "onseeking", - "onselect", - "onshow", - "onsort", - "onstalled", - "onstorage", - "onsubmit", - "onsuspend", - "ontimeupdate", - "ontoggle", - "onunhandledrejection", - "onunload", - "onvolumechange", - "onwaiting", -} - -// extra are ad-hoc values not covered by any of the lists above. -var extra = []string{ - "acronym", - "align", - "annotation", - "annotation-xml", - "applet", - "basefont", - "bgsound", - "big", - "blink", - "center", - "color", - "desc", - "face", - "font", - "foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive. - "foreignobject", - "frame", - "frameset", - "image", - "isindex", - "listing", - "malignmark", - "marquee", - "math", - "mglyph", - "mi", - "mn", - "mo", - "ms", - "mtext", - "nobr", - "noembed", - "noframes", - "plaintext", - "prompt", - "public", - "rb", - "rtc", - "spacer", - "strike", - "svg", - "system", - "tt", - "xmp", -} diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go deleted file mode 100644 index 2a938864..00000000 --- a/vendor/golang.org/x/net/html/atom/table.go +++ /dev/null @@ -1,783 +0,0 @@ -// Code generated by go generate gen.go; DO NOT EDIT. - -//go:generate go run gen.go - -package atom - -const ( - A Atom = 0x1 - Abbr Atom = 0x4 - Accept Atom = 0x1a06 - AcceptCharset Atom = 0x1a0e - Accesskey Atom = 0x2c09 - Acronym Atom = 0xaa07 - Action Atom = 0x27206 - Address Atom = 0x6f307 - Align Atom = 0xb105 - Allowfullscreen Atom = 0x2080f - Allowpaymentrequest Atom = 0xc113 - Allowusermedia Atom = 0xdd0e - Alt Atom = 0xf303 - Annotation Atom = 0x1c90a - AnnotationXml Atom = 0x1c90e - Applet Atom = 0x31906 - Area Atom = 0x35604 - Article Atom = 0x3fc07 - As Atom = 0x3c02 - Aside Atom = 0x10705 - Async Atom = 0xff05 - Audio Atom = 0x11505 - Autocomplete Atom = 0x2780c - Autofocus Atom = 0x12109 - Autoplay Atom = 0x13c08 - B Atom = 0x101 - Base Atom = 0x3b04 - Basefont Atom = 0x3b08 - Bdi Atom = 0xba03 - Bdo Atom = 0x14b03 - Bgsound Atom = 0x15e07 - Big Atom = 0x17003 - Blink Atom = 0x17305 - Blockquote Atom = 0x1870a - Body Atom = 0x2804 - Br Atom = 0x202 - Button Atom = 0x19106 - Canvas Atom = 0x10306 - Caption Atom = 0x23107 - Center Atom = 0x22006 - Challenge Atom = 0x29b09 - Charset Atom = 0x2107 - Checked Atom = 0x47907 - Cite Atom = 0x19c04 - Class Atom = 0x56405 - Code Atom = 0x5c504 - Col Atom = 0x1ab03 - Colgroup Atom = 0x1ab08 - Color Atom = 0x1bf05 - Cols Atom = 0x1c404 - Colspan Atom = 0x1c407 - Command Atom = 0x1d707 - Content Atom = 0x58b07 - Contenteditable Atom = 0x58b0f - Contextmenu Atom = 0x3800b - Controls Atom = 0x1de08 - Coords Atom = 0x1ea06 - Crossorigin Atom = 0x1fb0b - Data Atom = 0x4a504 - Datalist Atom = 0x4a508 - Datetime Atom = 0x2b808 - Dd Atom = 0x2d702 - Default Atom = 0x10a07 - Defer Atom = 0x5c705 - Del Atom = 0x45203 - Desc Atom = 0x56104 - Details Atom = 0x7207 - Dfn Atom = 0x8703 - Dialog Atom = 0xbb06 - Dir Atom = 0x9303 - Dirname Atom = 0x9307 - Disabled Atom = 0x16408 - Div Atom = 0x16b03 - Dl Atom = 0x5e602 - Download Atom = 0x46308 - Draggable Atom = 0x17a09 - Dropzone Atom = 0x40508 - Dt Atom = 0x64b02 - Em Atom = 0x6e02 - Embed Atom = 0x6e05 - Enctype Atom = 0x28d07 - Face Atom = 0x21e04 - Fieldset Atom = 0x22608 - Figcaption Atom = 0x22e0a - Figure Atom = 0x24806 - Font Atom = 0x3f04 - Footer Atom = 0xf606 - For Atom = 0x25403 - ForeignObject Atom = 0x2540d - Foreignobject Atom = 0x2610d - Form Atom = 0x26e04 - Formaction Atom = 0x26e0a - Formenctype Atom = 0x2890b - Formmethod Atom = 0x2a40a - Formnovalidate Atom = 0x2ae0e - Formtarget Atom = 0x2c00a - Frame Atom = 0x8b05 - Frameset Atom = 0x8b08 - H1 Atom = 0x15c02 - H2 Atom = 0x2de02 - H3 Atom = 0x30d02 - H4 Atom = 0x34502 - H5 Atom = 0x34f02 - H6 Atom = 0x64d02 - Head Atom = 0x33104 - Header Atom = 0x33106 - Headers Atom = 0x33107 - Height Atom = 0x5206 - Hgroup Atom = 0x2ca06 - Hidden Atom = 0x2d506 - High Atom = 0x2db04 - Hr Atom = 0x15702 - Href Atom = 0x2e004 - Hreflang Atom = 0x2e008 - Html Atom = 0x5604 - HttpEquiv Atom = 0x2e80a - I Atom = 0x601 - Icon Atom = 0x58a04 - Id Atom = 0x10902 - Iframe Atom = 0x2fc06 - Image Atom = 0x30205 - Img Atom = 0x30703 - Input Atom = 0x44b05 - Inputmode Atom = 0x44b09 - Ins Atom = 0x20403 - Integrity Atom = 0x23f09 - Is Atom = 0x16502 - Isindex Atom = 0x30f07 - Ismap Atom = 0x31605 - Itemid Atom = 0x38b06 - Itemprop Atom = 0x19d08 - Itemref Atom = 0x3cd07 - Itemscope Atom = 0x67109 - Itemtype Atom = 0x31f08 - Kbd Atom = 0xb903 - Keygen Atom = 0x3206 - Keytype Atom = 0xd607 - Kind Atom = 0x17704 - Label Atom = 0x5905 - Lang Atom = 0x2e404 - Legend Atom = 0x18106 - Li Atom = 0xb202 - Link Atom = 0x17404 - List Atom = 0x4a904 - Listing Atom = 0x4a907 - Loop Atom = 0x5d04 - Low Atom = 0xc303 - Main Atom = 0x1004 - Malignmark Atom = 0xb00a - Manifest Atom = 0x6d708 - Map Atom = 0x31803 - Mark Atom = 0xb604 - Marquee Atom = 0x32707 - Math Atom = 0x32e04 - Max Atom = 0x33d03 - Maxlength Atom = 0x33d09 - Media Atom = 0xe605 - Mediagroup Atom = 0xe60a - Menu Atom = 0x38704 - Menuitem Atom = 0x38708 - Meta Atom = 0x4b804 - Meter Atom = 0x9805 - Method Atom = 0x2a806 - Mglyph Atom = 0x30806 - Mi Atom = 0x34702 - Min Atom = 0x34703 - Minlength Atom = 0x34709 - Mn Atom = 0x2b102 - Mo Atom = 0xa402 - Ms Atom = 0x67402 - Mtext Atom = 0x35105 - Multiple Atom = 0x35f08 - Muted Atom = 0x36705 - Name Atom = 0x9604 - Nav Atom = 0x1303 - Nobr Atom = 0x3704 - Noembed Atom = 0x6c07 - Noframes Atom = 0x8908 - Nomodule Atom = 0xa208 - Nonce Atom = 0x1a605 - Noscript Atom = 0x21608 - Novalidate Atom = 0x2b20a - Object Atom = 0x26806 - Ol Atom = 0x13702 - Onabort Atom = 0x19507 - Onafterprint Atom = 0x2360c - Onautocomplete Atom = 0x2760e - Onautocompleteerror Atom = 0x27613 - Onauxclick Atom = 0x61f0a - Onbeforeprint Atom = 0x69e0d - Onbeforeunload Atom = 0x6e70e - Onblur Atom = 0x56d06 - Oncancel Atom = 0x11908 - Oncanplay Atom = 0x14d09 - Oncanplaythrough Atom = 0x14d10 - Onchange Atom = 0x41b08 - Onclick Atom = 0x2f507 - Onclose Atom = 0x36c07 - Oncontextmenu Atom = 0x37e0d - Oncopy Atom = 0x39106 - Oncuechange Atom = 0x3970b - Oncut Atom = 0x3a205 - Ondblclick Atom = 0x3a70a - Ondrag Atom = 0x3b106 - Ondragend Atom = 0x3b109 - Ondragenter Atom = 0x3ba0b - Ondragexit Atom = 0x3c50a - Ondragleave Atom = 0x3df0b - Ondragover Atom = 0x3ea0a - Ondragstart Atom = 0x3f40b - Ondrop Atom = 0x40306 - Ondurationchange Atom = 0x41310 - Onemptied Atom = 0x40a09 - Onended Atom = 0x42307 - Onerror Atom = 0x42a07 - Onfocus Atom = 0x43107 - Onhashchange Atom = 0x43d0c - Oninput Atom = 0x44907 - Oninvalid Atom = 0x45509 - Onkeydown Atom = 0x45e09 - Onkeypress Atom = 0x46b0a - Onkeyup Atom = 0x48007 - Onlanguagechange Atom = 0x48d10 - Onload Atom = 0x49d06 - Onloadeddata Atom = 0x49d0c - Onloadedmetadata Atom = 0x4b010 - Onloadend Atom = 0x4c609 - Onloadstart Atom = 0x4cf0b - Onmessage Atom = 0x4da09 - Onmessageerror Atom = 0x4da0e - Onmousedown Atom = 0x4e80b - Onmouseenter Atom = 0x4f30c - Onmouseleave Atom = 0x4ff0c - Onmousemove Atom = 0x50b0b - Onmouseout Atom = 0x5160a - Onmouseover Atom = 0x5230b - Onmouseup Atom = 0x52e09 - Onmousewheel Atom = 0x53c0c - Onoffline Atom = 0x54809 - Ononline Atom = 0x55108 - Onpagehide Atom = 0x5590a - Onpageshow Atom = 0x5730a - Onpaste Atom = 0x57f07 - Onpause Atom = 0x59a07 - Onplay Atom = 0x5a406 - Onplaying Atom = 0x5a409 - Onpopstate Atom = 0x5ad0a - Onprogress Atom = 0x5b70a - Onratechange Atom = 0x5cc0c - Onrejectionhandled Atom = 0x5d812 - Onreset Atom = 0x5ea07 - Onresize Atom = 0x5f108 - Onscroll Atom = 0x60008 - Onsecuritypolicyviolation Atom = 0x60819 - Onseeked Atom = 0x62908 - Onseeking Atom = 0x63109 - Onselect Atom = 0x63a08 - Onshow Atom = 0x64406 - Onsort Atom = 0x64f06 - Onstalled Atom = 0x65909 - Onstorage Atom = 0x66209 - Onsubmit Atom = 0x66b08 - Onsuspend Atom = 0x67b09 - Ontimeupdate Atom = 0x400c - Ontoggle Atom = 0x68408 - Onunhandledrejection Atom = 0x68c14 - Onunload Atom = 0x6ab08 - Onvolumechange Atom = 0x6b30e - Onwaiting Atom = 0x6c109 - Onwheel Atom = 0x6ca07 - Open Atom = 0x1a304 - Optgroup Atom = 0x5f08 - Optimum Atom = 0x6d107 - Option Atom = 0x6e306 - Output Atom = 0x51d06 - P Atom = 0xc01 - Param Atom = 0xc05 - Pattern Atom = 0x6607 - Picture Atom = 0x7b07 - Ping Atom = 0xef04 - Placeholder Atom = 0x1310b - Plaintext Atom = 0x1b209 - Playsinline Atom = 0x1400b - Poster Atom = 0x2cf06 - Pre Atom = 0x47003 - Preload Atom = 0x48607 - Progress Atom = 0x5b908 - Prompt Atom = 0x53606 - Public Atom = 0x58606 - Q Atom = 0xcf01 - Radiogroup Atom = 0x30a - Rb Atom = 0x3a02 - Readonly Atom = 0x35708 - Referrerpolicy Atom = 0x3d10e - Rel Atom = 0x48703 - Required Atom = 0x24c08 - Reversed Atom = 0x8008 - Rows Atom = 0x9c04 - Rowspan Atom = 0x9c07 - Rp Atom = 0x23c02 - Rt Atom = 0x19a02 - Rtc Atom = 0x19a03 - Ruby Atom = 0xfb04 - S Atom = 0x2501 - Samp Atom = 0x7804 - Sandbox Atom = 0x12907 - Scope Atom = 0x67505 - Scoped Atom = 0x67506 - Script Atom = 0x21806 - Seamless Atom = 0x37108 - Section Atom = 0x56807 - Select Atom = 0x63c06 - Selected Atom = 0x63c08 - Shape Atom = 0x1e505 - Size Atom = 0x5f504 - Sizes Atom = 0x5f505 - Slot Atom = 0x1ef04 - Small Atom = 0x20605 - Sortable Atom = 0x65108 - Sorted Atom = 0x33706 - Source Atom = 0x37806 - Spacer Atom = 0x43706 - Span Atom = 0x9f04 - Spellcheck Atom = 0x4740a - Src Atom = 0x5c003 - Srcdoc Atom = 0x5c006 - Srclang Atom = 0x5f907 - Srcset Atom = 0x6f906 - Start Atom = 0x3fa05 - Step Atom = 0x58304 - Strike Atom = 0xd206 - Strong Atom = 0x6dd06 - Style Atom = 0x6ff05 - Sub Atom = 0x66d03 - Summary Atom = 0x70407 - Sup Atom = 0x70b03 - Svg Atom = 0x70e03 - System Atom = 0x71106 - Tabindex Atom = 0x4be08 - Table Atom = 0x59505 - Target Atom = 0x2c406 - Tbody Atom = 0x2705 - Td Atom = 0x9202 - Template Atom = 0x71408 - Textarea Atom = 0x35208 - Tfoot Atom = 0xf505 - Th Atom = 0x15602 - Thead Atom = 0x33005 - Time Atom = 0x4204 - Title Atom = 0x11005 - Tr Atom = 0xcc02 - Track Atom = 0x1ba05 - Translate Atom = 0x1f209 - Tt Atom = 0x6802 - Type Atom = 0xd904 - Typemustmatch Atom = 0x2900d - U Atom = 0xb01 - Ul Atom = 0xa702 - Updateviacache Atom = 0x460e - Usemap Atom = 0x59e06 - Value Atom = 0x1505 - Var Atom = 0x16d03 - Video Atom = 0x2f105 - Wbr Atom = 0x57c03 - Width Atom = 0x64905 - Workertype Atom = 0x71c0a - Wrap Atom = 0x72604 - Xmp Atom = 0x12f03 -) - -const hash0 = 0x81cdf10e - -const maxAtomLen = 25 - -var table = [1 << 9]Atom{ - 0x1: 0xe60a, // mediagroup - 0x2: 0x2e404, // lang - 0x4: 0x2c09, // accesskey - 0x5: 0x8b08, // frameset - 0x7: 0x63a08, // onselect - 0x8: 0x71106, // system - 0xa: 0x64905, // width - 0xc: 0x2890b, // formenctype - 0xd: 0x13702, // ol - 0xe: 0x3970b, // oncuechange - 0x10: 0x14b03, // bdo - 0x11: 0x11505, // audio - 0x12: 0x17a09, // draggable - 0x14: 0x2f105, // video - 0x15: 0x2b102, // mn - 0x16: 0x38704, // menu - 0x17: 0x2cf06, // poster - 0x19: 0xf606, // footer - 0x1a: 0x2a806, // method - 0x1b: 0x2b808, // datetime - 0x1c: 0x19507, // onabort - 0x1d: 0x460e, // updateviacache - 0x1e: 0xff05, // async - 0x1f: 0x49d06, // onload - 0x21: 0x11908, // oncancel - 0x22: 0x62908, // onseeked - 0x23: 0x30205, // image - 0x24: 0x5d812, // onrejectionhandled - 0x26: 0x17404, // link - 0x27: 0x51d06, // output - 0x28: 0x33104, // head - 0x29: 0x4ff0c, // onmouseleave - 0x2a: 0x57f07, // onpaste - 0x2b: 0x5a409, // onplaying - 0x2c: 0x1c407, // colspan - 0x2f: 0x1bf05, // color - 0x30: 0x5f504, // size - 0x31: 0x2e80a, // http-equiv - 0x33: 0x601, // i - 0x34: 0x5590a, // onpagehide - 0x35: 0x68c14, // onunhandledrejection - 0x37: 0x42a07, // onerror - 0x3a: 0x3b08, // basefont - 0x3f: 0x1303, // nav - 0x40: 0x17704, // kind - 0x41: 0x35708, // readonly - 0x42: 0x30806, // mglyph - 0x44: 0xb202, // li - 0x46: 0x2d506, // hidden - 0x47: 0x70e03, // svg - 0x48: 0x58304, // step - 0x49: 0x23f09, // integrity - 0x4a: 0x58606, // public - 0x4c: 0x1ab03, // col - 0x4d: 0x1870a, // blockquote - 0x4e: 0x34f02, // h5 - 0x50: 0x5b908, // progress - 0x51: 0x5f505, // sizes - 0x52: 0x34502, // h4 - 0x56: 0x33005, // thead - 0x57: 0xd607, // keytype - 0x58: 0x5b70a, // onprogress - 0x59: 0x44b09, // inputmode - 0x5a: 0x3b109, // ondragend - 0x5d: 0x3a205, // oncut - 0x5e: 0x43706, // spacer - 0x5f: 0x1ab08, // colgroup - 0x62: 0x16502, // is - 0x65: 0x3c02, // as - 0x66: 0x54809, // onoffline - 0x67: 0x33706, // sorted - 0x69: 0x48d10, // onlanguagechange - 0x6c: 0x43d0c, // onhashchange - 0x6d: 0x9604, // name - 0x6e: 0xf505, // tfoot - 0x6f: 0x56104, // desc - 0x70: 0x33d03, // max - 0x72: 0x1ea06, // coords - 0x73: 0x30d02, // h3 - 0x74: 0x6e70e, // onbeforeunload - 0x75: 0x9c04, // rows - 0x76: 0x63c06, // select - 0x77: 0x9805, // meter - 0x78: 0x38b06, // itemid - 0x79: 0x53c0c, // onmousewheel - 0x7a: 0x5c006, // srcdoc - 0x7d: 0x1ba05, // track - 0x7f: 0x31f08, // itemtype - 0x82: 0xa402, // mo - 0x83: 0x41b08, // onchange - 0x84: 0x33107, // headers - 0x85: 0x5cc0c, // onratechange - 0x86: 0x60819, // onsecuritypolicyviolation - 0x88: 0x4a508, // datalist - 0x89: 0x4e80b, // onmousedown - 0x8a: 0x1ef04, // slot - 0x8b: 0x4b010, // onloadedmetadata - 0x8c: 0x1a06, // accept - 0x8d: 0x26806, // object - 0x91: 0x6b30e, // onvolumechange - 0x92: 0x2107, // charset - 0x93: 0x27613, // onautocompleteerror - 0x94: 0xc113, // allowpaymentrequest - 0x95: 0x2804, // body - 0x96: 0x10a07, // default - 0x97: 0x63c08, // selected - 0x98: 0x21e04, // face - 0x99: 0x1e505, // shape - 0x9b: 0x68408, // ontoggle - 0x9e: 0x64b02, // dt - 0x9f: 0xb604, // mark - 0xa1: 0xb01, // u - 0xa4: 0x6ab08, // onunload - 0xa5: 0x5d04, // loop - 0xa6: 0x16408, // disabled - 0xaa: 0x42307, // onended - 0xab: 0xb00a, // malignmark - 0xad: 0x67b09, // onsuspend - 0xae: 0x35105, // mtext - 0xaf: 0x64f06, // onsort - 0xb0: 0x19d08, // itemprop - 0xb3: 0x67109, // itemscope - 0xb4: 0x17305, // blink - 0xb6: 0x3b106, // ondrag - 0xb7: 0xa702, // ul - 0xb8: 0x26e04, // form - 0xb9: 0x12907, // sandbox - 0xba: 0x8b05, // frame - 0xbb: 0x1505, // value - 0xbc: 0x66209, // onstorage - 0xbf: 0xaa07, // acronym - 0xc0: 0x19a02, // rt - 0xc2: 0x202, // br - 0xc3: 0x22608, // fieldset - 0xc4: 0x2900d, // typemustmatch - 0xc5: 0xa208, // nomodule - 0xc6: 0x6c07, // noembed - 0xc7: 0x69e0d, // onbeforeprint - 0xc8: 0x19106, // button - 0xc9: 0x2f507, // onclick - 0xca: 0x70407, // summary - 0xcd: 0xfb04, // ruby - 0xce: 0x56405, // class - 0xcf: 0x3f40b, // ondragstart - 0xd0: 0x23107, // caption - 0xd4: 0xdd0e, // allowusermedia - 0xd5: 0x4cf0b, // onloadstart - 0xd9: 0x16b03, // div - 0xda: 0x4a904, // list - 0xdb: 0x32e04, // math - 0xdc: 0x44b05, // input - 0xdf: 0x3ea0a, // ondragover - 0xe0: 0x2de02, // h2 - 0xe2: 0x1b209, // plaintext - 0xe4: 0x4f30c, // onmouseenter - 0xe7: 0x47907, // checked - 0xe8: 0x47003, // pre - 0xea: 0x35f08, // multiple - 0xeb: 0xba03, // bdi - 0xec: 0x33d09, // maxlength - 0xed: 0xcf01, // q - 0xee: 0x61f0a, // onauxclick - 0xf0: 0x57c03, // wbr - 0xf2: 0x3b04, // base - 0xf3: 0x6e306, // option - 0xf5: 0x41310, // ondurationchange - 0xf7: 0x8908, // noframes - 0xf9: 0x40508, // dropzone - 0xfb: 0x67505, // scope - 0xfc: 0x8008, // reversed - 0xfd: 0x3ba0b, // ondragenter - 0xfe: 0x3fa05, // start - 0xff: 0x12f03, // xmp - 0x100: 0x5f907, // srclang - 0x101: 0x30703, // img - 0x104: 0x101, // b - 0x105: 0x25403, // for - 0x106: 0x10705, // aside - 0x107: 0x44907, // oninput - 0x108: 0x35604, // area - 0x109: 0x2a40a, // formmethod - 0x10a: 0x72604, // wrap - 0x10c: 0x23c02, // rp - 0x10d: 0x46b0a, // onkeypress - 0x10e: 0x6802, // tt - 0x110: 0x34702, // mi - 0x111: 0x36705, // muted - 0x112: 0xf303, // alt - 0x113: 0x5c504, // code - 0x114: 0x6e02, // em - 0x115: 0x3c50a, // ondragexit - 0x117: 0x9f04, // span - 0x119: 0x6d708, // manifest - 0x11a: 0x38708, // menuitem - 0x11b: 0x58b07, // content - 0x11d: 0x6c109, // onwaiting - 0x11f: 0x4c609, // onloadend - 0x121: 0x37e0d, // oncontextmenu - 0x123: 0x56d06, // onblur - 0x124: 0x3fc07, // article - 0x125: 0x9303, // dir - 0x126: 0xef04, // ping - 0x127: 0x24c08, // required - 0x128: 0x45509, // oninvalid - 0x129: 0xb105, // align - 0x12b: 0x58a04, // icon - 0x12c: 0x64d02, // h6 - 0x12d: 0x1c404, // cols - 0x12e: 0x22e0a, // figcaption - 0x12f: 0x45e09, // onkeydown - 0x130: 0x66b08, // onsubmit - 0x131: 0x14d09, // oncanplay - 0x132: 0x70b03, // sup - 0x133: 0xc01, // p - 0x135: 0x40a09, // onemptied - 0x136: 0x39106, // oncopy - 0x137: 0x19c04, // cite - 0x138: 0x3a70a, // ondblclick - 0x13a: 0x50b0b, // onmousemove - 0x13c: 0x66d03, // sub - 0x13d: 0x48703, // rel - 0x13e: 0x5f08, // optgroup - 0x142: 0x9c07, // rowspan - 0x143: 0x37806, // source - 0x144: 0x21608, // noscript - 0x145: 0x1a304, // open - 0x146: 0x20403, // ins - 0x147: 0x2540d, // foreignObject - 0x148: 0x5ad0a, // onpopstate - 0x14a: 0x28d07, // enctype - 0x14b: 0x2760e, // onautocomplete - 0x14c: 0x35208, // textarea - 0x14e: 0x2780c, // autocomplete - 0x14f: 0x15702, // hr - 0x150: 0x1de08, // controls - 0x151: 0x10902, // id - 0x153: 0x2360c, // onafterprint - 0x155: 0x2610d, // foreignobject - 0x156: 0x32707, // marquee - 0x157: 0x59a07, // onpause - 0x158: 0x5e602, // dl - 0x159: 0x5206, // height - 0x15a: 0x34703, // min - 0x15b: 0x9307, // dirname - 0x15c: 0x1f209, // translate - 0x15d: 0x5604, // html - 0x15e: 0x34709, // minlength - 0x15f: 0x48607, // preload - 0x160: 0x71408, // template - 0x161: 0x3df0b, // ondragleave - 0x162: 0x3a02, // rb - 0x164: 0x5c003, // src - 0x165: 0x6dd06, // strong - 0x167: 0x7804, // samp - 0x168: 0x6f307, // address - 0x169: 0x55108, // ononline - 0x16b: 0x1310b, // placeholder - 0x16c: 0x2c406, // target - 0x16d: 0x20605, // small - 0x16e: 0x6ca07, // onwheel - 0x16f: 0x1c90a, // annotation - 0x170: 0x4740a, // spellcheck - 0x171: 0x7207, // details - 0x172: 0x10306, // canvas - 0x173: 0x12109, // autofocus - 0x174: 0xc05, // param - 0x176: 0x46308, // download - 0x177: 0x45203, // del - 0x178: 0x36c07, // onclose - 0x179: 0xb903, // kbd - 0x17a: 0x31906, // applet - 0x17b: 0x2e004, // href - 0x17c: 0x5f108, // onresize - 0x17e: 0x49d0c, // onloadeddata - 0x180: 0xcc02, // tr - 0x181: 0x2c00a, // formtarget - 0x182: 0x11005, // title - 0x183: 0x6ff05, // style - 0x184: 0xd206, // strike - 0x185: 0x59e06, // usemap - 0x186: 0x2fc06, // iframe - 0x187: 0x1004, // main - 0x189: 0x7b07, // picture - 0x18c: 0x31605, // ismap - 0x18e: 0x4a504, // data - 0x18f: 0x5905, // label - 0x191: 0x3d10e, // referrerpolicy - 0x192: 0x15602, // th - 0x194: 0x53606, // prompt - 0x195: 0x56807, // section - 0x197: 0x6d107, // optimum - 0x198: 0x2db04, // high - 0x199: 0x15c02, // h1 - 0x19a: 0x65909, // onstalled - 0x19b: 0x16d03, // var - 0x19c: 0x4204, // time - 0x19e: 0x67402, // ms - 0x19f: 0x33106, // header - 0x1a0: 0x4da09, // onmessage - 0x1a1: 0x1a605, // nonce - 0x1a2: 0x26e0a, // formaction - 0x1a3: 0x22006, // center - 0x1a4: 0x3704, // nobr - 0x1a5: 0x59505, // table - 0x1a6: 0x4a907, // listing - 0x1a7: 0x18106, // legend - 0x1a9: 0x29b09, // challenge - 0x1aa: 0x24806, // figure - 0x1ab: 0xe605, // media - 0x1ae: 0xd904, // type - 0x1af: 0x3f04, // font - 0x1b0: 0x4da0e, // onmessageerror - 0x1b1: 0x37108, // seamless - 0x1b2: 0x8703, // dfn - 0x1b3: 0x5c705, // defer - 0x1b4: 0xc303, // low - 0x1b5: 0x19a03, // rtc - 0x1b6: 0x5230b, // onmouseover - 0x1b7: 0x2b20a, // novalidate - 0x1b8: 0x71c0a, // workertype - 0x1ba: 0x3cd07, // itemref - 0x1bd: 0x1, // a - 0x1be: 0x31803, // map - 0x1bf: 0x400c, // ontimeupdate - 0x1c0: 0x15e07, // bgsound - 0x1c1: 0x3206, // keygen - 0x1c2: 0x2705, // tbody - 0x1c5: 0x64406, // onshow - 0x1c7: 0x2501, // s - 0x1c8: 0x6607, // pattern - 0x1cc: 0x14d10, // oncanplaythrough - 0x1ce: 0x2d702, // dd - 0x1cf: 0x6f906, // srcset - 0x1d0: 0x17003, // big - 0x1d2: 0x65108, // sortable - 0x1d3: 0x48007, // onkeyup - 0x1d5: 0x5a406, // onplay - 0x1d7: 0x4b804, // meta - 0x1d8: 0x40306, // ondrop - 0x1da: 0x60008, // onscroll - 0x1db: 0x1fb0b, // crossorigin - 0x1dc: 0x5730a, // onpageshow - 0x1dd: 0x4, // abbr - 0x1de: 0x9202, // td - 0x1df: 0x58b0f, // contenteditable - 0x1e0: 0x27206, // action - 0x1e1: 0x1400b, // playsinline - 0x1e2: 0x43107, // onfocus - 0x1e3: 0x2e008, // hreflang - 0x1e5: 0x5160a, // onmouseout - 0x1e6: 0x5ea07, // onreset - 0x1e7: 0x13c08, // autoplay - 0x1e8: 0x63109, // onseeking - 0x1ea: 0x67506, // scoped - 0x1ec: 0x30a, // radiogroup - 0x1ee: 0x3800b, // contextmenu - 0x1ef: 0x52e09, // onmouseup - 0x1f1: 0x2ca06, // hgroup - 0x1f2: 0x2080f, // allowfullscreen - 0x1f3: 0x4be08, // tabindex - 0x1f6: 0x30f07, // isindex - 0x1f7: 0x1a0e, // accept-charset - 0x1f8: 0x2ae0e, // formnovalidate - 0x1fb: 0x1c90e, // annotation-xml - 0x1fc: 0x6e05, // embed - 0x1fd: 0x21806, // script - 0x1fe: 0xbb06, // dialog - 0x1ff: 0x1d707, // command -} - -const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + - "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + - "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + - "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + - "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + - "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + - "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + - "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + - "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" + - "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" + - "ignObjectforeignobjectformactionautocompleteerrorformenctype" + - "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" + - "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" + - "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" + - "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" + - "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" + - "enterondragexitemreferrerpolicyondragleaveondragoverondragst" + - "articleondropzonemptiedondurationchangeonendedonerroronfocus" + - "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" + - "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" + - "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" + - "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" + - "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" + - "classectionbluronpageshowbronpastepublicontenteditableonpaus" + - "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" + - "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" + - "violationauxclickonseekedonseekingonselectedonshowidth6onsor" + - "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" + - "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" + - "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" + - "arysupsvgsystemplateworkertypewrap" diff --git a/vendor/golang.org/x/net/html/charset/charset.go b/vendor/golang.org/x/net/html/charset/charset.go deleted file mode 100644 index 13bed159..00000000 --- a/vendor/golang.org/x/net/html/charset/charset.go +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2013 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 charset provides common text encodings for HTML documents. -// -// The mapping from encoding labels to encodings is defined at -// https://encoding.spec.whatwg.org/. -package charset // import "golang.org/x/net/html/charset" - -import ( - "bytes" - "fmt" - "io" - "mime" - "strings" - "unicode/utf8" - - "golang.org/x/net/html" - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/encoding/htmlindex" - "golang.org/x/text/transform" -) - -// Lookup returns the encoding with the specified label, and its canonical -// name. It returns nil and the empty string if label is not one of the -// standard encodings for HTML. Matching is case-insensitive and ignores -// leading and trailing whitespace. Encoders will use HTML escape sequences for -// runes that are not supported by the character set. -func Lookup(label string) (e encoding.Encoding, name string) { - e, err := htmlindex.Get(label) - if err != nil { - return nil, "" - } - name, _ = htmlindex.Name(e) - return &htmlEncoding{e}, name -} - -type htmlEncoding struct{ encoding.Encoding } - -func (h *htmlEncoding) NewEncoder() *encoding.Encoder { - // HTML requires a non-terminating legacy encoder. We use HTML escapes to - // substitute unsupported code points. - return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder()) -} - -// DetermineEncoding determines the encoding of an HTML document by examining -// up to the first 1024 bytes of content and the declared Content-Type. -// -// See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding -func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) { - if len(content) > 1024 { - content = content[:1024] - } - - for _, b := range boms { - if bytes.HasPrefix(content, b.bom) { - e, name = Lookup(b.enc) - return e, name, true - } - } - - if _, params, err := mime.ParseMediaType(contentType); err == nil { - if cs, ok := params["charset"]; ok { - if e, name = Lookup(cs); e != nil { - return e, name, true - } - } - } - - if len(content) > 0 { - e, name = prescan(content) - if e != nil { - return e, name, false - } - } - - // Try to detect UTF-8. - // First eliminate any partial rune at the end. - for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { - b := content[i] - if b < 0x80 { - break - } - if utf8.RuneStart(b) { - content = content[:i] - break - } - } - hasHighBit := false - for _, c := range content { - if c >= 0x80 { - hasHighBit = true - break - } - } - if hasHighBit && utf8.Valid(content) { - return encoding.Nop, "utf-8", false - } - - // TODO: change default depending on user's locale? - return charmap.Windows1252, "windows-1252", false -} - -// NewReader returns an io.Reader that converts the content of r to UTF-8. -// It calls DetermineEncoding to find out what r's encoding is. -func NewReader(r io.Reader, contentType string) (io.Reader, error) { - preview := make([]byte, 1024) - n, err := io.ReadFull(r, preview) - switch { - case err == io.ErrUnexpectedEOF: - preview = preview[:n] - r = bytes.NewReader(preview) - case err != nil: - return nil, err - default: - r = io.MultiReader(bytes.NewReader(preview), r) - } - - if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop { - r = transform.NewReader(r, e.NewDecoder()) - } - return r, nil -} - -// NewReaderLabel returns a reader that converts from the specified charset to -// UTF-8. It uses Lookup to find the encoding that corresponds to label, and -// returns an error if Lookup returns nil. It is suitable for use as -// encoding/xml.Decoder's CharsetReader function. -func NewReaderLabel(label string, input io.Reader) (io.Reader, error) { - e, _ := Lookup(label) - if e == nil { - return nil, fmt.Errorf("unsupported charset: %q", label) - } - return transform.NewReader(input, e.NewDecoder()), nil -} - -func prescan(content []byte) (e encoding.Encoding, name string) { - z := html.NewTokenizer(bytes.NewReader(content)) - for { - switch z.Next() { - case html.ErrorToken: - return nil, "" - - case html.StartTagToken, html.SelfClosingTagToken: - tagName, hasAttr := z.TagName() - if !bytes.Equal(tagName, []byte("meta")) { - continue - } - attrList := make(map[string]bool) - gotPragma := false - - const ( - dontKnow = iota - doNeedPragma - doNotNeedPragma - ) - needPragma := dontKnow - - name = "" - e = nil - for hasAttr { - var key, val []byte - key, val, hasAttr = z.TagAttr() - ks := string(key) - if attrList[ks] { - continue - } - attrList[ks] = true - for i, c := range val { - if 'A' <= c && c <= 'Z' { - val[i] = c + 0x20 - } - } - - switch ks { - case "http-equiv": - if bytes.Equal(val, []byte("content-type")) { - gotPragma = true - } - - case "content": - if e == nil { - name = fromMetaElement(string(val)) - if name != "" { - e, name = Lookup(name) - if e != nil { - needPragma = doNeedPragma - } - } - } - - case "charset": - e, name = Lookup(string(val)) - needPragma = doNotNeedPragma - } - } - - if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma { - continue - } - - if strings.HasPrefix(name, "utf-16") { - name = "utf-8" - e = encoding.Nop - } - - if e != nil { - return e, name - } - } - } -} - -func fromMetaElement(s string) string { - for s != "" { - csLoc := strings.Index(s, "charset") - if csLoc == -1 { - return "" - } - s = s[csLoc+len("charset"):] - s = strings.TrimLeft(s, " \t\n\f\r") - if !strings.HasPrefix(s, "=") { - continue - } - s = s[1:] - s = strings.TrimLeft(s, " \t\n\f\r") - if s == "" { - return "" - } - if q := s[0]; q == '"' || q == '\'' { - s = s[1:] - closeQuote := strings.IndexRune(s, rune(q)) - if closeQuote == -1 { - return "" - } - return s[:closeQuote] - } - - end := strings.IndexAny(s, "; \t\n\f\r") - if end == -1 { - end = len(s) - } - return s[:end] - } - return "" -} - -var boms = []struct { - bom []byte - enc string -}{ - {[]byte{0xfe, 0xff}, "utf-16be"}, - {[]byte{0xff, 0xfe}, "utf-16le"}, - {[]byte{0xef, 0xbb, 0xbf}, "utf-8"}, -} diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go deleted file mode 100644 index a3a918f0..00000000 --- a/vendor/golang.org/x/net/html/const.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2011 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 html - -// Section 12.2.4.2 of the HTML5 specification says "The following elements -// have varying levels of special parsing rules". -// https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements -var isSpecialElementMap = map[string]bool{ - "address": true, - "applet": true, - "area": true, - "article": true, - "aside": true, - "base": true, - "basefont": true, - "bgsound": true, - "blockquote": true, - "body": true, - "br": true, - "button": true, - "caption": true, - "center": true, - "col": true, - "colgroup": true, - "dd": true, - "details": true, - "dir": true, - "div": true, - "dl": true, - "dt": true, - "embed": true, - "fieldset": true, - "figcaption": true, - "figure": true, - "footer": true, - "form": true, - "frame": true, - "frameset": true, - "h1": true, - "h2": true, - "h3": true, - "h4": true, - "h5": true, - "h6": true, - "head": true, - "header": true, - "hgroup": true, - "hr": true, - "html": true, - "iframe": true, - "img": true, - "input": true, - "isindex": true, // The 'isindex' element has been removed, but keep it for backwards compatibility. - "keygen": true, - "li": true, - "link": true, - "listing": true, - "main": true, - "marquee": true, - "menu": true, - "meta": true, - "nav": true, - "noembed": true, - "noframes": true, - "noscript": true, - "object": true, - "ol": true, - "p": true, - "param": true, - "plaintext": true, - "pre": true, - "script": true, - "section": true, - "select": true, - "source": true, - "style": true, - "summary": true, - "table": true, - "tbody": true, - "td": true, - "template": true, - "textarea": true, - "tfoot": true, - "th": true, - "thead": true, - "title": true, - "tr": true, - "track": true, - "ul": true, - "wbr": true, - "xmp": true, -} - -func isSpecialElement(element *Node) bool { - switch element.Namespace { - case "", "html": - return isSpecialElementMap[element.Data] - case "math": - switch element.Data { - case "mi", "mo", "mn", "ms", "mtext", "annotation-xml": - return true - } - case "svg": - switch element.Data { - case "foreignObject", "desc", "title": - return true - } - } - return false -} diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go deleted file mode 100644 index 822ed42a..00000000 --- a/vendor/golang.org/x/net/html/doc.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2010 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 html implements an HTML5-compliant tokenizer and parser. - -Tokenization is done by creating a Tokenizer for an io.Reader r. It is the -caller's responsibility to ensure that r provides UTF-8 encoded HTML. - - z := html.NewTokenizer(r) - -Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), -which parses the next token and returns its type, or an error: - - for { - tt := z.Next() - if tt == html.ErrorToken { - // ... - return ... - } - // Process the current token. - } - -There are two APIs for retrieving the current token. The high-level API is to -call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs -allow optionally calling Raw after Next but before Token, Text, TagName, or -TagAttr. In EBNF notation, the valid call sequence per token is: - - Next {Raw} [ Token | Text | TagName {TagAttr} ] - -Token returns an independent data structure that completely describes a token. -Entities (such as "<") are unescaped, tag names and attribute keys are -lower-cased, and attributes are collected into a []Attribute. For example: - - for { - if z.Next() == html.ErrorToken { - // Returning io.EOF indicates success. - return z.Err() - } - emitToken(z.Token()) - } - -The low-level API performs fewer allocations and copies, but the contents of -the []byte values returned by Text, TagName and TagAttr may change on the next -call to Next. For example, to extract an HTML page's anchor text: - - depth := 0 - for { - tt := z.Next() - switch tt { - case html.ErrorToken: - return z.Err() - case html.TextToken: - if depth > 0 { - // emitBytes should copy the []byte it receives, - // if it doesn't process it immediately. - emitBytes(z.Text()) - } - case html.StartTagToken, html.EndTagToken: - tn, _ := z.TagName() - if len(tn) == 1 && tn[0] == 'a' { - if tt == html.StartTagToken { - depth++ - } else { - depth-- - } - } - } - } - -Parsing is done by calling Parse with an io.Reader, which returns the root of -the parse tree (the document element) as a *Node. It is the caller's -responsibility to ensure that the Reader provides UTF-8 encoded HTML. For -example, to process each anchor node in depth-first order: - - doc, err := html.Parse(r) - if err != nil { - // ... - } - var f func(*html.Node) - f = func(n *html.Node) { - if n.Type == html.ElementNode && n.Data == "a" { - // Do something with n... - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - f(c) - } - } - f(doc) - -The relevant specifications include: -https://html.spec.whatwg.org/multipage/syntax.html and -https://html.spec.whatwg.org/multipage/syntax.html#tokenization -*/ -package html // import "golang.org/x/net/html" - -// The tokenization algorithm implemented by this package is not a line-by-line -// transliteration of the relatively verbose state-machine in the WHATWG -// specification. A more direct approach is used instead, where the program -// counter implies the state, such as whether it is tokenizing a tag or a text -// node. Specification compliance is verified by checking expected and actual -// outputs over a test suite rather than aiming for algorithmic fidelity. - -// TODO(nigeltao): Does a DOM API belong in this package or a separate one? -// TODO(nigeltao): How does parsing interact with a JavaScript engine? diff --git a/vendor/golang.org/x/net/html/doctype.go b/vendor/golang.org/x/net/html/doctype.go deleted file mode 100644 index c484e5a9..00000000 --- a/vendor/golang.org/x/net/html/doctype.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2011 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 html - -import ( - "strings" -) - -// parseDoctype parses the data from a DoctypeToken into a name, -// public identifier, and system identifier. It returns a Node whose Type -// is DoctypeNode, whose Data is the name, and which has attributes -// named "system" and "public" for the two identifiers if they were present. -// quirks is whether the document should be parsed in "quirks mode". -func parseDoctype(s string) (n *Node, quirks bool) { - n = &Node{Type: DoctypeNode} - - // Find the name. - space := strings.IndexAny(s, whitespace) - if space == -1 { - space = len(s) - } - n.Data = s[:space] - // The comparison to "html" is case-sensitive. - if n.Data != "html" { - quirks = true - } - n.Data = strings.ToLower(n.Data) - s = strings.TrimLeft(s[space:], whitespace) - - if len(s) < 6 { - // It can't start with "PUBLIC" or "SYSTEM". - // Ignore the rest of the string. - return n, quirks || s != "" - } - - key := strings.ToLower(s[:6]) - s = s[6:] - for key == "public" || key == "system" { - s = strings.TrimLeft(s, whitespace) - if s == "" { - break - } - quote := s[0] - if quote != '"' && quote != '\'' { - break - } - s = s[1:] - q := strings.IndexRune(s, rune(quote)) - var id string - if q == -1 { - id = s - s = "" - } else { - id = s[:q] - s = s[q+1:] - } - n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) - if key == "public" { - key = "system" - } else { - key = "" - } - } - - if key != "" || s != "" { - quirks = true - } else if len(n.Attr) > 0 { - if n.Attr[0].Key == "public" { - public := strings.ToLower(n.Attr[0].Val) - switch public { - case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": - quirks = true - default: - for _, q := range quirkyIDs { - if strings.HasPrefix(public, q) { - quirks = true - break - } - } - } - // The following two public IDs only cause quirks mode if there is no system ID. - if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || - strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { - quirks = true - } - } - if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && - strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" { - quirks = true - } - } - - return n, quirks -} - -// quirkyIDs is a list of public doctype identifiers that cause a document -// to be interpreted in quirks mode. The identifiers should be in lower case. -var quirkyIDs = []string{ - "+//silmaril//dtd html pro v0r11 19970101//", - "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", - "-//as//dtd html 3.0 aswedit + extensions//", - "-//ietf//dtd html 2.0 level 1//", - "-//ietf//dtd html 2.0 level 2//", - "-//ietf//dtd html 2.0 strict level 1//", - "-//ietf//dtd html 2.0 strict level 2//", - "-//ietf//dtd html 2.0 strict//", - "-//ietf//dtd html 2.0//", - "-//ietf//dtd html 2.1e//", - "-//ietf//dtd html 3.0//", - "-//ietf//dtd html 3.2 final//", - "-//ietf//dtd html 3.2//", - "-//ietf//dtd html 3//", - "-//ietf//dtd html level 0//", - "-//ietf//dtd html level 1//", - "-//ietf//dtd html level 2//", - "-//ietf//dtd html level 3//", - "-//ietf//dtd html strict level 0//", - "-//ietf//dtd html strict level 1//", - "-//ietf//dtd html strict level 2//", - "-//ietf//dtd html strict level 3//", - "-//ietf//dtd html strict//", - "-//ietf//dtd html//", - "-//metrius//dtd metrius presentational//", - "-//microsoft//dtd internet explorer 2.0 html strict//", - "-//microsoft//dtd internet explorer 2.0 html//", - "-//microsoft//dtd internet explorer 2.0 tables//", - "-//microsoft//dtd internet explorer 3.0 html strict//", - "-//microsoft//dtd internet explorer 3.0 html//", - "-//microsoft//dtd internet explorer 3.0 tables//", - "-//netscape comm. corp.//dtd html//", - "-//netscape comm. corp.//dtd strict html//", - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", - "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", - "-//spyglass//dtd html 2.0 extended//", - "-//sq//dtd html 2.0 hotmetal + extensions//", - "-//sun microsystems corp.//dtd hotjava html//", - "-//sun microsystems corp.//dtd hotjava strict html//", - "-//w3c//dtd html 3 1995-03-24//", - "-//w3c//dtd html 3.2 draft//", - "-//w3c//dtd html 3.2 final//", - "-//w3c//dtd html 3.2//", - "-//w3c//dtd html 3.2s draft//", - "-//w3c//dtd html 4.0 frameset//", - "-//w3c//dtd html 4.0 transitional//", - "-//w3c//dtd html experimental 19960712//", - "-//w3c//dtd html experimental 970421//", - "-//w3c//dtd w3 html//", - "-//w3o//dtd w3 html 3.0//", - "-//webtechs//dtd mozilla html 2.0//", - "-//webtechs//dtd mozilla html//", -} diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go deleted file mode 100644 index b628880a..00000000 --- a/vendor/golang.org/x/net/html/entity.go +++ /dev/null @@ -1,2253 +0,0 @@ -// Copyright 2010 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 html - -// All entities that do not end with ';' are 6 or fewer bytes long. -const longestEntityWithoutSemicolon = 6 - -// entity is a map from HTML entity names to their values. The semicolon matters: -// https://html.spec.whatwg.org/multipage/syntax.html#named-character-references -// lists both "amp" and "amp;" as two separate entries. -// -// Note that the HTML5 list is larger than the HTML4 list at -// http://www.w3.org/TR/html4/sgml/entities.html -var entity = map[string]rune{ - "AElig;": '\U000000C6', - "AMP;": '\U00000026', - "Aacute;": '\U000000C1', - "Abreve;": '\U00000102', - "Acirc;": '\U000000C2', - "Acy;": '\U00000410', - "Afr;": '\U0001D504', - "Agrave;": '\U000000C0', - "Alpha;": '\U00000391', - "Amacr;": '\U00000100', - "And;": '\U00002A53', - "Aogon;": '\U00000104', - "Aopf;": '\U0001D538', - "ApplyFunction;": '\U00002061', - "Aring;": '\U000000C5', - "Ascr;": '\U0001D49C', - "Assign;": '\U00002254', - "Atilde;": '\U000000C3', - "Auml;": '\U000000C4', - "Backslash;": '\U00002216', - "Barv;": '\U00002AE7', - "Barwed;": '\U00002306', - "Bcy;": '\U00000411', - "Because;": '\U00002235', - "Bernoullis;": '\U0000212C', - "Beta;": '\U00000392', - "Bfr;": '\U0001D505', - "Bopf;": '\U0001D539', - "Breve;": '\U000002D8', - "Bscr;": '\U0000212C', - "Bumpeq;": '\U0000224E', - "CHcy;": '\U00000427', - "COPY;": '\U000000A9', - "Cacute;": '\U00000106', - "Cap;": '\U000022D2', - "CapitalDifferentialD;": '\U00002145', - "Cayleys;": '\U0000212D', - "Ccaron;": '\U0000010C', - "Ccedil;": '\U000000C7', - "Ccirc;": '\U00000108', - "Cconint;": '\U00002230', - "Cdot;": '\U0000010A', - "Cedilla;": '\U000000B8', - "CenterDot;": '\U000000B7', - "Cfr;": '\U0000212D', - "Chi;": '\U000003A7', - "CircleDot;": '\U00002299', - "CircleMinus;": '\U00002296', - "CirclePlus;": '\U00002295', - "CircleTimes;": '\U00002297', - "ClockwiseContourIntegral;": '\U00002232', - "CloseCurlyDoubleQuote;": '\U0000201D', - "CloseCurlyQuote;": '\U00002019', - "Colon;": '\U00002237', - "Colone;": '\U00002A74', - "Congruent;": '\U00002261', - "Conint;": '\U0000222F', - "ContourIntegral;": '\U0000222E', - "Copf;": '\U00002102', - "Coproduct;": '\U00002210', - "CounterClockwiseContourIntegral;": '\U00002233', - "Cross;": '\U00002A2F', - "Cscr;": '\U0001D49E', - "Cup;": '\U000022D3', - "CupCap;": '\U0000224D', - "DD;": '\U00002145', - "DDotrahd;": '\U00002911', - "DJcy;": '\U00000402', - "DScy;": '\U00000405', - "DZcy;": '\U0000040F', - "Dagger;": '\U00002021', - "Darr;": '\U000021A1', - "Dashv;": '\U00002AE4', - "Dcaron;": '\U0000010E', - "Dcy;": '\U00000414', - "Del;": '\U00002207', - "Delta;": '\U00000394', - "Dfr;": '\U0001D507', - "DiacriticalAcute;": '\U000000B4', - "DiacriticalDot;": '\U000002D9', - "DiacriticalDoubleAcute;": '\U000002DD', - "DiacriticalGrave;": '\U00000060', - "DiacriticalTilde;": '\U000002DC', - "Diamond;": '\U000022C4', - "DifferentialD;": '\U00002146', - "Dopf;": '\U0001D53B', - "Dot;": '\U000000A8', - "DotDot;": '\U000020DC', - "DotEqual;": '\U00002250', - "DoubleContourIntegral;": '\U0000222F', - "DoubleDot;": '\U000000A8', - "DoubleDownArrow;": '\U000021D3', - "DoubleLeftArrow;": '\U000021D0', - "DoubleLeftRightArrow;": '\U000021D4', - "DoubleLeftTee;": '\U00002AE4', - "DoubleLongLeftArrow;": '\U000027F8', - "DoubleLongLeftRightArrow;": '\U000027FA', - "DoubleLongRightArrow;": '\U000027F9', - "DoubleRightArrow;": '\U000021D2', - "DoubleRightTee;": '\U000022A8', - "DoubleUpArrow;": '\U000021D1', - "DoubleUpDownArrow;": '\U000021D5', - "DoubleVerticalBar;": '\U00002225', - "DownArrow;": '\U00002193', - "DownArrowBar;": '\U00002913', - "DownArrowUpArrow;": '\U000021F5', - "DownBreve;": '\U00000311', - "DownLeftRightVector;": '\U00002950', - "DownLeftTeeVector;": '\U0000295E', - "DownLeftVector;": '\U000021BD', - "DownLeftVectorBar;": '\U00002956', - "DownRightTeeVector;": '\U0000295F', - "DownRightVector;": '\U000021C1', - "DownRightVectorBar;": '\U00002957', - "DownTee;": '\U000022A4', - "DownTeeArrow;": '\U000021A7', - "Downarrow;": '\U000021D3', - "Dscr;": '\U0001D49F', - "Dstrok;": '\U00000110', - "ENG;": '\U0000014A', - "ETH;": '\U000000D0', - "Eacute;": '\U000000C9', - "Ecaron;": '\U0000011A', - "Ecirc;": '\U000000CA', - "Ecy;": '\U0000042D', - "Edot;": '\U00000116', - "Efr;": '\U0001D508', - "Egrave;": '\U000000C8', - "Element;": '\U00002208', - "Emacr;": '\U00000112', - "EmptySmallSquare;": '\U000025FB', - "EmptyVerySmallSquare;": '\U000025AB', - "Eogon;": '\U00000118', - "Eopf;": '\U0001D53C', - "Epsilon;": '\U00000395', - "Equal;": '\U00002A75', - "EqualTilde;": '\U00002242', - "Equilibrium;": '\U000021CC', - "Escr;": '\U00002130', - "Esim;": '\U00002A73', - "Eta;": '\U00000397', - "Euml;": '\U000000CB', - "Exists;": '\U00002203', - "ExponentialE;": '\U00002147', - "Fcy;": '\U00000424', - "Ffr;": '\U0001D509', - "FilledSmallSquare;": '\U000025FC', - "FilledVerySmallSquare;": '\U000025AA', - "Fopf;": '\U0001D53D', - "ForAll;": '\U00002200', - "Fouriertrf;": '\U00002131', - "Fscr;": '\U00002131', - "GJcy;": '\U00000403', - "GT;": '\U0000003E', - "Gamma;": '\U00000393', - "Gammad;": '\U000003DC', - "Gbreve;": '\U0000011E', - "Gcedil;": '\U00000122', - "Gcirc;": '\U0000011C', - "Gcy;": '\U00000413', - "Gdot;": '\U00000120', - "Gfr;": '\U0001D50A', - "Gg;": '\U000022D9', - "Gopf;": '\U0001D53E', - "GreaterEqual;": '\U00002265', - "GreaterEqualLess;": '\U000022DB', - "GreaterFullEqual;": '\U00002267', - "GreaterGreater;": '\U00002AA2', - "GreaterLess;": '\U00002277', - "GreaterSlantEqual;": '\U00002A7E', - "GreaterTilde;": '\U00002273', - "Gscr;": '\U0001D4A2', - "Gt;": '\U0000226B', - "HARDcy;": '\U0000042A', - "Hacek;": '\U000002C7', - "Hat;": '\U0000005E', - "Hcirc;": '\U00000124', - "Hfr;": '\U0000210C', - "HilbertSpace;": '\U0000210B', - "Hopf;": '\U0000210D', - "HorizontalLine;": '\U00002500', - "Hscr;": '\U0000210B', - "Hstrok;": '\U00000126', - "HumpDownHump;": '\U0000224E', - "HumpEqual;": '\U0000224F', - "IEcy;": '\U00000415', - "IJlig;": '\U00000132', - "IOcy;": '\U00000401', - "Iacute;": '\U000000CD', - "Icirc;": '\U000000CE', - "Icy;": '\U00000418', - "Idot;": '\U00000130', - "Ifr;": '\U00002111', - "Igrave;": '\U000000CC', - "Im;": '\U00002111', - "Imacr;": '\U0000012A', - "ImaginaryI;": '\U00002148', - "Implies;": '\U000021D2', - "Int;": '\U0000222C', - "Integral;": '\U0000222B', - "Intersection;": '\U000022C2', - "InvisibleComma;": '\U00002063', - "InvisibleTimes;": '\U00002062', - "Iogon;": '\U0000012E', - "Iopf;": '\U0001D540', - "Iota;": '\U00000399', - "Iscr;": '\U00002110', - "Itilde;": '\U00000128', - "Iukcy;": '\U00000406', - "Iuml;": '\U000000CF', - "Jcirc;": '\U00000134', - "Jcy;": '\U00000419', - "Jfr;": '\U0001D50D', - "Jopf;": '\U0001D541', - "Jscr;": '\U0001D4A5', - "Jsercy;": '\U00000408', - "Jukcy;": '\U00000404', - "KHcy;": '\U00000425', - "KJcy;": '\U0000040C', - "Kappa;": '\U0000039A', - "Kcedil;": '\U00000136', - "Kcy;": '\U0000041A', - "Kfr;": '\U0001D50E', - "Kopf;": '\U0001D542', - "Kscr;": '\U0001D4A6', - "LJcy;": '\U00000409', - "LT;": '\U0000003C', - "Lacute;": '\U00000139', - "Lambda;": '\U0000039B', - "Lang;": '\U000027EA', - "Laplacetrf;": '\U00002112', - "Larr;": '\U0000219E', - "Lcaron;": '\U0000013D', - "Lcedil;": '\U0000013B', - "Lcy;": '\U0000041B', - "LeftAngleBracket;": '\U000027E8', - "LeftArrow;": '\U00002190', - "LeftArrowBar;": '\U000021E4', - "LeftArrowRightArrow;": '\U000021C6', - "LeftCeiling;": '\U00002308', - "LeftDoubleBracket;": '\U000027E6', - "LeftDownTeeVector;": '\U00002961', - "LeftDownVector;": '\U000021C3', - "LeftDownVectorBar;": '\U00002959', - "LeftFloor;": '\U0000230A', - "LeftRightArrow;": '\U00002194', - "LeftRightVector;": '\U0000294E', - "LeftTee;": '\U000022A3', - "LeftTeeArrow;": '\U000021A4', - "LeftTeeVector;": '\U0000295A', - "LeftTriangle;": '\U000022B2', - "LeftTriangleBar;": '\U000029CF', - "LeftTriangleEqual;": '\U000022B4', - "LeftUpDownVector;": '\U00002951', - "LeftUpTeeVector;": '\U00002960', - "LeftUpVector;": '\U000021BF', - "LeftUpVectorBar;": '\U00002958', - "LeftVector;": '\U000021BC', - "LeftVectorBar;": '\U00002952', - "Leftarrow;": '\U000021D0', - "Leftrightarrow;": '\U000021D4', - "LessEqualGreater;": '\U000022DA', - "LessFullEqual;": '\U00002266', - "LessGreater;": '\U00002276', - "LessLess;": '\U00002AA1', - "LessSlantEqual;": '\U00002A7D', - "LessTilde;": '\U00002272', - "Lfr;": '\U0001D50F', - "Ll;": '\U000022D8', - "Lleftarrow;": '\U000021DA', - "Lmidot;": '\U0000013F', - "LongLeftArrow;": '\U000027F5', - "LongLeftRightArrow;": '\U000027F7', - "LongRightArrow;": '\U000027F6', - "Longleftarrow;": '\U000027F8', - "Longleftrightarrow;": '\U000027FA', - "Longrightarrow;": '\U000027F9', - "Lopf;": '\U0001D543', - "LowerLeftArrow;": '\U00002199', - "LowerRightArrow;": '\U00002198', - "Lscr;": '\U00002112', - "Lsh;": '\U000021B0', - "Lstrok;": '\U00000141', - "Lt;": '\U0000226A', - "Map;": '\U00002905', - "Mcy;": '\U0000041C', - "MediumSpace;": '\U0000205F', - "Mellintrf;": '\U00002133', - "Mfr;": '\U0001D510', - "MinusPlus;": '\U00002213', - "Mopf;": '\U0001D544', - "Mscr;": '\U00002133', - "Mu;": '\U0000039C', - "NJcy;": '\U0000040A', - "Nacute;": '\U00000143', - "Ncaron;": '\U00000147', - "Ncedil;": '\U00000145', - "Ncy;": '\U0000041D', - "NegativeMediumSpace;": '\U0000200B', - "NegativeThickSpace;": '\U0000200B', - "NegativeThinSpace;": '\U0000200B', - "NegativeVeryThinSpace;": '\U0000200B', - "NestedGreaterGreater;": '\U0000226B', - "NestedLessLess;": '\U0000226A', - "NewLine;": '\U0000000A', - "Nfr;": '\U0001D511', - "NoBreak;": '\U00002060', - "NonBreakingSpace;": '\U000000A0', - "Nopf;": '\U00002115', - "Not;": '\U00002AEC', - "NotCongruent;": '\U00002262', - "NotCupCap;": '\U0000226D', - "NotDoubleVerticalBar;": '\U00002226', - "NotElement;": '\U00002209', - "NotEqual;": '\U00002260', - "NotExists;": '\U00002204', - "NotGreater;": '\U0000226F', - "NotGreaterEqual;": '\U00002271', - "NotGreaterLess;": '\U00002279', - "NotGreaterTilde;": '\U00002275', - "NotLeftTriangle;": '\U000022EA', - "NotLeftTriangleEqual;": '\U000022EC', - "NotLess;": '\U0000226E', - "NotLessEqual;": '\U00002270', - "NotLessGreater;": '\U00002278', - "NotLessTilde;": '\U00002274', - "NotPrecedes;": '\U00002280', - "NotPrecedesSlantEqual;": '\U000022E0', - "NotReverseElement;": '\U0000220C', - "NotRightTriangle;": '\U000022EB', - "NotRightTriangleEqual;": '\U000022ED', - "NotSquareSubsetEqual;": '\U000022E2', - "NotSquareSupersetEqual;": '\U000022E3', - "NotSubsetEqual;": '\U00002288', - "NotSucceeds;": '\U00002281', - "NotSucceedsSlantEqual;": '\U000022E1', - "NotSupersetEqual;": '\U00002289', - "NotTilde;": '\U00002241', - "NotTildeEqual;": '\U00002244', - "NotTildeFullEqual;": '\U00002247', - "NotTildeTilde;": '\U00002249', - "NotVerticalBar;": '\U00002224', - "Nscr;": '\U0001D4A9', - "Ntilde;": '\U000000D1', - "Nu;": '\U0000039D', - "OElig;": '\U00000152', - "Oacute;": '\U000000D3', - "Ocirc;": '\U000000D4', - "Ocy;": '\U0000041E', - "Odblac;": '\U00000150', - "Ofr;": '\U0001D512', - "Ograve;": '\U000000D2', - "Omacr;": '\U0000014C', - "Omega;": '\U000003A9', - "Omicron;": '\U0000039F', - "Oopf;": '\U0001D546', - "OpenCurlyDoubleQuote;": '\U0000201C', - "OpenCurlyQuote;": '\U00002018', - "Or;": '\U00002A54', - "Oscr;": '\U0001D4AA', - "Oslash;": '\U000000D8', - "Otilde;": '\U000000D5', - "Otimes;": '\U00002A37', - "Ouml;": '\U000000D6', - "OverBar;": '\U0000203E', - "OverBrace;": '\U000023DE', - "OverBracket;": '\U000023B4', - "OverParenthesis;": '\U000023DC', - "PartialD;": '\U00002202', - "Pcy;": '\U0000041F', - "Pfr;": '\U0001D513', - "Phi;": '\U000003A6', - "Pi;": '\U000003A0', - "PlusMinus;": '\U000000B1', - "Poincareplane;": '\U0000210C', - "Popf;": '\U00002119', - "Pr;": '\U00002ABB', - "Precedes;": '\U0000227A', - "PrecedesEqual;": '\U00002AAF', - "PrecedesSlantEqual;": '\U0000227C', - "PrecedesTilde;": '\U0000227E', - "Prime;": '\U00002033', - "Product;": '\U0000220F', - "Proportion;": '\U00002237', - "Proportional;": '\U0000221D', - "Pscr;": '\U0001D4AB', - "Psi;": '\U000003A8', - "QUOT;": '\U00000022', - "Qfr;": '\U0001D514', - "Qopf;": '\U0000211A', - "Qscr;": '\U0001D4AC', - "RBarr;": '\U00002910', - "REG;": '\U000000AE', - "Racute;": '\U00000154', - "Rang;": '\U000027EB', - "Rarr;": '\U000021A0', - "Rarrtl;": '\U00002916', - "Rcaron;": '\U00000158', - "Rcedil;": '\U00000156', - "Rcy;": '\U00000420', - "Re;": '\U0000211C', - "ReverseElement;": '\U0000220B', - "ReverseEquilibrium;": '\U000021CB', - "ReverseUpEquilibrium;": '\U0000296F', - "Rfr;": '\U0000211C', - "Rho;": '\U000003A1', - "RightAngleBracket;": '\U000027E9', - "RightArrow;": '\U00002192', - "RightArrowBar;": '\U000021E5', - "RightArrowLeftArrow;": '\U000021C4', - "RightCeiling;": '\U00002309', - "RightDoubleBracket;": '\U000027E7', - "RightDownTeeVector;": '\U0000295D', - "RightDownVector;": '\U000021C2', - "RightDownVectorBar;": '\U00002955', - "RightFloor;": '\U0000230B', - "RightTee;": '\U000022A2', - "RightTeeArrow;": '\U000021A6', - "RightTeeVector;": '\U0000295B', - "RightTriangle;": '\U000022B3', - "RightTriangleBar;": '\U000029D0', - "RightTriangleEqual;": '\U000022B5', - "RightUpDownVector;": '\U0000294F', - "RightUpTeeVector;": '\U0000295C', - "RightUpVector;": '\U000021BE', - "RightUpVectorBar;": '\U00002954', - "RightVector;": '\U000021C0', - "RightVectorBar;": '\U00002953', - "Rightarrow;": '\U000021D2', - "Ropf;": '\U0000211D', - "RoundImplies;": '\U00002970', - "Rrightarrow;": '\U000021DB', - "Rscr;": '\U0000211B', - "Rsh;": '\U000021B1', - "RuleDelayed;": '\U000029F4', - "SHCHcy;": '\U00000429', - "SHcy;": '\U00000428', - "SOFTcy;": '\U0000042C', - "Sacute;": '\U0000015A', - "Sc;": '\U00002ABC', - "Scaron;": '\U00000160', - "Scedil;": '\U0000015E', - "Scirc;": '\U0000015C', - "Scy;": '\U00000421', - "Sfr;": '\U0001D516', - "ShortDownArrow;": '\U00002193', - "ShortLeftArrow;": '\U00002190', - "ShortRightArrow;": '\U00002192', - "ShortUpArrow;": '\U00002191', - "Sigma;": '\U000003A3', - "SmallCircle;": '\U00002218', - "Sopf;": '\U0001D54A', - "Sqrt;": '\U0000221A', - "Square;": '\U000025A1', - "SquareIntersection;": '\U00002293', - "SquareSubset;": '\U0000228F', - "SquareSubsetEqual;": '\U00002291', - "SquareSuperset;": '\U00002290', - "SquareSupersetEqual;": '\U00002292', - "SquareUnion;": '\U00002294', - "Sscr;": '\U0001D4AE', - "Star;": '\U000022C6', - "Sub;": '\U000022D0', - "Subset;": '\U000022D0', - "SubsetEqual;": '\U00002286', - "Succeeds;": '\U0000227B', - "SucceedsEqual;": '\U00002AB0', - "SucceedsSlantEqual;": '\U0000227D', - "SucceedsTilde;": '\U0000227F', - "SuchThat;": '\U0000220B', - "Sum;": '\U00002211', - "Sup;": '\U000022D1', - "Superset;": '\U00002283', - "SupersetEqual;": '\U00002287', - "Supset;": '\U000022D1', - "THORN;": '\U000000DE', - "TRADE;": '\U00002122', - "TSHcy;": '\U0000040B', - "TScy;": '\U00000426', - "Tab;": '\U00000009', - "Tau;": '\U000003A4', - "Tcaron;": '\U00000164', - "Tcedil;": '\U00000162', - "Tcy;": '\U00000422', - "Tfr;": '\U0001D517', - "Therefore;": '\U00002234', - "Theta;": '\U00000398', - "ThinSpace;": '\U00002009', - "Tilde;": '\U0000223C', - "TildeEqual;": '\U00002243', - "TildeFullEqual;": '\U00002245', - "TildeTilde;": '\U00002248', - "Topf;": '\U0001D54B', - "TripleDot;": '\U000020DB', - "Tscr;": '\U0001D4AF', - "Tstrok;": '\U00000166', - "Uacute;": '\U000000DA', - "Uarr;": '\U0000219F', - "Uarrocir;": '\U00002949', - "Ubrcy;": '\U0000040E', - "Ubreve;": '\U0000016C', - "Ucirc;": '\U000000DB', - "Ucy;": '\U00000423', - "Udblac;": '\U00000170', - "Ufr;": '\U0001D518', - "Ugrave;": '\U000000D9', - "Umacr;": '\U0000016A', - "UnderBar;": '\U0000005F', - "UnderBrace;": '\U000023DF', - "UnderBracket;": '\U000023B5', - "UnderParenthesis;": '\U000023DD', - "Union;": '\U000022C3', - "UnionPlus;": '\U0000228E', - "Uogon;": '\U00000172', - "Uopf;": '\U0001D54C', - "UpArrow;": '\U00002191', - "UpArrowBar;": '\U00002912', - "UpArrowDownArrow;": '\U000021C5', - "UpDownArrow;": '\U00002195', - "UpEquilibrium;": '\U0000296E', - "UpTee;": '\U000022A5', - "UpTeeArrow;": '\U000021A5', - "Uparrow;": '\U000021D1', - "Updownarrow;": '\U000021D5', - "UpperLeftArrow;": '\U00002196', - "UpperRightArrow;": '\U00002197', - "Upsi;": '\U000003D2', - "Upsilon;": '\U000003A5', - "Uring;": '\U0000016E', - "Uscr;": '\U0001D4B0', - "Utilde;": '\U00000168', - "Uuml;": '\U000000DC', - "VDash;": '\U000022AB', - "Vbar;": '\U00002AEB', - "Vcy;": '\U00000412', - "Vdash;": '\U000022A9', - "Vdashl;": '\U00002AE6', - "Vee;": '\U000022C1', - "Verbar;": '\U00002016', - "Vert;": '\U00002016', - "VerticalBar;": '\U00002223', - "VerticalLine;": '\U0000007C', - "VerticalSeparator;": '\U00002758', - "VerticalTilde;": '\U00002240', - "VeryThinSpace;": '\U0000200A', - "Vfr;": '\U0001D519', - "Vopf;": '\U0001D54D', - "Vscr;": '\U0001D4B1', - "Vvdash;": '\U000022AA', - "Wcirc;": '\U00000174', - "Wedge;": '\U000022C0', - "Wfr;": '\U0001D51A', - "Wopf;": '\U0001D54E', - "Wscr;": '\U0001D4B2', - "Xfr;": '\U0001D51B', - "Xi;": '\U0000039E', - "Xopf;": '\U0001D54F', - "Xscr;": '\U0001D4B3', - "YAcy;": '\U0000042F', - "YIcy;": '\U00000407', - "YUcy;": '\U0000042E', - "Yacute;": '\U000000DD', - "Ycirc;": '\U00000176', - "Ycy;": '\U0000042B', - "Yfr;": '\U0001D51C', - "Yopf;": '\U0001D550', - "Yscr;": '\U0001D4B4', - "Yuml;": '\U00000178', - "ZHcy;": '\U00000416', - "Zacute;": '\U00000179', - "Zcaron;": '\U0000017D', - "Zcy;": '\U00000417', - "Zdot;": '\U0000017B', - "ZeroWidthSpace;": '\U0000200B', - "Zeta;": '\U00000396', - "Zfr;": '\U00002128', - "Zopf;": '\U00002124', - "Zscr;": '\U0001D4B5', - "aacute;": '\U000000E1', - "abreve;": '\U00000103', - "ac;": '\U0000223E', - "acd;": '\U0000223F', - "acirc;": '\U000000E2', - "acute;": '\U000000B4', - "acy;": '\U00000430', - "aelig;": '\U000000E6', - "af;": '\U00002061', - "afr;": '\U0001D51E', - "agrave;": '\U000000E0', - "alefsym;": '\U00002135', - "aleph;": '\U00002135', - "alpha;": '\U000003B1', - "amacr;": '\U00000101', - "amalg;": '\U00002A3F', - "amp;": '\U00000026', - "and;": '\U00002227', - "andand;": '\U00002A55', - "andd;": '\U00002A5C', - "andslope;": '\U00002A58', - "andv;": '\U00002A5A', - "ang;": '\U00002220', - "ange;": '\U000029A4', - "angle;": '\U00002220', - "angmsd;": '\U00002221', - "angmsdaa;": '\U000029A8', - "angmsdab;": '\U000029A9', - "angmsdac;": '\U000029AA', - "angmsdad;": '\U000029AB', - "angmsdae;": '\U000029AC', - "angmsdaf;": '\U000029AD', - "angmsdag;": '\U000029AE', - "angmsdah;": '\U000029AF', - "angrt;": '\U0000221F', - "angrtvb;": '\U000022BE', - "angrtvbd;": '\U0000299D', - "angsph;": '\U00002222', - "angst;": '\U000000C5', - "angzarr;": '\U0000237C', - "aogon;": '\U00000105', - "aopf;": '\U0001D552', - "ap;": '\U00002248', - "apE;": '\U00002A70', - "apacir;": '\U00002A6F', - "ape;": '\U0000224A', - "apid;": '\U0000224B', - "apos;": '\U00000027', - "approx;": '\U00002248', - "approxeq;": '\U0000224A', - "aring;": '\U000000E5', - "ascr;": '\U0001D4B6', - "ast;": '\U0000002A', - "asymp;": '\U00002248', - "asympeq;": '\U0000224D', - "atilde;": '\U000000E3', - "auml;": '\U000000E4', - "awconint;": '\U00002233', - "awint;": '\U00002A11', - "bNot;": '\U00002AED', - "backcong;": '\U0000224C', - "backepsilon;": '\U000003F6', - "backprime;": '\U00002035', - "backsim;": '\U0000223D', - "backsimeq;": '\U000022CD', - "barvee;": '\U000022BD', - "barwed;": '\U00002305', - "barwedge;": '\U00002305', - "bbrk;": '\U000023B5', - "bbrktbrk;": '\U000023B6', - "bcong;": '\U0000224C', - "bcy;": '\U00000431', - "bdquo;": '\U0000201E', - "becaus;": '\U00002235', - "because;": '\U00002235', - "bemptyv;": '\U000029B0', - "bepsi;": '\U000003F6', - "bernou;": '\U0000212C', - "beta;": '\U000003B2', - "beth;": '\U00002136', - "between;": '\U0000226C', - "bfr;": '\U0001D51F', - "bigcap;": '\U000022C2', - "bigcirc;": '\U000025EF', - "bigcup;": '\U000022C3', - "bigodot;": '\U00002A00', - "bigoplus;": '\U00002A01', - "bigotimes;": '\U00002A02', - "bigsqcup;": '\U00002A06', - "bigstar;": '\U00002605', - "bigtriangledown;": '\U000025BD', - "bigtriangleup;": '\U000025B3', - "biguplus;": '\U00002A04', - "bigvee;": '\U000022C1', - "bigwedge;": '\U000022C0', - "bkarow;": '\U0000290D', - "blacklozenge;": '\U000029EB', - "blacksquare;": '\U000025AA', - "blacktriangle;": '\U000025B4', - "blacktriangledown;": '\U000025BE', - "blacktriangleleft;": '\U000025C2', - "blacktriangleright;": '\U000025B8', - "blank;": '\U00002423', - "blk12;": '\U00002592', - "blk14;": '\U00002591', - "blk34;": '\U00002593', - "block;": '\U00002588', - "bnot;": '\U00002310', - "bopf;": '\U0001D553', - "bot;": '\U000022A5', - "bottom;": '\U000022A5', - "bowtie;": '\U000022C8', - "boxDL;": '\U00002557', - "boxDR;": '\U00002554', - "boxDl;": '\U00002556', - "boxDr;": '\U00002553', - "boxH;": '\U00002550', - "boxHD;": '\U00002566', - "boxHU;": '\U00002569', - "boxHd;": '\U00002564', - "boxHu;": '\U00002567', - "boxUL;": '\U0000255D', - "boxUR;": '\U0000255A', - "boxUl;": '\U0000255C', - "boxUr;": '\U00002559', - "boxV;": '\U00002551', - "boxVH;": '\U0000256C', - "boxVL;": '\U00002563', - "boxVR;": '\U00002560', - "boxVh;": '\U0000256B', - "boxVl;": '\U00002562', - "boxVr;": '\U0000255F', - "boxbox;": '\U000029C9', - "boxdL;": '\U00002555', - "boxdR;": '\U00002552', - "boxdl;": '\U00002510', - "boxdr;": '\U0000250C', - "boxh;": '\U00002500', - "boxhD;": '\U00002565', - "boxhU;": '\U00002568', - "boxhd;": '\U0000252C', - "boxhu;": '\U00002534', - "boxminus;": '\U0000229F', - "boxplus;": '\U0000229E', - "boxtimes;": '\U000022A0', - "boxuL;": '\U0000255B', - "boxuR;": '\U00002558', - "boxul;": '\U00002518', - "boxur;": '\U00002514', - "boxv;": '\U00002502', - "boxvH;": '\U0000256A', - "boxvL;": '\U00002561', - "boxvR;": '\U0000255E', - "boxvh;": '\U0000253C', - "boxvl;": '\U00002524', - "boxvr;": '\U0000251C', - "bprime;": '\U00002035', - "breve;": '\U000002D8', - "brvbar;": '\U000000A6', - "bscr;": '\U0001D4B7', - "bsemi;": '\U0000204F', - "bsim;": '\U0000223D', - "bsime;": '\U000022CD', - "bsol;": '\U0000005C', - "bsolb;": '\U000029C5', - "bsolhsub;": '\U000027C8', - "bull;": '\U00002022', - "bullet;": '\U00002022', - "bump;": '\U0000224E', - "bumpE;": '\U00002AAE', - "bumpe;": '\U0000224F', - "bumpeq;": '\U0000224F', - "cacute;": '\U00000107', - "cap;": '\U00002229', - "capand;": '\U00002A44', - "capbrcup;": '\U00002A49', - "capcap;": '\U00002A4B', - "capcup;": '\U00002A47', - "capdot;": '\U00002A40', - "caret;": '\U00002041', - "caron;": '\U000002C7', - "ccaps;": '\U00002A4D', - "ccaron;": '\U0000010D', - "ccedil;": '\U000000E7', - "ccirc;": '\U00000109', - "ccups;": '\U00002A4C', - "ccupssm;": '\U00002A50', - "cdot;": '\U0000010B', - "cedil;": '\U000000B8', - "cemptyv;": '\U000029B2', - "cent;": '\U000000A2', - "centerdot;": '\U000000B7', - "cfr;": '\U0001D520', - "chcy;": '\U00000447', - "check;": '\U00002713', - "checkmark;": '\U00002713', - "chi;": '\U000003C7', - "cir;": '\U000025CB', - "cirE;": '\U000029C3', - "circ;": '\U000002C6', - "circeq;": '\U00002257', - "circlearrowleft;": '\U000021BA', - "circlearrowright;": '\U000021BB', - "circledR;": '\U000000AE', - "circledS;": '\U000024C8', - "circledast;": '\U0000229B', - "circledcirc;": '\U0000229A', - "circleddash;": '\U0000229D', - "cire;": '\U00002257', - "cirfnint;": '\U00002A10', - "cirmid;": '\U00002AEF', - "cirscir;": '\U000029C2', - "clubs;": '\U00002663', - "clubsuit;": '\U00002663', - "colon;": '\U0000003A', - "colone;": '\U00002254', - "coloneq;": '\U00002254', - "comma;": '\U0000002C', - "commat;": '\U00000040', - "comp;": '\U00002201', - "compfn;": '\U00002218', - "complement;": '\U00002201', - "complexes;": '\U00002102', - "cong;": '\U00002245', - "congdot;": '\U00002A6D', - "conint;": '\U0000222E', - "copf;": '\U0001D554', - "coprod;": '\U00002210', - "copy;": '\U000000A9', - "copysr;": '\U00002117', - "crarr;": '\U000021B5', - "cross;": '\U00002717', - "cscr;": '\U0001D4B8', - "csub;": '\U00002ACF', - "csube;": '\U00002AD1', - "csup;": '\U00002AD0', - "csupe;": '\U00002AD2', - "ctdot;": '\U000022EF', - "cudarrl;": '\U00002938', - "cudarrr;": '\U00002935', - "cuepr;": '\U000022DE', - "cuesc;": '\U000022DF', - "cularr;": '\U000021B6', - "cularrp;": '\U0000293D', - "cup;": '\U0000222A', - "cupbrcap;": '\U00002A48', - "cupcap;": '\U00002A46', - "cupcup;": '\U00002A4A', - "cupdot;": '\U0000228D', - "cupor;": '\U00002A45', - "curarr;": '\U000021B7', - "curarrm;": '\U0000293C', - "curlyeqprec;": '\U000022DE', - "curlyeqsucc;": '\U000022DF', - "curlyvee;": '\U000022CE', - "curlywedge;": '\U000022CF', - "curren;": '\U000000A4', - "curvearrowleft;": '\U000021B6', - "curvearrowright;": '\U000021B7', - "cuvee;": '\U000022CE', - "cuwed;": '\U000022CF', - "cwconint;": '\U00002232', - "cwint;": '\U00002231', - "cylcty;": '\U0000232D', - "dArr;": '\U000021D3', - "dHar;": '\U00002965', - "dagger;": '\U00002020', - "daleth;": '\U00002138', - "darr;": '\U00002193', - "dash;": '\U00002010', - "dashv;": '\U000022A3', - "dbkarow;": '\U0000290F', - "dblac;": '\U000002DD', - "dcaron;": '\U0000010F', - "dcy;": '\U00000434', - "dd;": '\U00002146', - "ddagger;": '\U00002021', - "ddarr;": '\U000021CA', - "ddotseq;": '\U00002A77', - "deg;": '\U000000B0', - "delta;": '\U000003B4', - "demptyv;": '\U000029B1', - "dfisht;": '\U0000297F', - "dfr;": '\U0001D521', - "dharl;": '\U000021C3', - "dharr;": '\U000021C2', - "diam;": '\U000022C4', - "diamond;": '\U000022C4', - "diamondsuit;": '\U00002666', - "diams;": '\U00002666', - "die;": '\U000000A8', - "digamma;": '\U000003DD', - "disin;": '\U000022F2', - "div;": '\U000000F7', - "divide;": '\U000000F7', - "divideontimes;": '\U000022C7', - "divonx;": '\U000022C7', - "djcy;": '\U00000452', - "dlcorn;": '\U0000231E', - "dlcrop;": '\U0000230D', - "dollar;": '\U00000024', - "dopf;": '\U0001D555', - "dot;": '\U000002D9', - "doteq;": '\U00002250', - "doteqdot;": '\U00002251', - "dotminus;": '\U00002238', - "dotplus;": '\U00002214', - "dotsquare;": '\U000022A1', - "doublebarwedge;": '\U00002306', - "downarrow;": '\U00002193', - "downdownarrows;": '\U000021CA', - "downharpoonleft;": '\U000021C3', - "downharpoonright;": '\U000021C2', - "drbkarow;": '\U00002910', - "drcorn;": '\U0000231F', - "drcrop;": '\U0000230C', - "dscr;": '\U0001D4B9', - "dscy;": '\U00000455', - "dsol;": '\U000029F6', - "dstrok;": '\U00000111', - "dtdot;": '\U000022F1', - "dtri;": '\U000025BF', - "dtrif;": '\U000025BE', - "duarr;": '\U000021F5', - "duhar;": '\U0000296F', - "dwangle;": '\U000029A6', - "dzcy;": '\U0000045F', - "dzigrarr;": '\U000027FF', - "eDDot;": '\U00002A77', - "eDot;": '\U00002251', - "eacute;": '\U000000E9', - "easter;": '\U00002A6E', - "ecaron;": '\U0000011B', - "ecir;": '\U00002256', - "ecirc;": '\U000000EA', - "ecolon;": '\U00002255', - "ecy;": '\U0000044D', - "edot;": '\U00000117', - "ee;": '\U00002147', - "efDot;": '\U00002252', - "efr;": '\U0001D522', - "eg;": '\U00002A9A', - "egrave;": '\U000000E8', - "egs;": '\U00002A96', - "egsdot;": '\U00002A98', - "el;": '\U00002A99', - "elinters;": '\U000023E7', - "ell;": '\U00002113', - "els;": '\U00002A95', - "elsdot;": '\U00002A97', - "emacr;": '\U00000113', - "empty;": '\U00002205', - "emptyset;": '\U00002205', - "emptyv;": '\U00002205', - "emsp;": '\U00002003', - "emsp13;": '\U00002004', - "emsp14;": '\U00002005', - "eng;": '\U0000014B', - "ensp;": '\U00002002', - "eogon;": '\U00000119', - "eopf;": '\U0001D556', - "epar;": '\U000022D5', - "eparsl;": '\U000029E3', - "eplus;": '\U00002A71', - "epsi;": '\U000003B5', - "epsilon;": '\U000003B5', - "epsiv;": '\U000003F5', - "eqcirc;": '\U00002256', - "eqcolon;": '\U00002255', - "eqsim;": '\U00002242', - "eqslantgtr;": '\U00002A96', - "eqslantless;": '\U00002A95', - "equals;": '\U0000003D', - "equest;": '\U0000225F', - "equiv;": '\U00002261', - "equivDD;": '\U00002A78', - "eqvparsl;": '\U000029E5', - "erDot;": '\U00002253', - "erarr;": '\U00002971', - "escr;": '\U0000212F', - "esdot;": '\U00002250', - "esim;": '\U00002242', - "eta;": '\U000003B7', - "eth;": '\U000000F0', - "euml;": '\U000000EB', - "euro;": '\U000020AC', - "excl;": '\U00000021', - "exist;": '\U00002203', - "expectation;": '\U00002130', - "exponentiale;": '\U00002147', - "fallingdotseq;": '\U00002252', - "fcy;": '\U00000444', - "female;": '\U00002640', - "ffilig;": '\U0000FB03', - "fflig;": '\U0000FB00', - "ffllig;": '\U0000FB04', - "ffr;": '\U0001D523', - "filig;": '\U0000FB01', - "flat;": '\U0000266D', - "fllig;": '\U0000FB02', - "fltns;": '\U000025B1', - "fnof;": '\U00000192', - "fopf;": '\U0001D557', - "forall;": '\U00002200', - "fork;": '\U000022D4', - "forkv;": '\U00002AD9', - "fpartint;": '\U00002A0D', - "frac12;": '\U000000BD', - "frac13;": '\U00002153', - "frac14;": '\U000000BC', - "frac15;": '\U00002155', - "frac16;": '\U00002159', - "frac18;": '\U0000215B', - "frac23;": '\U00002154', - "frac25;": '\U00002156', - "frac34;": '\U000000BE', - "frac35;": '\U00002157', - "frac38;": '\U0000215C', - "frac45;": '\U00002158', - "frac56;": '\U0000215A', - "frac58;": '\U0000215D', - "frac78;": '\U0000215E', - "frasl;": '\U00002044', - "frown;": '\U00002322', - "fscr;": '\U0001D4BB', - "gE;": '\U00002267', - "gEl;": '\U00002A8C', - "gacute;": '\U000001F5', - "gamma;": '\U000003B3', - "gammad;": '\U000003DD', - "gap;": '\U00002A86', - "gbreve;": '\U0000011F', - "gcirc;": '\U0000011D', - "gcy;": '\U00000433', - "gdot;": '\U00000121', - "ge;": '\U00002265', - "gel;": '\U000022DB', - "geq;": '\U00002265', - "geqq;": '\U00002267', - "geqslant;": '\U00002A7E', - "ges;": '\U00002A7E', - "gescc;": '\U00002AA9', - "gesdot;": '\U00002A80', - "gesdoto;": '\U00002A82', - "gesdotol;": '\U00002A84', - "gesles;": '\U00002A94', - "gfr;": '\U0001D524', - "gg;": '\U0000226B', - "ggg;": '\U000022D9', - "gimel;": '\U00002137', - "gjcy;": '\U00000453', - "gl;": '\U00002277', - "glE;": '\U00002A92', - "gla;": '\U00002AA5', - "glj;": '\U00002AA4', - "gnE;": '\U00002269', - "gnap;": '\U00002A8A', - "gnapprox;": '\U00002A8A', - "gne;": '\U00002A88', - "gneq;": '\U00002A88', - "gneqq;": '\U00002269', - "gnsim;": '\U000022E7', - "gopf;": '\U0001D558', - "grave;": '\U00000060', - "gscr;": '\U0000210A', - "gsim;": '\U00002273', - "gsime;": '\U00002A8E', - "gsiml;": '\U00002A90', - "gt;": '\U0000003E', - "gtcc;": '\U00002AA7', - "gtcir;": '\U00002A7A', - "gtdot;": '\U000022D7', - "gtlPar;": '\U00002995', - "gtquest;": '\U00002A7C', - "gtrapprox;": '\U00002A86', - "gtrarr;": '\U00002978', - "gtrdot;": '\U000022D7', - "gtreqless;": '\U000022DB', - "gtreqqless;": '\U00002A8C', - "gtrless;": '\U00002277', - "gtrsim;": '\U00002273', - "hArr;": '\U000021D4', - "hairsp;": '\U0000200A', - "half;": '\U000000BD', - "hamilt;": '\U0000210B', - "hardcy;": '\U0000044A', - "harr;": '\U00002194', - "harrcir;": '\U00002948', - "harrw;": '\U000021AD', - "hbar;": '\U0000210F', - "hcirc;": '\U00000125', - "hearts;": '\U00002665', - "heartsuit;": '\U00002665', - "hellip;": '\U00002026', - "hercon;": '\U000022B9', - "hfr;": '\U0001D525', - "hksearow;": '\U00002925', - "hkswarow;": '\U00002926', - "hoarr;": '\U000021FF', - "homtht;": '\U0000223B', - "hookleftarrow;": '\U000021A9', - "hookrightarrow;": '\U000021AA', - "hopf;": '\U0001D559', - "horbar;": '\U00002015', - "hscr;": '\U0001D4BD', - "hslash;": '\U0000210F', - "hstrok;": '\U00000127', - "hybull;": '\U00002043', - "hyphen;": '\U00002010', - "iacute;": '\U000000ED', - "ic;": '\U00002063', - "icirc;": '\U000000EE', - "icy;": '\U00000438', - "iecy;": '\U00000435', - "iexcl;": '\U000000A1', - "iff;": '\U000021D4', - "ifr;": '\U0001D526', - "igrave;": '\U000000EC', - "ii;": '\U00002148', - "iiiint;": '\U00002A0C', - "iiint;": '\U0000222D', - "iinfin;": '\U000029DC', - "iiota;": '\U00002129', - "ijlig;": '\U00000133', - "imacr;": '\U0000012B', - "image;": '\U00002111', - "imagline;": '\U00002110', - "imagpart;": '\U00002111', - "imath;": '\U00000131', - "imof;": '\U000022B7', - "imped;": '\U000001B5', - "in;": '\U00002208', - "incare;": '\U00002105', - "infin;": '\U0000221E', - "infintie;": '\U000029DD', - "inodot;": '\U00000131', - "int;": '\U0000222B', - "intcal;": '\U000022BA', - "integers;": '\U00002124', - "intercal;": '\U000022BA', - "intlarhk;": '\U00002A17', - "intprod;": '\U00002A3C', - "iocy;": '\U00000451', - "iogon;": '\U0000012F', - "iopf;": '\U0001D55A', - "iota;": '\U000003B9', - "iprod;": '\U00002A3C', - "iquest;": '\U000000BF', - "iscr;": '\U0001D4BE', - "isin;": '\U00002208', - "isinE;": '\U000022F9', - "isindot;": '\U000022F5', - "isins;": '\U000022F4', - "isinsv;": '\U000022F3', - "isinv;": '\U00002208', - "it;": '\U00002062', - "itilde;": '\U00000129', - "iukcy;": '\U00000456', - "iuml;": '\U000000EF', - "jcirc;": '\U00000135', - "jcy;": '\U00000439', - "jfr;": '\U0001D527', - "jmath;": '\U00000237', - "jopf;": '\U0001D55B', - "jscr;": '\U0001D4BF', - "jsercy;": '\U00000458', - "jukcy;": '\U00000454', - "kappa;": '\U000003BA', - "kappav;": '\U000003F0', - "kcedil;": '\U00000137', - "kcy;": '\U0000043A', - "kfr;": '\U0001D528', - "kgreen;": '\U00000138', - "khcy;": '\U00000445', - "kjcy;": '\U0000045C', - "kopf;": '\U0001D55C', - "kscr;": '\U0001D4C0', - "lAarr;": '\U000021DA', - "lArr;": '\U000021D0', - "lAtail;": '\U0000291B', - "lBarr;": '\U0000290E', - "lE;": '\U00002266', - "lEg;": '\U00002A8B', - "lHar;": '\U00002962', - "lacute;": '\U0000013A', - "laemptyv;": '\U000029B4', - "lagran;": '\U00002112', - "lambda;": '\U000003BB', - "lang;": '\U000027E8', - "langd;": '\U00002991', - "langle;": '\U000027E8', - "lap;": '\U00002A85', - "laquo;": '\U000000AB', - "larr;": '\U00002190', - "larrb;": '\U000021E4', - "larrbfs;": '\U0000291F', - "larrfs;": '\U0000291D', - "larrhk;": '\U000021A9', - "larrlp;": '\U000021AB', - "larrpl;": '\U00002939', - "larrsim;": '\U00002973', - "larrtl;": '\U000021A2', - "lat;": '\U00002AAB', - "latail;": '\U00002919', - "late;": '\U00002AAD', - "lbarr;": '\U0000290C', - "lbbrk;": '\U00002772', - "lbrace;": '\U0000007B', - "lbrack;": '\U0000005B', - "lbrke;": '\U0000298B', - "lbrksld;": '\U0000298F', - "lbrkslu;": '\U0000298D', - "lcaron;": '\U0000013E', - "lcedil;": '\U0000013C', - "lceil;": '\U00002308', - "lcub;": '\U0000007B', - "lcy;": '\U0000043B', - "ldca;": '\U00002936', - "ldquo;": '\U0000201C', - "ldquor;": '\U0000201E', - "ldrdhar;": '\U00002967', - "ldrushar;": '\U0000294B', - "ldsh;": '\U000021B2', - "le;": '\U00002264', - "leftarrow;": '\U00002190', - "leftarrowtail;": '\U000021A2', - "leftharpoondown;": '\U000021BD', - "leftharpoonup;": '\U000021BC', - "leftleftarrows;": '\U000021C7', - "leftrightarrow;": '\U00002194', - "leftrightarrows;": '\U000021C6', - "leftrightharpoons;": '\U000021CB', - "leftrightsquigarrow;": '\U000021AD', - "leftthreetimes;": '\U000022CB', - "leg;": '\U000022DA', - "leq;": '\U00002264', - "leqq;": '\U00002266', - "leqslant;": '\U00002A7D', - "les;": '\U00002A7D', - "lescc;": '\U00002AA8', - "lesdot;": '\U00002A7F', - "lesdoto;": '\U00002A81', - "lesdotor;": '\U00002A83', - "lesges;": '\U00002A93', - "lessapprox;": '\U00002A85', - "lessdot;": '\U000022D6', - "lesseqgtr;": '\U000022DA', - "lesseqqgtr;": '\U00002A8B', - "lessgtr;": '\U00002276', - "lesssim;": '\U00002272', - "lfisht;": '\U0000297C', - "lfloor;": '\U0000230A', - "lfr;": '\U0001D529', - "lg;": '\U00002276', - "lgE;": '\U00002A91', - "lhard;": '\U000021BD', - "lharu;": '\U000021BC', - "lharul;": '\U0000296A', - "lhblk;": '\U00002584', - "ljcy;": '\U00000459', - "ll;": '\U0000226A', - "llarr;": '\U000021C7', - "llcorner;": '\U0000231E', - "llhard;": '\U0000296B', - "lltri;": '\U000025FA', - "lmidot;": '\U00000140', - "lmoust;": '\U000023B0', - "lmoustache;": '\U000023B0', - "lnE;": '\U00002268', - "lnap;": '\U00002A89', - "lnapprox;": '\U00002A89', - "lne;": '\U00002A87', - "lneq;": '\U00002A87', - "lneqq;": '\U00002268', - "lnsim;": '\U000022E6', - "loang;": '\U000027EC', - "loarr;": '\U000021FD', - "lobrk;": '\U000027E6', - "longleftarrow;": '\U000027F5', - "longleftrightarrow;": '\U000027F7', - "longmapsto;": '\U000027FC', - "longrightarrow;": '\U000027F6', - "looparrowleft;": '\U000021AB', - "looparrowright;": '\U000021AC', - "lopar;": '\U00002985', - "lopf;": '\U0001D55D', - "loplus;": '\U00002A2D', - "lotimes;": '\U00002A34', - "lowast;": '\U00002217', - "lowbar;": '\U0000005F', - "loz;": '\U000025CA', - "lozenge;": '\U000025CA', - "lozf;": '\U000029EB', - "lpar;": '\U00000028', - "lparlt;": '\U00002993', - "lrarr;": '\U000021C6', - "lrcorner;": '\U0000231F', - "lrhar;": '\U000021CB', - "lrhard;": '\U0000296D', - "lrm;": '\U0000200E', - "lrtri;": '\U000022BF', - "lsaquo;": '\U00002039', - "lscr;": '\U0001D4C1', - "lsh;": '\U000021B0', - "lsim;": '\U00002272', - "lsime;": '\U00002A8D', - "lsimg;": '\U00002A8F', - "lsqb;": '\U0000005B', - "lsquo;": '\U00002018', - "lsquor;": '\U0000201A', - "lstrok;": '\U00000142', - "lt;": '\U0000003C', - "ltcc;": '\U00002AA6', - "ltcir;": '\U00002A79', - "ltdot;": '\U000022D6', - "lthree;": '\U000022CB', - "ltimes;": '\U000022C9', - "ltlarr;": '\U00002976', - "ltquest;": '\U00002A7B', - "ltrPar;": '\U00002996', - "ltri;": '\U000025C3', - "ltrie;": '\U000022B4', - "ltrif;": '\U000025C2', - "lurdshar;": '\U0000294A', - "luruhar;": '\U00002966', - "mDDot;": '\U0000223A', - "macr;": '\U000000AF', - "male;": '\U00002642', - "malt;": '\U00002720', - "maltese;": '\U00002720', - "map;": '\U000021A6', - "mapsto;": '\U000021A6', - "mapstodown;": '\U000021A7', - "mapstoleft;": '\U000021A4', - "mapstoup;": '\U000021A5', - "marker;": '\U000025AE', - "mcomma;": '\U00002A29', - "mcy;": '\U0000043C', - "mdash;": '\U00002014', - "measuredangle;": '\U00002221', - "mfr;": '\U0001D52A', - "mho;": '\U00002127', - "micro;": '\U000000B5', - "mid;": '\U00002223', - "midast;": '\U0000002A', - "midcir;": '\U00002AF0', - "middot;": '\U000000B7', - "minus;": '\U00002212', - "minusb;": '\U0000229F', - "minusd;": '\U00002238', - "minusdu;": '\U00002A2A', - "mlcp;": '\U00002ADB', - "mldr;": '\U00002026', - "mnplus;": '\U00002213', - "models;": '\U000022A7', - "mopf;": '\U0001D55E', - "mp;": '\U00002213', - "mscr;": '\U0001D4C2', - "mstpos;": '\U0000223E', - "mu;": '\U000003BC', - "multimap;": '\U000022B8', - "mumap;": '\U000022B8', - "nLeftarrow;": '\U000021CD', - "nLeftrightarrow;": '\U000021CE', - "nRightarrow;": '\U000021CF', - "nVDash;": '\U000022AF', - "nVdash;": '\U000022AE', - "nabla;": '\U00002207', - "nacute;": '\U00000144', - "nap;": '\U00002249', - "napos;": '\U00000149', - "napprox;": '\U00002249', - "natur;": '\U0000266E', - "natural;": '\U0000266E', - "naturals;": '\U00002115', - "nbsp;": '\U000000A0', - "ncap;": '\U00002A43', - "ncaron;": '\U00000148', - "ncedil;": '\U00000146', - "ncong;": '\U00002247', - "ncup;": '\U00002A42', - "ncy;": '\U0000043D', - "ndash;": '\U00002013', - "ne;": '\U00002260', - "neArr;": '\U000021D7', - "nearhk;": '\U00002924', - "nearr;": '\U00002197', - "nearrow;": '\U00002197', - "nequiv;": '\U00002262', - "nesear;": '\U00002928', - "nexist;": '\U00002204', - "nexists;": '\U00002204', - "nfr;": '\U0001D52B', - "nge;": '\U00002271', - "ngeq;": '\U00002271', - "ngsim;": '\U00002275', - "ngt;": '\U0000226F', - "ngtr;": '\U0000226F', - "nhArr;": '\U000021CE', - "nharr;": '\U000021AE', - "nhpar;": '\U00002AF2', - "ni;": '\U0000220B', - "nis;": '\U000022FC', - "nisd;": '\U000022FA', - "niv;": '\U0000220B', - "njcy;": '\U0000045A', - "nlArr;": '\U000021CD', - "nlarr;": '\U0000219A', - "nldr;": '\U00002025', - "nle;": '\U00002270', - "nleftarrow;": '\U0000219A', - "nleftrightarrow;": '\U000021AE', - "nleq;": '\U00002270', - "nless;": '\U0000226E', - "nlsim;": '\U00002274', - "nlt;": '\U0000226E', - "nltri;": '\U000022EA', - "nltrie;": '\U000022EC', - "nmid;": '\U00002224', - "nopf;": '\U0001D55F', - "not;": '\U000000AC', - "notin;": '\U00002209', - "notinva;": '\U00002209', - "notinvb;": '\U000022F7', - "notinvc;": '\U000022F6', - "notni;": '\U0000220C', - "notniva;": '\U0000220C', - "notnivb;": '\U000022FE', - "notnivc;": '\U000022FD', - "npar;": '\U00002226', - "nparallel;": '\U00002226', - "npolint;": '\U00002A14', - "npr;": '\U00002280', - "nprcue;": '\U000022E0', - "nprec;": '\U00002280', - "nrArr;": '\U000021CF', - "nrarr;": '\U0000219B', - "nrightarrow;": '\U0000219B', - "nrtri;": '\U000022EB', - "nrtrie;": '\U000022ED', - "nsc;": '\U00002281', - "nsccue;": '\U000022E1', - "nscr;": '\U0001D4C3', - "nshortmid;": '\U00002224', - "nshortparallel;": '\U00002226', - "nsim;": '\U00002241', - "nsime;": '\U00002244', - "nsimeq;": '\U00002244', - "nsmid;": '\U00002224', - "nspar;": '\U00002226', - "nsqsube;": '\U000022E2', - "nsqsupe;": '\U000022E3', - "nsub;": '\U00002284', - "nsube;": '\U00002288', - "nsubseteq;": '\U00002288', - "nsucc;": '\U00002281', - "nsup;": '\U00002285', - "nsupe;": '\U00002289', - "nsupseteq;": '\U00002289', - "ntgl;": '\U00002279', - "ntilde;": '\U000000F1', - "ntlg;": '\U00002278', - "ntriangleleft;": '\U000022EA', - "ntrianglelefteq;": '\U000022EC', - "ntriangleright;": '\U000022EB', - "ntrianglerighteq;": '\U000022ED', - "nu;": '\U000003BD', - "num;": '\U00000023', - "numero;": '\U00002116', - "numsp;": '\U00002007', - "nvDash;": '\U000022AD', - "nvHarr;": '\U00002904', - "nvdash;": '\U000022AC', - "nvinfin;": '\U000029DE', - "nvlArr;": '\U00002902', - "nvrArr;": '\U00002903', - "nwArr;": '\U000021D6', - "nwarhk;": '\U00002923', - "nwarr;": '\U00002196', - "nwarrow;": '\U00002196', - "nwnear;": '\U00002927', - "oS;": '\U000024C8', - "oacute;": '\U000000F3', - "oast;": '\U0000229B', - "ocir;": '\U0000229A', - "ocirc;": '\U000000F4', - "ocy;": '\U0000043E', - "odash;": '\U0000229D', - "odblac;": '\U00000151', - "odiv;": '\U00002A38', - "odot;": '\U00002299', - "odsold;": '\U000029BC', - "oelig;": '\U00000153', - "ofcir;": '\U000029BF', - "ofr;": '\U0001D52C', - "ogon;": '\U000002DB', - "ograve;": '\U000000F2', - "ogt;": '\U000029C1', - "ohbar;": '\U000029B5', - "ohm;": '\U000003A9', - "oint;": '\U0000222E', - "olarr;": '\U000021BA', - "olcir;": '\U000029BE', - "olcross;": '\U000029BB', - "oline;": '\U0000203E', - "olt;": '\U000029C0', - "omacr;": '\U0000014D', - "omega;": '\U000003C9', - "omicron;": '\U000003BF', - "omid;": '\U000029B6', - "ominus;": '\U00002296', - "oopf;": '\U0001D560', - "opar;": '\U000029B7', - "operp;": '\U000029B9', - "oplus;": '\U00002295', - "or;": '\U00002228', - "orarr;": '\U000021BB', - "ord;": '\U00002A5D', - "order;": '\U00002134', - "orderof;": '\U00002134', - "ordf;": '\U000000AA', - "ordm;": '\U000000BA', - "origof;": '\U000022B6', - "oror;": '\U00002A56', - "orslope;": '\U00002A57', - "orv;": '\U00002A5B', - "oscr;": '\U00002134', - "oslash;": '\U000000F8', - "osol;": '\U00002298', - "otilde;": '\U000000F5', - "otimes;": '\U00002297', - "otimesas;": '\U00002A36', - "ouml;": '\U000000F6', - "ovbar;": '\U0000233D', - "par;": '\U00002225', - "para;": '\U000000B6', - "parallel;": '\U00002225', - "parsim;": '\U00002AF3', - "parsl;": '\U00002AFD', - "part;": '\U00002202', - "pcy;": '\U0000043F', - "percnt;": '\U00000025', - "period;": '\U0000002E', - "permil;": '\U00002030', - "perp;": '\U000022A5', - "pertenk;": '\U00002031', - "pfr;": '\U0001D52D', - "phi;": '\U000003C6', - "phiv;": '\U000003D5', - "phmmat;": '\U00002133', - "phone;": '\U0000260E', - "pi;": '\U000003C0', - "pitchfork;": '\U000022D4', - "piv;": '\U000003D6', - "planck;": '\U0000210F', - "planckh;": '\U0000210E', - "plankv;": '\U0000210F', - "plus;": '\U0000002B', - "plusacir;": '\U00002A23', - "plusb;": '\U0000229E', - "pluscir;": '\U00002A22', - "plusdo;": '\U00002214', - "plusdu;": '\U00002A25', - "pluse;": '\U00002A72', - "plusmn;": '\U000000B1', - "plussim;": '\U00002A26', - "plustwo;": '\U00002A27', - "pm;": '\U000000B1', - "pointint;": '\U00002A15', - "popf;": '\U0001D561', - "pound;": '\U000000A3', - "pr;": '\U0000227A', - "prE;": '\U00002AB3', - "prap;": '\U00002AB7', - "prcue;": '\U0000227C', - "pre;": '\U00002AAF', - "prec;": '\U0000227A', - "precapprox;": '\U00002AB7', - "preccurlyeq;": '\U0000227C', - "preceq;": '\U00002AAF', - "precnapprox;": '\U00002AB9', - "precneqq;": '\U00002AB5', - "precnsim;": '\U000022E8', - "precsim;": '\U0000227E', - "prime;": '\U00002032', - "primes;": '\U00002119', - "prnE;": '\U00002AB5', - "prnap;": '\U00002AB9', - "prnsim;": '\U000022E8', - "prod;": '\U0000220F', - "profalar;": '\U0000232E', - "profline;": '\U00002312', - "profsurf;": '\U00002313', - "prop;": '\U0000221D', - "propto;": '\U0000221D', - "prsim;": '\U0000227E', - "prurel;": '\U000022B0', - "pscr;": '\U0001D4C5', - "psi;": '\U000003C8', - "puncsp;": '\U00002008', - "qfr;": '\U0001D52E', - "qint;": '\U00002A0C', - "qopf;": '\U0001D562', - "qprime;": '\U00002057', - "qscr;": '\U0001D4C6', - "quaternions;": '\U0000210D', - "quatint;": '\U00002A16', - "quest;": '\U0000003F', - "questeq;": '\U0000225F', - "quot;": '\U00000022', - "rAarr;": '\U000021DB', - "rArr;": '\U000021D2', - "rAtail;": '\U0000291C', - "rBarr;": '\U0000290F', - "rHar;": '\U00002964', - "racute;": '\U00000155', - "radic;": '\U0000221A', - "raemptyv;": '\U000029B3', - "rang;": '\U000027E9', - "rangd;": '\U00002992', - "range;": '\U000029A5', - "rangle;": '\U000027E9', - "raquo;": '\U000000BB', - "rarr;": '\U00002192', - "rarrap;": '\U00002975', - "rarrb;": '\U000021E5', - "rarrbfs;": '\U00002920', - "rarrc;": '\U00002933', - "rarrfs;": '\U0000291E', - "rarrhk;": '\U000021AA', - "rarrlp;": '\U000021AC', - "rarrpl;": '\U00002945', - "rarrsim;": '\U00002974', - "rarrtl;": '\U000021A3', - "rarrw;": '\U0000219D', - "ratail;": '\U0000291A', - "ratio;": '\U00002236', - "rationals;": '\U0000211A', - "rbarr;": '\U0000290D', - "rbbrk;": '\U00002773', - "rbrace;": '\U0000007D', - "rbrack;": '\U0000005D', - "rbrke;": '\U0000298C', - "rbrksld;": '\U0000298E', - "rbrkslu;": '\U00002990', - "rcaron;": '\U00000159', - "rcedil;": '\U00000157', - "rceil;": '\U00002309', - "rcub;": '\U0000007D', - "rcy;": '\U00000440', - "rdca;": '\U00002937', - "rdldhar;": '\U00002969', - "rdquo;": '\U0000201D', - "rdquor;": '\U0000201D', - "rdsh;": '\U000021B3', - "real;": '\U0000211C', - "realine;": '\U0000211B', - "realpart;": '\U0000211C', - "reals;": '\U0000211D', - "rect;": '\U000025AD', - "reg;": '\U000000AE', - "rfisht;": '\U0000297D', - "rfloor;": '\U0000230B', - "rfr;": '\U0001D52F', - "rhard;": '\U000021C1', - "rharu;": '\U000021C0', - "rharul;": '\U0000296C', - "rho;": '\U000003C1', - "rhov;": '\U000003F1', - "rightarrow;": '\U00002192', - "rightarrowtail;": '\U000021A3', - "rightharpoondown;": '\U000021C1', - "rightharpoonup;": '\U000021C0', - "rightleftarrows;": '\U000021C4', - "rightleftharpoons;": '\U000021CC', - "rightrightarrows;": '\U000021C9', - "rightsquigarrow;": '\U0000219D', - "rightthreetimes;": '\U000022CC', - "ring;": '\U000002DA', - "risingdotseq;": '\U00002253', - "rlarr;": '\U000021C4', - "rlhar;": '\U000021CC', - "rlm;": '\U0000200F', - "rmoust;": '\U000023B1', - "rmoustache;": '\U000023B1', - "rnmid;": '\U00002AEE', - "roang;": '\U000027ED', - "roarr;": '\U000021FE', - "robrk;": '\U000027E7', - "ropar;": '\U00002986', - "ropf;": '\U0001D563', - "roplus;": '\U00002A2E', - "rotimes;": '\U00002A35', - "rpar;": '\U00000029', - "rpargt;": '\U00002994', - "rppolint;": '\U00002A12', - "rrarr;": '\U000021C9', - "rsaquo;": '\U0000203A', - "rscr;": '\U0001D4C7', - "rsh;": '\U000021B1', - "rsqb;": '\U0000005D', - "rsquo;": '\U00002019', - "rsquor;": '\U00002019', - "rthree;": '\U000022CC', - "rtimes;": '\U000022CA', - "rtri;": '\U000025B9', - "rtrie;": '\U000022B5', - "rtrif;": '\U000025B8', - "rtriltri;": '\U000029CE', - "ruluhar;": '\U00002968', - "rx;": '\U0000211E', - "sacute;": '\U0000015B', - "sbquo;": '\U0000201A', - "sc;": '\U0000227B', - "scE;": '\U00002AB4', - "scap;": '\U00002AB8', - "scaron;": '\U00000161', - "sccue;": '\U0000227D', - "sce;": '\U00002AB0', - "scedil;": '\U0000015F', - "scirc;": '\U0000015D', - "scnE;": '\U00002AB6', - "scnap;": '\U00002ABA', - "scnsim;": '\U000022E9', - "scpolint;": '\U00002A13', - "scsim;": '\U0000227F', - "scy;": '\U00000441', - "sdot;": '\U000022C5', - "sdotb;": '\U000022A1', - "sdote;": '\U00002A66', - "seArr;": '\U000021D8', - "searhk;": '\U00002925', - "searr;": '\U00002198', - "searrow;": '\U00002198', - "sect;": '\U000000A7', - "semi;": '\U0000003B', - "seswar;": '\U00002929', - "setminus;": '\U00002216', - "setmn;": '\U00002216', - "sext;": '\U00002736', - "sfr;": '\U0001D530', - "sfrown;": '\U00002322', - "sharp;": '\U0000266F', - "shchcy;": '\U00000449', - "shcy;": '\U00000448', - "shortmid;": '\U00002223', - "shortparallel;": '\U00002225', - "shy;": '\U000000AD', - "sigma;": '\U000003C3', - "sigmaf;": '\U000003C2', - "sigmav;": '\U000003C2', - "sim;": '\U0000223C', - "simdot;": '\U00002A6A', - "sime;": '\U00002243', - "simeq;": '\U00002243', - "simg;": '\U00002A9E', - "simgE;": '\U00002AA0', - "siml;": '\U00002A9D', - "simlE;": '\U00002A9F', - "simne;": '\U00002246', - "simplus;": '\U00002A24', - "simrarr;": '\U00002972', - "slarr;": '\U00002190', - "smallsetminus;": '\U00002216', - "smashp;": '\U00002A33', - "smeparsl;": '\U000029E4', - "smid;": '\U00002223', - "smile;": '\U00002323', - "smt;": '\U00002AAA', - "smte;": '\U00002AAC', - "softcy;": '\U0000044C', - "sol;": '\U0000002F', - "solb;": '\U000029C4', - "solbar;": '\U0000233F', - "sopf;": '\U0001D564', - "spades;": '\U00002660', - "spadesuit;": '\U00002660', - "spar;": '\U00002225', - "sqcap;": '\U00002293', - "sqcup;": '\U00002294', - "sqsub;": '\U0000228F', - "sqsube;": '\U00002291', - "sqsubset;": '\U0000228F', - "sqsubseteq;": '\U00002291', - "sqsup;": '\U00002290', - "sqsupe;": '\U00002292', - "sqsupset;": '\U00002290', - "sqsupseteq;": '\U00002292', - "squ;": '\U000025A1', - "square;": '\U000025A1', - "squarf;": '\U000025AA', - "squf;": '\U000025AA', - "srarr;": '\U00002192', - "sscr;": '\U0001D4C8', - "ssetmn;": '\U00002216', - "ssmile;": '\U00002323', - "sstarf;": '\U000022C6', - "star;": '\U00002606', - "starf;": '\U00002605', - "straightepsilon;": '\U000003F5', - "straightphi;": '\U000003D5', - "strns;": '\U000000AF', - "sub;": '\U00002282', - "subE;": '\U00002AC5', - "subdot;": '\U00002ABD', - "sube;": '\U00002286', - "subedot;": '\U00002AC3', - "submult;": '\U00002AC1', - "subnE;": '\U00002ACB', - "subne;": '\U0000228A', - "subplus;": '\U00002ABF', - "subrarr;": '\U00002979', - "subset;": '\U00002282', - "subseteq;": '\U00002286', - "subseteqq;": '\U00002AC5', - "subsetneq;": '\U0000228A', - "subsetneqq;": '\U00002ACB', - "subsim;": '\U00002AC7', - "subsub;": '\U00002AD5', - "subsup;": '\U00002AD3', - "succ;": '\U0000227B', - "succapprox;": '\U00002AB8', - "succcurlyeq;": '\U0000227D', - "succeq;": '\U00002AB0', - "succnapprox;": '\U00002ABA', - "succneqq;": '\U00002AB6', - "succnsim;": '\U000022E9', - "succsim;": '\U0000227F', - "sum;": '\U00002211', - "sung;": '\U0000266A', - "sup;": '\U00002283', - "sup1;": '\U000000B9', - "sup2;": '\U000000B2', - "sup3;": '\U000000B3', - "supE;": '\U00002AC6', - "supdot;": '\U00002ABE', - "supdsub;": '\U00002AD8', - "supe;": '\U00002287', - "supedot;": '\U00002AC4', - "suphsol;": '\U000027C9', - "suphsub;": '\U00002AD7', - "suplarr;": '\U0000297B', - "supmult;": '\U00002AC2', - "supnE;": '\U00002ACC', - "supne;": '\U0000228B', - "supplus;": '\U00002AC0', - "supset;": '\U00002283', - "supseteq;": '\U00002287', - "supseteqq;": '\U00002AC6', - "supsetneq;": '\U0000228B', - "supsetneqq;": '\U00002ACC', - "supsim;": '\U00002AC8', - "supsub;": '\U00002AD4', - "supsup;": '\U00002AD6', - "swArr;": '\U000021D9', - "swarhk;": '\U00002926', - "swarr;": '\U00002199', - "swarrow;": '\U00002199', - "swnwar;": '\U0000292A', - "szlig;": '\U000000DF', - "target;": '\U00002316', - "tau;": '\U000003C4', - "tbrk;": '\U000023B4', - "tcaron;": '\U00000165', - "tcedil;": '\U00000163', - "tcy;": '\U00000442', - "tdot;": '\U000020DB', - "telrec;": '\U00002315', - "tfr;": '\U0001D531', - "there4;": '\U00002234', - "therefore;": '\U00002234', - "theta;": '\U000003B8', - "thetasym;": '\U000003D1', - "thetav;": '\U000003D1', - "thickapprox;": '\U00002248', - "thicksim;": '\U0000223C', - "thinsp;": '\U00002009', - "thkap;": '\U00002248', - "thksim;": '\U0000223C', - "thorn;": '\U000000FE', - "tilde;": '\U000002DC', - "times;": '\U000000D7', - "timesb;": '\U000022A0', - "timesbar;": '\U00002A31', - "timesd;": '\U00002A30', - "tint;": '\U0000222D', - "toea;": '\U00002928', - "top;": '\U000022A4', - "topbot;": '\U00002336', - "topcir;": '\U00002AF1', - "topf;": '\U0001D565', - "topfork;": '\U00002ADA', - "tosa;": '\U00002929', - "tprime;": '\U00002034', - "trade;": '\U00002122', - "triangle;": '\U000025B5', - "triangledown;": '\U000025BF', - "triangleleft;": '\U000025C3', - "trianglelefteq;": '\U000022B4', - "triangleq;": '\U0000225C', - "triangleright;": '\U000025B9', - "trianglerighteq;": '\U000022B5', - "tridot;": '\U000025EC', - "trie;": '\U0000225C', - "triminus;": '\U00002A3A', - "triplus;": '\U00002A39', - "trisb;": '\U000029CD', - "tritime;": '\U00002A3B', - "trpezium;": '\U000023E2', - "tscr;": '\U0001D4C9', - "tscy;": '\U00000446', - "tshcy;": '\U0000045B', - "tstrok;": '\U00000167', - "twixt;": '\U0000226C', - "twoheadleftarrow;": '\U0000219E', - "twoheadrightarrow;": '\U000021A0', - "uArr;": '\U000021D1', - "uHar;": '\U00002963', - "uacute;": '\U000000FA', - "uarr;": '\U00002191', - "ubrcy;": '\U0000045E', - "ubreve;": '\U0000016D', - "ucirc;": '\U000000FB', - "ucy;": '\U00000443', - "udarr;": '\U000021C5', - "udblac;": '\U00000171', - "udhar;": '\U0000296E', - "ufisht;": '\U0000297E', - "ufr;": '\U0001D532', - "ugrave;": '\U000000F9', - "uharl;": '\U000021BF', - "uharr;": '\U000021BE', - "uhblk;": '\U00002580', - "ulcorn;": '\U0000231C', - "ulcorner;": '\U0000231C', - "ulcrop;": '\U0000230F', - "ultri;": '\U000025F8', - "umacr;": '\U0000016B', - "uml;": '\U000000A8', - "uogon;": '\U00000173', - "uopf;": '\U0001D566', - "uparrow;": '\U00002191', - "updownarrow;": '\U00002195', - "upharpoonleft;": '\U000021BF', - "upharpoonright;": '\U000021BE', - "uplus;": '\U0000228E', - "upsi;": '\U000003C5', - "upsih;": '\U000003D2', - "upsilon;": '\U000003C5', - "upuparrows;": '\U000021C8', - "urcorn;": '\U0000231D', - "urcorner;": '\U0000231D', - "urcrop;": '\U0000230E', - "uring;": '\U0000016F', - "urtri;": '\U000025F9', - "uscr;": '\U0001D4CA', - "utdot;": '\U000022F0', - "utilde;": '\U00000169', - "utri;": '\U000025B5', - "utrif;": '\U000025B4', - "uuarr;": '\U000021C8', - "uuml;": '\U000000FC', - "uwangle;": '\U000029A7', - "vArr;": '\U000021D5', - "vBar;": '\U00002AE8', - "vBarv;": '\U00002AE9', - "vDash;": '\U000022A8', - "vangrt;": '\U0000299C', - "varepsilon;": '\U000003F5', - "varkappa;": '\U000003F0', - "varnothing;": '\U00002205', - "varphi;": '\U000003D5', - "varpi;": '\U000003D6', - "varpropto;": '\U0000221D', - "varr;": '\U00002195', - "varrho;": '\U000003F1', - "varsigma;": '\U000003C2', - "vartheta;": '\U000003D1', - "vartriangleleft;": '\U000022B2', - "vartriangleright;": '\U000022B3', - "vcy;": '\U00000432', - "vdash;": '\U000022A2', - "vee;": '\U00002228', - "veebar;": '\U000022BB', - "veeeq;": '\U0000225A', - "vellip;": '\U000022EE', - "verbar;": '\U0000007C', - "vert;": '\U0000007C', - "vfr;": '\U0001D533', - "vltri;": '\U000022B2', - "vopf;": '\U0001D567', - "vprop;": '\U0000221D', - "vrtri;": '\U000022B3', - "vscr;": '\U0001D4CB', - "vzigzag;": '\U0000299A', - "wcirc;": '\U00000175', - "wedbar;": '\U00002A5F', - "wedge;": '\U00002227', - "wedgeq;": '\U00002259', - "weierp;": '\U00002118', - "wfr;": '\U0001D534', - "wopf;": '\U0001D568', - "wp;": '\U00002118', - "wr;": '\U00002240', - "wreath;": '\U00002240', - "wscr;": '\U0001D4CC', - "xcap;": '\U000022C2', - "xcirc;": '\U000025EF', - "xcup;": '\U000022C3', - "xdtri;": '\U000025BD', - "xfr;": '\U0001D535', - "xhArr;": '\U000027FA', - "xharr;": '\U000027F7', - "xi;": '\U000003BE', - "xlArr;": '\U000027F8', - "xlarr;": '\U000027F5', - "xmap;": '\U000027FC', - "xnis;": '\U000022FB', - "xodot;": '\U00002A00', - "xopf;": '\U0001D569', - "xoplus;": '\U00002A01', - "xotime;": '\U00002A02', - "xrArr;": '\U000027F9', - "xrarr;": '\U000027F6', - "xscr;": '\U0001D4CD', - "xsqcup;": '\U00002A06', - "xuplus;": '\U00002A04', - "xutri;": '\U000025B3', - "xvee;": '\U000022C1', - "xwedge;": '\U000022C0', - "yacute;": '\U000000FD', - "yacy;": '\U0000044F', - "ycirc;": '\U00000177', - "ycy;": '\U0000044B', - "yen;": '\U000000A5', - "yfr;": '\U0001D536', - "yicy;": '\U00000457', - "yopf;": '\U0001D56A', - "yscr;": '\U0001D4CE', - "yucy;": '\U0000044E', - "yuml;": '\U000000FF', - "zacute;": '\U0000017A', - "zcaron;": '\U0000017E', - "zcy;": '\U00000437', - "zdot;": '\U0000017C', - "zeetrf;": '\U00002128', - "zeta;": '\U000003B6', - "zfr;": '\U0001D537', - "zhcy;": '\U00000436', - "zigrarr;": '\U000021DD', - "zopf;": '\U0001D56B', - "zscr;": '\U0001D4CF', - "zwj;": '\U0000200D', - "zwnj;": '\U0000200C', - "AElig": '\U000000C6', - "AMP": '\U00000026', - "Aacute": '\U000000C1', - "Acirc": '\U000000C2', - "Agrave": '\U000000C0', - "Aring": '\U000000C5', - "Atilde": '\U000000C3', - "Auml": '\U000000C4', - "COPY": '\U000000A9', - "Ccedil": '\U000000C7', - "ETH": '\U000000D0', - "Eacute": '\U000000C9', - "Ecirc": '\U000000CA', - "Egrave": '\U000000C8', - "Euml": '\U000000CB', - "GT": '\U0000003E', - "Iacute": '\U000000CD', - "Icirc": '\U000000CE', - "Igrave": '\U000000CC', - "Iuml": '\U000000CF', - "LT": '\U0000003C', - "Ntilde": '\U000000D1', - "Oacute": '\U000000D3', - "Ocirc": '\U000000D4', - "Ograve": '\U000000D2', - "Oslash": '\U000000D8', - "Otilde": '\U000000D5', - "Ouml": '\U000000D6', - "QUOT": '\U00000022', - "REG": '\U000000AE', - "THORN": '\U000000DE', - "Uacute": '\U000000DA', - "Ucirc": '\U000000DB', - "Ugrave": '\U000000D9', - "Uuml": '\U000000DC', - "Yacute": '\U000000DD', - "aacute": '\U000000E1', - "acirc": '\U000000E2', - "acute": '\U000000B4', - "aelig": '\U000000E6', - "agrave": '\U000000E0', - "amp": '\U00000026', - "aring": '\U000000E5', - "atilde": '\U000000E3', - "auml": '\U000000E4', - "brvbar": '\U000000A6', - "ccedil": '\U000000E7', - "cedil": '\U000000B8', - "cent": '\U000000A2', - "copy": '\U000000A9', - "curren": '\U000000A4', - "deg": '\U000000B0', - "divide": '\U000000F7', - "eacute": '\U000000E9', - "ecirc": '\U000000EA', - "egrave": '\U000000E8', - "eth": '\U000000F0', - "euml": '\U000000EB', - "frac12": '\U000000BD', - "frac14": '\U000000BC', - "frac34": '\U000000BE', - "gt": '\U0000003E', - "iacute": '\U000000ED', - "icirc": '\U000000EE', - "iexcl": '\U000000A1', - "igrave": '\U000000EC', - "iquest": '\U000000BF', - "iuml": '\U000000EF', - "laquo": '\U000000AB', - "lt": '\U0000003C', - "macr": '\U000000AF', - "micro": '\U000000B5', - "middot": '\U000000B7', - "nbsp": '\U000000A0', - "not": '\U000000AC', - "ntilde": '\U000000F1', - "oacute": '\U000000F3', - "ocirc": '\U000000F4', - "ograve": '\U000000F2', - "ordf": '\U000000AA', - "ordm": '\U000000BA', - "oslash": '\U000000F8', - "otilde": '\U000000F5', - "ouml": '\U000000F6', - "para": '\U000000B6', - "plusmn": '\U000000B1', - "pound": '\U000000A3', - "quot": '\U00000022', - "raquo": '\U000000BB', - "reg": '\U000000AE', - "sect": '\U000000A7', - "shy": '\U000000AD', - "sup1": '\U000000B9', - "sup2": '\U000000B2', - "sup3": '\U000000B3', - "szlig": '\U000000DF', - "thorn": '\U000000FE', - "times": '\U000000D7', - "uacute": '\U000000FA', - "ucirc": '\U000000FB', - "ugrave": '\U000000F9', - "uml": '\U000000A8', - "uuml": '\U000000FC', - "yacute": '\U000000FD', - "yen": '\U000000A5', - "yuml": '\U000000FF', -} - -// HTML entities that are two unicode codepoints. -var entity2 = map[string][2]rune{ - // TODO(nigeltao): Handle replacements that are wider than their names. - // "nLt;": {'\u226A', '\u20D2'}, - // "nGt;": {'\u226B', '\u20D2'}, - "NotEqualTilde;": {'\u2242', '\u0338'}, - "NotGreaterFullEqual;": {'\u2267', '\u0338'}, - "NotGreaterGreater;": {'\u226B', '\u0338'}, - "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, - "NotHumpDownHump;": {'\u224E', '\u0338'}, - "NotHumpEqual;": {'\u224F', '\u0338'}, - "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, - "NotLessLess;": {'\u226A', '\u0338'}, - "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, - "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, - "NotNestedLessLess;": {'\u2AA1', '\u0338'}, - "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, - "NotRightTriangleBar;": {'\u29D0', '\u0338'}, - "NotSquareSubset;": {'\u228F', '\u0338'}, - "NotSquareSuperset;": {'\u2290', '\u0338'}, - "NotSubset;": {'\u2282', '\u20D2'}, - "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, - "NotSucceedsTilde;": {'\u227F', '\u0338'}, - "NotSuperset;": {'\u2283', '\u20D2'}, - "ThickSpace;": {'\u205F', '\u200A'}, - "acE;": {'\u223E', '\u0333'}, - "bne;": {'\u003D', '\u20E5'}, - "bnequiv;": {'\u2261', '\u20E5'}, - "caps;": {'\u2229', '\uFE00'}, - "cups;": {'\u222A', '\uFE00'}, - "fjlig;": {'\u0066', '\u006A'}, - "gesl;": {'\u22DB', '\uFE00'}, - "gvertneqq;": {'\u2269', '\uFE00'}, - "gvnE;": {'\u2269', '\uFE00'}, - "lates;": {'\u2AAD', '\uFE00'}, - "lesg;": {'\u22DA', '\uFE00'}, - "lvertneqq;": {'\u2268', '\uFE00'}, - "lvnE;": {'\u2268', '\uFE00'}, - "nGg;": {'\u22D9', '\u0338'}, - "nGtv;": {'\u226B', '\u0338'}, - "nLl;": {'\u22D8', '\u0338'}, - "nLtv;": {'\u226A', '\u0338'}, - "nang;": {'\u2220', '\u20D2'}, - "napE;": {'\u2A70', '\u0338'}, - "napid;": {'\u224B', '\u0338'}, - "nbump;": {'\u224E', '\u0338'}, - "nbumpe;": {'\u224F', '\u0338'}, - "ncongdot;": {'\u2A6D', '\u0338'}, - "nedot;": {'\u2250', '\u0338'}, - "nesim;": {'\u2242', '\u0338'}, - "ngE;": {'\u2267', '\u0338'}, - "ngeqq;": {'\u2267', '\u0338'}, - "ngeqslant;": {'\u2A7E', '\u0338'}, - "nges;": {'\u2A7E', '\u0338'}, - "nlE;": {'\u2266', '\u0338'}, - "nleqq;": {'\u2266', '\u0338'}, - "nleqslant;": {'\u2A7D', '\u0338'}, - "nles;": {'\u2A7D', '\u0338'}, - "notinE;": {'\u22F9', '\u0338'}, - "notindot;": {'\u22F5', '\u0338'}, - "nparsl;": {'\u2AFD', '\u20E5'}, - "npart;": {'\u2202', '\u0338'}, - "npre;": {'\u2AAF', '\u0338'}, - "npreceq;": {'\u2AAF', '\u0338'}, - "nrarrc;": {'\u2933', '\u0338'}, - "nrarrw;": {'\u219D', '\u0338'}, - "nsce;": {'\u2AB0', '\u0338'}, - "nsubE;": {'\u2AC5', '\u0338'}, - "nsubset;": {'\u2282', '\u20D2'}, - "nsubseteqq;": {'\u2AC5', '\u0338'}, - "nsucceq;": {'\u2AB0', '\u0338'}, - "nsupE;": {'\u2AC6', '\u0338'}, - "nsupset;": {'\u2283', '\u20D2'}, - "nsupseteqq;": {'\u2AC6', '\u0338'}, - "nvap;": {'\u224D', '\u20D2'}, - "nvge;": {'\u2265', '\u20D2'}, - "nvgt;": {'\u003E', '\u20D2'}, - "nvle;": {'\u2264', '\u20D2'}, - "nvlt;": {'\u003C', '\u20D2'}, - "nvltrie;": {'\u22B4', '\u20D2'}, - "nvrtrie;": {'\u22B5', '\u20D2'}, - "nvsim;": {'\u223C', '\u20D2'}, - "race;": {'\u223D', '\u0331'}, - "smtes;": {'\u2AAC', '\uFE00'}, - "sqcaps;": {'\u2293', '\uFE00'}, - "sqcups;": {'\u2294', '\uFE00'}, - "varsubsetneq;": {'\u228A', '\uFE00'}, - "varsubsetneqq;": {'\u2ACB', '\uFE00'}, - "varsupsetneq;": {'\u228B', '\uFE00'}, - "varsupsetneqq;": {'\u2ACC', '\uFE00'}, - "vnsub;": {'\u2282', '\u20D2'}, - "vnsup;": {'\u2283', '\u20D2'}, - "vsubnE;": {'\u2ACB', '\uFE00'}, - "vsubne;": {'\u228A', '\uFE00'}, - "vsupnE;": {'\u2ACC', '\uFE00'}, - "vsupne;": {'\u228B', '\uFE00'}, -} diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go deleted file mode 100644 index d8561396..00000000 --- a/vendor/golang.org/x/net/html/escape.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2010 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 html - -import ( - "bytes" - "strings" - "unicode/utf8" -) - -// These replacements permit compatibility with old numeric entities that -// assumed Windows-1252 encoding. -// https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference -var replacementTable = [...]rune{ - '\u20AC', // First entry is what 0x80 should be replaced with. - '\u0081', - '\u201A', - '\u0192', - '\u201E', - '\u2026', - '\u2020', - '\u2021', - '\u02C6', - '\u2030', - '\u0160', - '\u2039', - '\u0152', - '\u008D', - '\u017D', - '\u008F', - '\u0090', - '\u2018', - '\u2019', - '\u201C', - '\u201D', - '\u2022', - '\u2013', - '\u2014', - '\u02DC', - '\u2122', - '\u0161', - '\u203A', - '\u0153', - '\u009D', - '\u017E', - '\u0178', // Last entry is 0x9F. - // 0x00->'\uFFFD' is handled programmatically. - // 0x0D->'\u000D' is a no-op. -} - -// unescapeEntity reads an entity like "<" from b[src:] and writes the -// corresponding "<" to b[dst:], returning the incremented dst and src cursors. -// Precondition: b[src] == '&' && dst <= src. -// attribute should be true if parsing an attribute value. -func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { - // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference - - // i starts at 1 because we already know that s[0] == '&'. - i, s := 1, b[src:] - - if len(s) <= 1 { - b[dst] = b[src] - return dst + 1, src + 1 - } - - if s[i] == '#' { - if len(s) <= 3 { // We need to have at least "&#.". - b[dst] = b[src] - return dst + 1, src + 1 - } - i++ - c := s[i] - hex := false - if c == 'x' || c == 'X' { - hex = true - i++ - } - - x := '\x00' - for i < len(s) { - c = s[i] - i++ - if hex { - if '0' <= c && c <= '9' { - x = 16*x + rune(c) - '0' - continue - } else if 'a' <= c && c <= 'f' { - x = 16*x + rune(c) - 'a' + 10 - continue - } else if 'A' <= c && c <= 'F' { - x = 16*x + rune(c) - 'A' + 10 - continue - } - } else if '0' <= c && c <= '9' { - x = 10*x + rune(c) - '0' - continue - } - if c != ';' { - i-- - } - break - } - - if i <= 3 { // No characters matched. - b[dst] = b[src] - return dst + 1, src + 1 - } - - if 0x80 <= x && x <= 0x9F { - // Replace characters from Windows-1252 with UTF-8 equivalents. - x = replacementTable[x-0x80] - } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { - // Replace invalid characters with the replacement character. - x = '\uFFFD' - } - - return dst + utf8.EncodeRune(b[dst:], x), src + i - } - - // Consume the maximum number of characters possible, with the - // consumed characters matching one of the named references. - - for i < len(s) { - c := s[i] - i++ - // Lower-cased characters are more common in entities, so we check for them first. - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - continue - } - if c != ';' { - i-- - } - break - } - - entityName := string(s[1:i]) - if entityName == "" { - // No-op. - } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { - // No-op. - } else if x := entity[entityName]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + i - } else if x := entity2[entityName]; x[0] != 0 { - dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) - return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i - } else if !attribute { - maxLen := len(entityName) - 1 - if maxLen > longestEntityWithoutSemicolon { - maxLen = longestEntityWithoutSemicolon - } - for j := maxLen; j > 1; j-- { - if x := entity[entityName[:j]]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 - } - } - } - - dst1, src1 = dst+i, src+i - copy(b[dst:dst1], b[src:src1]) - return dst1, src1 -} - -// unescape unescapes b's entities in-place, so that "a<b" becomes "a': - esc = ">" - case '"': - // """ is shorter than """. - esc = """ - case '\r': - esc = " " - default: - panic("unrecognized escape character") - } - s = s[i+1:] - if _, err := w.WriteString(esc); err != nil { - return err - } - i = strings.IndexAny(s, escapedChars) - } - _, err := w.WriteString(s) - return err -} - -// EscapeString escapes special characters like "<" to become "<". It -// escapes only five such characters: <, >, &, ' and ". -// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't -// always true. -func EscapeString(s string) string { - if strings.IndexAny(s, escapedChars) == -1 { - return s - } - var buf bytes.Buffer - escape(&buf, s) - return buf.String() -} - -// UnescapeString unescapes entities like "<" to become "<". It unescapes a -// larger range of entities than EscapeString escapes. For example, "á" -// unescapes to "á", as does "á" and "&xE1;". -// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't -// always true. -func UnescapeString(s string) string { - for _, c := range s { - if c == '&' { - return string(unescape([]byte(s), false)) - } - } - return s -} diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go deleted file mode 100644 index 01477a96..00000000 --- a/vendor/golang.org/x/net/html/foreign.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2011 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 html - -import ( - "strings" -) - -func adjustAttributeNames(aa []Attribute, nameMap map[string]string) { - for i := range aa { - if newName, ok := nameMap[aa[i].Key]; ok { - aa[i].Key = newName - } - } -} - -func adjustForeignAttributes(aa []Attribute) { - for i, a := range aa { - if a.Key == "" || a.Key[0] != 'x' { - continue - } - switch a.Key { - case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", - "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": - j := strings.Index(a.Key, ":") - aa[i].Namespace = a.Key[:j] - aa[i].Key = a.Key[j+1:] - } - } -} - -func htmlIntegrationPoint(n *Node) bool { - if n.Type != ElementNode { - return false - } - switch n.Namespace { - case "math": - if n.Data == "annotation-xml" { - for _, a := range n.Attr { - if a.Key == "encoding" { - val := strings.ToLower(a.Val) - if val == "text/html" || val == "application/xhtml+xml" { - return true - } - } - } - } - case "svg": - switch n.Data { - case "desc", "foreignObject", "title": - return true - } - } - return false -} - -func mathMLTextIntegrationPoint(n *Node) bool { - if n.Namespace != "math" { - return false - } - switch n.Data { - case "mi", "mo", "mn", "ms", "mtext": - return true - } - return false -} - -// Section 12.2.6.5. -var breakout = map[string]bool{ - "b": true, - "big": true, - "blockquote": true, - "body": true, - "br": true, - "center": true, - "code": true, - "dd": true, - "div": true, - "dl": true, - "dt": true, - "em": true, - "embed": true, - "h1": true, - "h2": true, - "h3": true, - "h4": true, - "h5": true, - "h6": true, - "head": true, - "hr": true, - "i": true, - "img": true, - "li": true, - "listing": true, - "menu": true, - "meta": true, - "nobr": true, - "ol": true, - "p": true, - "pre": true, - "ruby": true, - "s": true, - "small": true, - "span": true, - "strong": true, - "strike": true, - "sub": true, - "sup": true, - "table": true, - "tt": true, - "u": true, - "ul": true, - "var": true, -} - -// Section 12.2.6.5. -var svgTagNameAdjustments = map[string]string{ - "altglyph": "altGlyph", - "altglyphdef": "altGlyphDef", - "altglyphitem": "altGlyphItem", - "animatecolor": "animateColor", - "animatemotion": "animateMotion", - "animatetransform": "animateTransform", - "clippath": "clipPath", - "feblend": "feBlend", - "fecolormatrix": "feColorMatrix", - "fecomponenttransfer": "feComponentTransfer", - "fecomposite": "feComposite", - "feconvolvematrix": "feConvolveMatrix", - "fediffuselighting": "feDiffuseLighting", - "fedisplacementmap": "feDisplacementMap", - "fedistantlight": "feDistantLight", - "feflood": "feFlood", - "fefunca": "feFuncA", - "fefuncb": "feFuncB", - "fefuncg": "feFuncG", - "fefuncr": "feFuncR", - "fegaussianblur": "feGaussianBlur", - "feimage": "feImage", - "femerge": "feMerge", - "femergenode": "feMergeNode", - "femorphology": "feMorphology", - "feoffset": "feOffset", - "fepointlight": "fePointLight", - "fespecularlighting": "feSpecularLighting", - "fespotlight": "feSpotLight", - "fetile": "feTile", - "feturbulence": "feTurbulence", - "foreignobject": "foreignObject", - "glyphref": "glyphRef", - "lineargradient": "linearGradient", - "radialgradient": "radialGradient", - "textpath": "textPath", -} - -// Section 12.2.6.1 -var mathMLAttributeAdjustments = map[string]string{ - "definitionurl": "definitionURL", -} - -var svgAttributeAdjustments = map[string]string{ - "attributename": "attributeName", - "attributetype": "attributeType", - "basefrequency": "baseFrequency", - "baseprofile": "baseProfile", - "calcmode": "calcMode", - "clippathunits": "clipPathUnits", - "contentscripttype": "contentScriptType", - "contentstyletype": "contentStyleType", - "diffuseconstant": "diffuseConstant", - "edgemode": "edgeMode", - "externalresourcesrequired": "externalResourcesRequired", - "filterres": "filterRes", - "filterunits": "filterUnits", - "glyphref": "glyphRef", - "gradienttransform": "gradientTransform", - "gradientunits": "gradientUnits", - "kernelmatrix": "kernelMatrix", - "kernelunitlength": "kernelUnitLength", - "keypoints": "keyPoints", - "keysplines": "keySplines", - "keytimes": "keyTimes", - "lengthadjust": "lengthAdjust", - "limitingconeangle": "limitingConeAngle", - "markerheight": "markerHeight", - "markerunits": "markerUnits", - "markerwidth": "markerWidth", - "maskcontentunits": "maskContentUnits", - "maskunits": "maskUnits", - "numoctaves": "numOctaves", - "pathlength": "pathLength", - "patterncontentunits": "patternContentUnits", - "patterntransform": "patternTransform", - "patternunits": "patternUnits", - "pointsatx": "pointsAtX", - "pointsaty": "pointsAtY", - "pointsatz": "pointsAtZ", - "preservealpha": "preserveAlpha", - "preserveaspectratio": "preserveAspectRatio", - "primitiveunits": "primitiveUnits", - "refx": "refX", - "refy": "refY", - "repeatcount": "repeatCount", - "repeatdur": "repeatDur", - "requiredextensions": "requiredExtensions", - "requiredfeatures": "requiredFeatures", - "specularconstant": "specularConstant", - "specularexponent": "specularExponent", - "spreadmethod": "spreadMethod", - "startoffset": "startOffset", - "stddeviation": "stdDeviation", - "stitchtiles": "stitchTiles", - "surfacescale": "surfaceScale", - "systemlanguage": "systemLanguage", - "tablevalues": "tableValues", - "targetx": "targetX", - "targety": "targetY", - "textlength": "textLength", - "viewbox": "viewBox", - "viewtarget": "viewTarget", - "xchannelselector": "xChannelSelector", - "ychannelselector": "yChannelSelector", - "zoomandpan": "zoomAndPan", -} diff --git a/vendor/golang.org/x/net/html/node.go b/vendor/golang.org/x/net/html/node.go deleted file mode 100644 index 633ee15d..00000000 --- a/vendor/golang.org/x/net/html/node.go +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2011 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 html - -import ( - "golang.org/x/net/html/atom" -) - -// A NodeType is the type of a Node. -type NodeType uint32 - -const ( - ErrorNode NodeType = iota - TextNode - DocumentNode - ElementNode - CommentNode - DoctypeNode - scopeMarkerNode -) - -// Section 12.2.4.3 says "The markers are inserted when entering applet, -// object, marquee, template, td, th, and caption elements, and are used -// to prevent formatting from "leaking" into applet, object, marquee, -// template, td, th, and caption elements". -var scopeMarker = Node{Type: scopeMarkerNode} - -// A Node consists of a NodeType and some Data (tag name for element nodes, -// content for text) and are part of a tree of Nodes. Element nodes may also -// have a Namespace and contain a slice of Attributes. Data is unescaped, so -// that it looks like "a 0 { - return (*s)[i-1] - } - return nil -} - -// index returns the index of the top-most occurrence of n in the stack, or -1 -// if n is not present. -func (s *nodeStack) index(n *Node) int { - for i := len(*s) - 1; i >= 0; i-- { - if (*s)[i] == n { - return i - } - } - return -1 -} - -// contains returns whether a is within s. -func (s *nodeStack) contains(a atom.Atom) bool { - for _, n := range *s { - if n.DataAtom == a && n.Namespace == "" { - return true - } - } - return false -} - -// insert inserts a node at the given index. -func (s *nodeStack) insert(i int, n *Node) { - (*s) = append(*s, nil) - copy((*s)[i+1:], (*s)[i:]) - (*s)[i] = n -} - -// remove removes a node from the stack. It is a no-op if n is not present. -func (s *nodeStack) remove(n *Node) { - i := s.index(n) - if i == -1 { - return - } - copy((*s)[i:], (*s)[i+1:]) - j := len(*s) - 1 - (*s)[j] = nil - *s = (*s)[:j] -} - -type insertionModeStack []insertionMode - -func (s *insertionModeStack) pop() (im insertionMode) { - i := len(*s) - im = (*s)[i-1] - *s = (*s)[:i-1] - return im -} - -func (s *insertionModeStack) top() insertionMode { - if i := len(*s); i > 0 { - return (*s)[i-1] - } - return nil -} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go deleted file mode 100644 index ca2cb587..00000000 --- a/vendor/golang.org/x/net/html/parse.go +++ /dev/null @@ -1,2324 +0,0 @@ -// Copyright 2010 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 html - -import ( - "errors" - "fmt" - "io" - "strings" - - a "golang.org/x/net/html/atom" -) - -// A parser implements the HTML5 parsing algorithm: -// https://html.spec.whatwg.org/multipage/syntax.html#tree-construction -type parser struct { - // tokenizer provides the tokens for the parser. - tokenizer *Tokenizer - // tok is the most recently read token. - tok Token - // Self-closing tags like
are treated as start tags, except that - // hasSelfClosingToken is set while they are being processed. - hasSelfClosingToken bool - // doc is the document root element. - doc *Node - // The stack of open elements (section 12.2.4.2) and active formatting - // elements (section 12.2.4.3). - oe, afe nodeStack - // Element pointers (section 12.2.4.4). - head, form *Node - // Other parsing state flags (section 12.2.4.5). - scripting, framesetOK bool - // The stack of template insertion modes - templateStack insertionModeStack - // im is the current insertion mode. - im insertionMode - // originalIM is the insertion mode to go back to after completing a text - // or inTableText insertion mode. - originalIM insertionMode - // fosterParenting is whether new elements should be inserted according to - // the foster parenting rules (section 12.2.6.1). - fosterParenting bool - // quirks is whether the parser is operating in "quirks mode." - quirks bool - // fragment is whether the parser is parsing an HTML fragment. - fragment bool - // context is the context element when parsing an HTML fragment - // (section 12.4). - context *Node -} - -func (p *parser) top() *Node { - if n := p.oe.top(); n != nil { - return n - } - return p.doc -} - -// Stop tags for use in popUntil. These come from section 12.2.4.2. -var ( - defaultScopeStopTags = map[string][]a.Atom{ - "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, - "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, - "svg": {a.Desc, a.ForeignObject, a.Title}, - } -) - -type scope int - -const ( - defaultScope scope = iota - listItemScope - buttonScope - tableScope - tableRowScope - tableBodyScope - selectScope -) - -// popUntil pops the stack of open elements at the highest element whose tag -// is in matchTags, provided there is no higher element in the scope's stop -// tags (as defined in section 12.2.4.2). It returns whether or not there was -// such an element. If there was not, popUntil leaves the stack unchanged. -// -// For example, the set of stop tags for table scope is: "html", "table". If -// the stack was: -// ["html", "body", "font", "table", "b", "i", "u"] -// then popUntil(tableScope, "font") would return false, but -// popUntil(tableScope, "i") would return true and the stack would become: -// ["html", "body", "font", "table", "b"] -// -// If an element's tag is in both the stop tags and matchTags, then the stack -// will be popped and the function returns true (provided, of course, there was -// no higher element in the stack that was also in the stop tags). For example, -// popUntil(tableScope, "table") returns true and leaves: -// ["html", "body", "font"] -func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { - if i := p.indexOfElementInScope(s, matchTags...); i != -1 { - p.oe = p.oe[:i] - return true - } - return false -} - -// indexOfElementInScope returns the index in p.oe of the highest element whose -// tag is in matchTags that is in scope. If no matching element is in scope, it -// returns -1. -func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { - for i := len(p.oe) - 1; i >= 0; i-- { - tagAtom := p.oe[i].DataAtom - if p.oe[i].Namespace == "" { - for _, t := range matchTags { - if t == tagAtom { - return i - } - } - switch s { - case defaultScope: - // No-op. - case listItemScope: - if tagAtom == a.Ol || tagAtom == a.Ul { - return -1 - } - case buttonScope: - if tagAtom == a.Button { - return -1 - } - case tableScope: - if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { - return -1 - } - case selectScope: - if tagAtom != a.Optgroup && tagAtom != a.Option { - return -1 - } - default: - panic("unreachable") - } - } - switch s { - case defaultScope, listItemScope, buttonScope: - for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { - if t == tagAtom { - return -1 - } - } - } - } - return -1 -} - -// elementInScope is like popUntil, except that it doesn't modify the stack of -// open elements. -func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { - return p.indexOfElementInScope(s, matchTags...) != -1 -} - -// clearStackToContext pops elements off the stack of open elements until a -// scope-defined element is found. -func (p *parser) clearStackToContext(s scope) { - for i := len(p.oe) - 1; i >= 0; i-- { - tagAtom := p.oe[i].DataAtom - switch s { - case tableScope: - if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { - p.oe = p.oe[:i+1] - return - } - case tableRowScope: - if tagAtom == a.Html || tagAtom == a.Tr || tagAtom == a.Template { - p.oe = p.oe[:i+1] - return - } - case tableBodyScope: - if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead || tagAtom == a.Template { - p.oe = p.oe[:i+1] - return - } - default: - panic("unreachable") - } - } -} - -// generateImpliedEndTags pops nodes off the stack of open elements as long as -// the top node has a tag name of dd, dt, li, optgroup, option, p, rb, rp, rt or rtc. -// If exceptions are specified, nodes with that name will not be popped off. -func (p *parser) generateImpliedEndTags(exceptions ...string) { - var i int -loop: - for i = len(p.oe) - 1; i >= 0; i-- { - n := p.oe[i] - if n.Type == ElementNode { - switch n.DataAtom { - case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc: - for _, except := range exceptions { - if n.Data == except { - break loop - } - } - continue - } - } - break - } - - p.oe = p.oe[:i+1] -} - -// addChild adds a child node n to the top element, and pushes n onto the stack -// of open elements if it is an element node. -func (p *parser) addChild(n *Node) { - if p.shouldFosterParent() { - p.fosterParent(n) - } else { - p.top().AppendChild(n) - } - - if n.Type == ElementNode { - p.oe = append(p.oe, n) - } -} - -// shouldFosterParent returns whether the next node to be added should be -// foster parented. -func (p *parser) shouldFosterParent() bool { - if p.fosterParenting { - switch p.top().DataAtom { - case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: - return true - } - } - return false -} - -// fosterParent adds a child node according to the foster parenting rules. -// Section 12.2.6.1, "foster parenting". -func (p *parser) fosterParent(n *Node) { - var table, parent, prev, template *Node - var i int - for i = len(p.oe) - 1; i >= 0; i-- { - if p.oe[i].DataAtom == a.Table { - table = p.oe[i] - break - } - } - - var j int - for j = len(p.oe) - 1; j >= 0; j-- { - if p.oe[j].DataAtom == a.Template { - template = p.oe[j] - break - } - } - - if template != nil && (table == nil || j > i) { - template.AppendChild(n) - return - } - - if table == nil { - // The foster parent is the html element. - parent = p.oe[0] - } else { - parent = table.Parent - } - if parent == nil { - parent = p.oe[i-1] - } - - if table != nil { - prev = table.PrevSibling - } else { - prev = parent.LastChild - } - if prev != nil && prev.Type == TextNode && n.Type == TextNode { - prev.Data += n.Data - return - } - - parent.InsertBefore(n, table) -} - -// addText adds text to the preceding node if it is a text node, or else it -// calls addChild with a new text node. -func (p *parser) addText(text string) { - if text == "" { - return - } - - if p.shouldFosterParent() { - p.fosterParent(&Node{ - Type: TextNode, - Data: text, - }) - return - } - - t := p.top() - if n := t.LastChild; n != nil && n.Type == TextNode { - n.Data += text - return - } - p.addChild(&Node{ - Type: TextNode, - Data: text, - }) -} - -// addElement adds a child element based on the current token. -func (p *parser) addElement() { - p.addChild(&Node{ - Type: ElementNode, - DataAtom: p.tok.DataAtom, - Data: p.tok.Data, - Attr: p.tok.Attr, - }) -} - -// Section 12.2.4.3. -func (p *parser) addFormattingElement() { - tagAtom, attr := p.tok.DataAtom, p.tok.Attr - p.addElement() - - // Implement the Noah's Ark clause, but with three per family instead of two. - identicalElements := 0 -findIdenticalElements: - for i := len(p.afe) - 1; i >= 0; i-- { - n := p.afe[i] - if n.Type == scopeMarkerNode { - break - } - if n.Type != ElementNode { - continue - } - if n.Namespace != "" { - continue - } - if n.DataAtom != tagAtom { - continue - } - if len(n.Attr) != len(attr) { - continue - } - compareAttributes: - for _, t0 := range n.Attr { - for _, t1 := range attr { - if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val { - // Found a match for this attribute, continue with the next attribute. - continue compareAttributes - } - } - // If we get here, there is no attribute that matches a. - // Therefore the element is not identical to the new one. - continue findIdenticalElements - } - - identicalElements++ - if identicalElements >= 3 { - p.afe.remove(n) - } - } - - p.afe = append(p.afe, p.top()) -} - -// Section 12.2.4.3. -func (p *parser) clearActiveFormattingElements() { - for { - n := p.afe.pop() - if len(p.afe) == 0 || n.Type == scopeMarkerNode { - return - } - } -} - -// Section 12.2.4.3. -func (p *parser) reconstructActiveFormattingElements() { - n := p.afe.top() - if n == nil { - return - } - if n.Type == scopeMarkerNode || p.oe.index(n) != -1 { - return - } - i := len(p.afe) - 1 - for n.Type != scopeMarkerNode && p.oe.index(n) == -1 { - if i == 0 { - i = -1 - break - } - i-- - n = p.afe[i] - } - for { - i++ - clone := p.afe[i].clone() - p.addChild(clone) - p.afe[i] = clone - if i == len(p.afe)-1 { - break - } - } -} - -// Section 12.2.5. -func (p *parser) acknowledgeSelfClosingTag() { - p.hasSelfClosingToken = false -} - -// An insertion mode (section 12.2.4.1) is the state transition function from -// a particular state in the HTML5 parser's state machine. It updates the -// parser's fields depending on parser.tok (where ErrorToken means EOF). -// It returns whether the token was consumed. -type insertionMode func(*parser) bool - -// setOriginalIM sets the insertion mode to return to after completing a text or -// inTableText insertion mode. -// Section 12.2.4.1, "using the rules for". -func (p *parser) setOriginalIM() { - if p.originalIM != nil { - panic("html: bad parser state: originalIM was set twice") - } - p.originalIM = p.im -} - -// Section 12.2.4.1, "reset the insertion mode". -func (p *parser) resetInsertionMode() { - for i := len(p.oe) - 1; i >= 0; i-- { - n := p.oe[i] - last := i == 0 - if last && p.context != nil { - n = p.context - } - - switch n.DataAtom { - case a.Select: - if !last { - for ancestor, first := n, p.oe[0]; ancestor != first; { - ancestor = p.oe[p.oe.index(ancestor)-1] - switch ancestor.DataAtom { - case a.Template: - p.im = inSelectIM - return - case a.Table: - p.im = inSelectInTableIM - return - } - } - } - p.im = inSelectIM - case a.Td, a.Th: - // TODO: remove this divergence from the HTML5 spec. - // - // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 - p.im = inCellIM - case a.Tr: - p.im = inRowIM - case a.Tbody, a.Thead, a.Tfoot: - p.im = inTableBodyIM - case a.Caption: - p.im = inCaptionIM - case a.Colgroup: - p.im = inColumnGroupIM - case a.Table: - p.im = inTableIM - case a.Template: - // TODO: remove this divergence from the HTML5 spec. - if n.Namespace != "" { - continue - } - p.im = p.templateStack.top() - case a.Head: - // TODO: remove this divergence from the HTML5 spec. - // - // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 - p.im = inHeadIM - case a.Body: - p.im = inBodyIM - case a.Frameset: - p.im = inFramesetIM - case a.Html: - if p.head == nil { - p.im = beforeHeadIM - } else { - p.im = afterHeadIM - } - default: - if last { - p.im = inBodyIM - return - } - continue - } - return - } -} - -const whitespace = " \t\r\n\f" - -// Section 12.2.6.4.1. -func initialIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case CommentToken: - p.doc.AppendChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - n, quirks := parseDoctype(p.tok.Data) - p.doc.AppendChild(n) - p.quirks = quirks - p.im = beforeHTMLIM - return true - } - p.quirks = true - p.im = beforeHTMLIM - return false -} - -// Section 12.2.6.4.2. -func beforeHTMLIM(p *parser) bool { - switch p.tok.Type { - case DoctypeToken: - // Ignore the token. - return true - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case StartTagToken: - if p.tok.DataAtom == a.Html { - p.addElement() - p.im = beforeHeadIM - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head, a.Body, a.Html, a.Br: - p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) - return false - default: - // Ignore the token. - return true - } - case CommentToken: - p.doc.AppendChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - } - p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) - return false -} - -// Section 12.2.6.4.3. -func beforeHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Head: - p.addElement() - p.head = p.top() - p.im = inHeadIM - return true - case a.Html: - return inBodyIM(p) - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head, a.Body, a.Html, a.Br: - p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) - return false - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) - return false -} - -// Section 12.2.6.4.4. -func inHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - s := strings.TrimLeft(p.tok.Data, whitespace) - if len(s) < len(p.tok.Data) { - // Add the initial whitespace to the current node. - p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) - if s == "" { - return true - } - p.tok.Data = s - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Html: - return inBodyIM(p) - case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta: - p.addElement() - p.oe.pop() - p.acknowledgeSelfClosingTag() - return true - case a.Script, a.Title, a.Noscript, a.Noframes, a.Style: - p.addElement() - p.setOriginalIM() - p.im = textIM - return true - case a.Head: - // Ignore the token. - return true - case a.Template: - p.addElement() - p.afe = append(p.afe, &scopeMarker) - p.framesetOK = false - p.im = inTemplateIM - p.templateStack = append(p.templateStack, inTemplateIM) - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head: - p.oe.pop() - p.im = afterHeadIM - return true - case a.Body, a.Html, a.Br: - p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) - return false - case a.Template: - if !p.oe.contains(a.Template) { - return true - } - // TODO: remove this divergence from the HTML5 spec. - // - // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 - p.generateImpliedEndTags() - for i := len(p.oe) - 1; i >= 0; i-- { - if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template { - p.oe = p.oe[:i] - break - } - } - p.clearActiveFormattingElements() - p.templateStack.pop() - p.resetInsertionMode() - return true - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) - return false -} - -// Section 12.2.6.4.6. -func afterHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - s := strings.TrimLeft(p.tok.Data, whitespace) - if len(s) < len(p.tok.Data) { - // Add the initial whitespace to the current node. - p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) - if s == "" { - return true - } - p.tok.Data = s - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Html: - return inBodyIM(p) - case a.Body: - p.addElement() - p.framesetOK = false - p.im = inBodyIM - return true - case a.Frameset: - p.addElement() - p.im = inFramesetIM - return true - case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: - p.oe = append(p.oe, p.head) - defer p.oe.remove(p.head) - return inHeadIM(p) - case a.Head: - // Ignore the token. - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Body, a.Html, a.Br: - // Drop down to creating an implied tag. - case a.Template: - return inHeadIM(p) - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(StartTagToken, a.Body, a.Body.String()) - p.framesetOK = true - return false -} - -// copyAttributes copies attributes of src not found on dst to dst. -func copyAttributes(dst *Node, src Token) { - if len(src.Attr) == 0 { - return - } - attr := map[string]string{} - for _, t := range dst.Attr { - attr[t.Key] = t.Val - } - for _, t := range src.Attr { - if _, ok := attr[t.Key]; !ok { - dst.Attr = append(dst.Attr, t) - attr[t.Key] = t.Val - } - } -} - -// Section 12.2.6.4.7. -func inBodyIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - d := p.tok.Data - switch n := p.oe.top(); n.DataAtom { - case a.Pre, a.Listing: - if n.FirstChild == nil { - // Ignore a newline at the start of a
 block.
-				if d != "" && d[0] == '\r' {
-					d = d[1:]
-				}
-				if d != "" && d[0] == '\n' {
-					d = d[1:]
-				}
-			}
-		}
-		d = strings.Replace(d, "\x00", "", -1)
-		if d == "" {
-			return true
-		}
-		p.reconstructActiveFormattingElements()
-		p.addText(d)
-		if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
-			// There were non-whitespace characters inserted.
-			p.framesetOK = false
-		}
-	case StartTagToken:
-		switch p.tok.DataAtom {
-		case a.Html:
-			if p.oe.contains(a.Template) {
-				return true
-			}
-			copyAttributes(p.oe[0], p.tok)
-		case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
-			return inHeadIM(p)
-		case a.Body:
-			if p.oe.contains(a.Template) {
-				return true
-			}
-			if len(p.oe) >= 2 {
-				body := p.oe[1]
-				if body.Type == ElementNode && body.DataAtom == a.Body {
-					p.framesetOK = false
-					copyAttributes(body, p.tok)
-				}
-			}
-		case a.Frameset:
-			if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
-				// Ignore the token.
-				return true
-			}
-			body := p.oe[1]
-			if body.Parent != nil {
-				body.Parent.RemoveChild(body)
-			}
-			p.oe = p.oe[:1]
-			p.addElement()
-			p.im = inFramesetIM
-			return true
-		case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-			p.popUntil(buttonScope, a.P)
-			switch n := p.top(); n.DataAtom {
-			case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-				p.oe.pop()
-			}
-			p.addElement()
-		case a.Pre, a.Listing:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-			// The newline, if any, will be dealt with by the TextToken case.
-			p.framesetOK = false
-		case a.Form:
-			if p.form != nil && !p.oe.contains(a.Template) {
-				// Ignore the token
-				return true
-			}
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-			if !p.oe.contains(a.Template) {
-				p.form = p.top()
-			}
-		case a.Li:
-			p.framesetOK = false
-			for i := len(p.oe) - 1; i >= 0; i-- {
-				node := p.oe[i]
-				switch node.DataAtom {
-				case a.Li:
-					p.oe = p.oe[:i]
-				case a.Address, a.Div, a.P:
-					continue
-				default:
-					if !isSpecialElement(node) {
-						continue
-					}
-				}
-				break
-			}
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Dd, a.Dt:
-			p.framesetOK = false
-			for i := len(p.oe) - 1; i >= 0; i-- {
-				node := p.oe[i]
-				switch node.DataAtom {
-				case a.Dd, a.Dt:
-					p.oe = p.oe[:i]
-				case a.Address, a.Div, a.P:
-					continue
-				default:
-					if !isSpecialElement(node) {
-						continue
-					}
-				}
-				break
-			}
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Plaintext:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Button:
-			p.popUntil(defaultScope, a.Button)
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.framesetOK = false
-		case a.A:
-			for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
-				if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
-					p.inBodyEndTagFormatting(a.A)
-					p.oe.remove(n)
-					p.afe.remove(n)
-					break
-				}
-			}
-			p.reconstructActiveFormattingElements()
-			p.addFormattingElement()
-		case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
-			p.reconstructActiveFormattingElements()
-			p.addFormattingElement()
-		case a.Nobr:
-			p.reconstructActiveFormattingElements()
-			if p.elementInScope(defaultScope, a.Nobr) {
-				p.inBodyEndTagFormatting(a.Nobr)
-				p.reconstructActiveFormattingElements()
-			}
-			p.addFormattingElement()
-		case a.Applet, a.Marquee, a.Object:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.afe = append(p.afe, &scopeMarker)
-			p.framesetOK = false
-		case a.Table:
-			if !p.quirks {
-				p.popUntil(buttonScope, a.P)
-			}
-			p.addElement()
-			p.framesetOK = false
-			p.im = inTableIM
-			return true
-		case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-			if p.tok.DataAtom == a.Input {
-				for _, t := range p.tok.Attr {
-					if t.Key == "type" {
-						if strings.ToLower(t.Val) == "hidden" {
-							// Skip setting framesetOK = false
-							return true
-						}
-					}
-				}
-			}
-			p.framesetOK = false
-		case a.Param, a.Source, a.Track:
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-		case a.Hr:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-			p.framesetOK = false
-		case a.Image:
-			p.tok.DataAtom = a.Img
-			p.tok.Data = a.Img.String()
-			return false
-		case a.Isindex:
-			if p.form != nil {
-				// Ignore the token.
-				return true
-			}
-			action := ""
-			prompt := "This is a searchable index. Enter search keywords: "
-			attr := []Attribute{{Key: "name", Val: "isindex"}}
-			for _, t := range p.tok.Attr {
-				switch t.Key {
-				case "action":
-					action = t.Val
-				case "name":
-					// Ignore the attribute.
-				case "prompt":
-					prompt = t.Val
-				default:
-					attr = append(attr, t)
-				}
-			}
-			p.acknowledgeSelfClosingTag()
-			p.popUntil(buttonScope, a.P)
-			p.parseImpliedToken(StartTagToken, a.Form, a.Form.String())
-			if p.form == nil {
-				// NOTE: The 'isindex' element has been removed,
-				// and the 'template' element has not been designed to be
-				// collaborative with the index element.
-				//
-				// Ignore the token.
-				return true
-			}
-			if action != "" {
-				p.form.Attr = []Attribute{{Key: "action", Val: action}}
-			}
-			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
-			p.parseImpliedToken(StartTagToken, a.Label, a.Label.String())
-			p.addText(prompt)
-			p.addChild(&Node{
-				Type:     ElementNode,
-				DataAtom: a.Input,
-				Data:     a.Input.String(),
-				Attr:     attr,
-			})
-			p.oe.pop()
-			p.parseImpliedToken(EndTagToken, a.Label, a.Label.String())
-			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
-			p.parseImpliedToken(EndTagToken, a.Form, a.Form.String())
-		case a.Textarea:
-			p.addElement()
-			p.setOriginalIM()
-			p.framesetOK = false
-			p.im = textIM
-		case a.Xmp:
-			p.popUntil(buttonScope, a.P)
-			p.reconstructActiveFormattingElements()
-			p.framesetOK = false
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Iframe:
-			p.framesetOK = false
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Noembed, a.Noscript:
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Select:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.framesetOK = false
-			p.im = inSelectIM
-			return true
-		case a.Optgroup, a.Option:
-			if p.top().DataAtom == a.Option {
-				p.oe.pop()
-			}
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-		case a.Rb, a.Rtc:
-			if p.elementInScope(defaultScope, a.Ruby) {
-				p.generateImpliedEndTags()
-			}
-			p.addElement()
-		case a.Rp, a.Rt:
-			if p.elementInScope(defaultScope, a.Ruby) {
-				p.generateImpliedEndTags("rtc")
-			}
-			p.addElement()
-		case a.Math, a.Svg:
-			p.reconstructActiveFormattingElements()
-			if p.tok.DataAtom == a.Math {
-				adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
-			} else {
-				adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
-			}
-			adjustForeignAttributes(p.tok.Attr)
-			p.addElement()
-			p.top().Namespace = p.tok.Data
-			if p.hasSelfClosingToken {
-				p.oe.pop()
-				p.acknowledgeSelfClosingTag()
-			}
-			return true
-		case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
-			// Ignore the token.
-		default:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-		}
-	case EndTagToken:
-		switch p.tok.DataAtom {
-		case a.Body:
-			if p.elementInScope(defaultScope, a.Body) {
-				p.im = afterBodyIM
-			}
-		case a.Html:
-			if p.elementInScope(defaultScope, a.Body) {
-				p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
-				return false
-			}
-			return true
-		case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
-			p.popUntil(defaultScope, p.tok.DataAtom)
-		case a.Form:
-			if p.oe.contains(a.Template) {
-				i := p.indexOfElementInScope(defaultScope, a.Form)
-				if i == -1 {
-					// Ignore the token.
-					return true
-				}
-				p.generateImpliedEndTags()
-				if p.oe[i].DataAtom != a.Form {
-					// Ignore the token.
-					return true
-				}
-				p.popUntil(defaultScope, a.Form)
-			} else {
-				node := p.form
-				p.form = nil
-				i := p.indexOfElementInScope(defaultScope, a.Form)
-				if node == nil || i == -1 || p.oe[i] != node {
-					// Ignore the token.
-					return true
-				}
-				p.generateImpliedEndTags()
-				p.oe.remove(node)
-			}
-		case a.P:
-			if !p.elementInScope(buttonScope, a.P) {
-				p.parseImpliedToken(StartTagToken, a.P, a.P.String())
-			}
-			p.popUntil(buttonScope, a.P)
-		case a.Li:
-			p.popUntil(listItemScope, a.Li)
-		case a.Dd, a.Dt:
-			p.popUntil(defaultScope, p.tok.DataAtom)
-		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-			p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
-		case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
-			p.inBodyEndTagFormatting(p.tok.DataAtom)
-		case a.Applet, a.Marquee, a.Object:
-			if p.popUntil(defaultScope, p.tok.DataAtom) {
-				p.clearActiveFormattingElements()
-			}
-		case a.Br:
-			p.tok.Type = StartTagToken
-			return false
-		case a.Template:
-			return inHeadIM(p)
-		default:
-			p.inBodyEndTagOther(p.tok.DataAtom)
-		}
-	case CommentToken:
-		p.addChild(&Node{
-			Type: CommentNode,
-			Data: p.tok.Data,
-		})
-	case ErrorToken:
-		// TODO: remove this divergence from the HTML5 spec.
-		if len(p.templateStack) > 0 {
-			p.im = inTemplateIM
-			return false
-		} else {
-			for _, e := range p.oe {
-				switch e.DataAtom {
-				case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc, a.Tbody, a.Td, a.Tfoot, a.Th,
-					a.Thead, a.Tr, a.Body, a.Html:
-				default:
-					return true
-				}
-			}
-		}
-	}
-
-	return true
-}
-
-func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
-	// This is the "adoption agency" algorithm, described at
-	// https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
-
-	// TODO: this is a fairly literal line-by-line translation of that algorithm.
-	// Once the code successfully parses the comprehensive test suite, we should
-	// refactor this code to be more idiomatic.
-
-	// Steps 1-4. The outer loop.
-	for i := 0; i < 8; i++ {
-		// Step 5. Find the formatting element.
-		var formattingElement *Node
-		for j := len(p.afe) - 1; j >= 0; j-- {
-			if p.afe[j].Type == scopeMarkerNode {
-				break
-			}
-			if p.afe[j].DataAtom == tagAtom {
-				formattingElement = p.afe[j]
-				break
-			}
-		}
-		if formattingElement == nil {
-			p.inBodyEndTagOther(tagAtom)
-			return
-		}
-		feIndex := p.oe.index(formattingElement)
-		if feIndex == -1 {
-			p.afe.remove(formattingElement)
-			return
-		}
-		if !p.elementInScope(defaultScope, tagAtom) {
-			// Ignore the tag.
-			return
-		}
-
-		// Steps 9-10. Find the furthest block.
-		var furthestBlock *Node
-		for _, e := range p.oe[feIndex:] {
-			if isSpecialElement(e) {
-				furthestBlock = e
-				break
-			}
-		}
-		if furthestBlock == nil {
-			e := p.oe.pop()
-			for e != formattingElement {
-				e = p.oe.pop()
-			}
-			p.afe.remove(e)
-			return
-		}
-
-		// Steps 11-12. Find the common ancestor and bookmark node.
-		commonAncestor := p.oe[feIndex-1]
-		bookmark := p.afe.index(formattingElement)
-
-		// Step 13. The inner loop. Find the lastNode to reparent.
-		lastNode := furthestBlock
-		node := furthestBlock
-		x := p.oe.index(node)
-		// Steps 13.1-13.2
-		for j := 0; j < 3; j++ {
-			// Step 13.3.
-			x--
-			node = p.oe[x]
-			// Step 13.4 - 13.5.
-			if p.afe.index(node) == -1 {
-				p.oe.remove(node)
-				continue
-			}
-			// Step 13.6.
-			if node == formattingElement {
-				break
-			}
-			// Step 13.7.
-			clone := node.clone()
-			p.afe[p.afe.index(node)] = clone
-			p.oe[p.oe.index(node)] = clone
-			node = clone
-			// Step 13.8.
-			if lastNode == furthestBlock {
-				bookmark = p.afe.index(node) + 1
-			}
-			// Step 13.9.
-			if lastNode.Parent != nil {
-				lastNode.Parent.RemoveChild(lastNode)
-			}
-			node.AppendChild(lastNode)
-			// Step 13.10.
-			lastNode = node
-		}
-
-		// Step 14. Reparent lastNode to the common ancestor,
-		// or for misnested table nodes, to the foster parent.
-		if lastNode.Parent != nil {
-			lastNode.Parent.RemoveChild(lastNode)
-		}
-		switch commonAncestor.DataAtom {
-		case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
-			p.fosterParent(lastNode)
-		default:
-			commonAncestor.AppendChild(lastNode)
-		}
-
-		// Steps 15-17. Reparent nodes from the furthest block's children
-		// to a clone of the formatting element.
-		clone := formattingElement.clone()
-		reparentChildren(clone, furthestBlock)
-		furthestBlock.AppendChild(clone)
-
-		// Step 18. Fix up the list of active formatting elements.
-		if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
-			// Move the bookmark with the rest of the list.
-			bookmark--
-		}
-		p.afe.remove(formattingElement)
-		p.afe.insert(bookmark, clone)
-
-		// Step 19. Fix up the stack of open elements.
-		p.oe.remove(formattingElement)
-		p.oe.insert(p.oe.index(furthestBlock)+1, clone)
-	}
-}
-
-// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
-// "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content
-// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
-func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
-	for i := len(p.oe) - 1; i >= 0; i-- {
-		if p.oe[i].DataAtom == tagAtom {
-			p.oe = p.oe[:i]
-			break
-		}
-		if isSpecialElement(p.oe[i]) {
-			break
-		}
-	}
-}
-
-// Section 12.2.6.4.8.
-func textIM(p *parser) bool {
-	switch p.tok.Type {
-	case ErrorToken:
-		p.oe.pop()
-	case TextToken:
-		d := p.tok.Data
-		if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
-			// Ignore a newline at the start of a