├── .gitignore ├── .travis.yml ├── Godeps ├── Godeps.json └── Readme ├── README.md ├── app.go ├── crypt ├── encryption.go └── encryption_test.go ├── main.go ├── publisher ├── publisher.go └── publisher_test.go ├── secrets ├── secrets.go └── secrets_test.go └── vendor ├── github.com ├── fatih │ └── structs │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── README.md │ │ ├── field.go │ │ ├── structs.go │ │ └── tags.go ├── hashicorp │ ├── errwrap │ │ ├── LICENSE │ │ ├── README.md │ │ └── errwrap.go │ ├── go-cleanhttp │ │ ├── LICENSE │ │ ├── README.md │ │ ├── cleanhttp.go │ │ └── doc.go │ ├── go-multierror │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── Makefile │ │ ├── README.md │ │ ├── append.go │ │ ├── flatten.go │ │ ├── format.go │ │ ├── multierror.go │ │ └── prefix.go │ ├── go-rootcerts │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── Makefile │ │ ├── README.md │ │ ├── doc.go │ │ ├── rootcerts.go │ │ ├── rootcerts_base.go │ │ └── rootcerts_darwin.go │ ├── hcl │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── Makefile │ │ ├── README.md │ │ ├── appveyor.yml │ │ ├── decoder.go │ │ ├── hcl.go │ │ ├── hcl │ │ │ ├── ast │ │ │ │ ├── ast.go │ │ │ │ └── walk.go │ │ │ ├── parser │ │ │ │ ├── error.go │ │ │ │ └── parser.go │ │ │ ├── scanner │ │ │ │ └── scanner.go │ │ │ ├── strconv │ │ │ │ └── quote.go │ │ │ └── token │ │ │ │ ├── position.go │ │ │ │ └── token.go │ │ ├── json │ │ │ ├── parser │ │ │ │ ├── flatten.go │ │ │ │ └── parser.go │ │ │ ├── scanner │ │ │ │ └── scanner.go │ │ │ └── token │ │ │ │ ├── position.go │ │ │ │ └── token.go │ │ ├── lex.go │ │ └── parse.go │ └── vault │ │ ├── LICENSE │ │ ├── api │ │ ├── SPEC.md │ │ ├── auth.go │ │ ├── auth_token.go │ │ ├── client.go │ │ ├── help.go │ │ ├── logical.go │ │ ├── request.go │ │ ├── response.go │ │ ├── secret.go │ │ ├── ssh.go │ │ ├── ssh_agent.go │ │ ├── sys.go │ │ ├── sys_audit.go │ │ ├── sys_auth.go │ │ ├── sys_capabilities.go │ │ ├── sys_generate_root.go │ │ ├── sys_init.go │ │ ├── sys_leader.go │ │ ├── sys_lease.go │ │ ├── sys_mounts.go │ │ ├── sys_policy.go │ │ ├── sys_rekey.go │ │ ├── sys_rotate.go │ │ ├── sys_seal.go │ │ └── sys_stepdown.go │ │ └── helper │ │ ├── compressutil │ │ └── compress.go │ │ └── jsonutil │ │ └── json.go ├── mitchellh │ ├── go-homedir │ │ ├── LICENSE │ │ ├── README.md │ │ └── homedir.go │ └── mapstructure │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── README.md │ │ ├── decode_hooks.go │ │ ├── error.go │ │ └── mapstructure.go └── sethgrid │ └── pester │ ├── LICENSE.md │ ├── README.md │ └── main.go ├── golang.org └── x │ ├── net │ ├── AUTHORS │ ├── CONTRIBUTORS │ ├── LICENSE │ ├── PATENTS │ ├── http2 │ │ ├── .gitignore │ │ ├── Dockerfile │ │ ├── Makefile │ │ ├── README │ │ ├── client_conn_pool.go │ │ ├── configure_transport.go │ │ ├── databuffer.go │ │ ├── errors.go │ │ ├── flow.go │ │ ├── frame.go │ │ ├── go16.go │ │ ├── go17.go │ │ ├── go17_not18.go │ │ ├── go18.go │ │ ├── gotrack.go │ │ ├── headermap.go │ │ ├── hpack │ │ │ ├── encode.go │ │ │ ├── hpack.go │ │ │ ├── huffman.go │ │ │ └── tables.go │ │ ├── http2.go │ │ ├── not_go16.go │ │ ├── not_go17.go │ │ ├── not_go18.go │ │ ├── pipe.go │ │ ├── server.go │ │ ├── transport.go │ │ ├── write.go │ │ ├── writesched.go │ │ ├── writesched_priority.go │ │ └── writesched_random.go │ ├── idna │ │ ├── idna.go │ │ ├── punycode.go │ │ ├── tables.go │ │ ├── trie.go │ │ └── trieval.go │ └── lex │ │ └── httplex │ │ └── httplex.go │ └── text │ ├── AUTHORS │ ├── CONTRIBUTORS │ ├── LICENSE │ ├── PATENTS │ ├── secure │ └── bidirule │ │ └── bidirule.go │ ├── transform │ └── transform.go │ └── unicode │ ├── bidi │ ├── bidi.go │ ├── bracket.go │ ├── core.go │ ├── gen.go │ ├── gen_ranges.go │ ├── gen_trieval.go │ ├── prop.go │ ├── tables.go │ └── trieval.go │ └── norm │ ├── composition.go │ ├── forminfo.go │ ├── input.go │ ├── iter.go │ ├── maketables.go │ ├── normalize.go │ ├── readwriter.go │ ├── tables.go │ ├── transform.go │ ├── trie.go │ └── triegen.go └── gopkg.in └── yaml.v2 ├── .travis.yml ├── LICENSE ├── LICENSE.libyaml ├── README.md ├── apic.go ├── decode.go ├── emitterc.go ├── encode.go ├── parserc.go ├── readerc.go ├── resolve.go ├── scannerc.go ├── sorter.go ├── writerc.go ├── yaml.go ├── yamlh.go └── yamlprivateh.go /.gitignore: -------------------------------------------------------------------------------- 1 | springboard 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: go 3 | go: 4 | - 1.8 5 | - tip 6 | 7 | env: 8 | - PATH=/home/travis/gopath/bin:$PATH VAULT_TOKEN=horde VAULT_ADDR=http://localhost:8200 9 | 10 | before_install: 11 | - go get github.com/golang/lint/golint 12 | - go get github.com/mitchellh/gox 13 | - wget http://dl.fligl.io/vault.gz 14 | - gunzip vault.gz 15 | - chmod +x vault 16 | - ./vault server -dev -dev-root-token-id=horde & 17 | - sleep 3 18 | - ./vault mount transit 19 | - ./vault write -f transit/keys/my-key 20 | script: 21 | - go vet $(go list ./... | grep -v vendor) 22 | - go test $(go list ./... | grep -v '/vendor/') 23 | - gox -ldflags "-X main.Version=$TRAVIS_BUILD_NUMBER" -output "springboard_{{.OS}}_{{.Arch}}" -osarch="linux/amd64" 24 | - gox -ldflags "-X main.Version=$TRAVIS_BUILD_NUMBER" -output "springboard_{{.OS}}_{{.Arch}}" -osarch="darwin/amd64" 25 | - gzip springboard_linux_amd64 26 | - gzip springboard_darwin_amd64 27 | - mkdir dist release 28 | - cp springboard_linux_amd64.gz dist/ 29 | - cp springboard_darwin_amd64.gz dist/ 30 | - cp springboard_linux_amd64.gz release/springboard_linux_amd64_$(git describe --tags).gz 31 | - cp springboard_darwin_amd64.gz release/springboard_darwin_amd64_$(git describe --tags).gz 32 | 33 | deploy: 34 | - provider: s3 35 | access_key_id: AKIAJWN36CZNBCQXFFTQ 36 | secret_access_key: 37 | secure: YkjuVVEsvzC/JjcmdN8f7jKQ/yEbxQotslQaFOr4Yq9l23tPaZ8YK8J2PnSti4wcwYlXd0U7qUcby8z5gabaGJOH2UvhuNs8FkLDfrQltYF17kE5N/tmLjjHRsxQpcRsLVoLsyNf6AUKGo8HqVKhpfrlaZPj3qfNUwVIOwcbZya4waX8H14n94t4LLkeGV9CFq+0tmDJz6Uug2yfmw1PNkrl+DLlbJJ7HJfHv295MHHDvfxQSJT4tKt4sbloDNTvTKna2mQyXBHuh2PeJTF9rdvqgOpvC1u3YTkD9c9PRe7ZE8CAEBjNStYkNJE6zLrsN+NN2hnnATuveZgRsdWvzmGzhaye255qDUQEsUl3Artat+sPACNdYtoeBdgvX9/f6EnkDut54gLIy9WVqs2FZTgTC+x/lMhXfaouJWFHGWk59nI+ENd7cxZyS5w5XcSCbPxbX1VunelXsWuXdayiviIVskHWJ1CwQLt8Nwipesb4743uP9WDxGMMRd/6gXUIFE6EcH/5Q+zi3Y5+0Yn7jtT4e/pd/Zob6o4PiWRojgTV1Zvr4skcQ9vQJfZx9sAu8nScwDpVPI5tyUqqOofkeOgIFea+EkGuKpoQMYzoEPMhqTP6KRhawP//fbvOlh0tzTUJQT6CcMLrXUS93+cybAvws03jiWqu0c30HP0WKEs= 38 | bucket: dl.fligl.io 39 | skip_cleanup: true 40 | local-dir: dist 41 | upload-dir: artifacts/springboard 42 | acl: public_read 43 | - provider: s3 44 | access_key_id: AKIAJWN36CZNBCQXFFTQ 45 | secret_access_key: 46 | secure: YkjuVVEsvzC/JjcmdN8f7jKQ/yEbxQotslQaFOr4Yq9l23tPaZ8YK8J2PnSti4wcwYlXd0U7qUcby8z5gabaGJOH2UvhuNs8FkLDfrQltYF17kE5N/tmLjjHRsxQpcRsLVoLsyNf6AUKGo8HqVKhpfrlaZPj3qfNUwVIOwcbZya4waX8H14n94t4LLkeGV9CFq+0tmDJz6Uug2yfmw1PNkrl+DLlbJJ7HJfHv295MHHDvfxQSJT4tKt4sbloDNTvTKna2mQyXBHuh2PeJTF9rdvqgOpvC1u3YTkD9c9PRe7ZE8CAEBjNStYkNJE6zLrsN+NN2hnnATuveZgRsdWvzmGzhaye255qDUQEsUl3Artat+sPACNdYtoeBdgvX9/f6EnkDut54gLIy9WVqs2FZTgTC+x/lMhXfaouJWFHGWk59nI+ENd7cxZyS5w5XcSCbPxbX1VunelXsWuXdayiviIVskHWJ1CwQLt8Nwipesb4743uP9WDxGMMRd/6gXUIFE6EcH/5Q+zi3Y5+0Yn7jtT4e/pd/Zob6o4PiWRojgTV1Zvr4skcQ9vQJfZx9sAu8nScwDpVPI5tyUqqOofkeOgIFea+EkGuKpoQMYzoEPMhqTP6KRhawP//fbvOlh0tzTUJQT6CcMLrXUS93+cybAvws03jiWqu0c30HP0WKEs= 47 | bucket: dl.fligl.io 48 | skip_cleanup: true 49 | local-dir: release 50 | upload-dir: artifacts/springboard 51 | acl: public_read 52 | on: 53 | tags: true 54 | -------------------------------------------------------------------------------- /Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/benschw/springboard", 3 | "GoVersion": "go1.8", 4 | "GodepVersion": "v79", 5 | "Deps": [ 6 | { 7 | "ImportPath": "github.com/fatih/structs", 8 | "Comment": "v1.0", 9 | "Rev": "a720dfa8df582c51dee1b36feabb906bde1588bd" 10 | }, 11 | { 12 | "ImportPath": "github.com/hashicorp/errwrap", 13 | "Rev": "7554cd9344cec97297fa6649b055a8c98c2a1e55" 14 | }, 15 | { 16 | "ImportPath": "github.com/hashicorp/go-cleanhttp", 17 | "Rev": "3573b8b52aa7b37b9358d966a898feb387f62437" 18 | }, 19 | { 20 | "ImportPath": "github.com/hashicorp/go-multierror", 21 | "Rev": "ed905158d87462226a13fe39ddf685ea65f1c11f" 22 | }, 23 | { 24 | "ImportPath": "github.com/hashicorp/go-rootcerts", 25 | "Rev": "6bb64b370b90e7ef1fa532be9e591a81c3493e00" 26 | }, 27 | { 28 | "ImportPath": "github.com/hashicorp/hcl", 29 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 30 | }, 31 | { 32 | "ImportPath": "github.com/hashicorp/hcl/hcl/ast", 33 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 34 | }, 35 | { 36 | "ImportPath": "github.com/hashicorp/hcl/hcl/parser", 37 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 38 | }, 39 | { 40 | "ImportPath": "github.com/hashicorp/hcl/hcl/scanner", 41 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 42 | }, 43 | { 44 | "ImportPath": "github.com/hashicorp/hcl/hcl/strconv", 45 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 46 | }, 47 | { 48 | "ImportPath": "github.com/hashicorp/hcl/hcl/token", 49 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 50 | }, 51 | { 52 | "ImportPath": "github.com/hashicorp/hcl/json/parser", 53 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 54 | }, 55 | { 56 | "ImportPath": "github.com/hashicorp/hcl/json/scanner", 57 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 58 | }, 59 | { 60 | "ImportPath": "github.com/hashicorp/hcl/json/token", 61 | "Rev": "630949a3c5fa3c613328e1b8256052cbc2327c9b" 62 | }, 63 | { 64 | "ImportPath": "github.com/hashicorp/vault/api", 65 | "Comment": "v0.7.0-88-g9d013a07", 66 | "Rev": "9d013a0707a8fe9e1a891abcc4e3a2105bd97fcb" 67 | }, 68 | { 69 | "ImportPath": "github.com/hashicorp/vault/helper/compressutil", 70 | "Comment": "v0.7.0-88-g9d013a07", 71 | "Rev": "9d013a0707a8fe9e1a891abcc4e3a2105bd97fcb" 72 | }, 73 | { 74 | "ImportPath": "github.com/hashicorp/vault/helper/jsonutil", 75 | "Comment": "v0.7.0-88-g9d013a07", 76 | "Rev": "9d013a0707a8fe9e1a891abcc4e3a2105bd97fcb" 77 | }, 78 | { 79 | "ImportPath": "github.com/mitchellh/go-homedir", 80 | "Rev": "b8bc1bf767474819792c23f32d8286a45736f1c6" 81 | }, 82 | { 83 | "ImportPath": "github.com/mitchellh/mapstructure", 84 | "Rev": "53818660ed4955e899c0bcafa97299a388bd7c8e" 85 | }, 86 | { 87 | "ImportPath": "github.com/sethgrid/pester", 88 | "Rev": "ad2265b06c1300b29bd9352e597121db34656d40" 89 | }, 90 | { 91 | "ImportPath": "golang.org/x/net/http2", 92 | "Rev": "ffcf1bedda3b04ebb15a168a59800a73d6dc0f4d" 93 | }, 94 | { 95 | "ImportPath": "golang.org/x/net/http2/hpack", 96 | "Rev": "ffcf1bedda3b04ebb15a168a59800a73d6dc0f4d" 97 | }, 98 | { 99 | "ImportPath": "golang.org/x/net/idna", 100 | "Rev": "ffcf1bedda3b04ebb15a168a59800a73d6dc0f4d" 101 | }, 102 | { 103 | "ImportPath": "golang.org/x/net/lex/httplex", 104 | "Rev": "ffcf1bedda3b04ebb15a168a59800a73d6dc0f4d" 105 | }, 106 | { 107 | "ImportPath": "golang.org/x/text/secure/bidirule", 108 | "Rev": "f4b4367115ec2de254587813edaa901bc1c723a8" 109 | }, 110 | { 111 | "ImportPath": "golang.org/x/text/transform", 112 | "Rev": "f4b4367115ec2de254587813edaa901bc1c723a8" 113 | }, 114 | { 115 | "ImportPath": "golang.org/x/text/unicode/bidi", 116 | "Rev": "f4b4367115ec2de254587813edaa901bc1c723a8" 117 | }, 118 | { 119 | "ImportPath": "golang.org/x/text/unicode/norm", 120 | "Rev": "f4b4367115ec2de254587813edaa901bc1c723a8" 121 | }, 122 | { 123 | "ImportPath": "gopkg.in/yaml.v2", 124 | "Rev": "a3f3340b5840cee44f372bddb5880fcbc419b46a" 125 | } 126 | ] 127 | } 128 | -------------------------------------------------------------------------------- /Godeps/Readme: -------------------------------------------------------------------------------- 1 | This directory tree is generated automatically by godep. 2 | 3 | Please do not edit. 4 | 5 | See https://github.com/tools/godep for more information. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/benschw/springboard.svg?branch=master)](https://travis-ci.org/benschw/springboard) 2 | [![Downloads](https://img.shields.io/badge/download-release-blue.svg)](http://dl.fligl.io/#/springboard) 3 | 4 | # Springboard 5 | 6 | `springboard` is a cli utility to help get your secrets into [vault](https://www.vaultproject.io) 7 | 8 | It leverages the [transit](https://www.vaultproject.io/docs/secrets/transit/index.html) secret backend to 9 | protect your secrets locally in a yaml formatted secrets file and facilitates pushing 10 | the secrets stored in this file into a specified path of the 11 | [generic](https://www.vaultproject.io/docs/secrets/generic/index.html) secret backend. 12 | 13 | Since the values in your secrets file are encrypted with vault's transit backend, 14 | you can commit these files to source control. This allows you to be more deliberate about 15 | tracking and publishing the sensitive data needed to run your applications. 16 | 17 | 18 | # Usage 19 | 20 | ## Install 21 | 22 | wget http://dl.fligl.io/artifacts/springboard/springboard_linux_amd64.gz 23 | gunzip springboard_linux_amd64.gz 24 | chmod +x springboard_linux_amd64 25 | mv springboard_linux_amd64 /usr/local/bin/springboard 26 | 27 | ## Configure Vault 28 | 29 | _Hard coding tokens etc. is only suitable for dev. See 30 | [Installing Vault](https://www.vaultproject.io/docs/install/index.html) 31 | for complete install instructions_ 32 | 33 | export VAULT_TOKEN=springboard 34 | export VAULT_ADDR=http://localhost:8200 35 | 36 | vault server -dev -dev-root-token-id=springboard 37 | 38 | vault mount transit 39 | Successfully mounted 'transit' at 'transit'! 40 | 41 | vault write -f transit/keys/my-key 42 | Success! Data written to: transit/keys/my-key 43 | 44 | 45 | ## Managing Secrets with Springboard 46 | 47 | export VAULT_TOKEN=springboard 48 | export VAULT_ADDR=http://localhost:8200 49 | 50 | springboard set -s ./test.yml -t my-key foo "hello world" 51 | springboard set -s ./test.yml -t my-key bar "hello galaxy" 52 | springboard get -s ./test.yml -t my-key foo 53 | hello world 54 | springboard push -s ./test.yml -t my-key secret/my-secrets 55 | 56 | vault read secret/my-secrets 57 | Key Value 58 | --- ----- 59 | refresh_interval 768h0m0s 60 | bar hello galaxy 61 | foo hello world 62 | 63 | ## Complete Usage 64 | 65 | Usage: springboard -s -t [args] 66 | 67 | Subcommands: 68 | help display this help screen and exit 69 | set set/encrypt 'value' in local secrets file 70 | get get/decrypt 'value' from local secrets file 71 | push publish secrets in local secrets file to 72 | 'path' in vault generic secrets backend 73 | 74 | Flags: 75 | -s string secrets file 76 | -t string transit key 77 | 78 | Examples: 79 | springboard set -s secrets.yml -t my-key user_name supersecret 80 | springboard get -s secrets.yml -t my-key user_name 81 | springboard push -s secrets.yml -t my-key secret/my-space 82 | 83 | github.com/benschw/springboard 84 | -------------------------------------------------------------------------------- /app.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/benschw/springboard/crypt" 7 | "github.com/benschw/springboard/publisher" 8 | "github.com/benschw/springboard/secrets" 9 | vaultapi "github.com/hashicorp/vault/api" 10 | ) 11 | 12 | func NewApp(secretsFile string, transitKey string) (*App, error) { 13 | cfg := vaultapi.DefaultConfig() 14 | client, err := vaultapi.NewClient(cfg) 15 | if err != nil { 16 | return nil, err 17 | } 18 | vault := client.Logical() 19 | 20 | c := crypt.New(vault, transitKey) 21 | 22 | s, err := secrets.New(secretsFile, c) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return &App{vault: vault, secrets: s}, nil 27 | } 28 | 29 | type App struct { 30 | vault *vaultapi.Logical 31 | secrets *secrets.Secrets 32 | } 33 | 34 | func (a *App) get(key string) error { 35 | val, err := a.secrets.Get(key) 36 | if err != nil { 37 | return err 38 | } 39 | 40 | fmt.Println(val) 41 | return nil 42 | } 43 | 44 | func (a *App) set(key string, value string) error { 45 | if err := a.secrets.Set(key, value); err != nil { 46 | return err 47 | } 48 | return a.secrets.Save() 49 | } 50 | 51 | func (a *App) remove(key string) error { 52 | if err := a.secrets.Remove(key); err != nil { 53 | return err 54 | } 55 | return a.secrets.Save() 56 | } 57 | 58 | func (a *App) push(path string) error { 59 | pub := publisher.New(a.vault, path) 60 | 61 | return pub.Push(a.secrets) 62 | } 63 | -------------------------------------------------------------------------------- /crypt/encryption.go: -------------------------------------------------------------------------------- 1 | package crypt 2 | 3 | import ( 4 | "fmt" 5 | b64 "encoding/base64" 6 | vaultapi "github.com/hashicorp/vault/api" 7 | ) 8 | 9 | func New(vault *vaultapi.Logical, key string) *Crypt { 10 | return &Crypt{vault: vault, key: key} 11 | } 12 | 13 | type Crypt struct { 14 | vault *vaultapi.Logical 15 | key string 16 | } 17 | 18 | func (c Crypt) Encrypt(val string) (string, error) { 19 | enc := b64.StdEncoding.EncodeToString([]byte(val)) 20 | 21 | v, err := c.vault.Write(fmt.Sprintf("transit/encrypt/%s", c.key), 22 | map[string]interface{}{ 23 | "plaintext": enc, 24 | }) 25 | if err != nil { 26 | return "", err 27 | } 28 | return fmt.Sprintf("%s", v.Data["ciphertext"]), nil 29 | } 30 | 31 | func (c Crypt) Decrypt(val string) (string, error) { 32 | v, err := c.vault.Write(fmt.Sprintf("transit/decrypt/%s", c.key), 33 | map[string]interface{}{ 34 | "ciphertext": val, 35 | }) 36 | if err != nil { 37 | return "", err 38 | } 39 | 40 | enc := v.Data["plaintext"] 41 | dec, err := b64.StdEncoding.DecodeString(fmt.Sprintf("%s", enc)) 42 | 43 | if err != nil { 44 | return "", err 45 | } 46 | return string(dec[:]), nil 47 | } 48 | -------------------------------------------------------------------------------- /crypt/encryption_test.go: -------------------------------------------------------------------------------- 1 | package crypt 2 | 3 | import ( 4 | "testing" 5 | vaultapi "github.com/hashicorp/vault/api" 6 | ) 7 | 8 | func TestEncryption(t *testing.T) { 9 | 10 | 11 | cfg := vaultapi.DefaultConfig() 12 | client, err := vaultapi.NewClient(cfg) 13 | if err != nil { 14 | panic(err) 15 | } 16 | c := client.Logical() 17 | 18 | 19 | lib := New(c, "my-key") 20 | 21 | secret := "hello world" 22 | 23 | enc, err := lib.Encrypt(secret) 24 | if err != nil { 25 | t.Error(err) 26 | } 27 | 28 | dec, err := lib.Decrypt(enc) 29 | if err != nil { 30 | t.Error(err) 31 | } 32 | 33 | if dec != secret { 34 | t.Error("decrypted doesn't match original", dec) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func usage() { 10 | fmt.Printf("Usage: springboard -s -t [args]\n\n") 11 | 12 | fmt.Printf("Subcommands:\n") 13 | fmt.Printf(" help display this help screen and exit\n") 14 | fmt.Printf(" set set/encrypt 'value' in local secrets file\n") 15 | fmt.Printf(" get get/decrypt 'value' from local secrets file\n") 16 | fmt.Printf(" remove remove 'key' (and its value) from local secrets file\n") 17 | fmt.Printf(" push publish secrets in local secrets file to\n") 18 | fmt.Printf(" 'path' in vault generic secrets backend\n\n") 19 | 20 | fmt.Printf("Flags:\n") 21 | fmt.Printf(" -s string secrets file\n") 22 | fmt.Printf(" -t string transit key\n\n") 23 | 24 | fmt.Printf("Examples:\n") 25 | fmt.Printf(" springboard set -s secrets.yml -t my-key user_name supersecret\n") 26 | fmt.Printf(" springboard get -s secrets.yml -t my-key user_name\n") 27 | fmt.Printf(" springboard remove -s secrets.yml -t my-key user_name\n") 28 | fmt.Printf(" springboard push -s secrets.yml -t my-key secret/my-space\n\n") 29 | 30 | fmt.Printf("github.com/benschw/springboard\n") 31 | } 32 | 33 | func main() { 34 | // flags 35 | f := flag.NewFlagSet("", flag.ExitOnError) 36 | f.Usage = usage 37 | 38 | secretsFile := f.String("s", "", "secrets file path") 39 | transitKey := f.String("t", "", "transit key") 40 | 41 | if len(os.Args) < 2 { 42 | f.Usage() 43 | os.Exit(2) 44 | } 45 | 46 | f.Parse(os.Args[2:]) 47 | 48 | if *secretsFile == "" || *transitKey == "" { 49 | f.Usage() 50 | os.Exit(2) 51 | } 52 | 53 | args := f.Args() 54 | 55 | // App 56 | app, err := NewApp(*secretsFile, *transitKey) 57 | if err != nil { 58 | f.Usage() 59 | os.Exit(1) 60 | } 61 | 62 | // subcommands 63 | switch os.Args[1] { 64 | case "get": 65 | if len(args) != 1 { 66 | f.Usage() 67 | os.Exit(2) 68 | } 69 | if err := app.get(args[0]); err != nil { 70 | fmt.Println(err) 71 | os.Exit(1) 72 | } 73 | case "set": 74 | if len(args) != 2 { 75 | f.Usage() 76 | os.Exit(2) 77 | } 78 | if err := app.set(args[0], args[1]); err != nil { 79 | fmt.Println(err) 80 | os.Exit(1) 81 | } 82 | case "remove": 83 | if len(args) != 1 { 84 | f.Usage() 85 | os.Exit(2) 86 | } 87 | if err := app.remove(args[0]); err != nil { 88 | fmt.Println(err) 89 | os.Exit(1) 90 | } 91 | case "push": 92 | if len(args) != 1 { 93 | f.Usage() 94 | os.Exit(2) 95 | } 96 | if err := app.push(args[0]); err != nil { 97 | fmt.Println(err) 98 | os.Exit(1) 99 | } 100 | case "help": 101 | f.Usage() 102 | os.Exit(0) 103 | default: 104 | fmt.Printf("%q is not valid command.\n", os.Args[1]) 105 | f.Usage() 106 | os.Exit(2) 107 | } 108 | 109 | os.Exit(0) 110 | } 111 | -------------------------------------------------------------------------------- /publisher/publisher.go: -------------------------------------------------------------------------------- 1 | package publisher 2 | 3 | import ( 4 | vaultapi "github.com/hashicorp/vault/api" 5 | ) 6 | 7 | type secretsStore interface { 8 | Keys() []string 9 | Get(string) (string, error) 10 | } 11 | 12 | func New(vault *vaultapi.Logical, path string) *Publisher { 13 | return &Publisher{ 14 | vault: vault, 15 | path: path, 16 | } 17 | } 18 | 19 | type Publisher struct { 20 | vault *vaultapi.Logical 21 | path string 22 | } 23 | 24 | func (p *Publisher) Push(secrets secretsStore) error { 25 | 26 | dec := make(map[string]interface{}) 27 | 28 | for _, key := range secrets.Keys() { 29 | val, err := secrets.Get(key) 30 | if err != nil { 31 | return err 32 | } 33 | dec[key] = val 34 | } 35 | 36 | _, err := p.vault.Write(p.path, dec) 37 | 38 | return err 39 | } 40 | -------------------------------------------------------------------------------- /publisher/publisher_test.go: -------------------------------------------------------------------------------- 1 | package publisher 2 | 3 | import ( 4 | "testing" 5 | vaultapi "github.com/hashicorp/vault/api" 6 | ) 7 | 8 | type secretsStoreStub struct { 9 | data map[string]string 10 | } 11 | func (s *secretsStoreStub) Keys() []string { 12 | keys := make([]string, 0, len(s.data)) 13 | for k := range s.data { 14 | keys = append(keys, k) 15 | } 16 | 17 | return keys 18 | } 19 | func (s *secretsStoreStub) Get(key string) (string, error) { 20 | return s.data[key], nil 21 | } 22 | 23 | func TestEncryption(t *testing.T) { 24 | 25 | 26 | cfg := vaultapi.DefaultConfig() 27 | client, err := vaultapi.NewClient(cfg) 28 | if err != nil { 29 | panic(err) 30 | } 31 | v := client.Logical() 32 | 33 | s := &secretsStoreStub{ 34 | data: map[string]string{ 35 | "foo": "bar", 36 | "baz": "boo", 37 | }, 38 | } 39 | 40 | p := New(v, "secret/test") 41 | 42 | err = p.Push(s) 43 | if err != nil { 44 | t.Error(err) 45 | } 46 | result, _ := v.Read(p.path) 47 | 48 | if result.Data["foo"] != "bar" { 49 | t.Error("foo should be set to bar", result.Data) 50 | } 51 | if result.Data["baz"] != "boo" { 52 | t.Error("baz should be set to boo", result.Data) 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /secrets/secrets.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "errors" 5 | "io/ioutil" 6 | "os" 7 | 8 | "gopkg.in/yaml.v2" 9 | ) 10 | 11 | type crypt interface { 12 | Encrypt(string) (string, error) 13 | Decrypt(string) (string, error) 14 | } 15 | 16 | func New(path string, crypt crypt) (*Secrets, error) { 17 | if _, err := os.Stat(path); err != nil { 18 | ioutil.WriteFile(path, []byte{}, 0644) 19 | } 20 | 21 | ymlData, err := ioutil.ReadFile(path) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | data := make([]SecretsEntry, 0) 27 | 28 | if err = yaml.Unmarshal([]byte(ymlData), &data); err != nil { 29 | return nil, err 30 | } 31 | 32 | return &Secrets{path: path, crypt: crypt, data: data}, nil 33 | } 34 | 35 | type Secrets struct { 36 | path string 37 | crypt crypt 38 | data []SecretsEntry 39 | } 40 | 41 | func (s *Secrets) Keys() []string { 42 | keys := make([]string, len(s.data)) 43 | for i := 0; i < len(s.data); i++ { 44 | keys[i] = s.data[i].Key 45 | } 46 | return keys 47 | } 48 | 49 | func (s *Secrets) Set(key string, value string) error { 50 | val, err := s.crypt.Encrypt(value) 51 | if err != nil { 52 | return err 53 | } 54 | for i := 0; i < len(s.data); i++ { 55 | if s.data[i].Key == key { 56 | s.data[i].Value = val 57 | return nil 58 | } 59 | } 60 | s.data = append(s.data, SecretsEntry{Key: key, Value: val}) 61 | return nil 62 | } 63 | 64 | func (s *Secrets) Remove(key string) error { 65 | for i := 0; i < len(s.data); i++ { 66 | if s.data[i].Key == key { 67 | //remove the element 68 | s.data = append(s.data[:i], s.data[i+1:]...) 69 | return nil 70 | } 71 | } 72 | return errors.New("key not found") 73 | } 74 | 75 | func (s *Secrets) Get(key string) (string, error) { 76 | for i := 0; i < len(s.data); i++ { 77 | if s.data[i].Key == key { 78 | return s.crypt.Decrypt(s.data[i].Value) 79 | } 80 | } 81 | return "", errors.New("key not found") 82 | } 83 | func (s *Secrets) Save() error { 84 | b, err := yaml.Marshal(s.data) 85 | if err != nil { 86 | return err 87 | } 88 | return ioutil.WriteFile(s.path, b, 0644) 89 | } 90 | 91 | type SecretsEntry struct { 92 | Key string 93 | Value string 94 | } 95 | -------------------------------------------------------------------------------- /secrets/secrets_test.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "testing" 7 | ) 8 | 9 | type stubCrypt struct{} 10 | 11 | func (s stubCrypt) Encrypt(val string) (string, error) { 12 | return val, nil 13 | } 14 | func (s stubCrypt) Decrypt(val string) (string, error) { 15 | return val, nil 16 | } 17 | 18 | func TestSecretAccess(t *testing.T) { 19 | file, _ := ioutil.TempFile(os.TempDir(), "vault") 20 | defer os.Remove(file.Name()) 21 | 22 | s, err := New(file.Name(), stubCrypt{}) 23 | 24 | if err != nil { 25 | t.Error("problem loading config: ", err) 26 | } 27 | 28 | s.Set("foo", "bar") 29 | 30 | val, err := s.Get("foo") 31 | if err != nil { 32 | t.Error("problem retreiving key: ", err) 33 | } 34 | 35 | if val != "bar" { 36 | t.Error("should equal bar", val) 37 | } 38 | 39 | } 40 | 41 | func TestSecretStorage(t *testing.T) { 42 | file, _ := ioutil.TempFile(os.TempDir(), "vault") 43 | defer os.Remove(file.Name()) 44 | 45 | s, _ := New(file.Name(), &stubCrypt{}) 46 | 47 | s.Set("foo", "bar") 48 | 49 | if err := s.Save(); err != nil { 50 | t.Error("problem saving", err) 51 | } 52 | 53 | s2, _ := New(file.Name(), &stubCrypt{}) 54 | 55 | val, _ := s2.Get("foo") 56 | 57 | if val != "bar" { 58 | t.Error("should equal bar", val) 59 | } 60 | } 61 | 62 | func TestSecretRemove(t *testing.T) { 63 | file, _ := ioutil.TempFile(os.TempDir(), "vault") 64 | defer os.Remove(file.Name()) 65 | 66 | s, _ := New(file.Name(), &stubCrypt{}) 67 | 68 | s.Set("foo", "bar") 69 | if err := s.Save(); err != nil { 70 | t.Error("problem saving", err) 71 | } 72 | 73 | s.Remove("foo") 74 | if err := s.Save(); err != nil { 75 | t.Error("problem saving", err) 76 | } 77 | 78 | s2, _ := New(file.Name(), &stubCrypt{}) 79 | 80 | val, err := s2.Get("foo") 81 | 82 | if err == nil { 83 | t.Error("should have been removed", val) 84 | } 85 | } 86 | 87 | func TestKeys(t *testing.T) { 88 | file, _ := ioutil.TempFile(os.TempDir(), "vault") 89 | defer os.Remove(file.Name()) 90 | 91 | s, _ := New(file.Name(), &stubCrypt{}) 92 | 93 | s.Set("foo", "bar") 94 | s.Set("baz", "boo") 95 | 96 | val := s.Keys() 97 | 98 | if val[0] != "foo" && val[1] != "foo" { 99 | t.Error("should have foo key", val) 100 | } 101 | if val[0] != "baz" && val[1] != "baz" { 102 | t.Error("should have baz key", val) 103 | } 104 | } 105 | func TestNoFile(t *testing.T) { 106 | s, err := New("./dne", &stubCrypt{}) 107 | if err != nil { 108 | t.Error("config doesn't exist, should have created it", err) 109 | } 110 | defer os.Remove("./dne") 111 | 112 | s.Set("foo", "bar") 113 | s.Save() 114 | 115 | s2, _ := New("./dne", &stubCrypt{}) 116 | 117 | val, _ := s2.Get("foo") 118 | 119 | if val != "bar" { 120 | t.Error("should equal bar", val) 121 | } 122 | } 123 | 124 | func TestNoKey(t *testing.T) { 125 | file, _ := ioutil.TempFile(os.TempDir(), "vault") 126 | defer os.Remove(file.Name()) 127 | 128 | s, _ := New(file.Name(), &stubCrypt{}) 129 | 130 | _, err := s.Get("foo") 131 | if err == nil { 132 | t.Error("key doesn't exist, should have errored") 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /vendor/github.com/fatih/structs/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | -------------------------------------------------------------------------------- /vendor/github.com/fatih/structs/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - 1.7.x 4 | - tip 5 | sudo: false 6 | before_install: 7 | - go get github.com/axw/gocov/gocov 8 | - go get github.com/mattn/goveralls 9 | - if ! go get github.com/golang/tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi 10 | script: 11 | - $HOME/gopath/bin/goveralls -service=travis-ci 12 | -------------------------------------------------------------------------------- /vendor/github.com/fatih/structs/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Fatih Arslan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /vendor/github.com/fatih/structs/field.go: -------------------------------------------------------------------------------- 1 | package structs 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "reflect" 7 | ) 8 | 9 | var ( 10 | errNotExported = errors.New("field is not exported") 11 | errNotSettable = errors.New("field is not settable") 12 | ) 13 | 14 | // Field represents a single struct field that encapsulates high level 15 | // functions around the field. 16 | type Field struct { 17 | value reflect.Value 18 | field reflect.StructField 19 | defaultTag string 20 | } 21 | 22 | // Tag returns the value associated with key in the tag string. If there is no 23 | // such key in the tag, Tag returns the empty string. 24 | func (f *Field) Tag(key string) string { 25 | return f.field.Tag.Get(key) 26 | } 27 | 28 | // Value returns the underlying value of the field. It panics if the field 29 | // is not exported. 30 | func (f *Field) Value() interface{} { 31 | return f.value.Interface() 32 | } 33 | 34 | // IsEmbedded returns true if the given field is an anonymous field (embedded) 35 | func (f *Field) IsEmbedded() bool { 36 | return f.field.Anonymous 37 | } 38 | 39 | // IsExported returns true if the given field is exported. 40 | func (f *Field) IsExported() bool { 41 | return f.field.PkgPath == "" 42 | } 43 | 44 | // IsZero returns true if the given field is not initialized (has a zero value). 45 | // It panics if the field is not exported. 46 | func (f *Field) IsZero() bool { 47 | zero := reflect.Zero(f.value.Type()).Interface() 48 | current := f.Value() 49 | 50 | return reflect.DeepEqual(current, zero) 51 | } 52 | 53 | // Name returns the name of the given field 54 | func (f *Field) Name() string { 55 | return f.field.Name 56 | } 57 | 58 | // Kind returns the fields kind, such as "string", "map", "bool", etc .. 59 | func (f *Field) Kind() reflect.Kind { 60 | return f.value.Kind() 61 | } 62 | 63 | // Set sets the field to given value v. It returns an error if the field is not 64 | // settable (not addressable or not exported) or if the given value's type 65 | // doesn't match the fields type. 66 | func (f *Field) Set(val interface{}) error { 67 | // we can't set unexported fields, so be sure this field is exported 68 | if !f.IsExported() { 69 | return errNotExported 70 | } 71 | 72 | // do we get here? not sure... 73 | if !f.value.CanSet() { 74 | return errNotSettable 75 | } 76 | 77 | given := reflect.ValueOf(val) 78 | 79 | if f.value.Kind() != given.Kind() { 80 | return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind()) 81 | } 82 | 83 | f.value.Set(given) 84 | return nil 85 | } 86 | 87 | // Zero sets the field to its zero value. It returns an error if the field is not 88 | // settable (not addressable or not exported). 89 | func (f *Field) Zero() error { 90 | zero := reflect.Zero(f.value.Type()).Interface() 91 | return f.Set(zero) 92 | } 93 | 94 | // Fields returns a slice of Fields. This is particular handy to get the fields 95 | // of a nested struct . A struct tag with the content of "-" ignores the 96 | // checking of that particular field. Example: 97 | // 98 | // // Field is ignored by this package. 99 | // Field *http.Request `structs:"-"` 100 | // 101 | // It panics if field is not exported or if field's kind is not struct 102 | func (f *Field) Fields() []*Field { 103 | return getFields(f.value, f.defaultTag) 104 | } 105 | 106 | // Field returns the field from a nested struct. It panics if the nested struct 107 | // is not exported or if the field was not found. 108 | func (f *Field) Field(name string) *Field { 109 | field, ok := f.FieldOk(name) 110 | if !ok { 111 | panic("field not found") 112 | } 113 | 114 | return field 115 | } 116 | 117 | // FieldOk returns the field from a nested struct. The boolean returns whether 118 | // the field was found (true) or not (false). 119 | func (f *Field) FieldOk(name string) (*Field, bool) { 120 | value := &f.value 121 | // value must be settable so we need to make sure it holds the address of the 122 | // variable and not a copy, so we can pass the pointer to strctVal instead of a 123 | // copy (which is not assigned to any variable, hence not settable). 124 | // see "https://blog.golang.org/laws-of-reflection#TOC_8." 125 | if f.value.Kind() != reflect.Ptr { 126 | a := f.value.Addr() 127 | value = &a 128 | } 129 | v := strctVal(value.Interface()) 130 | t := v.Type() 131 | 132 | field, ok := t.FieldByName(name) 133 | if !ok { 134 | return nil, false 135 | } 136 | 137 | return &Field{ 138 | field: field, 139 | value: v.FieldByName(name), 140 | }, true 141 | } 142 | -------------------------------------------------------------------------------- /vendor/github.com/fatih/structs/tags.go: -------------------------------------------------------------------------------- 1 | package structs 2 | 3 | import "strings" 4 | 5 | // tagOptions contains a slice of tag options 6 | type tagOptions []string 7 | 8 | // Has returns true if the given optiton is available in tagOptions 9 | func (t tagOptions) Has(opt string) bool { 10 | for _, tagOpt := range t { 11 | if tagOpt == opt { 12 | return true 13 | } 14 | } 15 | 16 | return false 17 | } 18 | 19 | // parseTag splits a struct field's tag into its name and a list of options 20 | // which comes after a name. A tag is in the form of: "name,option1,option2". 21 | // The name can be neglectected. 22 | func parseTag(tag string) (string, tagOptions) { 23 | // tag is one of followings: 24 | // "" 25 | // "name" 26 | // "name,opt" 27 | // "name,opt,opt2" 28 | // ",opt" 29 | 30 | res := strings.Split(tag, ",") 31 | return res[0], res[1:] 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/errwrap/README.md: -------------------------------------------------------------------------------- 1 | # errwrap 2 | 3 | `errwrap` is a package for Go that formalizes the pattern of wrapping errors 4 | and checking if an error contains another error. 5 | 6 | There is a common pattern in Go of taking a returned `error` value and 7 | then wrapping it (such as with `fmt.Errorf`) before returning it. The problem 8 | with this pattern is that you completely lose the original `error` structure. 9 | 10 | Arguably the _correct_ approach is that you should make a custom structure 11 | implementing the `error` interface, and have the original error as a field 12 | on that structure, such [as this example](http://golang.org/pkg/os/#PathError). 13 | This is a good approach, but you have to know the entire chain of possible 14 | rewrapping that happens, when you might just care about one. 15 | 16 | `errwrap` formalizes this pattern (it doesn't matter what approach you use 17 | above) by giving a single interface for wrapping errors, checking if a specific 18 | error is wrapped, and extracting that error. 19 | 20 | ## Installation and Docs 21 | 22 | Install using `go get github.com/hashicorp/errwrap`. 23 | 24 | Full documentation is available at 25 | http://godoc.org/github.com/hashicorp/errwrap 26 | 27 | ## Usage 28 | 29 | #### Basic Usage 30 | 31 | Below is a very basic example of its usage: 32 | 33 | ```go 34 | // A function that always returns an error, but wraps it, like a real 35 | // function might. 36 | func tryOpen() error { 37 | _, err := os.Open("/i/dont/exist") 38 | if err != nil { 39 | return errwrap.Wrapf("Doesn't exist: {{err}}", err) 40 | } 41 | 42 | return nil 43 | } 44 | 45 | func main() { 46 | err := tryOpen() 47 | 48 | // We can use the Contains helpers to check if an error contains 49 | // another error. It is safe to do this with a nil error, or with 50 | // an error that doesn't even use the errwrap package. 51 | if errwrap.Contains(err, ErrNotExist) { 52 | // Do something 53 | } 54 | if errwrap.ContainsType(err, new(os.PathError)) { 55 | // Do something 56 | } 57 | 58 | // Or we can use the associated `Get` functions to just extract 59 | // a specific error. This would return nil if that specific error doesn't 60 | // exist. 61 | perr := errwrap.GetType(err, new(os.PathError)) 62 | } 63 | ``` 64 | 65 | #### Custom Types 66 | 67 | If you're already making custom types that properly wrap errors, then 68 | you can get all the functionality of `errwraps.Contains` and such by 69 | implementing the `Wrapper` interface with just one function. Example: 70 | 71 | ```go 72 | type AppError { 73 | Code ErrorCode 74 | Err error 75 | } 76 | 77 | func (e *AppError) WrappedErrors() []error { 78 | return []error{e.Err} 79 | } 80 | ``` 81 | 82 | Now this works: 83 | 84 | ```go 85 | err := &AppError{Err: fmt.Errorf("an error")} 86 | if errwrap.ContainsType(err, fmt.Errorf("")) { 87 | // This will work! 88 | } 89 | ``` 90 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-cleanhttp/README.md: -------------------------------------------------------------------------------- 1 | # cleanhttp 2 | 3 | Functions for accessing "clean" Go http.Client values 4 | 5 | ------------- 6 | 7 | The Go standard library contains a default `http.Client` called 8 | `http.DefaultClient`. It is a common idiom in Go code to start with 9 | `http.DefaultClient` and tweak it as necessary, and in fact, this is 10 | encouraged; from the `http` package documentation: 11 | 12 | > The Client's Transport typically has internal state (cached TCP connections), 13 | so Clients should be reused instead of created as needed. Clients are safe for 14 | concurrent use by multiple goroutines. 15 | 16 | Unfortunately, this is a shared value, and it is not uncommon for libraries to 17 | assume that they are free to modify it at will. With enough dependencies, it 18 | can be very easy to encounter strange problems and race conditions due to 19 | manipulation of this shared value across libraries and goroutines (clients are 20 | safe for concurrent use, but writing values to the client struct itself is not 21 | protected). 22 | 23 | Making things worse is the fact that a bare `http.Client` will use a default 24 | `http.Transport` called `http.DefaultTransport`, which is another global value 25 | that behaves the same way. So it is not simply enough to replace 26 | `http.DefaultClient` with `&http.Client{}`. 27 | 28 | This repository provides some simple functions to get a "clean" `http.Client` 29 | -- one that uses the same default values as the Go standard library, but 30 | returns a client that does not share any state with other clients. 31 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go: -------------------------------------------------------------------------------- 1 | package cleanhttp 2 | 3 | import ( 4 | "net" 5 | "net/http" 6 | "runtime" 7 | "time" 8 | ) 9 | 10 | // DefaultTransport returns a new http.Transport with similar default values to 11 | // http.DefaultTransport, but with idle connections and keepalives disabled. 12 | func DefaultTransport() *http.Transport { 13 | transport := DefaultPooledTransport() 14 | transport.DisableKeepAlives = true 15 | transport.MaxIdleConnsPerHost = -1 16 | return transport 17 | } 18 | 19 | // DefaultPooledTransport returns a new http.Transport with similar default 20 | // values to http.DefaultTransport. Do not use this for transient transports as 21 | // it can leak file descriptors over time. Only use this for transports that 22 | // will be re-used for the same host(s). 23 | func DefaultPooledTransport() *http.Transport { 24 | transport := &http.Transport{ 25 | Proxy: http.ProxyFromEnvironment, 26 | DialContext: (&net.Dialer{ 27 | Timeout: 30 * time.Second, 28 | KeepAlive: 30 * time.Second, 29 | }).DialContext, 30 | MaxIdleConns: 100, 31 | IdleConnTimeout: 90 * time.Second, 32 | TLSHandshakeTimeout: 10 * time.Second, 33 | ExpectContinueTimeout: 1 * time.Second, 34 | MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, 35 | } 36 | return transport 37 | } 38 | 39 | // DefaultClient returns a new http.Client with similar default values to 40 | // http.Client, but with a non-shared Transport, idle connections disabled, and 41 | // keepalives disabled. 42 | func DefaultClient() *http.Client { 43 | return &http.Client{ 44 | Transport: DefaultTransport(), 45 | } 46 | } 47 | 48 | // DefaultPooledClient returns a new http.Client with similar default values to 49 | // http.Client, but with a shared Transport. Do not use this function for 50 | // transient clients as it can leak file descriptors over time. Only use this 51 | // for clients that will be re-used for the same host(s). 52 | func DefaultPooledClient() *http.Client { 53 | return &http.Client{ 54 | Transport: DefaultPooledTransport(), 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-cleanhttp/doc.go: -------------------------------------------------------------------------------- 1 | // Package cleanhttp offers convenience utilities for acquiring "clean" 2 | // http.Transport and http.Client structs. 3 | // 4 | // Values set on http.DefaultClient and http.DefaultTransport affect all 5 | // callers. This can have detrimental effects, esepcially in TLS contexts, 6 | // where client or root certificates set to talk to multiple endpoints can end 7 | // up displacing each other, leading to hard-to-debug issues. This package 8 | // provides non-shared http.Client and http.Transport structs to ensure that 9 | // the configuration will not be overwritten by other parts of the application 10 | // or dependencies. 11 | // 12 | // The DefaultClient and DefaultTransport functions disable idle connections 13 | // and keepalives. Without ensuring that idle connections are closed before 14 | // garbage collection, short-term clients/transports can leak file descriptors, 15 | // eventually leading to "too many open files" errors. If you will be 16 | // connecting to the same hosts repeatedly from the same client, you can use 17 | // DefaultPooledClient to receive a client that has connection pooling 18 | // semantics similar to http.DefaultClient. 19 | // 20 | package cleanhttp 21 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: go 4 | 5 | go: 6 | - 1.6 7 | 8 | branches: 9 | only: 10 | - master 11 | 12 | script: make test testrace 13 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/Makefile: -------------------------------------------------------------------------------- 1 | TEST?=./... 2 | 3 | default: test 4 | 5 | # test runs the test suite and vets the code. 6 | test: generate 7 | @echo "==> Running tests..." 8 | @go list $(TEST) \ 9 | | grep -v "/vendor/" \ 10 | | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} 11 | 12 | # testrace runs the race checker 13 | testrace: generate 14 | @echo "==> Running tests (race)..." 15 | @go list $(TEST) \ 16 | | grep -v "/vendor/" \ 17 | | xargs -n1 go test -timeout=60s -race ${TESTARGS} 18 | 19 | # updatedeps installs all the dependencies needed to run and build. 20 | updatedeps: 21 | @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" 22 | 23 | # generate runs `go generate` to build the dynamically generated source files. 24 | generate: 25 | @echo "==> Generating..." 26 | @find . -type f -name '.DS_Store' -delete 27 | @go list ./... \ 28 | | grep -v "/vendor/" \ 29 | | xargs -n1 go generate 30 | 31 | .PHONY: default test testrace updatedeps generate 32 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/README.md: -------------------------------------------------------------------------------- 1 | # go-multierror 2 | 3 | [![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis] 4 | [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] 5 | 6 | [travis]: https://travis-ci.org/hashicorp/go-multierror 7 | [godocs]: https://godoc.org/github.com/hashicorp/go-multierror 8 | 9 | `go-multierror` is a package for Go that provides a mechanism for 10 | representing a list of `error` values as a single `error`. 11 | 12 | This allows a function in Go to return an `error` that might actually 13 | be a list of errors. If the caller knows this, they can unwrap the 14 | list and access the errors. If the caller doesn't know, the error 15 | formats to a nice human-readable format. 16 | 17 | `go-multierror` implements the 18 | [errwrap](https://github.com/hashicorp/errwrap) interface so that it can 19 | be used with that library, as well. 20 | 21 | ## Installation and Docs 22 | 23 | Install using `go get github.com/hashicorp/go-multierror`. 24 | 25 | Full documentation is available at 26 | http://godoc.org/github.com/hashicorp/go-multierror 27 | 28 | ## Usage 29 | 30 | go-multierror is easy to use and purposely built to be unobtrusive in 31 | existing Go applications/libraries that may not be aware of it. 32 | 33 | **Building a list of errors** 34 | 35 | The `Append` function is used to create a list of errors. This function 36 | behaves a lot like the Go built-in `append` function: it doesn't matter 37 | if the first argument is nil, a `multierror.Error`, or any other `error`, 38 | the function behaves as you would expect. 39 | 40 | ```go 41 | var result error 42 | 43 | if err := step1(); err != nil { 44 | result = multierror.Append(result, err) 45 | } 46 | if err := step2(); err != nil { 47 | result = multierror.Append(result, err) 48 | } 49 | 50 | return result 51 | ``` 52 | 53 | **Customizing the formatting of the errors** 54 | 55 | By specifying a custom `ErrorFormat`, you can customize the format 56 | of the `Error() string` function: 57 | 58 | ```go 59 | var result *multierror.Error 60 | 61 | // ... accumulate errors here, maybe using Append 62 | 63 | if result != nil { 64 | result.ErrorFormat = func([]error) string { 65 | return "errors!" 66 | } 67 | } 68 | ``` 69 | 70 | **Accessing the list of errors** 71 | 72 | `multierror.Error` implements `error` so if the caller doesn't know about 73 | multierror, it will work just fine. But if you're aware a multierror might 74 | be returned, you can use type switches to access the list of errors: 75 | 76 | ```go 77 | if err := something(); err != nil { 78 | if merr, ok := err.(*multierror.Error); ok { 79 | // Use merr.Errors 80 | } 81 | } 82 | ``` 83 | 84 | **Returning a multierror only if there are errors** 85 | 86 | If you build a `multierror.Error`, you can use the `ErrorOrNil` function 87 | to return an `error` implementation only if there are errors to return: 88 | 89 | ```go 90 | var result *multierror.Error 91 | 92 | // ... accumulate errors here 93 | 94 | // Return the `error` only if errors were added to the multierror, otherwise 95 | // return nil since there are no errors. 96 | return result.ErrorOrNil() 97 | ``` 98 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/append.go: -------------------------------------------------------------------------------- 1 | package multierror 2 | 3 | // Append is a helper function that will append more errors 4 | // onto an Error in order to create a larger multi-error. 5 | // 6 | // If err is not a multierror.Error, then it will be turned into 7 | // one. If any of the errs are multierr.Error, they will be flattened 8 | // one level into err. 9 | func Append(err error, errs ...error) *Error { 10 | switch err := err.(type) { 11 | case *Error: 12 | // Typed nils can reach here, so initialize if we are nil 13 | if err == nil { 14 | err = new(Error) 15 | } 16 | 17 | // Go through each error and flatten 18 | for _, e := range errs { 19 | switch e := e.(type) { 20 | case *Error: 21 | if e != nil { 22 | err.Errors = append(err.Errors, e.Errors...) 23 | } 24 | default: 25 | if e != nil { 26 | err.Errors = append(err.Errors, e) 27 | } 28 | } 29 | } 30 | 31 | return err 32 | default: 33 | newErrs := make([]error, 0, len(errs)+1) 34 | if err != nil { 35 | newErrs = append(newErrs, err) 36 | } 37 | newErrs = append(newErrs, errs...) 38 | 39 | return Append(&Error{}, newErrs...) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/flatten.go: -------------------------------------------------------------------------------- 1 | package multierror 2 | 3 | // Flatten flattens the given error, merging any *Errors together into 4 | // a single *Error. 5 | func Flatten(err error) error { 6 | // If it isn't an *Error, just return the error as-is 7 | if _, ok := err.(*Error); !ok { 8 | return err 9 | } 10 | 11 | // Otherwise, make the result and flatten away! 12 | flatErr := new(Error) 13 | flatten(err, flatErr) 14 | return flatErr 15 | } 16 | 17 | func flatten(err error, flatErr *Error) { 18 | switch err := err.(type) { 19 | case *Error: 20 | for _, e := range err.Errors { 21 | flatten(e, flatErr) 22 | } 23 | default: 24 | flatErr.Errors = append(flatErr.Errors, err) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/format.go: -------------------------------------------------------------------------------- 1 | package multierror 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | // ErrorFormatFunc is a function callback that is called by Error to 9 | // turn the list of errors into a string. 10 | type ErrorFormatFunc func([]error) string 11 | 12 | // ListFormatFunc is a basic formatter that outputs the number of errors 13 | // that occurred along with a bullet point list of the errors. 14 | func ListFormatFunc(es []error) string { 15 | if len(es) == 1 { 16 | return fmt.Sprintf("1 error occurred:\n\n* %s", es[0]) 17 | } 18 | 19 | points := make([]string, len(es)) 20 | for i, err := range es { 21 | points[i] = fmt.Sprintf("* %s", err) 22 | } 23 | 24 | return fmt.Sprintf( 25 | "%d errors occurred:\n\n%s", 26 | len(es), strings.Join(points, "\n")) 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/multierror.go: -------------------------------------------------------------------------------- 1 | package multierror 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Error is an error type to track multiple errors. This is used to 8 | // accumulate errors in cases and return them as a single "error". 9 | type Error struct { 10 | Errors []error 11 | ErrorFormat ErrorFormatFunc 12 | } 13 | 14 | func (e *Error) Error() string { 15 | fn := e.ErrorFormat 16 | if fn == nil { 17 | fn = ListFormatFunc 18 | } 19 | 20 | return fn(e.Errors) 21 | } 22 | 23 | // ErrorOrNil returns an error interface if this Error represents 24 | // a list of errors, or returns nil if the list of errors is empty. This 25 | // function is useful at the end of accumulation to make sure that the value 26 | // returned represents the existence of errors. 27 | func (e *Error) ErrorOrNil() error { 28 | if e == nil { 29 | return nil 30 | } 31 | if len(e.Errors) == 0 { 32 | return nil 33 | } 34 | 35 | return e 36 | } 37 | 38 | func (e *Error) GoString() string { 39 | return fmt.Sprintf("*%#v", *e) 40 | } 41 | 42 | // WrappedErrors returns the list of errors that this Error is wrapping. 43 | // It is an implementatin of the errwrap.Wrapper interface so that 44 | // multierror.Error can be used with that library. 45 | // 46 | // This method is not safe to be called concurrently and is no different 47 | // than accessing the Errors field directly. It is implementd only to 48 | // satisfy the errwrap.Wrapper interface. 49 | func (e *Error) WrappedErrors() []error { 50 | return e.Errors 51 | } 52 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-multierror/prefix.go: -------------------------------------------------------------------------------- 1 | package multierror 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/hashicorp/errwrap" 7 | ) 8 | 9 | // Prefix is a helper function that will prefix some text 10 | // to the given error. If the error is a multierror.Error, then 11 | // it will be prefixed to each wrapped error. 12 | // 13 | // This is useful to use when appending multiple multierrors 14 | // together in order to give better scoping. 15 | func Prefix(err error, prefix string) error { 16 | if err == nil { 17 | return nil 18 | } 19 | 20 | format := fmt.Sprintf("%s {{err}}", prefix) 21 | switch err := err.(type) { 22 | case *Error: 23 | // Typed nils can reach here, so initialize if we are nil 24 | if err == nil { 25 | err = new(Error) 26 | } 27 | 28 | // Wrap each of the errors 29 | for i, e := range err.Errors { 30 | err.Errors[i] = errwrap.Wrapf(format, e) 31 | } 32 | 33 | return err 34 | default: 35 | return errwrap.Wrapf(format, err) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: go 4 | 5 | go: 6 | - 1.6 7 | 8 | branches: 9 | only: 10 | - master 11 | 12 | script: make test 13 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/Makefile: -------------------------------------------------------------------------------- 1 | TEST?=./... 2 | 3 | test: 4 | go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 5 | go vet $(TEST) 6 | go test $(TEST) -race 7 | 8 | .PHONY: test 9 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/README.md: -------------------------------------------------------------------------------- 1 | # rootcerts 2 | 3 | Functions for loading root certificates for TLS connections. 4 | 5 | ----- 6 | 7 | Go's standard library `crypto/tls` provides a common mechanism for configuring 8 | TLS connections in `tls.Config`. The `RootCAs` field on this struct is a pool 9 | of certificates for the client to use as a trust store when verifying server 10 | certificates. 11 | 12 | This library contains utility functions for loading certificates destined for 13 | that field, as well as one other important thing: 14 | 15 | When the `RootCAs` field is `nil`, the standard library attempts to load the 16 | host's root CA set. This behavior is OS-specific, and the Darwin 17 | implementation contains [a bug that prevents trusted certificates from the 18 | System and Login keychains from being loaded][1]. This library contains 19 | Darwin-specific behavior that works around that bug. 20 | 21 | [1]: https://github.com/golang/go/issues/14514 22 | 23 | ## Example Usage 24 | 25 | Here's a snippet demonstrating how this library is meant to be used: 26 | 27 | ```go 28 | func httpClient() (*http.Client, error) 29 | tlsConfig := &tls.Config{} 30 | err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{ 31 | CAFile: os.Getenv("MYAPP_CAFILE"), 32 | CAPath: os.Getenv("MYAPP_CAPATH"), 33 | }) 34 | if err != nil { 35 | return nil, err 36 | } 37 | c := cleanhttp.DefaultClient() 38 | t := cleanhttp.DefaultTransport() 39 | t.TLSClientConfig = tlsConfig 40 | c.Transport = t 41 | return c, nil 42 | } 43 | ``` 44 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/doc.go: -------------------------------------------------------------------------------- 1 | // Package rootcerts contains functions to aid in loading CA certificates for 2 | // TLS connections. 3 | // 4 | // In addition, its default behavior on Darwin works around an open issue [1] 5 | // in Go's crypto/x509 that prevents certicates from being loaded from the 6 | // System or Login keychains. 7 | // 8 | // [1] https://github.com/golang/go/issues/14514 9 | package rootcerts 10 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/rootcerts.go: -------------------------------------------------------------------------------- 1 | package rootcerts 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "path/filepath" 10 | ) 11 | 12 | // Config determines where LoadCACerts will load certificates from. When both 13 | // CAFile and CAPath are blank, this library's functions will either load 14 | // system roots explicitly and return them, or set the CertPool to nil to allow 15 | // Go's standard library to load system certs. 16 | type Config struct { 17 | // CAFile is a path to a PEM-encoded certificate file or bundle. Takes 18 | // precedence over CAPath. 19 | CAFile string 20 | 21 | // CAPath is a path to a directory populated with PEM-encoded certificates. 22 | CAPath string 23 | } 24 | 25 | // ConfigureTLS sets up the RootCAs on the provided tls.Config based on the 26 | // Config specified. 27 | func ConfigureTLS(t *tls.Config, c *Config) error { 28 | if t == nil { 29 | return nil 30 | } 31 | pool, err := LoadCACerts(c) 32 | if err != nil { 33 | return err 34 | } 35 | t.RootCAs = pool 36 | return nil 37 | } 38 | 39 | // LoadCACerts loads a CertPool based on the Config specified. 40 | func LoadCACerts(c *Config) (*x509.CertPool, error) { 41 | if c == nil { 42 | c = &Config{} 43 | } 44 | if c.CAFile != "" { 45 | return LoadCAFile(c.CAFile) 46 | } 47 | if c.CAPath != "" { 48 | return LoadCAPath(c.CAPath) 49 | } 50 | 51 | return LoadSystemCAs() 52 | } 53 | 54 | // LoadCAFile loads a single PEM-encoded file from the path specified. 55 | func LoadCAFile(caFile string) (*x509.CertPool, error) { 56 | pool := x509.NewCertPool() 57 | 58 | pem, err := ioutil.ReadFile(caFile) 59 | if err != nil { 60 | return nil, fmt.Errorf("Error loading CA File: %s", err) 61 | } 62 | 63 | ok := pool.AppendCertsFromPEM(pem) 64 | if !ok { 65 | return nil, fmt.Errorf("Error loading CA File: Couldn't parse PEM in: %s", caFile) 66 | } 67 | 68 | return pool, nil 69 | } 70 | 71 | // LoadCAPath walks the provided path and loads all certificates encounted into 72 | // a pool. 73 | func LoadCAPath(caPath string) (*x509.CertPool, error) { 74 | pool := x509.NewCertPool() 75 | walkFn := func(path string, info os.FileInfo, err error) error { 76 | if err != nil { 77 | return err 78 | } 79 | 80 | if info.IsDir() { 81 | return nil 82 | } 83 | 84 | pem, err := ioutil.ReadFile(path) 85 | if err != nil { 86 | return fmt.Errorf("Error loading file from CAPath: %s", err) 87 | } 88 | 89 | ok := pool.AppendCertsFromPEM(pem) 90 | if !ok { 91 | return fmt.Errorf("Error loading CA Path: Couldn't parse PEM in: %s", path) 92 | } 93 | 94 | return nil 95 | } 96 | 97 | err := filepath.Walk(caPath, walkFn) 98 | if err != nil { 99 | return nil, err 100 | } 101 | 102 | return pool, nil 103 | } 104 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go: -------------------------------------------------------------------------------- 1 | // +build !darwin 2 | 3 | package rootcerts 4 | 5 | import "crypto/x509" 6 | 7 | // LoadSystemCAs does nothing on non-Darwin systems. We return nil so that 8 | // default behavior of standard TLS config libraries is triggered, which is to 9 | // load system certs. 10 | func LoadSystemCAs() (*x509.CertPool, error) { 11 | return nil, nil 12 | } 13 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go: -------------------------------------------------------------------------------- 1 | package rootcerts 2 | 3 | import ( 4 | "crypto/x509" 5 | "os/exec" 6 | "path" 7 | 8 | "github.com/mitchellh/go-homedir" 9 | ) 10 | 11 | // LoadSystemCAs has special behavior on Darwin systems to work around 12 | func LoadSystemCAs() (*x509.CertPool, error) { 13 | pool := x509.NewCertPool() 14 | 15 | for _, keychain := range certKeychains() { 16 | err := addCertsFromKeychain(pool, keychain) 17 | if err != nil { 18 | return nil, err 19 | } 20 | } 21 | 22 | return pool, nil 23 | } 24 | 25 | func addCertsFromKeychain(pool *x509.CertPool, keychain string) error { 26 | cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain) 27 | data, err := cmd.Output() 28 | if err != nil { 29 | return err 30 | } 31 | 32 | pool.AppendCertsFromPEM(data) 33 | 34 | return nil 35 | } 36 | 37 | func certKeychains() []string { 38 | keychains := []string{ 39 | "/System/Library/Keychains/SystemRootCertificates.keychain", 40 | "/Library/Keychains/System.keychain", 41 | } 42 | home, err := homedir.Dir() 43 | if err == nil { 44 | loginKeychain := path.Join(home, "Library", "Keychains", "login.keychain") 45 | keychains = append(keychains, loginKeychain) 46 | } 47 | return keychains 48 | } 49 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/.gitignore: -------------------------------------------------------------------------------- 1 | y.output 2 | 3 | # ignore intellij files 4 | .idea 5 | *.iml 6 | *.ipr 7 | *.iws 8 | 9 | *.test 10 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: go 4 | 5 | go: 6 | - 1.8 7 | 8 | branches: 9 | only: 10 | - master 11 | 12 | script: make test 13 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/Makefile: -------------------------------------------------------------------------------- 1 | TEST?=./... 2 | 3 | default: test 4 | 5 | fmt: generate 6 | go fmt ./... 7 | 8 | test: generate 9 | go get -t ./... 10 | go test $(TEST) $(TESTARGS) 11 | 12 | generate: 13 | go generate ./... 14 | 15 | updatedeps: 16 | go get -u golang.org/x/tools/cmd/stringer 17 | 18 | .PHONY: default generate test updatedeps 19 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/README.md: -------------------------------------------------------------------------------- 1 | # HCL 2 | 3 | [![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) 4 | 5 | HCL (HashiCorp Configuration Language) is a configuration language built 6 | by HashiCorp. The goal of HCL is to build a structured configuration language 7 | that is both human and machine friendly for use with command-line tools, but 8 | specifically targeted towards DevOps tools, servers, etc. 9 | 10 | HCL is also fully JSON compatible. That is, JSON can be used as completely 11 | valid input to a system expecting HCL. This helps makes systems 12 | interoperable with other systems. 13 | 14 | HCL is heavily inspired by 15 | [libucl](https://github.com/vstakhov/libucl), 16 | nginx configuration, and others similar. 17 | 18 | ## Why? 19 | 20 | A common question when viewing HCL is to ask the question: why not 21 | JSON, YAML, etc.? 22 | 23 | Prior to HCL, the tools we built at [HashiCorp](http://www.hashicorp.com) 24 | used a variety of configuration languages from full programming languages 25 | such as Ruby to complete data structure languages such as JSON. What we 26 | learned is that some people wanted human-friendly configuration languages 27 | and some people wanted machine-friendly languages. 28 | 29 | JSON fits a nice balance in this, but is fairly verbose and most 30 | importantly doesn't support comments. With YAML, we found that beginners 31 | had a really hard time determining what the actual structure was, and 32 | ended up guessing more often than not whether to use a hyphen, colon, etc. 33 | in order to represent some configuration key. 34 | 35 | Full programming languages such as Ruby enable complex behavior 36 | a configuration language shouldn't usually allow, and also forces 37 | people to learn some set of Ruby. 38 | 39 | Because of this, we decided to create our own configuration language 40 | that is JSON-compatible. Our configuration language (HCL) is designed 41 | to be written and modified by humans. The API for HCL allows JSON 42 | as an input so that it is also machine-friendly (machines can generate 43 | JSON instead of trying to generate HCL). 44 | 45 | Our goal with HCL is not to alienate other configuration languages. 46 | It is instead to provide HCL as a specialized language for our tools, 47 | and JSON as the interoperability layer. 48 | 49 | ## Syntax 50 | 51 | For a complete grammar, please see the parser itself. A high-level overview 52 | of the syntax and grammar is listed here. 53 | 54 | * Single line comments start with `#` or `//` 55 | 56 | * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments 57 | are not allowed. A multi-line comment (also known as a block comment) 58 | terminates at the first `*/` found. 59 | 60 | * Values are assigned with the syntax `key = value` (whitespace doesn't 61 | matter). The value can be any primitive: a string, number, boolean, 62 | object, or list. 63 | 64 | * Strings are double-quoted and can contain any UTF-8 characters. 65 | Example: `"Hello, World"` 66 | 67 | * Multi-line strings start with `<- 10 | echo %Path% 11 | 12 | go version 13 | 14 | go env 15 | 16 | go get -t ./... 17 | 18 | build_script: 19 | - cmd: go test -v ./... 20 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/hcl.go: -------------------------------------------------------------------------------- 1 | // Package hcl decodes HCL into usable Go structures. 2 | // 3 | // hcl input can come in either pure HCL format or JSON format. 4 | // It can be parsed into an AST, and then decoded into a structure, 5 | // or it can be decoded directly from a string into a structure. 6 | // 7 | // If you choose to parse HCL into a raw AST, the benefit is that you 8 | // can write custom visitor implementations to implement custom 9 | // semantic checks. By default, HCL does not perform any semantic 10 | // checks. 11 | package hcl 12 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/hcl/ast/walk.go: -------------------------------------------------------------------------------- 1 | package ast 2 | 3 | import "fmt" 4 | 5 | // WalkFunc describes a function to be called for each node during a Walk. The 6 | // returned node can be used to rewrite the AST. Walking stops the returned 7 | // bool is false. 8 | type WalkFunc func(Node) (Node, bool) 9 | 10 | // Walk traverses an AST in depth-first order: It starts by calling fn(node); 11 | // node must not be nil. If fn returns true, Walk invokes fn recursively for 12 | // each of the non-nil children of node, followed by a call of fn(nil). The 13 | // returned node of fn can be used to rewrite the passed node to fn. 14 | func Walk(node Node, fn WalkFunc) Node { 15 | rewritten, ok := fn(node) 16 | if !ok { 17 | return rewritten 18 | } 19 | 20 | switch n := node.(type) { 21 | case *File: 22 | n.Node = Walk(n.Node, fn) 23 | case *ObjectList: 24 | for i, item := range n.Items { 25 | n.Items[i] = Walk(item, fn).(*ObjectItem) 26 | } 27 | case *ObjectKey: 28 | // nothing to do 29 | case *ObjectItem: 30 | for i, k := range n.Keys { 31 | n.Keys[i] = Walk(k, fn).(*ObjectKey) 32 | } 33 | 34 | if n.Val != nil { 35 | n.Val = Walk(n.Val, fn) 36 | } 37 | case *LiteralType: 38 | // nothing to do 39 | case *ListType: 40 | for i, l := range n.List { 41 | n.List[i] = Walk(l, fn) 42 | } 43 | case *ObjectType: 44 | n.List = Walk(n.List, fn).(*ObjectList) 45 | default: 46 | // should we panic here? 47 | fmt.Printf("unknown type: %T\n", n) 48 | } 49 | 50 | fn(nil) 51 | return rewritten 52 | } 53 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/hcl/parser/error.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/hashicorp/hcl/hcl/token" 7 | ) 8 | 9 | // PosError is a parse error that contains a position. 10 | type PosError struct { 11 | Pos token.Pos 12 | Err error 13 | } 14 | 15 | func (e *PosError) Error() string { 16 | return fmt.Sprintf("At %s: %s", e.Pos, e.Err) 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/hcl/token/position.go: -------------------------------------------------------------------------------- 1 | package token 2 | 3 | import "fmt" 4 | 5 | // Pos describes an arbitrary source position 6 | // including the file, line, and column location. 7 | // A Position is valid if the line number is > 0. 8 | type Pos struct { 9 | Filename string // filename, if any 10 | Offset int // offset, starting at 0 11 | Line int // line number, starting at 1 12 | Column int // column number, starting at 1 (character count) 13 | } 14 | 15 | // IsValid returns true if the position is valid. 16 | func (p *Pos) IsValid() bool { return p.Line > 0 } 17 | 18 | // String returns a string in one of several forms: 19 | // 20 | // file:line:column valid position with file name 21 | // line:column valid position without file name 22 | // file invalid position with file name 23 | // - invalid position without file name 24 | func (p Pos) String() string { 25 | s := p.Filename 26 | if p.IsValid() { 27 | if s != "" { 28 | s += ":" 29 | } 30 | s += fmt.Sprintf("%d:%d", p.Line, p.Column) 31 | } 32 | if s == "" { 33 | s = "-" 34 | } 35 | return s 36 | } 37 | 38 | // Before reports whether the position p is before u. 39 | func (p Pos) Before(u Pos) bool { 40 | return u.Offset > p.Offset || u.Line > p.Line 41 | } 42 | 43 | // After reports whether the position p is after u. 44 | func (p Pos) After(u Pos) bool { 45 | return u.Offset < p.Offset || u.Line < p.Line 46 | } 47 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/json/parser/flatten.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import "github.com/hashicorp/hcl/hcl/ast" 4 | 5 | // flattenObjects takes an AST node, walks it, and flattens 6 | func flattenObjects(node ast.Node) { 7 | ast.Walk(node, func(n ast.Node) (ast.Node, bool) { 8 | // We only care about lists, because this is what we modify 9 | list, ok := n.(*ast.ObjectList) 10 | if !ok { 11 | return n, true 12 | } 13 | 14 | // Rebuild the item list 15 | items := make([]*ast.ObjectItem, 0, len(list.Items)) 16 | frontier := make([]*ast.ObjectItem, len(list.Items)) 17 | copy(frontier, list.Items) 18 | for len(frontier) > 0 { 19 | // Pop the current item 20 | n := len(frontier) 21 | item := frontier[n-1] 22 | frontier = frontier[:n-1] 23 | 24 | switch v := item.Val.(type) { 25 | case *ast.ObjectType: 26 | items, frontier = flattenObjectType(v, item, items, frontier) 27 | case *ast.ListType: 28 | items, frontier = flattenListType(v, item, items, frontier) 29 | default: 30 | items = append(items, item) 31 | } 32 | } 33 | 34 | // Reverse the list since the frontier model runs things backwards 35 | for i := len(items)/2 - 1; i >= 0; i-- { 36 | opp := len(items) - 1 - i 37 | items[i], items[opp] = items[opp], items[i] 38 | } 39 | 40 | // Done! Set the original items 41 | list.Items = items 42 | return n, true 43 | }) 44 | } 45 | 46 | func flattenListType( 47 | ot *ast.ListType, 48 | item *ast.ObjectItem, 49 | items []*ast.ObjectItem, 50 | frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { 51 | // If the list is empty, keep the original list 52 | if len(ot.List) == 0 { 53 | items = append(items, item) 54 | return items, frontier 55 | } 56 | 57 | // All the elements of this object must also be objects! 58 | for _, subitem := range ot.List { 59 | if _, ok := subitem.(*ast.ObjectType); !ok { 60 | items = append(items, item) 61 | return items, frontier 62 | } 63 | } 64 | 65 | // Great! We have a match go through all the items and flatten 66 | for _, elem := range ot.List { 67 | // Add it to the frontier so that we can recurse 68 | frontier = append(frontier, &ast.ObjectItem{ 69 | Keys: item.Keys, 70 | Assign: item.Assign, 71 | Val: elem, 72 | LeadComment: item.LeadComment, 73 | LineComment: item.LineComment, 74 | }) 75 | } 76 | 77 | return items, frontier 78 | } 79 | 80 | func flattenObjectType( 81 | ot *ast.ObjectType, 82 | item *ast.ObjectItem, 83 | items []*ast.ObjectItem, 84 | frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { 85 | // If the list has no items we do not have to flatten anything 86 | if ot.List.Items == nil { 87 | items = append(items, item) 88 | return items, frontier 89 | } 90 | 91 | // All the elements of this object must also be objects! 92 | for _, subitem := range ot.List.Items { 93 | if _, ok := subitem.Val.(*ast.ObjectType); !ok { 94 | items = append(items, item) 95 | return items, frontier 96 | } 97 | } 98 | 99 | // Great! We have a match go through all the items and flatten 100 | for _, subitem := range ot.List.Items { 101 | // Copy the new key 102 | keys := make([]*ast.ObjectKey, len(item.Keys)+len(subitem.Keys)) 103 | copy(keys, item.Keys) 104 | copy(keys[len(item.Keys):], subitem.Keys) 105 | 106 | // Add it to the frontier so that we can recurse 107 | frontier = append(frontier, &ast.ObjectItem{ 108 | Keys: keys, 109 | Assign: item.Assign, 110 | Val: subitem.Val, 111 | LeadComment: item.LeadComment, 112 | LineComment: item.LineComment, 113 | }) 114 | } 115 | 116 | return items, frontier 117 | } 118 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/json/token/position.go: -------------------------------------------------------------------------------- 1 | package token 2 | 3 | import "fmt" 4 | 5 | // Pos describes an arbitrary source position 6 | // including the file, line, and column location. 7 | // A Position is valid if the line number is > 0. 8 | type Pos struct { 9 | Filename string // filename, if any 10 | Offset int // offset, starting at 0 11 | Line int // line number, starting at 1 12 | Column int // column number, starting at 1 (character count) 13 | } 14 | 15 | // IsValid returns true if the position is valid. 16 | func (p *Pos) IsValid() bool { return p.Line > 0 } 17 | 18 | // String returns a string in one of several forms: 19 | // 20 | // file:line:column valid position with file name 21 | // line:column valid position without file name 22 | // file invalid position with file name 23 | // - invalid position without file name 24 | func (p Pos) String() string { 25 | s := p.Filename 26 | if p.IsValid() { 27 | if s != "" { 28 | s += ":" 29 | } 30 | s += fmt.Sprintf("%d:%d", p.Line, p.Column) 31 | } 32 | if s == "" { 33 | s = "-" 34 | } 35 | return s 36 | } 37 | 38 | // Before reports whether the position p is before u. 39 | func (p Pos) Before(u Pos) bool { 40 | return u.Offset > p.Offset || u.Line > p.Line 41 | } 42 | 43 | // After reports whether the position p is after u. 44 | func (p Pos) After(u Pos) bool { 45 | return u.Offset < p.Offset || u.Line < p.Line 46 | } 47 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/json/token/token.go: -------------------------------------------------------------------------------- 1 | package token 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | 7 | hcltoken "github.com/hashicorp/hcl/hcl/token" 8 | ) 9 | 10 | // Token defines a single HCL token which can be obtained via the Scanner 11 | type Token struct { 12 | Type Type 13 | Pos Pos 14 | Text string 15 | } 16 | 17 | // Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) 18 | type Type int 19 | 20 | const ( 21 | // Special tokens 22 | ILLEGAL Type = iota 23 | EOF 24 | 25 | identifier_beg 26 | literal_beg 27 | NUMBER // 12345 28 | FLOAT // 123.45 29 | BOOL // true,false 30 | STRING // "abc" 31 | NULL // null 32 | literal_end 33 | identifier_end 34 | 35 | operator_beg 36 | LBRACK // [ 37 | LBRACE // { 38 | COMMA // , 39 | PERIOD // . 40 | COLON // : 41 | 42 | RBRACK // ] 43 | RBRACE // } 44 | 45 | operator_end 46 | ) 47 | 48 | var tokens = [...]string{ 49 | ILLEGAL: "ILLEGAL", 50 | 51 | EOF: "EOF", 52 | 53 | NUMBER: "NUMBER", 54 | FLOAT: "FLOAT", 55 | BOOL: "BOOL", 56 | STRING: "STRING", 57 | NULL: "NULL", 58 | 59 | LBRACK: "LBRACK", 60 | LBRACE: "LBRACE", 61 | COMMA: "COMMA", 62 | PERIOD: "PERIOD", 63 | COLON: "COLON", 64 | 65 | RBRACK: "RBRACK", 66 | RBRACE: "RBRACE", 67 | } 68 | 69 | // String returns the string corresponding to the token tok. 70 | func (t Type) String() string { 71 | s := "" 72 | if 0 <= t && t < Type(len(tokens)) { 73 | s = tokens[t] 74 | } 75 | if s == "" { 76 | s = "token(" + strconv.Itoa(int(t)) + ")" 77 | } 78 | return s 79 | } 80 | 81 | // IsIdentifier returns true for tokens corresponding to identifiers and basic 82 | // type literals; it returns false otherwise. 83 | func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end } 84 | 85 | // IsLiteral returns true for tokens corresponding to basic type literals; it 86 | // returns false otherwise. 87 | func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end } 88 | 89 | // IsOperator returns true for tokens corresponding to operators and 90 | // delimiters; it returns false otherwise. 91 | func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end } 92 | 93 | // String returns the token's literal text. Note that this is only 94 | // applicable for certain token types, such as token.IDENT, 95 | // token.STRING, etc.. 96 | func (t Token) String() string { 97 | return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text) 98 | } 99 | 100 | // HCLToken converts this token to an HCL token. 101 | // 102 | // The token type must be a literal type or this will panic. 103 | func (t Token) HCLToken() hcltoken.Token { 104 | switch t.Type { 105 | case BOOL: 106 | return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text} 107 | case FLOAT: 108 | return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text} 109 | case NULL: 110 | return hcltoken.Token{Type: hcltoken.STRING, Text: ""} 111 | case NUMBER: 112 | return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text} 113 | case STRING: 114 | return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true} 115 | default: 116 | panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type)) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/lex.go: -------------------------------------------------------------------------------- 1 | package hcl 2 | 3 | import ( 4 | "unicode" 5 | "unicode/utf8" 6 | ) 7 | 8 | type lexModeValue byte 9 | 10 | const ( 11 | lexModeUnknown lexModeValue = iota 12 | lexModeHcl 13 | lexModeJson 14 | ) 15 | 16 | // lexMode returns whether we're going to be parsing in JSON 17 | // mode or HCL mode. 18 | func lexMode(v []byte) lexModeValue { 19 | var ( 20 | r rune 21 | w int 22 | offset int 23 | ) 24 | 25 | for { 26 | r, w = utf8.DecodeRune(v[offset:]) 27 | offset += w 28 | if unicode.IsSpace(r) { 29 | continue 30 | } 31 | if r == '{' { 32 | return lexModeJson 33 | } 34 | break 35 | } 36 | 37 | return lexModeHcl 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/hcl/parse.go: -------------------------------------------------------------------------------- 1 | package hcl 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/hashicorp/hcl/hcl/ast" 7 | hclParser "github.com/hashicorp/hcl/hcl/parser" 8 | jsonParser "github.com/hashicorp/hcl/json/parser" 9 | ) 10 | 11 | // ParseBytes accepts as input byte slice and returns ast tree. 12 | // 13 | // Input can be either JSON or HCL 14 | func ParseBytes(in []byte) (*ast.File, error) { 15 | return parse(in) 16 | } 17 | 18 | // ParseString accepts input as a string and returns ast tree. 19 | func ParseString(input string) (*ast.File, error) { 20 | return parse([]byte(input)) 21 | } 22 | 23 | func parse(in []byte) (*ast.File, error) { 24 | switch lexMode(in) { 25 | case lexModeHcl: 26 | return hclParser.Parse(in) 27 | case lexModeJson: 28 | return jsonParser.Parse(in) 29 | } 30 | 31 | return nil, fmt.Errorf("unknown config format") 32 | } 33 | 34 | // Parse parses the given input and returns the root object. 35 | // 36 | // The input format can be either HCL or JSON. 37 | func Parse(input string) (*ast.File, error) { 38 | return parse([]byte(input)) 39 | } 40 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/auth.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | // Auth is used to perform credential backend related operations. 4 | type Auth struct { 5 | c *Client 6 | } 7 | 8 | // Auth is used to return the client for credential-backend API calls. 9 | func (c *Client) Auth() *Auth { 10 | return &Auth{c: c} 11 | } 12 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/help.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Help reads the help information for the given path. 8 | func (c *Client) Help(path string) (*Help, error) { 9 | r := c.NewRequest("GET", fmt.Sprintf("/v1/%s", path)) 10 | r.Params.Add("help", "1") 11 | resp, err := c.RawRequest(r) 12 | if err != nil { 13 | return nil, err 14 | } 15 | defer resp.Body.Close() 16 | 17 | var result Help 18 | err = resp.DecodeJSON(&result) 19 | return &result, err 20 | } 21 | 22 | type Help struct { 23 | Help string `json:"help"` 24 | SeeAlso []string `json:"see_also"` 25 | } 26 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/request.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "io" 7 | "net/http" 8 | "net/url" 9 | ) 10 | 11 | // Request is a raw request configuration structure used to initiate 12 | // API requests to the Vault server. 13 | type Request struct { 14 | Method string 15 | URL *url.URL 16 | Params url.Values 17 | ClientToken string 18 | WrapTTL string 19 | Obj interface{} 20 | Body io.Reader 21 | BodySize int64 22 | } 23 | 24 | // SetJSONBody is used to set a request body that is a JSON-encoded value. 25 | func (r *Request) SetJSONBody(val interface{}) error { 26 | buf := bytes.NewBuffer(nil) 27 | enc := json.NewEncoder(buf) 28 | if err := enc.Encode(val); err != nil { 29 | return err 30 | } 31 | 32 | r.Obj = val 33 | r.Body = buf 34 | r.BodySize = int64(buf.Len()) 35 | return nil 36 | } 37 | 38 | // ResetJSONBody is used to reset the body for a redirect 39 | func (r *Request) ResetJSONBody() error { 40 | if r.Body == nil { 41 | return nil 42 | } 43 | return r.SetJSONBody(r.Obj) 44 | } 45 | 46 | // ToHTTP turns this request into a valid *http.Request for use with the 47 | // net/http package. 48 | func (r *Request) ToHTTP() (*http.Request, error) { 49 | // Encode the query parameters 50 | r.URL.RawQuery = r.Params.Encode() 51 | 52 | // Create the HTTP request 53 | req, err := http.NewRequest(r.Method, r.URL.RequestURI(), r.Body) 54 | if err != nil { 55 | return nil, err 56 | } 57 | 58 | req.URL.User = r.URL.User 59 | req.URL.Scheme = r.URL.Scheme 60 | req.URL.Host = r.URL.Host 61 | req.Host = r.URL.Host 62 | 63 | if len(r.ClientToken) != 0 { 64 | req.Header.Set("X-Vault-Token", r.ClientToken) 65 | } 66 | 67 | if len(r.WrapTTL) != 0 { 68 | req.Header.Set("X-Vault-Wrap-TTL", r.WrapTTL) 69 | } 70 | 71 | return req, nil 72 | } 73 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/response.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | 9 | "github.com/hashicorp/vault/helper/jsonutil" 10 | ) 11 | 12 | // Response is a raw response that wraps an HTTP response. 13 | type Response struct { 14 | *http.Response 15 | } 16 | 17 | // DecodeJSON will decode the response body to a JSON structure. This 18 | // will consume the response body, but will not close it. Close must 19 | // still be called. 20 | func (r *Response) DecodeJSON(out interface{}) error { 21 | return jsonutil.DecodeJSONFromReader(r.Body, out) 22 | } 23 | 24 | // Error returns an error response if there is one. If there is an error, 25 | // this will fully consume the response body, but will not close it. The 26 | // body must still be closed manually. 27 | func (r *Response) Error() error { 28 | // 200 to 399 are okay status codes 29 | if r.StatusCode >= 200 && r.StatusCode < 400 { 30 | return nil 31 | } 32 | 33 | // We have an error. Let's copy the body into our own buffer first, 34 | // so that if we can't decode JSON, we can at least copy it raw. 35 | var bodyBuf bytes.Buffer 36 | if _, err := io.Copy(&bodyBuf, r.Body); err != nil { 37 | return err 38 | } 39 | 40 | // Decode the error response if we can. Note that we wrap the bodyBuf 41 | // in a bytes.Reader here so that the JSON decoder doesn't move the 42 | // read pointer for the original buffer. 43 | var resp ErrorResponse 44 | if err := jsonutil.DecodeJSON(bodyBuf.Bytes(), &resp); err != nil { 45 | // Ignore the decoding error and just drop the raw response 46 | return fmt.Errorf( 47 | "Error making API request.\n\n"+ 48 | "URL: %s %s\n"+ 49 | "Code: %d. Raw Message:\n\n%s", 50 | r.Request.Method, r.Request.URL.String(), 51 | r.StatusCode, bodyBuf.String()) 52 | } 53 | 54 | var errBody bytes.Buffer 55 | errBody.WriteString(fmt.Sprintf( 56 | "Error making API request.\n\n"+ 57 | "URL: %s %s\n"+ 58 | "Code: %d. Errors:\n\n", 59 | r.Request.Method, r.Request.URL.String(), 60 | r.StatusCode)) 61 | for _, err := range resp.Errors { 62 | errBody.WriteString(fmt.Sprintf("* %s", err)) 63 | } 64 | 65 | return fmt.Errorf(errBody.String()) 66 | } 67 | 68 | // ErrorResponse is the raw structure of errors when they're returned by the 69 | // HTTP API. 70 | type ErrorResponse struct { 71 | Errors []string 72 | } 73 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/secret.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "io" 5 | "time" 6 | 7 | "github.com/hashicorp/vault/helper/jsonutil" 8 | ) 9 | 10 | // Secret is the structure returned for every secret within Vault. 11 | type Secret struct { 12 | // The request ID that generated this response 13 | RequestID string `json:"request_id"` 14 | 15 | LeaseID string `json:"lease_id"` 16 | LeaseDuration int `json:"lease_duration"` 17 | Renewable bool `json:"renewable"` 18 | 19 | // Data is the actual contents of the secret. The format of the data 20 | // is arbitrary and up to the secret backend. 21 | Data map[string]interface{} `json:"data"` 22 | 23 | // Warnings contains any warnings related to the operation. These 24 | // are not issues that caused the command to fail, but that the 25 | // client should be aware of. 26 | Warnings []string `json:"warnings"` 27 | 28 | // Auth, if non-nil, means that there was authentication information 29 | // attached to this response. 30 | Auth *SecretAuth `json:"auth,omitempty"` 31 | 32 | // WrapInfo, if non-nil, means that the initial response was wrapped in the 33 | // cubbyhole of the given token (which has a TTL of the given number of 34 | // seconds) 35 | WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"` 36 | } 37 | 38 | // SecretWrapInfo contains wrapping information if we have it. If what is 39 | // contained is an authentication token, the accessor for the token will be 40 | // available in WrappedAccessor. 41 | type SecretWrapInfo struct { 42 | Token string `json:"token"` 43 | TTL int `json:"ttl"` 44 | CreationTime time.Time `json:"creation_time"` 45 | WrappedAccessor string `json:"wrapped_accessor"` 46 | } 47 | 48 | // SecretAuth is the structure containing auth information if we have it. 49 | type SecretAuth struct { 50 | ClientToken string `json:"client_token"` 51 | Accessor string `json:"accessor"` 52 | Policies []string `json:"policies"` 53 | Metadata map[string]string `json:"metadata"` 54 | 55 | LeaseDuration int `json:"lease_duration"` 56 | Renewable bool `json:"renewable"` 57 | } 58 | 59 | // ParseSecret is used to parse a secret value from JSON from an io.Reader. 60 | func ParseSecret(r io.Reader) (*Secret, error) { 61 | // First decode the JSON into a map[string]interface{} 62 | var secret Secret 63 | if err := jsonutil.DecodeJSONFromReader(r, &secret); err != nil { 64 | return nil, err 65 | } 66 | 67 | return &secret, nil 68 | } 69 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/ssh.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "fmt" 4 | 5 | // SSH is used to return a client to invoke operations on SSH backend. 6 | type SSH struct { 7 | c *Client 8 | MountPoint string 9 | } 10 | 11 | // SSH returns the client for logical-backend API calls. 12 | func (c *Client) SSH() *SSH { 13 | return c.SSHWithMountPoint(SSHHelperDefaultMountPoint) 14 | } 15 | 16 | // SSHWithMountPoint returns the client with specific SSH mount point. 17 | func (c *Client) SSHWithMountPoint(mountPoint string) *SSH { 18 | return &SSH{ 19 | c: c, 20 | MountPoint: mountPoint, 21 | } 22 | } 23 | 24 | // Credential invokes the SSH backend API to create a credential to establish an SSH session. 25 | func (c *SSH) Credential(role string, data map[string]interface{}) (*Secret, error) { 26 | r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/creds/%s", c.MountPoint, role)) 27 | if err := r.SetJSONBody(data); err != nil { 28 | return nil, err 29 | } 30 | 31 | resp, err := c.c.RawRequest(r) 32 | if err != nil { 33 | return nil, err 34 | } 35 | defer resp.Body.Close() 36 | 37 | return ParseSecret(resp.Body) 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | // Sys is used to perform system-related operations on Vault. 4 | type Sys struct { 5 | c *Client 6 | } 7 | 8 | // Sys is used to return the client for sys-related API calls. 9 | func (c *Client) Sys() *Sys { 10 | return &Sys{c: c} 11 | } 12 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_audit.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/fatih/structs" 7 | "github.com/mitchellh/mapstructure" 8 | ) 9 | 10 | func (c *Sys) AuditHash(path string, input string) (string, error) { 11 | body := map[string]interface{}{ 12 | "input": input, 13 | } 14 | 15 | r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit-hash/%s", path)) 16 | if err := r.SetJSONBody(body); err != nil { 17 | return "", err 18 | } 19 | 20 | resp, err := c.c.RawRequest(r) 21 | if err != nil { 22 | return "", err 23 | } 24 | defer resp.Body.Close() 25 | 26 | type d struct { 27 | Hash string `json:"hash"` 28 | } 29 | 30 | var result d 31 | err = resp.DecodeJSON(&result) 32 | if err != nil { 33 | return "", err 34 | } 35 | 36 | return result.Hash, err 37 | } 38 | 39 | func (c *Sys) ListAudit() (map[string]*Audit, error) { 40 | r := c.c.NewRequest("GET", "/v1/sys/audit") 41 | resp, err := c.c.RawRequest(r) 42 | if err != nil { 43 | return nil, err 44 | } 45 | defer resp.Body.Close() 46 | 47 | var result map[string]interface{} 48 | err = resp.DecodeJSON(&result) 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | mounts := map[string]*Audit{} 54 | for k, v := range result { 55 | switch v.(type) { 56 | case map[string]interface{}: 57 | default: 58 | continue 59 | } 60 | var res Audit 61 | err = mapstructure.Decode(v, &res) 62 | if err != nil { 63 | return nil, err 64 | } 65 | // Not a mount, some other api.Secret data 66 | if res.Type == "" { 67 | continue 68 | } 69 | mounts[k] = &res 70 | } 71 | 72 | return mounts, nil 73 | } 74 | 75 | // DEPRECATED: Use EnableAuditWithOptions instead 76 | func (c *Sys) EnableAudit( 77 | path string, auditType string, desc string, opts map[string]string) error { 78 | return c.EnableAuditWithOptions(path, &EnableAuditOptions{ 79 | Type: auditType, 80 | Description: desc, 81 | Options: opts, 82 | }) 83 | } 84 | 85 | func (c *Sys) EnableAuditWithOptions(path string, options *EnableAuditOptions) error { 86 | body := structs.Map(options) 87 | 88 | r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit/%s", path)) 89 | if err := r.SetJSONBody(body); err != nil { 90 | return err 91 | } 92 | 93 | resp, err := c.c.RawRequest(r) 94 | if err != nil { 95 | return err 96 | } 97 | defer resp.Body.Close() 98 | 99 | return nil 100 | } 101 | 102 | func (c *Sys) DisableAudit(path string) error { 103 | r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/audit/%s", path)) 104 | resp, err := c.c.RawRequest(r) 105 | if err == nil { 106 | defer resp.Body.Close() 107 | } 108 | return err 109 | } 110 | 111 | // Structures for the requests/resposne are all down here. They aren't 112 | // individually documented because the map almost directly to the raw HTTP API 113 | // documentation. Please refer to that documentation for more details. 114 | 115 | type EnableAuditOptions struct { 116 | Type string `json:"type" structs:"type"` 117 | Description string `json:"description" structs:"description"` 118 | Options map[string]string `json:"options" structs:"options"` 119 | Local bool `json:"local" structs:"local"` 120 | } 121 | 122 | type Audit struct { 123 | Path string 124 | Type string 125 | Description string 126 | Options map[string]string 127 | Local bool 128 | } 129 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_auth.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/fatih/structs" 7 | "github.com/mitchellh/mapstructure" 8 | ) 9 | 10 | func (c *Sys) ListAuth() (map[string]*AuthMount, error) { 11 | r := c.c.NewRequest("GET", "/v1/sys/auth") 12 | resp, err := c.c.RawRequest(r) 13 | if err != nil { 14 | return nil, err 15 | } 16 | defer resp.Body.Close() 17 | 18 | var result map[string]interface{} 19 | err = resp.DecodeJSON(&result) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | mounts := map[string]*AuthMount{} 25 | for k, v := range result { 26 | switch v.(type) { 27 | case map[string]interface{}: 28 | default: 29 | continue 30 | } 31 | var res AuthMount 32 | err = mapstructure.Decode(v, &res) 33 | if err != nil { 34 | return nil, err 35 | } 36 | // Not a mount, some other api.Secret data 37 | if res.Type == "" { 38 | continue 39 | } 40 | mounts[k] = &res 41 | } 42 | 43 | return mounts, nil 44 | } 45 | 46 | // DEPRECATED: Use EnableAuthWithOptions instead 47 | func (c *Sys) EnableAuth(path, authType, desc string) error { 48 | return c.EnableAuthWithOptions(path, &EnableAuthOptions{ 49 | Type: authType, 50 | Description: desc, 51 | }) 52 | } 53 | 54 | func (c *Sys) EnableAuthWithOptions(path string, options *EnableAuthOptions) error { 55 | body := structs.Map(options) 56 | 57 | r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/auth/%s", path)) 58 | if err := r.SetJSONBody(body); err != nil { 59 | return err 60 | } 61 | 62 | resp, err := c.c.RawRequest(r) 63 | if err != nil { 64 | return err 65 | } 66 | defer resp.Body.Close() 67 | 68 | return nil 69 | } 70 | 71 | func (c *Sys) DisableAuth(path string) error { 72 | r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/auth/%s", path)) 73 | resp, err := c.c.RawRequest(r) 74 | if err == nil { 75 | defer resp.Body.Close() 76 | } 77 | return err 78 | } 79 | 80 | // Structures for the requests/resposne are all down here. They aren't 81 | // individually documentd because the map almost directly to the raw HTTP API 82 | // documentation. Please refer to that documentation for more details. 83 | 84 | type EnableAuthOptions struct { 85 | Type string `json:"type" structs:"type"` 86 | Description string `json:"description" structs:"description"` 87 | Local bool `json:"local" structs:"local"` 88 | } 89 | 90 | type AuthMount struct { 91 | Type string `json:"type" structs:"type" mapstructure:"type"` 92 | Description string `json:"description" structs:"description" mapstructure:"description"` 93 | Config AuthConfigOutput `json:"config" structs:"config" mapstructure:"config"` 94 | Local bool `json:"local" structs:"local" mapstructure:"local"` 95 | } 96 | 97 | type AuthConfigOutput struct { 98 | DefaultLeaseTTL int `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` 99 | MaxLeaseTTL int `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_capabilities.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "fmt" 4 | 5 | func (c *Sys) CapabilitiesSelf(path string) ([]string, error) { 6 | return c.Capabilities(c.c.Token(), path) 7 | } 8 | 9 | func (c *Sys) Capabilities(token, path string) ([]string, error) { 10 | body := map[string]string{ 11 | "token": token, 12 | "path": path, 13 | } 14 | 15 | reqPath := "/v1/sys/capabilities" 16 | if token == c.c.Token() { 17 | reqPath = fmt.Sprintf("%s-self", reqPath) 18 | } 19 | 20 | r := c.c.NewRequest("POST", reqPath) 21 | if err := r.SetJSONBody(body); err != nil { 22 | return nil, err 23 | } 24 | 25 | resp, err := c.c.RawRequest(r) 26 | if err != nil { 27 | return nil, err 28 | } 29 | defer resp.Body.Close() 30 | 31 | var result map[string]interface{} 32 | err = resp.DecodeJSON(&result) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | var capabilities []string 38 | capabilitiesRaw := result["capabilities"].([]interface{}) 39 | for _, capability := range capabilitiesRaw { 40 | capabilities = append(capabilities, capability.(string)) 41 | } 42 | return capabilities, nil 43 | } 44 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_generate_root.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) GenerateRootStatus() (*GenerateRootStatusResponse, error) { 4 | r := c.c.NewRequest("GET", "/v1/sys/generate-root/attempt") 5 | resp, err := c.c.RawRequest(r) 6 | if err != nil { 7 | return nil, err 8 | } 9 | defer resp.Body.Close() 10 | 11 | var result GenerateRootStatusResponse 12 | err = resp.DecodeJSON(&result) 13 | return &result, err 14 | } 15 | 16 | func (c *Sys) GenerateRootInit(otp, pgpKey string) (*GenerateRootStatusResponse, error) { 17 | body := map[string]interface{}{ 18 | "otp": otp, 19 | "pgp_key": pgpKey, 20 | } 21 | 22 | r := c.c.NewRequest("PUT", "/v1/sys/generate-root/attempt") 23 | if err := r.SetJSONBody(body); err != nil { 24 | return nil, err 25 | } 26 | 27 | resp, err := c.c.RawRequest(r) 28 | if err != nil { 29 | return nil, err 30 | } 31 | defer resp.Body.Close() 32 | 33 | var result GenerateRootStatusResponse 34 | err = resp.DecodeJSON(&result) 35 | return &result, err 36 | } 37 | 38 | func (c *Sys) GenerateRootCancel() error { 39 | r := c.c.NewRequest("DELETE", "/v1/sys/generate-root/attempt") 40 | resp, err := c.c.RawRequest(r) 41 | if err == nil { 42 | defer resp.Body.Close() 43 | } 44 | return err 45 | } 46 | 47 | func (c *Sys) GenerateRootUpdate(shard, nonce string) (*GenerateRootStatusResponse, error) { 48 | body := map[string]interface{}{ 49 | "key": shard, 50 | "nonce": nonce, 51 | } 52 | 53 | r := c.c.NewRequest("PUT", "/v1/sys/generate-root/update") 54 | if err := r.SetJSONBody(body); err != nil { 55 | return nil, err 56 | } 57 | 58 | resp, err := c.c.RawRequest(r) 59 | if err != nil { 60 | return nil, err 61 | } 62 | defer resp.Body.Close() 63 | 64 | var result GenerateRootStatusResponse 65 | err = resp.DecodeJSON(&result) 66 | return &result, err 67 | } 68 | 69 | type GenerateRootStatusResponse struct { 70 | Nonce string 71 | Started bool 72 | Progress int 73 | Required int 74 | Complete bool 75 | EncodedRootToken string `json:"encoded_root_token"` 76 | PGPFingerprint string `json:"pgp_fingerprint"` 77 | } 78 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_init.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) InitStatus() (bool, error) { 4 | r := c.c.NewRequest("GET", "/v1/sys/init") 5 | resp, err := c.c.RawRequest(r) 6 | if err != nil { 7 | return false, err 8 | } 9 | defer resp.Body.Close() 10 | 11 | var result InitStatusResponse 12 | err = resp.DecodeJSON(&result) 13 | return result.Initialized, err 14 | } 15 | 16 | func (c *Sys) Init(opts *InitRequest) (*InitResponse, error) { 17 | r := c.c.NewRequest("PUT", "/v1/sys/init") 18 | if err := r.SetJSONBody(opts); err != nil { 19 | return nil, err 20 | } 21 | 22 | resp, err := c.c.RawRequest(r) 23 | if err != nil { 24 | return nil, err 25 | } 26 | defer resp.Body.Close() 27 | 28 | var result InitResponse 29 | err = resp.DecodeJSON(&result) 30 | return &result, err 31 | } 32 | 33 | type InitRequest struct { 34 | SecretShares int `json:"secret_shares"` 35 | SecretThreshold int `json:"secret_threshold"` 36 | StoredShares int `json:"stored_shares"` 37 | PGPKeys []string `json:"pgp_keys"` 38 | RecoveryShares int `json:"recovery_shares"` 39 | RecoveryThreshold int `json:"recovery_threshold"` 40 | RecoveryPGPKeys []string `json:"recovery_pgp_keys"` 41 | RootTokenPGPKey string `json:"root_token_pgp_key"` 42 | } 43 | 44 | type InitStatusResponse struct { 45 | Initialized bool 46 | } 47 | 48 | type InitResponse struct { 49 | Keys []string `json:"keys"` 50 | KeysB64 []string `json:"keys_base64"` 51 | RecoveryKeys []string `json:"recovery_keys"` 52 | RecoveryKeysB64 []string `json:"recovery_keys_base64"` 53 | RootToken string `json:"root_token"` 54 | } 55 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_leader.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) Leader() (*LeaderResponse, error) { 4 | r := c.c.NewRequest("GET", "/v1/sys/leader") 5 | resp, err := c.c.RawRequest(r) 6 | if err != nil { 7 | return nil, err 8 | } 9 | defer resp.Body.Close() 10 | 11 | var result LeaderResponse 12 | err = resp.DecodeJSON(&result) 13 | return &result, err 14 | } 15 | 16 | type LeaderResponse struct { 17 | HAEnabled bool `json:"ha_enabled"` 18 | IsSelf bool `json:"is_self"` 19 | LeaderAddress string `json:"leader_address"` 20 | } 21 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_lease.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) Renew(id string, increment int) (*Secret, error) { 4 | r := c.c.NewRequest("PUT", "/v1/sys/renew") 5 | 6 | body := map[string]interface{}{ 7 | "increment": increment, 8 | "lease_id": id, 9 | } 10 | if err := r.SetJSONBody(body); err != nil { 11 | return nil, err 12 | } 13 | 14 | resp, err := c.c.RawRequest(r) 15 | if err != nil { 16 | return nil, err 17 | } 18 | defer resp.Body.Close() 19 | 20 | return ParseSecret(resp.Body) 21 | } 22 | 23 | func (c *Sys) Revoke(id string) error { 24 | r := c.c.NewRequest("PUT", "/v1/sys/revoke/"+id) 25 | resp, err := c.c.RawRequest(r) 26 | if err == nil { 27 | defer resp.Body.Close() 28 | } 29 | return err 30 | } 31 | 32 | func (c *Sys) RevokePrefix(id string) error { 33 | r := c.c.NewRequest("PUT", "/v1/sys/revoke-prefix/"+id) 34 | resp, err := c.c.RawRequest(r) 35 | if err == nil { 36 | defer resp.Body.Close() 37 | } 38 | return err 39 | } 40 | 41 | func (c *Sys) RevokeForce(id string) error { 42 | r := c.c.NewRequest("PUT", "/v1/sys/revoke-force/"+id) 43 | resp, err := c.c.RawRequest(r) 44 | if err == nil { 45 | defer resp.Body.Close() 46 | } 47 | return err 48 | } 49 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_mounts.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/fatih/structs" 7 | "github.com/mitchellh/mapstructure" 8 | ) 9 | 10 | func (c *Sys) ListMounts() (map[string]*MountOutput, error) { 11 | r := c.c.NewRequest("GET", "/v1/sys/mounts") 12 | resp, err := c.c.RawRequest(r) 13 | if err != nil { 14 | return nil, err 15 | } 16 | defer resp.Body.Close() 17 | 18 | var result map[string]interface{} 19 | err = resp.DecodeJSON(&result) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | mounts := map[string]*MountOutput{} 25 | for k, v := range result { 26 | switch v.(type) { 27 | case map[string]interface{}: 28 | default: 29 | continue 30 | } 31 | var res MountOutput 32 | err = mapstructure.Decode(v, &res) 33 | if err != nil { 34 | return nil, err 35 | } 36 | // Not a mount, some other api.Secret data 37 | if res.Type == "" { 38 | continue 39 | } 40 | mounts[k] = &res 41 | } 42 | 43 | return mounts, nil 44 | } 45 | 46 | func (c *Sys) Mount(path string, mountInfo *MountInput) error { 47 | body := structs.Map(mountInfo) 48 | 49 | r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s", path)) 50 | if err := r.SetJSONBody(body); err != nil { 51 | return err 52 | } 53 | 54 | resp, err := c.c.RawRequest(r) 55 | if err != nil { 56 | return err 57 | } 58 | defer resp.Body.Close() 59 | 60 | return nil 61 | } 62 | 63 | func (c *Sys) Unmount(path string) error { 64 | r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/mounts/%s", path)) 65 | resp, err := c.c.RawRequest(r) 66 | if err == nil { 67 | defer resp.Body.Close() 68 | } 69 | return err 70 | } 71 | 72 | func (c *Sys) Remount(from, to string) error { 73 | body := map[string]interface{}{ 74 | "from": from, 75 | "to": to, 76 | } 77 | 78 | r := c.c.NewRequest("POST", "/v1/sys/remount") 79 | if err := r.SetJSONBody(body); err != nil { 80 | return err 81 | } 82 | 83 | resp, err := c.c.RawRequest(r) 84 | if err == nil { 85 | defer resp.Body.Close() 86 | } 87 | return err 88 | } 89 | 90 | func (c *Sys) TuneMount(path string, config MountConfigInput) error { 91 | body := structs.Map(config) 92 | r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) 93 | if err := r.SetJSONBody(body); err != nil { 94 | return err 95 | } 96 | 97 | resp, err := c.c.RawRequest(r) 98 | if err == nil { 99 | defer resp.Body.Close() 100 | } 101 | return err 102 | } 103 | 104 | func (c *Sys) MountConfig(path string) (*MountConfigOutput, error) { 105 | r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) 106 | 107 | resp, err := c.c.RawRequest(r) 108 | if err != nil { 109 | return nil, err 110 | } 111 | defer resp.Body.Close() 112 | 113 | var result MountConfigOutput 114 | err = resp.DecodeJSON(&result) 115 | if err != nil { 116 | return nil, err 117 | } 118 | 119 | return &result, err 120 | } 121 | 122 | type MountInput struct { 123 | Type string `json:"type" structs:"type"` 124 | Description string `json:"description" structs:"description"` 125 | Config MountConfigInput `json:"config" structs:"config"` 126 | Local bool `json:"local" structs:"local"` 127 | } 128 | 129 | type MountConfigInput struct { 130 | DefaultLeaseTTL string `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` 131 | MaxLeaseTTL string `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` 132 | ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` 133 | } 134 | 135 | type MountOutput struct { 136 | Type string `json:"type" structs:"type"` 137 | Description string `json:"description" structs:"description"` 138 | Config MountConfigOutput `json:"config" structs:"config"` 139 | Local bool `json:"local" structs:"local"` 140 | } 141 | 142 | type MountConfigOutput struct { 143 | DefaultLeaseTTL int `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` 144 | MaxLeaseTTL int `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` 145 | ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` 146 | } 147 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_policy.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "fmt" 4 | 5 | func (c *Sys) ListPolicies() ([]string, error) { 6 | r := c.c.NewRequest("GET", "/v1/sys/policy") 7 | resp, err := c.c.RawRequest(r) 8 | if err != nil { 9 | return nil, err 10 | } 11 | defer resp.Body.Close() 12 | 13 | var result map[string]interface{} 14 | err = resp.DecodeJSON(&result) 15 | if err != nil { 16 | return nil, err 17 | } 18 | 19 | var ok bool 20 | if _, ok = result["policies"]; !ok { 21 | return nil, fmt.Errorf("policies not found in response") 22 | } 23 | 24 | listRaw := result["policies"].([]interface{}) 25 | var policies []string 26 | 27 | for _, val := range listRaw { 28 | policies = append(policies, val.(string)) 29 | } 30 | 31 | return policies, err 32 | } 33 | 34 | func (c *Sys) GetPolicy(name string) (string, error) { 35 | r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/policy/%s", name)) 36 | resp, err := c.c.RawRequest(r) 37 | if resp != nil { 38 | defer resp.Body.Close() 39 | if resp.StatusCode == 404 { 40 | return "", nil 41 | } 42 | } 43 | if err != nil { 44 | return "", err 45 | } 46 | 47 | var result map[string]interface{} 48 | err = resp.DecodeJSON(&result) 49 | if err != nil { 50 | return "", err 51 | } 52 | 53 | var ok bool 54 | if _, ok = result["rules"]; !ok { 55 | return "", fmt.Errorf("rules not found in response") 56 | } 57 | 58 | return result["rules"].(string), nil 59 | } 60 | 61 | func (c *Sys) PutPolicy(name, rules string) error { 62 | body := map[string]string{ 63 | "rules": rules, 64 | } 65 | 66 | r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/policy/%s", name)) 67 | if err := r.SetJSONBody(body); err != nil { 68 | return err 69 | } 70 | 71 | resp, err := c.c.RawRequest(r) 72 | if err != nil { 73 | return err 74 | } 75 | defer resp.Body.Close() 76 | 77 | return nil 78 | } 79 | 80 | func (c *Sys) DeletePolicy(name string) error { 81 | r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/policy/%s", name)) 82 | resp, err := c.c.RawRequest(r) 83 | if err == nil { 84 | defer resp.Body.Close() 85 | } 86 | return err 87 | } 88 | 89 | type getPoliciesResp struct { 90 | Rules string `json:"rules"` 91 | } 92 | 93 | type listPoliciesResp struct { 94 | Policies []string `json:"policies"` 95 | } 96 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_rotate.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "time" 4 | 5 | func (c *Sys) Rotate() error { 6 | r := c.c.NewRequest("POST", "/v1/sys/rotate") 7 | resp, err := c.c.RawRequest(r) 8 | if err == nil { 9 | defer resp.Body.Close() 10 | } 11 | return err 12 | } 13 | 14 | func (c *Sys) KeyStatus() (*KeyStatus, error) { 15 | r := c.c.NewRequest("GET", "/v1/sys/key-status") 16 | resp, err := c.c.RawRequest(r) 17 | if err != nil { 18 | return nil, err 19 | } 20 | defer resp.Body.Close() 21 | 22 | result := new(KeyStatus) 23 | err = resp.DecodeJSON(result) 24 | return result, err 25 | } 26 | 27 | type KeyStatus struct { 28 | Term int `json:"term"` 29 | InstallTime time.Time `json:"install_time"` 30 | } 31 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_seal.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) SealStatus() (*SealStatusResponse, error) { 4 | r := c.c.NewRequest("GET", "/v1/sys/seal-status") 5 | return sealStatusRequest(c, r) 6 | } 7 | 8 | func (c *Sys) Seal() error { 9 | r := c.c.NewRequest("PUT", "/v1/sys/seal") 10 | resp, err := c.c.RawRequest(r) 11 | if err == nil { 12 | defer resp.Body.Close() 13 | } 14 | return err 15 | } 16 | 17 | func (c *Sys) ResetUnsealProcess() (*SealStatusResponse, error) { 18 | body := map[string]interface{}{"reset": true} 19 | 20 | r := c.c.NewRequest("PUT", "/v1/sys/unseal") 21 | if err := r.SetJSONBody(body); err != nil { 22 | return nil, err 23 | } 24 | 25 | return sealStatusRequest(c, r) 26 | } 27 | 28 | func (c *Sys) Unseal(shard string) (*SealStatusResponse, error) { 29 | body := map[string]interface{}{"key": shard} 30 | 31 | r := c.c.NewRequest("PUT", "/v1/sys/unseal") 32 | if err := r.SetJSONBody(body); err != nil { 33 | return nil, err 34 | } 35 | 36 | return sealStatusRequest(c, r) 37 | } 38 | 39 | func sealStatusRequest(c *Sys, r *Request) (*SealStatusResponse, error) { 40 | resp, err := c.c.RawRequest(r) 41 | if err != nil { 42 | return nil, err 43 | } 44 | defer resp.Body.Close() 45 | 46 | var result SealStatusResponse 47 | err = resp.DecodeJSON(&result) 48 | return &result, err 49 | } 50 | 51 | type SealStatusResponse struct { 52 | Sealed bool `json:"sealed"` 53 | T int `json:"t"` 54 | N int `json:"n"` 55 | Progress int `json:"progress"` 56 | Nonce string `json:"nonce"` 57 | Version string `json:"version"` 58 | ClusterName string `json:"cluster_name,omitempty"` 59 | ClusterID string `json:"cluster_id,omitempty"` 60 | } 61 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/api/sys_stepdown.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | func (c *Sys) StepDown() error { 4 | r := c.c.NewRequest("PUT", "/v1/sys/step-down") 5 | resp, err := c.c.RawRequest(r) 6 | if err == nil { 7 | defer resp.Body.Close() 8 | } 9 | return err 10 | } 11 | -------------------------------------------------------------------------------- /vendor/github.com/hashicorp/vault/helper/jsonutil/json.go: -------------------------------------------------------------------------------- 1 | package jsonutil 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | 10 | "github.com/hashicorp/vault/helper/compressutil" 11 | ) 12 | 13 | // Encodes/Marshals the given object into JSON 14 | func EncodeJSON(in interface{}) ([]byte, error) { 15 | if in == nil { 16 | return nil, fmt.Errorf("input for encoding is nil") 17 | } 18 | var buf bytes.Buffer 19 | enc := json.NewEncoder(&buf) 20 | if err := enc.Encode(in); err != nil { 21 | return nil, err 22 | } 23 | return buf.Bytes(), nil 24 | } 25 | 26 | // EncodeJSONAndCompress encodes the given input into JSON and compresses the 27 | // encoded value (using Gzip format BestCompression level, by default). A 28 | // canary byte is placed at the beginning of the returned bytes for the logic 29 | // in decompression method to identify compressed input. 30 | func EncodeJSONAndCompress(in interface{}, config *compressutil.CompressionConfig) ([]byte, error) { 31 | if in == nil { 32 | return nil, fmt.Errorf("input for encoding is nil") 33 | } 34 | 35 | // First JSON encode the given input 36 | encodedBytes, err := EncodeJSON(in) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | if config == nil { 42 | config = &compressutil.CompressionConfig{ 43 | Type: compressutil.CompressionTypeGzip, 44 | GzipCompressionLevel: gzip.BestCompression, 45 | } 46 | } 47 | 48 | return compressutil.Compress(encodedBytes, config) 49 | } 50 | 51 | // DecodeJSON tries to decompress the given data. The call to decompress, fails 52 | // if the content was not compressed in the first place, which is identified by 53 | // a canary byte before the compressed data. If the data is not compressed, it 54 | // is JSON decoded directly. Otherwise the decompressed data will be JSON 55 | // decoded. 56 | func DecodeJSON(data []byte, out interface{}) error { 57 | if data == nil || len(data) == 0 { 58 | return fmt.Errorf("'data' being decoded is nil") 59 | } 60 | if out == nil { 61 | return fmt.Errorf("output parameter 'out' is nil") 62 | } 63 | 64 | // Decompress the data if it was compressed in the first place 65 | decompressedBytes, uncompressed, err := compressutil.Decompress(data) 66 | if err != nil { 67 | return fmt.Errorf("failed to decompress JSON: err: %v", err) 68 | } 69 | if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { 70 | return fmt.Errorf("decompressed data being decoded is invalid") 71 | } 72 | 73 | // If the input supplied failed to contain the compression canary, it 74 | // will be notified by the compression utility. Decode the decompressed 75 | // input. 76 | if !uncompressed { 77 | data = decompressedBytes 78 | } 79 | 80 | return DecodeJSONFromReader(bytes.NewReader(data), out) 81 | } 82 | 83 | // Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object 84 | func DecodeJSONFromReader(r io.Reader, out interface{}) error { 85 | if r == nil { 86 | return fmt.Errorf("'io.Reader' being decoded is nil") 87 | } 88 | if out == nil { 89 | return fmt.Errorf("output parameter 'out' is nil") 90 | } 91 | 92 | dec := json.NewDecoder(r) 93 | 94 | // While decoding JSON values, intepret the integer values as `json.Number`s instead of `float64`. 95 | dec.UseNumber() 96 | 97 | // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' 98 | return dec.Decode(out) 99 | } 100 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/go-homedir/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Mitchell Hashimoto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/go-homedir/README.md: -------------------------------------------------------------------------------- 1 | # go-homedir 2 | 3 | This is a Go library for detecting the user's home directory without 4 | the use of cgo, so the library can be used in cross-compilation environments. 5 | 6 | Usage is incredibly simple, just call `homedir.Dir()` to get the home directory 7 | for a user, and `homedir.Expand()` to expand the `~` in a path to the home 8 | directory. 9 | 10 | **Why not just use `os/user`?** The built-in `os/user` package requires 11 | cgo on Darwin systems. This means that any Go code that uses that package 12 | cannot cross compile. But 99% of the time the use for `os/user` is just to 13 | retrieve the home directory, which we can do for the current user without 14 | cgo. This library does that, enabling cross-compilation. 15 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/go-homedir/homedir.go: -------------------------------------------------------------------------------- 1 | package homedir 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "os" 7 | "os/exec" 8 | "path/filepath" 9 | "runtime" 10 | "strconv" 11 | "strings" 12 | "sync" 13 | ) 14 | 15 | // DisableCache will disable caching of the home directory. Caching is enabled 16 | // by default. 17 | var DisableCache bool 18 | 19 | var homedirCache string 20 | var cacheLock sync.RWMutex 21 | 22 | // Dir returns the home directory for the executing user. 23 | // 24 | // This uses an OS-specific method for discovering the home directory. 25 | // An error is returned if a home directory cannot be detected. 26 | func Dir() (string, error) { 27 | if !DisableCache { 28 | cacheLock.RLock() 29 | cached := homedirCache 30 | cacheLock.RUnlock() 31 | if cached != "" { 32 | return cached, nil 33 | } 34 | } 35 | 36 | cacheLock.Lock() 37 | defer cacheLock.Unlock() 38 | 39 | var result string 40 | var err error 41 | if runtime.GOOS == "windows" { 42 | result, err = dirWindows() 43 | } else { 44 | // Unix-like system, so just assume Unix 45 | result, err = dirUnix() 46 | } 47 | 48 | if err != nil { 49 | return "", err 50 | } 51 | homedirCache = result 52 | return result, nil 53 | } 54 | 55 | // Expand expands the path to include the home directory if the path 56 | // is prefixed with `~`. If it isn't prefixed with `~`, the path is 57 | // returned as-is. 58 | func Expand(path string) (string, error) { 59 | if len(path) == 0 { 60 | return path, nil 61 | } 62 | 63 | if path[0] != '~' { 64 | return path, nil 65 | } 66 | 67 | if len(path) > 1 && path[1] != '/' && path[1] != '\\' { 68 | return "", errors.New("cannot expand user-specific home dir") 69 | } 70 | 71 | dir, err := Dir() 72 | if err != nil { 73 | return "", err 74 | } 75 | 76 | return filepath.Join(dir, path[1:]), nil 77 | } 78 | 79 | func dirUnix() (string, error) { 80 | // First prefer the HOME environmental variable 81 | if home := os.Getenv("HOME"); home != "" { 82 | return home, nil 83 | } 84 | 85 | // If that fails, try getent 86 | var stdout bytes.Buffer 87 | cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) 88 | cmd.Stdout = &stdout 89 | if err := cmd.Run(); err != nil { 90 | // If the error is ErrNotFound, we ignore it. Otherwise, return it. 91 | if err != exec.ErrNotFound { 92 | return "", err 93 | } 94 | } else { 95 | if passwd := strings.TrimSpace(stdout.String()); passwd != "" { 96 | // username:password:uid:gid:gecos:home:shell 97 | passwdParts := strings.SplitN(passwd, ":", 7) 98 | if len(passwdParts) > 5 { 99 | return passwdParts[5], nil 100 | } 101 | } 102 | } 103 | 104 | // If all else fails, try the shell 105 | stdout.Reset() 106 | cmd = exec.Command("sh", "-c", "cd && pwd") 107 | cmd.Stdout = &stdout 108 | if err := cmd.Run(); err != nil { 109 | return "", err 110 | } 111 | 112 | result := strings.TrimSpace(stdout.String()) 113 | if result == "" { 114 | return "", errors.New("blank output when reading home directory") 115 | } 116 | 117 | return result, nil 118 | } 119 | 120 | func dirWindows() (string, error) { 121 | // First prefer the HOME environmental variable 122 | if home := os.Getenv("HOME"); home != "" { 123 | return home, nil 124 | } 125 | 126 | drive := os.Getenv("HOMEDRIVE") 127 | path := os.Getenv("HOMEPATH") 128 | home := drive + path 129 | if drive == "" || path == "" { 130 | home = os.Getenv("USERPROFILE") 131 | } 132 | if home == "" { 133 | return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") 134 | } 135 | 136 | return home, nil 137 | } 138 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/mapstructure/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4 5 | 6 | script: 7 | - go test 8 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/mapstructure/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Mitchell Hashimoto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/mapstructure/README.md: -------------------------------------------------------------------------------- 1 | # mapstructure 2 | 3 | mapstructure is a Go library for decoding generic map values to structures 4 | and vice versa, while providing helpful error handling. 5 | 6 | This library is most useful when decoding values from some data stream (JSON, 7 | Gob, etc.) where you don't _quite_ know the structure of the underlying data 8 | until you read a part of it. You can therefore read a `map[string]interface{}` 9 | and use this library to decode it into the proper underlying native Go 10 | structure. 11 | 12 | ## Installation 13 | 14 | Standard `go get`: 15 | 16 | ``` 17 | $ go get github.com/mitchellh/mapstructure 18 | ``` 19 | 20 | ## Usage & Example 21 | 22 | For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). 23 | 24 | The `Decode` function has examples associated with it there. 25 | 26 | ## But Why?! 27 | 28 | Go offers fantastic standard libraries for decoding formats such as JSON. 29 | The standard method is to have a struct pre-created, and populate that struct 30 | from the bytes of the encoded format. This is great, but the problem is if 31 | you have configuration or an encoding that changes slightly depending on 32 | specific fields. For example, consider this JSON: 33 | 34 | ```json 35 | { 36 | "type": "person", 37 | "name": "Mitchell" 38 | } 39 | ``` 40 | 41 | Perhaps we can't populate a specific structure without first reading 42 | the "type" field from the JSON. We could always do two passes over the 43 | decoding of the JSON (reading the "type" first, and the rest later). 44 | However, it is much simpler to just decode this into a `map[string]interface{}` 45 | structure, read the "type" key, then use something like this library 46 | to decode it into the proper structure. 47 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/mapstructure/decode_hooks.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | "strconv" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | // typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns 12 | // it into the proper DecodeHookFunc type, such as DecodeHookFuncType. 13 | func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { 14 | // Create variables here so we can reference them with the reflect pkg 15 | var f1 DecodeHookFuncType 16 | var f2 DecodeHookFuncKind 17 | 18 | // Fill in the variables into this interface and the rest is done 19 | // automatically using the reflect package. 20 | potential := []interface{}{f1, f2} 21 | 22 | v := reflect.ValueOf(h) 23 | vt := v.Type() 24 | for _, raw := range potential { 25 | pt := reflect.ValueOf(raw).Type() 26 | if vt.ConvertibleTo(pt) { 27 | return v.Convert(pt).Interface() 28 | } 29 | } 30 | 31 | return nil 32 | } 33 | 34 | // DecodeHookExec executes the given decode hook. This should be used 35 | // since it'll naturally degrade to the older backwards compatible DecodeHookFunc 36 | // that took reflect.Kind instead of reflect.Type. 37 | func DecodeHookExec( 38 | raw DecodeHookFunc, 39 | from reflect.Type, to reflect.Type, 40 | data interface{}) (interface{}, error) { 41 | // Build our arguments that reflect expects 42 | argVals := make([]reflect.Value, 3) 43 | argVals[0] = reflect.ValueOf(from) 44 | argVals[1] = reflect.ValueOf(to) 45 | argVals[2] = reflect.ValueOf(data) 46 | 47 | switch f := typedDecodeHook(raw).(type) { 48 | case DecodeHookFuncType: 49 | return f(from, to, data) 50 | case DecodeHookFuncKind: 51 | return f(from.Kind(), to.Kind(), data) 52 | default: 53 | return nil, errors.New("invalid decode hook signature") 54 | } 55 | } 56 | 57 | // ComposeDecodeHookFunc creates a single DecodeHookFunc that 58 | // automatically composes multiple DecodeHookFuncs. 59 | // 60 | // The composed funcs are called in order, with the result of the 61 | // previous transformation. 62 | func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { 63 | return func( 64 | f reflect.Type, 65 | t reflect.Type, 66 | data interface{}) (interface{}, error) { 67 | var err error 68 | for _, f1 := range fs { 69 | data, err = DecodeHookExec(f1, f, t, data) 70 | if err != nil { 71 | return nil, err 72 | } 73 | 74 | // Modify the from kind to be correct with the new data 75 | f = nil 76 | if val := reflect.ValueOf(data); val.IsValid() { 77 | f = val.Type() 78 | } 79 | } 80 | 81 | return data, nil 82 | } 83 | } 84 | 85 | // StringToSliceHookFunc returns a DecodeHookFunc that converts 86 | // string to []string by splitting on the given sep. 87 | func StringToSliceHookFunc(sep string) DecodeHookFunc { 88 | return func( 89 | f reflect.Kind, 90 | t reflect.Kind, 91 | data interface{}) (interface{}, error) { 92 | if f != reflect.String || t != reflect.Slice { 93 | return data, nil 94 | } 95 | 96 | raw := data.(string) 97 | if raw == "" { 98 | return []string{}, nil 99 | } 100 | 101 | return strings.Split(raw, sep), nil 102 | } 103 | } 104 | 105 | // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts 106 | // strings to time.Duration. 107 | func StringToTimeDurationHookFunc() DecodeHookFunc { 108 | return func( 109 | f reflect.Type, 110 | t reflect.Type, 111 | data interface{}) (interface{}, error) { 112 | if f.Kind() != reflect.String { 113 | return data, nil 114 | } 115 | if t != reflect.TypeOf(time.Duration(5)) { 116 | return data, nil 117 | } 118 | 119 | // Convert it by parsing 120 | return time.ParseDuration(data.(string)) 121 | } 122 | } 123 | 124 | func WeaklyTypedHook( 125 | f reflect.Kind, 126 | t reflect.Kind, 127 | data interface{}) (interface{}, error) { 128 | dataVal := reflect.ValueOf(data) 129 | switch t { 130 | case reflect.String: 131 | switch f { 132 | case reflect.Bool: 133 | if dataVal.Bool() { 134 | return "1", nil 135 | } else { 136 | return "0", nil 137 | } 138 | case reflect.Float32: 139 | return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil 140 | case reflect.Int: 141 | return strconv.FormatInt(dataVal.Int(), 10), nil 142 | case reflect.Slice: 143 | dataType := dataVal.Type() 144 | elemKind := dataType.Elem().Kind() 145 | if elemKind == reflect.Uint8 { 146 | return string(dataVal.Interface().([]uint8)), nil 147 | } 148 | case reflect.Uint: 149 | return strconv.FormatUint(dataVal.Uint(), 10), nil 150 | } 151 | } 152 | 153 | return data, nil 154 | } 155 | -------------------------------------------------------------------------------- /vendor/github.com/mitchellh/mapstructure/error.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "sort" 7 | "strings" 8 | ) 9 | 10 | // Error implements the error interface and can represents multiple 11 | // errors that occur in the course of a single decode. 12 | type Error struct { 13 | Errors []string 14 | } 15 | 16 | func (e *Error) Error() string { 17 | points := make([]string, len(e.Errors)) 18 | for i, err := range e.Errors { 19 | points[i] = fmt.Sprintf("* %s", err) 20 | } 21 | 22 | sort.Strings(points) 23 | return fmt.Sprintf( 24 | "%d error(s) decoding:\n\n%s", 25 | len(e.Errors), strings.Join(points, "\n")) 26 | } 27 | 28 | // WrappedErrors implements the errwrap.Wrapper interface to make this 29 | // return value more useful with the errwrap and go-multierror libraries. 30 | func (e *Error) WrappedErrors() []error { 31 | if e == nil { 32 | return nil 33 | } 34 | 35 | result := make([]error, len(e.Errors)) 36 | for i, e := range e.Errors { 37 | result[i] = errors.New(e) 38 | } 39 | 40 | return result 41 | } 42 | 43 | func appendErrors(errors []string, err error) []string { 44 | switch e := err.(type) { 45 | case *Error: 46 | return append(errors, e.Errors...) 47 | default: 48 | return append(errors, e.Error()) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /vendor/github.com/sethgrid/pester/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) SendGrid 2016 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | h2i/h2i 3 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # This Dockerfile builds a recent curl with HTTP/2 client support, using 3 | # a recent nghttp2 build. 4 | # 5 | # See the Makefile for how to tag it. If Docker and that image is found, the 6 | # Go tests use this curl binary for integration tests. 7 | # 8 | 9 | FROM ubuntu:trusty 10 | 11 | RUN apt-get update && \ 12 | apt-get upgrade -y && \ 13 | apt-get install -y git-core build-essential wget 14 | 15 | RUN apt-get install -y --no-install-recommends \ 16 | autotools-dev libtool pkg-config zlib1g-dev \ 17 | libcunit1-dev libssl-dev libxml2-dev libevent-dev \ 18 | automake autoconf 19 | 20 | # The list of packages nghttp2 recommends for h2load: 21 | RUN apt-get install -y --no-install-recommends make binutils \ 22 | autoconf automake autotools-dev \ 23 | libtool pkg-config zlib1g-dev libcunit1-dev libssl-dev libxml2-dev \ 24 | libev-dev libevent-dev libjansson-dev libjemalloc-dev \ 25 | cython python3.4-dev python-setuptools 26 | 27 | # Note: setting NGHTTP2_VER before the git clone, so an old git clone isn't cached: 28 | ENV NGHTTP2_VER 895da9a 29 | RUN cd /root && git clone https://github.com/tatsuhiro-t/nghttp2.git 30 | 31 | WORKDIR /root/nghttp2 32 | RUN git reset --hard $NGHTTP2_VER 33 | RUN autoreconf -i 34 | RUN automake 35 | RUN autoconf 36 | RUN ./configure 37 | RUN make 38 | RUN make install 39 | 40 | WORKDIR /root 41 | RUN wget http://curl.haxx.se/download/curl-7.45.0.tar.gz 42 | RUN tar -zxvf curl-7.45.0.tar.gz 43 | WORKDIR /root/curl-7.45.0 44 | RUN ./configure --with-ssl --with-nghttp2=/usr/local 45 | RUN make 46 | RUN make install 47 | RUN ldconfig 48 | 49 | CMD ["-h"] 50 | ENTRYPOINT ["/usr/local/bin/curl"] 51 | 52 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/Makefile: -------------------------------------------------------------------------------- 1 | curlimage: 2 | docker build -t gohttp2/curl . 3 | 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/README: -------------------------------------------------------------------------------- 1 | This is a work-in-progress HTTP/2 implementation for Go. 2 | 3 | It will eventually live in the Go standard library and won't require 4 | any changes to your code to use. It will just be automatic. 5 | 6 | Status: 7 | 8 | * The server support is pretty good. A few things are missing 9 | but are being worked on. 10 | * The client work has just started but shares a lot of code 11 | is coming along much quicker. 12 | 13 | Docs are at https://godoc.org/golang.org/x/net/http2 14 | 15 | Demo test server at https://http2.golang.org/ 16 | 17 | Help & bug reports welcome! 18 | 19 | Contributing: https://golang.org/doc/contribute.html 20 | Bugs: https://golang.org/issue/new?title=x/net/http2:+ 21 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/configure_transport.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.6 6 | 7 | package http2 8 | 9 | import ( 10 | "crypto/tls" 11 | "fmt" 12 | "net/http" 13 | ) 14 | 15 | func configureTransport(t1 *http.Transport) (*Transport, error) { 16 | connPool := new(clientConnPool) 17 | t2 := &Transport{ 18 | ConnPool: noDialClientConnPool{connPool}, 19 | t1: t1, 20 | } 21 | connPool.t = t2 22 | if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil { 23 | return nil, err 24 | } 25 | if t1.TLSClientConfig == nil { 26 | t1.TLSClientConfig = new(tls.Config) 27 | } 28 | if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") { 29 | t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...) 30 | } 31 | if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") { 32 | t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1") 33 | } 34 | upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper { 35 | addr := authorityAddr("https", authority) 36 | if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil { 37 | go c.Close() 38 | return erringRoundTripper{err} 39 | } else if !used { 40 | // Turns out we don't need this c. 41 | // For example, two goroutines made requests to the same host 42 | // at the same time, both kicking off TCP dials. (since protocol 43 | // was unknown) 44 | go c.Close() 45 | } 46 | return t2 47 | } 48 | if m := t1.TLSNextProto; len(m) == 0 { 49 | t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{ 50 | "h2": upgradeFn, 51 | } 52 | } else { 53 | m["h2"] = upgradeFn 54 | } 55 | return t2, nil 56 | } 57 | 58 | // registerHTTPSProtocol calls Transport.RegisterProtocol but 59 | // convering panics into errors. 60 | func registerHTTPSProtocol(t *http.Transport, rt http.RoundTripper) (err error) { 61 | defer func() { 62 | if e := recover(); e != nil { 63 | err = fmt.Errorf("%v", e) 64 | } 65 | }() 66 | t.RegisterProtocol("https", rt) 67 | return nil 68 | } 69 | 70 | // noDialH2RoundTripper is a RoundTripper which only tries to complete the request 71 | // if there's already has a cached connection to the host. 72 | type noDialH2RoundTripper struct{ t *Transport } 73 | 74 | func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 75 | res, err := rt.t.RoundTrip(req) 76 | if err == ErrNoCachedConn { 77 | return nil, http.ErrSkipAltProtocol 78 | } 79 | return res, err 80 | } 81 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/databuffer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package http2 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "sync" 11 | ) 12 | 13 | // Buffer chunks are allocated from a pool to reduce pressure on GC. 14 | // The maximum wasted space per dataBuffer is 2x the largest size class, 15 | // which happens when the dataBuffer has multiple chunks and there is 16 | // one unread byte in both the first and last chunks. We use a few size 17 | // classes to minimize overheads for servers that typically receive very 18 | // small request bodies. 19 | // 20 | // TODO: Benchmark to determine if the pools are necessary. The GC may have 21 | // improved enough that we can instead allocate chunks like this: 22 | // make([]byte, max(16<<10, expectedBytesRemaining)) 23 | var ( 24 | dataChunkSizeClasses = []int{ 25 | 1 << 10, 26 | 2 << 10, 27 | 4 << 10, 28 | 8 << 10, 29 | 16 << 10, 30 | } 31 | dataChunkPools = [...]sync.Pool{ 32 | {New: func() interface{} { return make([]byte, 1<<10) }}, 33 | {New: func() interface{} { return make([]byte, 2<<10) }}, 34 | {New: func() interface{} { return make([]byte, 4<<10) }}, 35 | {New: func() interface{} { return make([]byte, 8<<10) }}, 36 | {New: func() interface{} { return make([]byte, 16<<10) }}, 37 | } 38 | ) 39 | 40 | func getDataBufferChunk(size int64) []byte { 41 | i := 0 42 | for ; i < len(dataChunkSizeClasses)-1; i++ { 43 | if size <= int64(dataChunkSizeClasses[i]) { 44 | break 45 | } 46 | } 47 | return dataChunkPools[i].Get().([]byte) 48 | } 49 | 50 | func putDataBufferChunk(p []byte) { 51 | for i, n := range dataChunkSizeClasses { 52 | if len(p) == n { 53 | dataChunkPools[i].Put(p) 54 | return 55 | } 56 | } 57 | panic(fmt.Sprintf("unexpected buffer len=%v", len(p))) 58 | } 59 | 60 | // dataBuffer is an io.ReadWriter backed by a list of data chunks. 61 | // Each dataBuffer is used to read DATA frames on a single stream. 62 | // The buffer is divided into chunks so the server can limit the 63 | // total memory used by a single connection without limiting the 64 | // request body size on any single stream. 65 | type dataBuffer struct { 66 | chunks [][]byte 67 | r int // next byte to read is chunks[0][r] 68 | w int // next byte to write is chunks[len(chunks)-1][w] 69 | size int // total buffered bytes 70 | expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0) 71 | } 72 | 73 | var errReadEmpty = errors.New("read from empty dataBuffer") 74 | 75 | // Read copies bytes from the buffer into p. 76 | // It is an error to read when no data is available. 77 | func (b *dataBuffer) Read(p []byte) (int, error) { 78 | if b.size == 0 { 79 | return 0, errReadEmpty 80 | } 81 | var ntotal int 82 | for len(p) > 0 && b.size > 0 { 83 | readFrom := b.bytesFromFirstChunk() 84 | n := copy(p, readFrom) 85 | p = p[n:] 86 | ntotal += n 87 | b.r += n 88 | b.size -= n 89 | // If the first chunk has been consumed, advance to the next chunk. 90 | if b.r == len(b.chunks[0]) { 91 | putDataBufferChunk(b.chunks[0]) 92 | end := len(b.chunks) - 1 93 | copy(b.chunks[:end], b.chunks[1:]) 94 | b.chunks[end] = nil 95 | b.chunks = b.chunks[:end] 96 | b.r = 0 97 | } 98 | } 99 | return ntotal, nil 100 | } 101 | 102 | func (b *dataBuffer) bytesFromFirstChunk() []byte { 103 | if len(b.chunks) == 1 { 104 | return b.chunks[0][b.r:b.w] 105 | } 106 | return b.chunks[0][b.r:] 107 | } 108 | 109 | // Len returns the number of bytes of the unread portion of the buffer. 110 | func (b *dataBuffer) Len() int { 111 | return b.size 112 | } 113 | 114 | // Write appends p to the buffer. 115 | func (b *dataBuffer) Write(p []byte) (int, error) { 116 | ntotal := len(p) 117 | for len(p) > 0 { 118 | // If the last chunk is empty, allocate a new chunk. Try to allocate 119 | // enough to fully copy p plus any additional bytes we expect to 120 | // receive. However, this may allocate less than len(p). 121 | want := int64(len(p)) 122 | if b.expected > want { 123 | want = b.expected 124 | } 125 | chunk := b.lastChunkOrAlloc(want) 126 | n := copy(chunk[b.w:], p) 127 | p = p[n:] 128 | b.w += n 129 | b.size += n 130 | b.expected -= int64(n) 131 | } 132 | return ntotal, nil 133 | } 134 | 135 | func (b *dataBuffer) lastChunkOrAlloc(want int64) []byte { 136 | if len(b.chunks) != 0 { 137 | last := b.chunks[len(b.chunks)-1] 138 | if b.w < len(last) { 139 | return last 140 | } 141 | } 142 | chunk := getDataBufferChunk(want) 143 | b.chunks = append(b.chunks, chunk) 144 | b.w = 0 145 | return chunk 146 | } 147 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package http2 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | ) 11 | 12 | // An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec. 13 | type ErrCode uint32 14 | 15 | const ( 16 | ErrCodeNo ErrCode = 0x0 17 | ErrCodeProtocol ErrCode = 0x1 18 | ErrCodeInternal ErrCode = 0x2 19 | ErrCodeFlowControl ErrCode = 0x3 20 | ErrCodeSettingsTimeout ErrCode = 0x4 21 | ErrCodeStreamClosed ErrCode = 0x5 22 | ErrCodeFrameSize ErrCode = 0x6 23 | ErrCodeRefusedStream ErrCode = 0x7 24 | ErrCodeCancel ErrCode = 0x8 25 | ErrCodeCompression ErrCode = 0x9 26 | ErrCodeConnect ErrCode = 0xa 27 | ErrCodeEnhanceYourCalm ErrCode = 0xb 28 | ErrCodeInadequateSecurity ErrCode = 0xc 29 | ErrCodeHTTP11Required ErrCode = 0xd 30 | ) 31 | 32 | var errCodeName = map[ErrCode]string{ 33 | ErrCodeNo: "NO_ERROR", 34 | ErrCodeProtocol: "PROTOCOL_ERROR", 35 | ErrCodeInternal: "INTERNAL_ERROR", 36 | ErrCodeFlowControl: "FLOW_CONTROL_ERROR", 37 | ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT", 38 | ErrCodeStreamClosed: "STREAM_CLOSED", 39 | ErrCodeFrameSize: "FRAME_SIZE_ERROR", 40 | ErrCodeRefusedStream: "REFUSED_STREAM", 41 | ErrCodeCancel: "CANCEL", 42 | ErrCodeCompression: "COMPRESSION_ERROR", 43 | ErrCodeConnect: "CONNECT_ERROR", 44 | ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM", 45 | ErrCodeInadequateSecurity: "INADEQUATE_SECURITY", 46 | ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED", 47 | } 48 | 49 | func (e ErrCode) String() string { 50 | if s, ok := errCodeName[e]; ok { 51 | return s 52 | } 53 | return fmt.Sprintf("unknown error code 0x%x", uint32(e)) 54 | } 55 | 56 | // ConnectionError is an error that results in the termination of the 57 | // entire connection. 58 | type ConnectionError ErrCode 59 | 60 | func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: %s", ErrCode(e)) } 61 | 62 | // StreamError is an error that only affects one stream within an 63 | // HTTP/2 connection. 64 | type StreamError struct { 65 | StreamID uint32 66 | Code ErrCode 67 | Cause error // optional additional detail 68 | } 69 | 70 | func streamError(id uint32, code ErrCode) StreamError { 71 | return StreamError{StreamID: id, Code: code} 72 | } 73 | 74 | func (e StreamError) Error() string { 75 | if e.Cause != nil { 76 | return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause) 77 | } 78 | return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code) 79 | } 80 | 81 | // 6.9.1 The Flow Control Window 82 | // "If a sender receives a WINDOW_UPDATE that causes a flow control 83 | // window to exceed this maximum it MUST terminate either the stream 84 | // or the connection, as appropriate. For streams, [...]; for the 85 | // connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code." 86 | type goAwayFlowError struct{} 87 | 88 | func (goAwayFlowError) Error() string { return "connection exceeded flow control window size" } 89 | 90 | // connErrorReason wraps a ConnectionError with an informative error about why it occurs. 91 | 92 | // Errors of this type are only returned by the frame parser functions 93 | // and converted into ConnectionError(ErrCodeProtocol). 94 | type connError struct { 95 | Code ErrCode 96 | Reason string 97 | } 98 | 99 | func (e connError) Error() string { 100 | return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason) 101 | } 102 | 103 | type pseudoHeaderError string 104 | 105 | func (e pseudoHeaderError) Error() string { 106 | return fmt.Sprintf("invalid pseudo-header %q", string(e)) 107 | } 108 | 109 | type duplicatePseudoHeaderError string 110 | 111 | func (e duplicatePseudoHeaderError) Error() string { 112 | return fmt.Sprintf("duplicate pseudo-header %q", string(e)) 113 | } 114 | 115 | type headerFieldNameError string 116 | 117 | func (e headerFieldNameError) Error() string { 118 | return fmt.Sprintf("invalid header field name %q", string(e)) 119 | } 120 | 121 | type headerFieldValueError string 122 | 123 | func (e headerFieldValueError) Error() string { 124 | return fmt.Sprintf("invalid header field value %q", string(e)) 125 | } 126 | 127 | var ( 128 | errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers") 129 | errPseudoAfterRegular = errors.New("pseudo header field after regular") 130 | ) 131 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/flow.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Flow control 6 | 7 | package http2 8 | 9 | // flow is the flow control window's size. 10 | type flow struct { 11 | // n is the number of DATA bytes we're allowed to send. 12 | // A flow is kept both on a conn and a per-stream. 13 | n int32 14 | 15 | // conn points to the shared connection-level flow that is 16 | // shared by all streams on that conn. It is nil for the flow 17 | // that's on the conn directly. 18 | conn *flow 19 | } 20 | 21 | func (f *flow) setConnFlow(cf *flow) { f.conn = cf } 22 | 23 | func (f *flow) available() int32 { 24 | n := f.n 25 | if f.conn != nil && f.conn.n < n { 26 | n = f.conn.n 27 | } 28 | return n 29 | } 30 | 31 | func (f *flow) take(n int32) { 32 | if n > f.available() { 33 | panic("internal error: took too much") 34 | } 35 | f.n -= n 36 | if f.conn != nil { 37 | f.conn.n -= n 38 | } 39 | } 40 | 41 | // add adds n bytes (positive or negative) to the flow control window. 42 | // It returns false if the sum would exceed 2^31-1. 43 | func (f *flow) add(n int32) bool { 44 | remain := (1<<31 - 1) - f.n 45 | if n > remain { 46 | return false 47 | } 48 | f.n += n 49 | return true 50 | } 51 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/go16.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.6 6 | 7 | package http2 8 | 9 | import ( 10 | "crypto/tls" 11 | "net/http" 12 | "time" 13 | ) 14 | 15 | func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { 16 | return t1.ExpectContinueTimeout 17 | } 18 | 19 | // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. 20 | func isBadCipher(cipher uint16) bool { 21 | switch cipher { 22 | case tls.TLS_RSA_WITH_RC4_128_SHA, 23 | tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24 | tls.TLS_RSA_WITH_AES_128_CBC_SHA, 25 | tls.TLS_RSA_WITH_AES_256_CBC_SHA, 26 | tls.TLS_RSA_WITH_AES_128_GCM_SHA256, 27 | tls.TLS_RSA_WITH_AES_256_GCM_SHA384, 28 | tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 29 | tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 30 | tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 31 | tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, 32 | tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 33 | tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 34 | tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: 35 | // Reject cipher suites from Appendix A. 36 | // "This list includes those cipher suites that do not 37 | // offer an ephemeral key exchange and those that are 38 | // based on the TLS null, stream or block cipher type" 39 | return true 40 | default: 41 | return false 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/go17.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.7 6 | 7 | package http2 8 | 9 | import ( 10 | "context" 11 | "net" 12 | "net/http" 13 | "net/http/httptrace" 14 | "time" 15 | ) 16 | 17 | type contextContext interface { 18 | context.Context 19 | } 20 | 21 | func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { 22 | ctx, cancel = context.WithCancel(context.Background()) 23 | ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) 24 | if hs := opts.baseConfig(); hs != nil { 25 | ctx = context.WithValue(ctx, http.ServerContextKey, hs) 26 | } 27 | return 28 | } 29 | 30 | func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { 31 | return context.WithCancel(ctx) 32 | } 33 | 34 | func requestWithContext(req *http.Request, ctx contextContext) *http.Request { 35 | return req.WithContext(ctx) 36 | } 37 | 38 | type clientTrace httptrace.ClientTrace 39 | 40 | func reqContext(r *http.Request) context.Context { return r.Context() } 41 | 42 | func (t *Transport) idleConnTimeout() time.Duration { 43 | if t.t1 != nil { 44 | return t.t1.IdleConnTimeout 45 | } 46 | return 0 47 | } 48 | 49 | func setResponseUncompressed(res *http.Response) { res.Uncompressed = true } 50 | 51 | func traceGotConn(req *http.Request, cc *ClientConn) { 52 | trace := httptrace.ContextClientTrace(req.Context()) 53 | if trace == nil || trace.GotConn == nil { 54 | return 55 | } 56 | ci := httptrace.GotConnInfo{Conn: cc.tconn} 57 | cc.mu.Lock() 58 | ci.Reused = cc.nextStreamID > 1 59 | ci.WasIdle = len(cc.streams) == 0 && ci.Reused 60 | if ci.WasIdle && !cc.lastActive.IsZero() { 61 | ci.IdleTime = time.Now().Sub(cc.lastActive) 62 | } 63 | cc.mu.Unlock() 64 | 65 | trace.GotConn(ci) 66 | } 67 | 68 | func traceWroteHeaders(trace *clientTrace) { 69 | if trace != nil && trace.WroteHeaders != nil { 70 | trace.WroteHeaders() 71 | } 72 | } 73 | 74 | func traceGot100Continue(trace *clientTrace) { 75 | if trace != nil && trace.Got100Continue != nil { 76 | trace.Got100Continue() 77 | } 78 | } 79 | 80 | func traceWait100Continue(trace *clientTrace) { 81 | if trace != nil && trace.Wait100Continue != nil { 82 | trace.Wait100Continue() 83 | } 84 | } 85 | 86 | func traceWroteRequest(trace *clientTrace, err error) { 87 | if trace != nil && trace.WroteRequest != nil { 88 | trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) 89 | } 90 | } 91 | 92 | func traceFirstResponseByte(trace *clientTrace) { 93 | if trace != nil && trace.GotFirstResponseByte != nil { 94 | trace.GotFirstResponseByte() 95 | } 96 | } 97 | 98 | func requestTrace(req *http.Request) *clientTrace { 99 | trace := httptrace.ContextClientTrace(req.Context()) 100 | return (*clientTrace)(trace) 101 | } 102 | 103 | // Ping sends a PING frame to the server and waits for the ack. 104 | func (cc *ClientConn) Ping(ctx context.Context) error { 105 | return cc.ping(ctx) 106 | } 107 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/go17_not18.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.7,!go1.8 6 | 7 | package http2 8 | 9 | import "crypto/tls" 10 | 11 | // temporary copy of Go 1.7's private tls.Config.clone: 12 | func cloneTLSConfig(c *tls.Config) *tls.Config { 13 | return &tls.Config{ 14 | Rand: c.Rand, 15 | Time: c.Time, 16 | Certificates: c.Certificates, 17 | NameToCertificate: c.NameToCertificate, 18 | GetCertificate: c.GetCertificate, 19 | RootCAs: c.RootCAs, 20 | NextProtos: c.NextProtos, 21 | ServerName: c.ServerName, 22 | ClientAuth: c.ClientAuth, 23 | ClientCAs: c.ClientCAs, 24 | InsecureSkipVerify: c.InsecureSkipVerify, 25 | CipherSuites: c.CipherSuites, 26 | PreferServerCipherSuites: c.PreferServerCipherSuites, 27 | SessionTicketsDisabled: c.SessionTicketsDisabled, 28 | SessionTicketKey: c.SessionTicketKey, 29 | ClientSessionCache: c.ClientSessionCache, 30 | MinVersion: c.MinVersion, 31 | MaxVersion: c.MaxVersion, 32 | CurvePreferences: c.CurvePreferences, 33 | DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, 34 | Renegotiation: c.Renegotiation, 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/go18.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.8 6 | 7 | package http2 8 | 9 | import ( 10 | "crypto/tls" 11 | "io" 12 | "net/http" 13 | ) 14 | 15 | func cloneTLSConfig(c *tls.Config) *tls.Config { 16 | c2 := c.Clone() 17 | c2.GetClientCertificate = c.GetClientCertificate // golang.org/issue/19264 18 | return c2 19 | } 20 | 21 | var _ http.Pusher = (*responseWriter)(nil) 22 | 23 | // Push implements http.Pusher. 24 | func (w *responseWriter) Push(target string, opts *http.PushOptions) error { 25 | internalOpts := pushOptions{} 26 | if opts != nil { 27 | internalOpts.Method = opts.Method 28 | internalOpts.Header = opts.Header 29 | } 30 | return w.push(target, internalOpts) 31 | } 32 | 33 | func configureServer18(h1 *http.Server, h2 *Server) error { 34 | if h2.IdleTimeout == 0 { 35 | if h1.IdleTimeout != 0 { 36 | h2.IdleTimeout = h1.IdleTimeout 37 | } else { 38 | h2.IdleTimeout = h1.ReadTimeout 39 | } 40 | } 41 | return nil 42 | } 43 | 44 | func shouldLogPanic(panicValue interface{}) bool { 45 | return panicValue != nil && panicValue != http.ErrAbortHandler 46 | } 47 | 48 | func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { 49 | return req.GetBody 50 | } 51 | 52 | func reqBodyIsNoBody(body io.ReadCloser) bool { 53 | return body == http.NoBody 54 | } 55 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/gotrack.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Defensive debug-only utility to track that functions run on the 6 | // goroutine that they're supposed to. 7 | 8 | package http2 9 | 10 | import ( 11 | "bytes" 12 | "errors" 13 | "fmt" 14 | "os" 15 | "runtime" 16 | "strconv" 17 | "sync" 18 | ) 19 | 20 | var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1" 21 | 22 | type goroutineLock uint64 23 | 24 | func newGoroutineLock() goroutineLock { 25 | if !DebugGoroutines { 26 | return 0 27 | } 28 | return goroutineLock(curGoroutineID()) 29 | } 30 | 31 | func (g goroutineLock) check() { 32 | if !DebugGoroutines { 33 | return 34 | } 35 | if curGoroutineID() != uint64(g) { 36 | panic("running on the wrong goroutine") 37 | } 38 | } 39 | 40 | func (g goroutineLock) checkNotOn() { 41 | if !DebugGoroutines { 42 | return 43 | } 44 | if curGoroutineID() == uint64(g) { 45 | panic("running on the wrong goroutine") 46 | } 47 | } 48 | 49 | var goroutineSpace = []byte("goroutine ") 50 | 51 | func curGoroutineID() uint64 { 52 | bp := littleBuf.Get().(*[]byte) 53 | defer littleBuf.Put(bp) 54 | b := *bp 55 | b = b[:runtime.Stack(b, false)] 56 | // Parse the 4707 out of "goroutine 4707 [" 57 | b = bytes.TrimPrefix(b, goroutineSpace) 58 | i := bytes.IndexByte(b, ' ') 59 | if i < 0 { 60 | panic(fmt.Sprintf("No space found in %q", b)) 61 | } 62 | b = b[:i] 63 | n, err := parseUintBytes(b, 10, 64) 64 | if err != nil { 65 | panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) 66 | } 67 | return n 68 | } 69 | 70 | var littleBuf = sync.Pool{ 71 | New: func() interface{} { 72 | buf := make([]byte, 64) 73 | return &buf 74 | }, 75 | } 76 | 77 | // parseUintBytes is like strconv.ParseUint, but using a []byte. 78 | func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { 79 | var cutoff, maxVal uint64 80 | 81 | if bitSize == 0 { 82 | bitSize = int(strconv.IntSize) 83 | } 84 | 85 | s0 := s 86 | switch { 87 | case len(s) < 1: 88 | err = strconv.ErrSyntax 89 | goto Error 90 | 91 | case 2 <= base && base <= 36: 92 | // valid base; nothing to do 93 | 94 | case base == 0: 95 | // Look for octal, hex prefix. 96 | switch { 97 | case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): 98 | base = 16 99 | s = s[2:] 100 | if len(s) < 1 { 101 | err = strconv.ErrSyntax 102 | goto Error 103 | } 104 | case s[0] == '0': 105 | base = 8 106 | default: 107 | base = 10 108 | } 109 | 110 | default: 111 | err = errors.New("invalid base " + strconv.Itoa(base)) 112 | goto Error 113 | } 114 | 115 | n = 0 116 | cutoff = cutoff64(base) 117 | maxVal = 1<= base { 135 | n = 0 136 | err = strconv.ErrSyntax 137 | goto Error 138 | } 139 | 140 | if n >= cutoff { 141 | // n*base overflows 142 | n = 1<<64 - 1 143 | err = strconv.ErrRange 144 | goto Error 145 | } 146 | n *= uint64(base) 147 | 148 | n1 := n + uint64(v) 149 | if n1 < n || n1 > maxVal { 150 | // n+v overflows 151 | n = 1<<64 - 1 152 | err = strconv.ErrRange 153 | goto Error 154 | } 155 | n = n1 156 | } 157 | 158 | return n, nil 159 | 160 | Error: 161 | return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} 162 | } 163 | 164 | // Return the first number n such that n*base >= 1<<64. 165 | func cutoff64(base int) uint64 { 166 | if base < 2 { 167 | return 0 168 | } 169 | return (1<<64-1)/uint64(base) + 1 170 | } 171 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/headermap.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package http2 6 | 7 | import ( 8 | "net/http" 9 | "strings" 10 | ) 11 | 12 | var ( 13 | commonLowerHeader = map[string]string{} // Go-Canonical-Case -> lower-case 14 | commonCanonHeader = map[string]string{} // lower-case -> Go-Canonical-Case 15 | ) 16 | 17 | func init() { 18 | for _, v := range []string{ 19 | "accept", 20 | "accept-charset", 21 | "accept-encoding", 22 | "accept-language", 23 | "accept-ranges", 24 | "age", 25 | "access-control-allow-origin", 26 | "allow", 27 | "authorization", 28 | "cache-control", 29 | "content-disposition", 30 | "content-encoding", 31 | "content-language", 32 | "content-length", 33 | "content-location", 34 | "content-range", 35 | "content-type", 36 | "cookie", 37 | "date", 38 | "etag", 39 | "expect", 40 | "expires", 41 | "from", 42 | "host", 43 | "if-match", 44 | "if-modified-since", 45 | "if-none-match", 46 | "if-unmodified-since", 47 | "last-modified", 48 | "link", 49 | "location", 50 | "max-forwards", 51 | "proxy-authenticate", 52 | "proxy-authorization", 53 | "range", 54 | "referer", 55 | "refresh", 56 | "retry-after", 57 | "server", 58 | "set-cookie", 59 | "strict-transport-security", 60 | "trailer", 61 | "transfer-encoding", 62 | "user-agent", 63 | "vary", 64 | "via", 65 | "www-authenticate", 66 | } { 67 | chk := http.CanonicalHeaderKey(v) 68 | commonLowerHeader[chk] = v 69 | commonCanonHeader[v] = chk 70 | } 71 | } 72 | 73 | func lowerHeader(v string) string { 74 | if s, ok := commonLowerHeader[v]; ok { 75 | return s 76 | } 77 | return strings.ToLower(v) 78 | } 79 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/not_go16.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.6 6 | 7 | package http2 8 | 9 | import ( 10 | "crypto/tls" 11 | "net/http" 12 | "time" 13 | ) 14 | 15 | func configureTransport(t1 *http.Transport) (*Transport, error) { 16 | return nil, errTransportVersion 17 | } 18 | 19 | func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { 20 | return 0 21 | 22 | } 23 | 24 | // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. 25 | func isBadCipher(cipher uint16) bool { 26 | switch cipher { 27 | case tls.TLS_RSA_WITH_RC4_128_SHA, 28 | tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 29 | tls.TLS_RSA_WITH_AES_128_CBC_SHA, 30 | tls.TLS_RSA_WITH_AES_256_CBC_SHA, 31 | tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 32 | tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 33 | tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 34 | tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, 35 | tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 36 | tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 37 | tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: 38 | // Reject cipher suites from Appendix A. 39 | // "This list includes those cipher suites that do not 40 | // offer an ephemeral key exchange and those that are 41 | // based on the TLS null, stream or block cipher type" 42 | return true 43 | default: 44 | return false 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/not_go17.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.7 6 | 7 | package http2 8 | 9 | import ( 10 | "crypto/tls" 11 | "net" 12 | "net/http" 13 | "time" 14 | ) 15 | 16 | type contextContext interface { 17 | Done() <-chan struct{} 18 | Err() error 19 | } 20 | 21 | type fakeContext struct{} 22 | 23 | func (fakeContext) Done() <-chan struct{} { return nil } 24 | func (fakeContext) Err() error { panic("should not be called") } 25 | 26 | func reqContext(r *http.Request) fakeContext { 27 | return fakeContext{} 28 | } 29 | 30 | func setResponseUncompressed(res *http.Response) { 31 | // Nothing. 32 | } 33 | 34 | type clientTrace struct{} 35 | 36 | func requestTrace(*http.Request) *clientTrace { return nil } 37 | func traceGotConn(*http.Request, *ClientConn) {} 38 | func traceFirstResponseByte(*clientTrace) {} 39 | func traceWroteHeaders(*clientTrace) {} 40 | func traceWroteRequest(*clientTrace, error) {} 41 | func traceGot100Continue(trace *clientTrace) {} 42 | func traceWait100Continue(trace *clientTrace) {} 43 | 44 | func nop() {} 45 | 46 | func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { 47 | return nil, nop 48 | } 49 | 50 | func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { 51 | return ctx, nop 52 | } 53 | 54 | func requestWithContext(req *http.Request, ctx contextContext) *http.Request { 55 | return req 56 | } 57 | 58 | // temporary copy of Go 1.6's private tls.Config.clone: 59 | func cloneTLSConfig(c *tls.Config) *tls.Config { 60 | return &tls.Config{ 61 | Rand: c.Rand, 62 | Time: c.Time, 63 | Certificates: c.Certificates, 64 | NameToCertificate: c.NameToCertificate, 65 | GetCertificate: c.GetCertificate, 66 | RootCAs: c.RootCAs, 67 | NextProtos: c.NextProtos, 68 | ServerName: c.ServerName, 69 | ClientAuth: c.ClientAuth, 70 | ClientCAs: c.ClientCAs, 71 | InsecureSkipVerify: c.InsecureSkipVerify, 72 | CipherSuites: c.CipherSuites, 73 | PreferServerCipherSuites: c.PreferServerCipherSuites, 74 | SessionTicketsDisabled: c.SessionTicketsDisabled, 75 | SessionTicketKey: c.SessionTicketKey, 76 | ClientSessionCache: c.ClientSessionCache, 77 | MinVersion: c.MinVersion, 78 | MaxVersion: c.MaxVersion, 79 | CurvePreferences: c.CurvePreferences, 80 | } 81 | } 82 | 83 | func (cc *ClientConn) Ping(ctx contextContext) error { 84 | return cc.ping(ctx) 85 | } 86 | 87 | func (t *Transport) idleConnTimeout() time.Duration { return 0 } 88 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/not_go18.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.8 6 | 7 | package http2 8 | 9 | import ( 10 | "io" 11 | "net/http" 12 | ) 13 | 14 | func configureServer18(h1 *http.Server, h2 *Server) error { 15 | // No IdleTimeout to sync prior to Go 1.8. 16 | return nil 17 | } 18 | 19 | func shouldLogPanic(panicValue interface{}) bool { 20 | return panicValue != nil 21 | } 22 | 23 | func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { 24 | return nil 25 | } 26 | 27 | func reqBodyIsNoBody(io.ReadCloser) bool { return false } 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/pipe.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package http2 6 | 7 | import ( 8 | "errors" 9 | "io" 10 | "sync" 11 | ) 12 | 13 | // pipe is a goroutine-safe io.Reader/io.Writer pair. It's like 14 | // io.Pipe except there are no PipeReader/PipeWriter halves, and the 15 | // underlying buffer is an interface. (io.Pipe is always unbuffered) 16 | type pipe struct { 17 | mu sync.Mutex 18 | c sync.Cond // c.L lazily initialized to &p.mu 19 | b pipeBuffer 20 | err error // read error once empty. non-nil means closed. 21 | breakErr error // immediate read error (caller doesn't see rest of b) 22 | donec chan struct{} // closed on error 23 | readFn func() // optional code to run in Read before error 24 | } 25 | 26 | type pipeBuffer interface { 27 | Len() int 28 | io.Writer 29 | io.Reader 30 | } 31 | 32 | func (p *pipe) Len() int { 33 | p.mu.Lock() 34 | defer p.mu.Unlock() 35 | return p.b.Len() 36 | } 37 | 38 | // Read waits until data is available and copies bytes 39 | // from the buffer into p. 40 | func (p *pipe) Read(d []byte) (n int, err error) { 41 | p.mu.Lock() 42 | defer p.mu.Unlock() 43 | if p.c.L == nil { 44 | p.c.L = &p.mu 45 | } 46 | for { 47 | if p.breakErr != nil { 48 | return 0, p.breakErr 49 | } 50 | if p.b.Len() > 0 { 51 | return p.b.Read(d) 52 | } 53 | if p.err != nil { 54 | if p.readFn != nil { 55 | p.readFn() // e.g. copy trailers 56 | p.readFn = nil // not sticky like p.err 57 | } 58 | return 0, p.err 59 | } 60 | p.c.Wait() 61 | } 62 | } 63 | 64 | var errClosedPipeWrite = errors.New("write on closed buffer") 65 | 66 | // Write copies bytes from p into the buffer and wakes a reader. 67 | // It is an error to write more data than the buffer can hold. 68 | func (p *pipe) Write(d []byte) (n int, err error) { 69 | p.mu.Lock() 70 | defer p.mu.Unlock() 71 | if p.c.L == nil { 72 | p.c.L = &p.mu 73 | } 74 | defer p.c.Signal() 75 | if p.err != nil { 76 | return 0, errClosedPipeWrite 77 | } 78 | return p.b.Write(d) 79 | } 80 | 81 | // CloseWithError causes the next Read (waking up a current blocked 82 | // Read if needed) to return the provided err after all data has been 83 | // read. 84 | // 85 | // The error must be non-nil. 86 | func (p *pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) } 87 | 88 | // BreakWithError causes the next Read (waking up a current blocked 89 | // Read if needed) to return the provided err immediately, without 90 | // waiting for unread data. 91 | func (p *pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) } 92 | 93 | // closeWithErrorAndCode is like CloseWithError but also sets some code to run 94 | // in the caller's goroutine before returning the error. 95 | func (p *pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) } 96 | 97 | func (p *pipe) closeWithError(dst *error, err error, fn func()) { 98 | if err == nil { 99 | panic("err must be non-nil") 100 | } 101 | p.mu.Lock() 102 | defer p.mu.Unlock() 103 | if p.c.L == nil { 104 | p.c.L = &p.mu 105 | } 106 | defer p.c.Signal() 107 | if *dst != nil { 108 | // Already been done. 109 | return 110 | } 111 | p.readFn = fn 112 | *dst = err 113 | p.closeDoneLocked() 114 | } 115 | 116 | // requires p.mu be held. 117 | func (p *pipe) closeDoneLocked() { 118 | if p.donec == nil { 119 | return 120 | } 121 | // Close if unclosed. This isn't racy since we always 122 | // hold p.mu while closing. 123 | select { 124 | case <-p.donec: 125 | default: 126 | close(p.donec) 127 | } 128 | } 129 | 130 | // Err returns the error (if any) first set by BreakWithError or CloseWithError. 131 | func (p *pipe) Err() error { 132 | p.mu.Lock() 133 | defer p.mu.Unlock() 134 | if p.breakErr != nil { 135 | return p.breakErr 136 | } 137 | return p.err 138 | } 139 | 140 | // Done returns a channel which is closed if and when this pipe is closed 141 | // with CloseWithError. 142 | func (p *pipe) Done() <-chan struct{} { 143 | p.mu.Lock() 144 | defer p.mu.Unlock() 145 | if p.donec == nil { 146 | p.donec = make(chan struct{}) 147 | if p.err != nil || p.breakErr != nil { 148 | // Already hit an error. 149 | p.closeDoneLocked() 150 | } 151 | } 152 | return p.donec 153 | } 154 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/http2/writesched_random.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package http2 6 | 7 | import "math" 8 | 9 | // NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2 10 | // priorities. Control frames like SETTINGS and PING are written before DATA 11 | // frames, but if no control frames are queued and multiple streams have queued 12 | // HEADERS or DATA frames, Pop selects a ready stream arbitrarily. 13 | func NewRandomWriteScheduler() WriteScheduler { 14 | return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} 15 | } 16 | 17 | type randomWriteScheduler struct { 18 | // zero are frames not associated with a specific stream. 19 | zero writeQueue 20 | 21 | // sq contains the stream-specific queues, keyed by stream ID. 22 | // When a stream is idle or closed, it's deleted from the map. 23 | sq map[uint32]*writeQueue 24 | 25 | // pool of empty queues for reuse. 26 | queuePool writeQueuePool 27 | } 28 | 29 | func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { 30 | // no-op: idle streams are not tracked 31 | } 32 | 33 | func (ws *randomWriteScheduler) CloseStream(streamID uint32) { 34 | q, ok := ws.sq[streamID] 35 | if !ok { 36 | return 37 | } 38 | delete(ws.sq, streamID) 39 | ws.queuePool.put(q) 40 | } 41 | 42 | func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { 43 | // no-op: priorities are ignored 44 | } 45 | 46 | func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) { 47 | id := wr.StreamID() 48 | if id == 0 { 49 | ws.zero.push(wr) 50 | return 51 | } 52 | q, ok := ws.sq[id] 53 | if !ok { 54 | q = ws.queuePool.get() 55 | ws.sq[id] = q 56 | } 57 | q.push(wr) 58 | } 59 | 60 | func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) { 61 | // Control frames first. 62 | if !ws.zero.empty() { 63 | return ws.zero.shift(), true 64 | } 65 | // Iterate over all non-idle streams until finding one that can be consumed. 66 | for _, q := range ws.sq { 67 | if wr, ok := q.consume(math.MaxInt32); ok { 68 | return wr, true 69 | } 70 | } 71 | return FrameWriteRequest{}, false 72 | } 73 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/idna/trie.go: -------------------------------------------------------------------------------- 1 | // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. 2 | 3 | // Copyright 2016 The Go Authors. All rights reserved. 4 | // Use of this source code is governed by a BSD-style 5 | // license that can be found in the LICENSE file. 6 | 7 | package idna 8 | 9 | // appendMapping appends the mapping for the respective rune. isMapped must be 10 | // true. A mapping is a categorization of a rune as defined in UTS #46. 11 | func (c info) appendMapping(b []byte, s string) []byte { 12 | index := int(c >> indexShift) 13 | if c&xorBit == 0 { 14 | s := mappings[index:] 15 | return append(b, s[1:s[0]+1]...) 16 | } 17 | b = append(b, s...) 18 | if c&inlineXOR == inlineXOR { 19 | // TODO: support and handle two-byte inline masks 20 | b[len(b)-1] ^= byte(index) 21 | } else { 22 | for p := len(b) - int(xorData[index]); p < len(b); p++ { 23 | index++ 24 | b[p] ^= xorData[index] 25 | } 26 | } 27 | return b 28 | } 29 | 30 | // Sparse block handling code. 31 | 32 | type valueRange struct { 33 | value uint16 // header: value:stride 34 | lo, hi byte // header: lo:n 35 | } 36 | 37 | type sparseBlocks struct { 38 | values []valueRange 39 | offset []uint16 40 | } 41 | 42 | var idnaSparse = sparseBlocks{ 43 | values: idnaSparseValues[:], 44 | offset: idnaSparseOffset[:], 45 | } 46 | 47 | // Don't use newIdnaTrie to avoid unconditional linking in of the table. 48 | var trie = &idnaTrie{} 49 | 50 | // lookup determines the type of block n and looks up the value for b. 51 | // For n < t.cutoff, the block is a simple lookup table. Otherwise, the block 52 | // is a list of ranges with an accompanying value. Given a matching range r, 53 | // the value for b is by r.value + (b - r.lo) * stride. 54 | func (t *sparseBlocks) lookup(n uint32, b byte) uint16 { 55 | offset := t.offset[n] 56 | header := t.values[offset] 57 | lo := offset + 1 58 | hi := lo + uint16(header.lo) 59 | for lo < hi { 60 | m := lo + (hi-lo)/2 61 | r := t.values[m] 62 | if r.lo <= b && b <= r.hi { 63 | return r.value + uint16(b-r.lo)*header.value 64 | } 65 | if b < r.lo { 66 | hi = m 67 | } else { 68 | lo = m + 1 69 | } 70 | } 71 | return 0 72 | } 73 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/idna/trieval.go: -------------------------------------------------------------------------------- 1 | // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. 2 | 3 | package idna 4 | 5 | // This file contains definitions for interpreting the trie value of the idna 6 | // trie generated by "go run gen*.go". It is shared by both the generator 7 | // program and the resultant package. Sharing is achieved by the generator 8 | // copying gen_trieval.go to trieval.go and changing what's above this comment. 9 | 10 | // info holds information from the IDNA mapping table for a single rune. It is 11 | // the value returned by a trie lookup. In most cases, all information fits in 12 | // a 16-bit value. For mappings, this value may contain an index into a slice 13 | // with the mapped string. Such mappings can consist of the actual mapped value 14 | // or an XOR pattern to be applied to the bytes of the UTF8 encoding of the 15 | // input rune. This technique is used by the cases packages and reduces the 16 | // table size significantly. 17 | // 18 | // The per-rune values have the following format: 19 | // 20 | // if mapped { 21 | // if inlinedXOR { 22 | // 15..13 inline XOR marker 23 | // 12..11 unused 24 | // 10..3 inline XOR mask 25 | // } else { 26 | // 15..3 index into xor or mapping table 27 | // } 28 | // } else { 29 | // 15..13 unused 30 | // 12 modifier (including virama) 31 | // 11 virama modifier 32 | // 10..8 joining type 33 | // 7..3 category type 34 | // } 35 | // 2 use xor pattern 36 | // 1..0 mapped category 37 | // 38 | // See the definitions below for a more detailed description of the various 39 | // bits. 40 | type info uint16 41 | 42 | const ( 43 | catSmallMask = 0x3 44 | catBigMask = 0xF8 45 | indexShift = 3 46 | xorBit = 0x4 // interpret the index as an xor pattern 47 | inlineXOR = 0xE000 // These bits are set if the XOR pattern is inlined. 48 | 49 | joinShift = 8 50 | joinMask = 0x07 51 | 52 | viramaModifier = 0x0800 53 | modifier = 0x1000 54 | ) 55 | 56 | // A category corresponds to a category defined in the IDNA mapping table. 57 | type category uint16 58 | 59 | const ( 60 | unknown category = 0 // not defined currently in unicode. 61 | mapped category = 1 62 | disallowedSTD3Mapped category = 2 63 | deviation category = 3 64 | ) 65 | 66 | const ( 67 | valid category = 0x08 68 | validNV8 category = 0x18 69 | validXV8 category = 0x28 70 | disallowed category = 0x40 71 | disallowedSTD3Valid category = 0x80 72 | ignored category = 0xC0 73 | ) 74 | 75 | // join types and additional rune information 76 | const ( 77 | joiningL = (iota + 1) 78 | joiningD 79 | joiningT 80 | joiningR 81 | 82 | //the following types are derived during processing 83 | joinZWJ 84 | joinZWNJ 85 | joinVirama 86 | numJoinTypes 87 | ) 88 | 89 | func (c info) isMapped() bool { 90 | return c&0x3 != 0 91 | } 92 | 93 | func (c info) category() category { 94 | small := c & catSmallMask 95 | if small != 0 { 96 | return category(small) 97 | } 98 | return category(c & catBigMask) 99 | } 100 | 101 | func (c info) joinType() info { 102 | if c.isMapped() { 103 | return 0 104 | } 105 | return (c >> joinShift) & joinMask 106 | } 107 | 108 | func (c info) isModifier() bool { 109 | return c&(modifier|catSmallMask) == modifier 110 | } 111 | 112 | func (c info) isViramaModifier() bool { 113 | return c&(viramaModifier|catSmallMask) == viramaModifier 114 | } 115 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/bidi/gen.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build ignore 6 | 7 | package main 8 | 9 | import ( 10 | "flag" 11 | "log" 12 | 13 | "golang.org/x/text/internal/gen" 14 | "golang.org/x/text/internal/triegen" 15 | "golang.org/x/text/internal/ucd" 16 | ) 17 | 18 | var outputFile = flag.String("out", "tables.go", "output file") 19 | 20 | func main() { 21 | gen.Init() 22 | gen.Repackage("gen_trieval.go", "trieval.go", "bidi") 23 | gen.Repackage("gen_ranges.go", "ranges_test.go", "bidi") 24 | 25 | genTables() 26 | } 27 | 28 | // bidiClass names and codes taken from class "bc" in 29 | // http://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt 30 | var bidiClass = map[string]Class{ 31 | "AL": AL, // ArabicLetter 32 | "AN": AN, // ArabicNumber 33 | "B": B, // ParagraphSeparator 34 | "BN": BN, // BoundaryNeutral 35 | "CS": CS, // CommonSeparator 36 | "EN": EN, // EuropeanNumber 37 | "ES": ES, // EuropeanSeparator 38 | "ET": ET, // EuropeanTerminator 39 | "L": L, // LeftToRight 40 | "NSM": NSM, // NonspacingMark 41 | "ON": ON, // OtherNeutral 42 | "R": R, // RightToLeft 43 | "S": S, // SegmentSeparator 44 | "WS": WS, // WhiteSpace 45 | 46 | "FSI": Control, 47 | "PDF": Control, 48 | "PDI": Control, 49 | "LRE": Control, 50 | "LRI": Control, 51 | "LRO": Control, 52 | "RLE": Control, 53 | "RLI": Control, 54 | "RLO": Control, 55 | } 56 | 57 | func genTables() { 58 | if numClass > 0x0F { 59 | log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass) 60 | } 61 | w := gen.NewCodeWriter() 62 | defer w.WriteGoFile(*outputFile, "bidi") 63 | 64 | gen.WriteUnicodeVersion(w) 65 | 66 | t := triegen.NewTrie("bidi") 67 | 68 | // Build data about bracket mapping. These bits need to be or-ed with 69 | // any other bits. 70 | orMask := map[rune]uint64{} 71 | 72 | xorMap := map[rune]int{} 73 | xorMasks := []rune{0} // First value is no-op. 74 | 75 | ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) { 76 | r1 := p.Rune(0) 77 | r2 := p.Rune(1) 78 | xor := r1 ^ r2 79 | if _, ok := xorMap[xor]; !ok { 80 | xorMap[xor] = len(xorMasks) 81 | xorMasks = append(xorMasks, xor) 82 | } 83 | entry := uint64(xorMap[xor]) << xorMaskShift 84 | switch p.String(2) { 85 | case "o": 86 | entry |= openMask 87 | case "c", "n": 88 | default: 89 | log.Fatalf("Unknown bracket class %q.", p.String(2)) 90 | } 91 | orMask[r1] = entry 92 | }) 93 | 94 | w.WriteComment(` 95 | xorMasks contains masks to be xor-ed with brackets to get the reverse 96 | version.`) 97 | w.WriteVar("xorMasks", xorMasks) 98 | 99 | done := map[rune]bool{} 100 | 101 | insert := func(r rune, c Class) { 102 | if !done[r] { 103 | t.Insert(r, orMask[r]|uint64(c)) 104 | done[r] = true 105 | } 106 | } 107 | 108 | // Insert the derived BiDi properties. 109 | ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) { 110 | r := p.Rune(0) 111 | class, ok := bidiClass[p.String(1)] 112 | if !ok { 113 | log.Fatalf("%U: Unknown BiDi class %q", r, p.String(1)) 114 | } 115 | insert(r, class) 116 | }) 117 | visitDefaults(insert) 118 | 119 | // TODO: use sparse blocks. This would reduce table size considerably 120 | // from the looks of it. 121 | 122 | sz, err := t.Gen(w) 123 | if err != nil { 124 | log.Fatal(err) 125 | } 126 | w.Size += sz 127 | } 128 | 129 | // dummy values to make methods in gen_common compile. The real versions 130 | // will be generated by this file to tables.go. 131 | var ( 132 | xorMasks []rune 133 | ) 134 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/bidi/gen_ranges.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build ignore 6 | 7 | package main 8 | 9 | import ( 10 | "unicode" 11 | 12 | "golang.org/x/text/internal/gen" 13 | "golang.org/x/text/internal/ucd" 14 | "golang.org/x/text/unicode/rangetable" 15 | ) 16 | 17 | // These tables are hand-extracted from: 18 | // http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedBidiClass.txt 19 | func visitDefaults(fn func(r rune, c Class)) { 20 | // first write default values for ranges listed above. 21 | visitRunes(fn, AL, []rune{ 22 | 0x0600, 0x07BF, // Arabic 23 | 0x08A0, 0x08FF, // Arabic Extended-A 24 | 0xFB50, 0xFDCF, // Arabic Presentation Forms 25 | 0xFDF0, 0xFDFF, 26 | 0xFE70, 0xFEFF, 27 | 0x0001EE00, 0x0001EEFF, // Arabic Mathematical Alpha Symbols 28 | }) 29 | visitRunes(fn, R, []rune{ 30 | 0x0590, 0x05FF, // Hebrew 31 | 0x07C0, 0x089F, // Nko et al. 32 | 0xFB1D, 0xFB4F, 33 | 0x00010800, 0x00010FFF, // Cypriot Syllabary et. al. 34 | 0x0001E800, 0x0001EDFF, 35 | 0x0001EF00, 0x0001EFFF, 36 | }) 37 | visitRunes(fn, ET, []rune{ // European Terminator 38 | 0x20A0, 0x20Cf, // Currency symbols 39 | }) 40 | rangetable.Visit(unicode.Noncharacter_Code_Point, func(r rune) { 41 | fn(r, BN) // Boundary Neutral 42 | }) 43 | ucd.Parse(gen.OpenUCDFile("DerivedCoreProperties.txt"), func(p *ucd.Parser) { 44 | if p.String(1) == "Default_Ignorable_Code_Point" { 45 | fn(p.Rune(0), BN) // Boundary Neutral 46 | } 47 | }) 48 | } 49 | 50 | func visitRunes(fn func(r rune, c Class), c Class, runes []rune) { 51 | for i := 0; i < len(runes); i += 2 { 52 | lo, hi := runes[i], runes[i+1] 53 | for j := lo; j <= hi; j++ { 54 | fn(j, c) 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/bidi/gen_trieval.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build ignore 6 | 7 | package main 8 | 9 | // Class is the Unicode BiDi class. Each rune has a single class. 10 | type Class uint 11 | 12 | const ( 13 | L Class = iota // LeftToRight 14 | R // RightToLeft 15 | EN // EuropeanNumber 16 | ES // EuropeanSeparator 17 | ET // EuropeanTerminator 18 | AN // ArabicNumber 19 | CS // CommonSeparator 20 | B // ParagraphSeparator 21 | S // SegmentSeparator 22 | WS // WhiteSpace 23 | ON // OtherNeutral 24 | BN // BoundaryNeutral 25 | NSM // NonspacingMark 26 | AL // ArabicLetter 27 | Control // Control LRO - PDI 28 | 29 | numClass 30 | 31 | LRO // LeftToRightOverride 32 | RLO // RightToLeftOverride 33 | LRE // LeftToRightEmbedding 34 | RLE // RightToLeftEmbedding 35 | PDF // PopDirectionalFormat 36 | LRI // LeftToRightIsolate 37 | RLI // RightToLeftIsolate 38 | FSI // FirstStrongIsolate 39 | PDI // PopDirectionalIsolate 40 | 41 | unknownClass = ^Class(0) 42 | ) 43 | 44 | var controlToClass = map[rune]Class{ 45 | 0x202D: LRO, // LeftToRightOverride, 46 | 0x202E: RLO, // RightToLeftOverride, 47 | 0x202A: LRE, // LeftToRightEmbedding, 48 | 0x202B: RLE, // RightToLeftEmbedding, 49 | 0x202C: PDF, // PopDirectionalFormat, 50 | 0x2066: LRI, // LeftToRightIsolate, 51 | 0x2067: RLI, // RightToLeftIsolate, 52 | 0x2068: FSI, // FirstStrongIsolate, 53 | 0x2069: PDI, // PopDirectionalIsolate, 54 | } 55 | 56 | // A trie entry has the following bits: 57 | // 7..5 XOR mask for brackets 58 | // 4 1: Bracket open, 0: Bracket close 59 | // 3..0 Class type 60 | 61 | const ( 62 | openMask = 0x10 63 | xorMaskShift = 5 64 | ) 65 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/bidi/trieval.go: -------------------------------------------------------------------------------- 1 | // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. 2 | 3 | package bidi 4 | 5 | // Class is the Unicode BiDi class. Each rune has a single class. 6 | type Class uint 7 | 8 | const ( 9 | L Class = iota // LeftToRight 10 | R // RightToLeft 11 | EN // EuropeanNumber 12 | ES // EuropeanSeparator 13 | ET // EuropeanTerminator 14 | AN // ArabicNumber 15 | CS // CommonSeparator 16 | B // ParagraphSeparator 17 | S // SegmentSeparator 18 | WS // WhiteSpace 19 | ON // OtherNeutral 20 | BN // BoundaryNeutral 21 | NSM // NonspacingMark 22 | AL // ArabicLetter 23 | Control // Control LRO - PDI 24 | 25 | numClass 26 | 27 | LRO // LeftToRightOverride 28 | RLO // RightToLeftOverride 29 | LRE // LeftToRightEmbedding 30 | RLE // RightToLeftEmbedding 31 | PDF // PopDirectionalFormat 32 | LRI // LeftToRightIsolate 33 | RLI // RightToLeftIsolate 34 | FSI // FirstStrongIsolate 35 | PDI // PopDirectionalIsolate 36 | 37 | unknownClass = ^Class(0) 38 | ) 39 | 40 | var controlToClass = map[rune]Class{ 41 | 0x202D: LRO, // LeftToRightOverride, 42 | 0x202E: RLO, // RightToLeftOverride, 43 | 0x202A: LRE, // LeftToRightEmbedding, 44 | 0x202B: RLE, // RightToLeftEmbedding, 45 | 0x202C: PDF, // PopDirectionalFormat, 46 | 0x2066: LRI, // LeftToRightIsolate, 47 | 0x2067: RLI, // RightToLeftIsolate, 48 | 0x2068: FSI, // FirstStrongIsolate, 49 | 0x2069: PDI, // PopDirectionalIsolate, 50 | } 51 | 52 | // A trie entry has the following bits: 53 | // 7..5 XOR mask for brackets 54 | // 4 1: Bracket open, 0: Bracket close 55 | // 3..0 Class type 56 | 57 | const ( 58 | openMask = 0x10 59 | xorMaskShift = 5 60 | ) 61 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/norm/input.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package norm 6 | 7 | import "unicode/utf8" 8 | 9 | type input struct { 10 | str string 11 | bytes []byte 12 | } 13 | 14 | func inputBytes(str []byte) input { 15 | return input{bytes: str} 16 | } 17 | 18 | func inputString(str string) input { 19 | return input{str: str} 20 | } 21 | 22 | func (in *input) setBytes(str []byte) { 23 | in.str = "" 24 | in.bytes = str 25 | } 26 | 27 | func (in *input) setString(str string) { 28 | in.str = str 29 | in.bytes = nil 30 | } 31 | 32 | func (in *input) _byte(p int) byte { 33 | if in.bytes == nil { 34 | return in.str[p] 35 | } 36 | return in.bytes[p] 37 | } 38 | 39 | func (in *input) skipASCII(p, max int) int { 40 | if in.bytes == nil { 41 | for ; p < max && in.str[p] < utf8.RuneSelf; p++ { 42 | } 43 | } else { 44 | for ; p < max && in.bytes[p] < utf8.RuneSelf; p++ { 45 | } 46 | } 47 | return p 48 | } 49 | 50 | func (in *input) skipContinuationBytes(p int) int { 51 | if in.bytes == nil { 52 | for ; p < len(in.str) && !utf8.RuneStart(in.str[p]); p++ { 53 | } 54 | } else { 55 | for ; p < len(in.bytes) && !utf8.RuneStart(in.bytes[p]); p++ { 56 | } 57 | } 58 | return p 59 | } 60 | 61 | func (in *input) appendSlice(buf []byte, b, e int) []byte { 62 | if in.bytes != nil { 63 | return append(buf, in.bytes[b:e]...) 64 | } 65 | for i := b; i < e; i++ { 66 | buf = append(buf, in.str[i]) 67 | } 68 | return buf 69 | } 70 | 71 | func (in *input) copySlice(buf []byte, b, e int) int { 72 | if in.bytes == nil { 73 | return copy(buf, in.str[b:e]) 74 | } 75 | return copy(buf, in.bytes[b:e]) 76 | } 77 | 78 | func (in *input) charinfoNFC(p int) (uint16, int) { 79 | if in.bytes == nil { 80 | return nfcData.lookupString(in.str[p:]) 81 | } 82 | return nfcData.lookup(in.bytes[p:]) 83 | } 84 | 85 | func (in *input) charinfoNFKC(p int) (uint16, int) { 86 | if in.bytes == nil { 87 | return nfkcData.lookupString(in.str[p:]) 88 | } 89 | return nfkcData.lookup(in.bytes[p:]) 90 | } 91 | 92 | func (in *input) hangul(p int) (r rune) { 93 | if in.bytes == nil { 94 | if !isHangulString(in.str[p:]) { 95 | return 0 96 | } 97 | r, _ = utf8.DecodeRuneInString(in.str[p:]) 98 | } else { 99 | if !isHangul(in.bytes[p:]) { 100 | return 0 101 | } 102 | r, _ = utf8.DecodeRune(in.bytes[p:]) 103 | } 104 | return r 105 | } 106 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/norm/readwriter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package norm 6 | 7 | import "io" 8 | 9 | type normWriter struct { 10 | rb reorderBuffer 11 | w io.Writer 12 | buf []byte 13 | } 14 | 15 | // Write implements the standard write interface. If the last characters are 16 | // not at a normalization boundary, the bytes will be buffered for the next 17 | // write. The remaining bytes will be written on close. 18 | func (w *normWriter) Write(data []byte) (n int, err error) { 19 | // Process data in pieces to keep w.buf size bounded. 20 | const chunk = 4000 21 | 22 | for len(data) > 0 { 23 | // Normalize into w.buf. 24 | m := len(data) 25 | if m > chunk { 26 | m = chunk 27 | } 28 | w.rb.src = inputBytes(data[:m]) 29 | w.rb.nsrc = m 30 | w.buf = doAppend(&w.rb, w.buf, 0) 31 | data = data[m:] 32 | n += m 33 | 34 | // Write out complete prefix, save remainder. 35 | // Note that lastBoundary looks back at most 31 runes. 36 | i := lastBoundary(&w.rb.f, w.buf) 37 | if i == -1 { 38 | i = 0 39 | } 40 | if i > 0 { 41 | if _, err = w.w.Write(w.buf[:i]); err != nil { 42 | break 43 | } 44 | bn := copy(w.buf, w.buf[i:]) 45 | w.buf = w.buf[:bn] 46 | } 47 | } 48 | return n, err 49 | } 50 | 51 | // Close forces data that remains in the buffer to be written. 52 | func (w *normWriter) Close() error { 53 | if len(w.buf) > 0 { 54 | _, err := w.w.Write(w.buf) 55 | if err != nil { 56 | return err 57 | } 58 | } 59 | return nil 60 | } 61 | 62 | // Writer returns a new writer that implements Write(b) 63 | // by writing f(b) to w. The returned writer may use an 64 | // an internal buffer to maintain state across Write calls. 65 | // Calling its Close method writes any buffered data to w. 66 | func (f Form) Writer(w io.Writer) io.WriteCloser { 67 | wr := &normWriter{rb: reorderBuffer{}, w: w} 68 | wr.rb.init(f, nil) 69 | return wr 70 | } 71 | 72 | type normReader struct { 73 | rb reorderBuffer 74 | r io.Reader 75 | inbuf []byte 76 | outbuf []byte 77 | bufStart int 78 | lastBoundary int 79 | err error 80 | } 81 | 82 | // Read implements the standard read interface. 83 | func (r *normReader) Read(p []byte) (int, error) { 84 | for { 85 | if r.lastBoundary-r.bufStart > 0 { 86 | n := copy(p, r.outbuf[r.bufStart:r.lastBoundary]) 87 | r.bufStart += n 88 | if r.lastBoundary-r.bufStart > 0 { 89 | return n, nil 90 | } 91 | return n, r.err 92 | } 93 | if r.err != nil { 94 | return 0, r.err 95 | } 96 | outn := copy(r.outbuf, r.outbuf[r.lastBoundary:]) 97 | r.outbuf = r.outbuf[0:outn] 98 | r.bufStart = 0 99 | 100 | n, err := r.r.Read(r.inbuf) 101 | r.rb.src = inputBytes(r.inbuf[0:n]) 102 | r.rb.nsrc, r.err = n, err 103 | if n > 0 { 104 | r.outbuf = doAppend(&r.rb, r.outbuf, 0) 105 | } 106 | if err == io.EOF { 107 | r.lastBoundary = len(r.outbuf) 108 | } else { 109 | r.lastBoundary = lastBoundary(&r.rb.f, r.outbuf) 110 | if r.lastBoundary == -1 { 111 | r.lastBoundary = 0 112 | } 113 | } 114 | } 115 | } 116 | 117 | // Reader returns a new reader that implements Read 118 | // by reading data from r and returning f(data). 119 | func (f Form) Reader(r io.Reader) io.Reader { 120 | const chunk = 4000 121 | buf := make([]byte, chunk) 122 | rr := &normReader{rb: reorderBuffer{}, r: r, inbuf: buf} 123 | rr.rb.init(f, buf) 124 | return rr 125 | } 126 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/norm/transform.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package norm 6 | 7 | import ( 8 | "unicode/utf8" 9 | 10 | "golang.org/x/text/transform" 11 | ) 12 | 13 | // Reset implements the Reset method of the transform.Transformer interface. 14 | func (Form) Reset() {} 15 | 16 | // Transform implements the Transform method of the transform.Transformer 17 | // interface. It may need to write segments of up to MaxSegmentSize at once. 18 | // Users should either catch ErrShortDst and allow dst to grow or have dst be at 19 | // least of size MaxTransformChunkSize to be guaranteed of progress. 20 | func (f Form) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { 21 | n := 0 22 | // Cap the maximum number of src bytes to check. 23 | b := src 24 | eof := atEOF 25 | if ns := len(dst); ns < len(b) { 26 | err = transform.ErrShortDst 27 | eof = false 28 | b = b[:ns] 29 | } 30 | i, ok := formTable[f].quickSpan(inputBytes(b), n, len(b), eof) 31 | n += copy(dst[n:], b[n:i]) 32 | if !ok { 33 | nDst, nSrc, err = f.transform(dst[n:], src[n:], atEOF) 34 | return nDst + n, nSrc + n, err 35 | } 36 | if n < len(src) && !atEOF { 37 | err = transform.ErrShortSrc 38 | } 39 | return n, n, err 40 | } 41 | 42 | func flushTransform(rb *reorderBuffer) bool { 43 | // Write out (must fully fit in dst, or else it is a ErrShortDst). 44 | if len(rb.out) < rb.nrune*utf8.UTFMax { 45 | return false 46 | } 47 | rb.out = rb.out[rb.flushCopy(rb.out):] 48 | return true 49 | } 50 | 51 | var errs = []error{nil, transform.ErrShortDst, transform.ErrShortSrc} 52 | 53 | // transform implements the transform.Transformer interface. It is only called 54 | // when quickSpan does not pass for a given string. 55 | func (f Form) transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { 56 | // TODO: get rid of reorderBuffer. See CL 23460044. 57 | rb := reorderBuffer{} 58 | rb.init(f, src) 59 | for { 60 | // Load segment into reorder buffer. 61 | rb.setFlusher(dst[nDst:], flushTransform) 62 | end := decomposeSegment(&rb, nSrc, atEOF) 63 | if end < 0 { 64 | return nDst, nSrc, errs[-end] 65 | } 66 | nDst = len(dst) - len(rb.out) 67 | nSrc = end 68 | 69 | // Next quickSpan. 70 | end = rb.nsrc 71 | eof := atEOF 72 | if n := nSrc + len(dst) - nDst; n < end { 73 | err = transform.ErrShortDst 74 | end = n 75 | eof = false 76 | } 77 | end, ok := rb.f.quickSpan(rb.src, nSrc, end, eof) 78 | n := copy(dst[nDst:], rb.src.bytes[nSrc:end]) 79 | nSrc += n 80 | nDst += n 81 | if ok { 82 | if n < rb.nsrc && !atEOF { 83 | err = transform.ErrShortSrc 84 | } 85 | return nDst, nSrc, err 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/norm/trie.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package norm 6 | 7 | type valueRange struct { 8 | value uint16 // header: value:stride 9 | lo, hi byte // header: lo:n 10 | } 11 | 12 | type sparseBlocks struct { 13 | values []valueRange 14 | offset []uint16 15 | } 16 | 17 | var nfcSparse = sparseBlocks{ 18 | values: nfcSparseValues[:], 19 | offset: nfcSparseOffset[:], 20 | } 21 | 22 | var nfkcSparse = sparseBlocks{ 23 | values: nfkcSparseValues[:], 24 | offset: nfkcSparseOffset[:], 25 | } 26 | 27 | var ( 28 | nfcData = newNfcTrie(0) 29 | nfkcData = newNfkcTrie(0) 30 | ) 31 | 32 | // lookupValue determines the type of block n and looks up the value for b. 33 | // For n < t.cutoff, the block is a simple lookup table. Otherwise, the block 34 | // is a list of ranges with an accompanying value. Given a matching range r, 35 | // the value for b is by r.value + (b - r.lo) * stride. 36 | func (t *sparseBlocks) lookup(n uint32, b byte) uint16 { 37 | offset := t.offset[n] 38 | header := t.values[offset] 39 | lo := offset + 1 40 | hi := lo + uint16(header.lo) 41 | for lo < hi { 42 | m := lo + (hi-lo)/2 43 | r := t.values[m] 44 | if r.lo <= b && b <= r.hi { 45 | return r.value + uint16(b-r.lo)*header.value 46 | } 47 | if b < r.lo { 48 | hi = m 49 | } else { 50 | lo = m + 1 51 | } 52 | } 53 | return 0 54 | } 55 | -------------------------------------------------------------------------------- /vendor/golang.org/x/text/unicode/norm/triegen.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build ignore 6 | 7 | // Trie table generator. 8 | // Used by make*tables tools to generate a go file with trie data structures 9 | // for mapping UTF-8 to a 16-bit value. All but the last byte in a UTF-8 byte 10 | // sequence are used to lookup offsets in the index table to be used for the 11 | // next byte. The last byte is used to index into a table with 16-bit values. 12 | 13 | package main 14 | 15 | import ( 16 | "fmt" 17 | "io" 18 | ) 19 | 20 | const maxSparseEntries = 16 21 | 22 | type normCompacter struct { 23 | sparseBlocks [][]uint64 24 | sparseOffset []uint16 25 | sparseCount int 26 | name string 27 | } 28 | 29 | func mostFrequentStride(a []uint64) int { 30 | counts := make(map[int]int) 31 | var v int 32 | for _, x := range a { 33 | if stride := int(x) - v; v != 0 && stride >= 0 { 34 | counts[stride]++ 35 | } 36 | v = int(x) 37 | } 38 | var maxs, maxc int 39 | for stride, cnt := range counts { 40 | if cnt > maxc || (cnt == maxc && stride < maxs) { 41 | maxs, maxc = stride, cnt 42 | } 43 | } 44 | return maxs 45 | } 46 | 47 | func countSparseEntries(a []uint64) int { 48 | stride := mostFrequentStride(a) 49 | var v, count int 50 | for _, tv := range a { 51 | if int(tv)-v != stride { 52 | if tv != 0 { 53 | count++ 54 | } 55 | } 56 | v = int(tv) 57 | } 58 | return count 59 | } 60 | 61 | func (c *normCompacter) Size(v []uint64) (sz int, ok bool) { 62 | if n := countSparseEntries(v); n <= maxSparseEntries { 63 | return (n+1)*4 + 2, true 64 | } 65 | return 0, false 66 | } 67 | 68 | func (c *normCompacter) Store(v []uint64) uint32 { 69 | h := uint32(len(c.sparseOffset)) 70 | c.sparseBlocks = append(c.sparseBlocks, v) 71 | c.sparseOffset = append(c.sparseOffset, uint16(c.sparseCount)) 72 | c.sparseCount += countSparseEntries(v) + 1 73 | return h 74 | } 75 | 76 | func (c *normCompacter) Handler() string { 77 | return c.name + "Sparse.lookup" 78 | } 79 | 80 | func (c *normCompacter) Print(w io.Writer) (retErr error) { 81 | p := func(f string, x ...interface{}) { 82 | if _, err := fmt.Fprintf(w, f, x...); retErr == nil && err != nil { 83 | retErr = err 84 | } 85 | } 86 | 87 | ls := len(c.sparseBlocks) 88 | p("// %sSparseOffset: %d entries, %d bytes\n", c.name, ls, ls*2) 89 | p("var %sSparseOffset = %#v\n\n", c.name, c.sparseOffset) 90 | 91 | ns := c.sparseCount 92 | p("// %sSparseValues: %d entries, %d bytes\n", c.name, ns, ns*4) 93 | p("var %sSparseValues = [%d]valueRange {", c.name, ns) 94 | for i, b := range c.sparseBlocks { 95 | p("\n// Block %#x, offset %#x", i, c.sparseOffset[i]) 96 | var v int 97 | stride := mostFrequentStride(b) 98 | n := countSparseEntries(b) 99 | p("\n{value:%#04x,lo:%#02x},", stride, uint8(n)) 100 | for i, nv := range b { 101 | if int(nv)-v != stride { 102 | if v != 0 { 103 | p(",hi:%#02x},", 0x80+i-1) 104 | } 105 | if nv != 0 { 106 | p("\n{value:%#04x,lo:%#02x", nv, 0x80+i) 107 | } 108 | } 109 | v = int(nv) 110 | } 111 | if v != 0 { 112 | p(",hi:%#02x},", 0x80+len(b)-1) 113 | } 114 | } 115 | p("\n}\n\n") 116 | return 117 | } 118 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4 5 | - 1.5 6 | - 1.6 7 | - tip 8 | 9 | go_import_path: gopkg.in/yaml.v2 10 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2011-2016 Canonical Ltd. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/LICENSE.libyaml: -------------------------------------------------------------------------------- 1 | The following files were ported to Go from C files of libyaml, and thus 2 | are still covered by their original copyright and license: 3 | 4 | apic.go 5 | emitterc.go 6 | parserc.go 7 | readerc.go 8 | scannerc.go 9 | writerc.go 10 | yamlh.go 11 | yamlprivateh.go 12 | 13 | Copyright (c) 2006 Kirill Simonov 14 | 15 | Permission is hereby granted, free of charge, to any person obtaining a copy of 16 | this software and associated documentation files (the "Software"), to deal in 17 | the Software without restriction, including without limitation the rights to 18 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 19 | of the Software, and to permit persons to whom the Software is furnished to do 20 | so, subject to the following conditions: 21 | 22 | The above copyright notice and this permission notice shall be included in all 23 | copies or substantial portions of the Software. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/README.md: -------------------------------------------------------------------------------- 1 | # YAML support for the Go language 2 | 3 | Introduction 4 | ------------ 5 | 6 | The yaml package enables Go programs to comfortably encode and decode YAML 7 | values. It was developed within [Canonical](https://www.canonical.com) as 8 | part of the [juju](https://juju.ubuntu.com) project, and is based on a 9 | pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) 10 | C library to parse and generate YAML data quickly and reliably. 11 | 12 | Compatibility 13 | ------------- 14 | 15 | The yaml package supports most of YAML 1.1 and 1.2, including support for 16 | anchors, tags, map merging, etc. Multi-document unmarshalling is not yet 17 | implemented, and base-60 floats from YAML 1.1 are purposefully not 18 | supported since they're a poor design and are gone in YAML 1.2. 19 | 20 | Installation and usage 21 | ---------------------- 22 | 23 | The import path for the package is *gopkg.in/yaml.v2*. 24 | 25 | To install it, run: 26 | 27 | go get gopkg.in/yaml.v2 28 | 29 | API documentation 30 | ----------------- 31 | 32 | If opened in a browser, the import path itself leads to the API documentation: 33 | 34 | * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) 35 | 36 | API stability 37 | ------------- 38 | 39 | The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). 40 | 41 | 42 | License 43 | ------- 44 | 45 | The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. 46 | 47 | 48 | Example 49 | ------- 50 | 51 | ```Go 52 | package main 53 | 54 | import ( 55 | "fmt" 56 | "log" 57 | 58 | "gopkg.in/yaml.v2" 59 | ) 60 | 61 | var data = ` 62 | a: Easy! 63 | b: 64 | c: 2 65 | d: [3, 4] 66 | ` 67 | 68 | type T struct { 69 | A string 70 | B struct { 71 | RenamedC int `yaml:"c"` 72 | D []int `yaml:",flow"` 73 | } 74 | } 75 | 76 | func main() { 77 | t := T{} 78 | 79 | err := yaml.Unmarshal([]byte(data), &t) 80 | if err != nil { 81 | log.Fatalf("error: %v", err) 82 | } 83 | fmt.Printf("--- t:\n%v\n\n", t) 84 | 85 | d, err := yaml.Marshal(&t) 86 | if err != nil { 87 | log.Fatalf("error: %v", err) 88 | } 89 | fmt.Printf("--- t dump:\n%s\n\n", string(d)) 90 | 91 | m := make(map[interface{}]interface{}) 92 | 93 | err = yaml.Unmarshal([]byte(data), &m) 94 | if err != nil { 95 | log.Fatalf("error: %v", err) 96 | } 97 | fmt.Printf("--- m:\n%v\n\n", m) 98 | 99 | d, err = yaml.Marshal(&m) 100 | if err != nil { 101 | log.Fatalf("error: %v", err) 102 | } 103 | fmt.Printf("--- m dump:\n%s\n\n", string(d)) 104 | } 105 | ``` 106 | 107 | This example will generate the following output: 108 | 109 | ``` 110 | --- t: 111 | {Easy! {2 [3 4]}} 112 | 113 | --- t dump: 114 | a: Easy! 115 | b: 116 | c: 2 117 | d: [3, 4] 118 | 119 | 120 | --- m: 121 | map[a:Easy! b:map[c:2 d:[3 4]]] 122 | 123 | --- m dump: 124 | a: Easy! 125 | b: 126 | c: 2 127 | d: 128 | - 3 129 | - 4 130 | ``` 131 | 132 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/sorter.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "reflect" 5 | "unicode" 6 | ) 7 | 8 | type keyList []reflect.Value 9 | 10 | func (l keyList) Len() int { return len(l) } 11 | func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } 12 | func (l keyList) Less(i, j int) bool { 13 | a := l[i] 14 | b := l[j] 15 | ak := a.Kind() 16 | bk := b.Kind() 17 | for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { 18 | a = a.Elem() 19 | ak = a.Kind() 20 | } 21 | for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { 22 | b = b.Elem() 23 | bk = b.Kind() 24 | } 25 | af, aok := keyFloat(a) 26 | bf, bok := keyFloat(b) 27 | if aok && bok { 28 | if af != bf { 29 | return af < bf 30 | } 31 | if ak != bk { 32 | return ak < bk 33 | } 34 | return numLess(a, b) 35 | } 36 | if ak != reflect.String || bk != reflect.String { 37 | return ak < bk 38 | } 39 | ar, br := []rune(a.String()), []rune(b.String()) 40 | for i := 0; i < len(ar) && i < len(br); i++ { 41 | if ar[i] == br[i] { 42 | continue 43 | } 44 | al := unicode.IsLetter(ar[i]) 45 | bl := unicode.IsLetter(br[i]) 46 | if al && bl { 47 | return ar[i] < br[i] 48 | } 49 | if al || bl { 50 | return bl 51 | } 52 | var ai, bi int 53 | var an, bn int64 54 | for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { 55 | an = an*10 + int64(ar[ai]-'0') 56 | } 57 | for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { 58 | bn = bn*10 + int64(br[bi]-'0') 59 | } 60 | if an != bn { 61 | return an < bn 62 | } 63 | if ai != bi { 64 | return ai < bi 65 | } 66 | return ar[i] < br[i] 67 | } 68 | return len(ar) < len(br) 69 | } 70 | 71 | // keyFloat returns a float value for v if it is a number/bool 72 | // and whether it is a number/bool or not. 73 | func keyFloat(v reflect.Value) (f float64, ok bool) { 74 | switch v.Kind() { 75 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 76 | return float64(v.Int()), true 77 | case reflect.Float32, reflect.Float64: 78 | return v.Float(), true 79 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 80 | return float64(v.Uint()), true 81 | case reflect.Bool: 82 | if v.Bool() { 83 | return 1, true 84 | } 85 | return 0, true 86 | } 87 | return 0, false 88 | } 89 | 90 | // numLess returns whether a < b. 91 | // a and b must necessarily have the same kind. 92 | func numLess(a, b reflect.Value) bool { 93 | switch a.Kind() { 94 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 95 | return a.Int() < b.Int() 96 | case reflect.Float32, reflect.Float64: 97 | return a.Float() < b.Float() 98 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 99 | return a.Uint() < b.Uint() 100 | case reflect.Bool: 101 | return !a.Bool() && b.Bool() 102 | } 103 | panic("not a number") 104 | } 105 | -------------------------------------------------------------------------------- /vendor/gopkg.in/yaml.v2/writerc.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | // Set the writer error and return false. 4 | func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { 5 | emitter.error = yaml_WRITER_ERROR 6 | emitter.problem = problem 7 | return false 8 | } 9 | 10 | // Flush the output buffer. 11 | func yaml_emitter_flush(emitter *yaml_emitter_t) bool { 12 | if emitter.write_handler == nil { 13 | panic("write handler not set") 14 | } 15 | 16 | // Check if the buffer is empty. 17 | if emitter.buffer_pos == 0 { 18 | return true 19 | } 20 | 21 | // If the output encoding is UTF-8, we don't need to recode the buffer. 22 | if emitter.encoding == yaml_UTF8_ENCODING { 23 | if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { 24 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 25 | } 26 | emitter.buffer_pos = 0 27 | return true 28 | } 29 | 30 | // Recode the buffer into the raw buffer. 31 | var low, high int 32 | if emitter.encoding == yaml_UTF16LE_ENCODING { 33 | low, high = 0, 1 34 | } else { 35 | high, low = 1, 0 36 | } 37 | 38 | pos := 0 39 | for pos < emitter.buffer_pos { 40 | // See the "reader.c" code for more details on UTF-8 encoding. Note 41 | // that we assume that the buffer contains a valid UTF-8 sequence. 42 | 43 | // Read the next UTF-8 character. 44 | octet := emitter.buffer[pos] 45 | 46 | var w int 47 | var value rune 48 | switch { 49 | case octet&0x80 == 0x00: 50 | w, value = 1, rune(octet&0x7F) 51 | case octet&0xE0 == 0xC0: 52 | w, value = 2, rune(octet&0x1F) 53 | case octet&0xF0 == 0xE0: 54 | w, value = 3, rune(octet&0x0F) 55 | case octet&0xF8 == 0xF0: 56 | w, value = 4, rune(octet&0x07) 57 | } 58 | for k := 1; k < w; k++ { 59 | octet = emitter.buffer[pos+k] 60 | value = (value << 6) + (rune(octet) & 0x3F) 61 | } 62 | pos += w 63 | 64 | // Write the character. 65 | if value < 0x10000 { 66 | var b [2]byte 67 | b[high] = byte(value >> 8) 68 | b[low] = byte(value & 0xFF) 69 | emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1]) 70 | } else { 71 | // Write the character using a surrogate pair (check "reader.c"). 72 | var b [4]byte 73 | value -= 0x10000 74 | b[high] = byte(0xD8 + (value >> 18)) 75 | b[low] = byte((value >> 10) & 0xFF) 76 | b[high+2] = byte(0xDC + ((value >> 8) & 0xFF)) 77 | b[low+2] = byte(value & 0xFF) 78 | emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3]) 79 | } 80 | } 81 | 82 | // Write the raw buffer. 83 | if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil { 84 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) 85 | } 86 | emitter.buffer_pos = 0 87 | emitter.raw_buffer = emitter.raw_buffer[:0] 88 | return true 89 | } 90 | --------------------------------------------------------------------------------